Fix warnings for Linux, FreeBSD and Solaris.
[wine] / server / request.c
1 /*
2  * Server-side request handling
3  *
4  * Copyright (C) 1998 Alexandre Julliard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 #include "config.h"
22 #include "wine/port.h"
23
24 #include <assert.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <pwd.h>
28 #include <signal.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <stdarg.h>
32 #include <string.h>
33 #include <sys/stat.h>
34 #include <sys/time.h>
35 #include <sys/types.h>
36 #ifdef HAVE_SYS_SOCKET_H
37 # include <sys/socket.h>
38 #endif
39 #include <sys/uio.h>
40 #include <sys/un.h>
41 #include <unistd.h>
42
43 #include "winnt.h"
44 #include "winbase.h"
45 #include "wincon.h"
46 #include "thread.h"
47 #include "process.h"
48 #define WANT_REQUEST_HANDLERS
49 #include "request.h"
50
51 /* Some versions of glibc don't define this */
52 #ifndef SCM_RIGHTS
53 #define SCM_RIGHTS 1
54 #endif
55
56  /* path names for server master Unix socket */
57 #define CONFDIR    "/.wine"        /* directory for Wine config relative to $HOME */
58 #define SERVERDIR  "wineserver-"   /* server socket directory (hostname appended) */
59 #define SOCKETNAME "socket"        /* name of the socket file */
60
61 struct master_socket
62 {
63     struct object       obj;         /* object header */
64 };
65
66 static void master_socket_dump( struct object *obj, int verbose );
67 static void master_socket_poll_event( struct object *obj, int event );
68 static void master_socket_destroy( struct object *obj );
69
70 static const struct object_ops master_socket_ops =
71 {
72     sizeof(struct master_socket),  /* size */
73     master_socket_dump,            /* dump */
74     no_add_queue,                  /* add_queue */
75     NULL,                          /* remove_queue */
76     NULL,                          /* signaled */
77     NULL,                          /* satisfied */
78     NULL,                          /* get_poll_events */
79     master_socket_poll_event,      /* poll_event */
80     no_get_fd,                     /* get_fd */
81     no_flush,                      /* flush */
82     no_get_file_info,              /* get_file_info */
83     NULL,                          /* queue_async */
84     master_socket_destroy          /* destroy */
85 };
86
87
88 struct thread *current = NULL;  /* thread handling the current request */
89 unsigned int global_error = 0;  /* global error code for when no thread is current */
90 unsigned int server_start_ticks = 0;  /* tick count offset from server startup */
91
92 static struct master_socket *master_socket;  /* the master socket object */
93
94 /* socket communication static structures */
95 static struct iovec myiovec;
96 static struct msghdr msghdr;
97 #ifndef HAVE_MSGHDR_ACCRIGHTS
98 struct cmsg_fd
99 {
100     int len;   /* sizeof structure */
101     int level; /* SOL_SOCKET */
102     int type;  /* SCM_RIGHTS */
103     int fd;    /* fd to pass */
104 };
105 static struct cmsg_fd cmsg = { sizeof(cmsg), SOL_SOCKET, SCM_RIGHTS, -1 };
106 #endif  /* HAVE_MSGHDR_ACCRIGHTS */
107
108 /* complain about a protocol error and terminate the client connection */
109 void fatal_protocol_error( struct thread *thread, const char *err, ... )
110 {
111     va_list args;
112
113     va_start( args, err );
114     fprintf( stderr, "Protocol error:%p: ", thread );
115     vfprintf( stderr, err, args );
116     va_end( args );
117     thread->exit_code = 1;
118     kill_thread( thread, 1 );
119 }
120
121 /* complain about a protocol error and terminate the client connection */
122 void fatal_protocol_perror( struct thread *thread, const char *err, ... )
123 {
124     va_list args;
125
126     va_start( args, err );
127     fprintf( stderr, "Protocol error:%p: ", thread );
128     vfprintf( stderr, err, args );
129     perror( " " );
130     va_end( args );
131     thread->exit_code = 1;
132     kill_thread( thread, 1 );
133 }
134
135 /* die on a fatal error */
136 void fatal_error( const char *err, ... )
137 {
138     va_list args;
139
140     va_start( args, err );
141     fprintf( stderr, "wineserver: " );
142     vfprintf( stderr, err, args );
143     va_end( args );
144     exit(1);
145 }
146
147 /* die on a fatal error */
148 void fatal_perror( const char *err, ... )
149 {
150     va_list args;
151
152     va_start( args, err );
153     fprintf( stderr, "wineserver: " );
154     vfprintf( stderr, err, args );
155     perror( " " );
156     va_end( args );
157     exit(1);
158 }
159
160 /* allocate the reply data */
161 void *set_reply_data_size( size_t size )
162 {
163     assert( size <= get_reply_max_size() );
164     if (size && !(current->reply_data = mem_alloc( size ))) size = 0;
165     current->reply_size = size;
166     return current->reply_data;
167 }
168
169 /* write the remaining part of the reply */
170 void write_reply( struct thread *thread )
171 {
172     int ret;
173
174     if ((ret = write( thread->reply_fd,
175                       (char *)thread->reply_data + thread->reply_size - thread->reply_towrite,
176                       thread->reply_towrite )) >= 0)
177     {
178         if (!(thread->reply_towrite -= ret))
179         {
180             free( thread->reply_data );
181             thread->reply_data = NULL;
182             /* sent everything, can go back to waiting for requests */
183             change_select_fd( &thread->obj, thread->request_fd, POLLIN );
184         }
185         return;
186     }
187     if (errno == EPIPE)
188         kill_thread( thread, 0 );  /* normal death */
189     else if (errno != EWOULDBLOCK && errno != EAGAIN)
190         fatal_protocol_perror( thread, "reply write" );
191 }
192
193 /* send a reply to the current thread */
194 static void send_reply( union generic_reply *reply )
195 {
196     int ret;
197
198     if (!current->reply_size)
199     {
200         if ((ret = write( current->reply_fd, reply, sizeof(*reply) )) != sizeof(*reply)) goto error;
201     }
202     else
203     {
204         struct iovec vec[2];
205
206         vec[0].iov_base = (void *)reply;
207         vec[0].iov_len  = sizeof(*reply);
208         vec[1].iov_base = current->reply_data;
209         vec[1].iov_len  = current->reply_size;
210
211         if ((ret = writev( current->reply_fd, vec, 2 )) < sizeof(*reply)) goto error;
212
213         if ((current->reply_towrite = current->reply_size - (ret - sizeof(*reply))))
214         {
215             /* couldn't write it all, wait for POLLOUT */
216             change_select_fd( &current->obj, current->reply_fd, POLLOUT );
217             return;
218         }
219     }
220     if (current->reply_data)
221     {
222         free( current->reply_data );
223         current->reply_data = NULL;
224     }
225     return;
226
227  error:
228     if (ret >= 0)
229         fatal_protocol_error( current, "partial write %d\n", ret );
230     else if (errno == EPIPE)
231         kill_thread( current, 0 );  /* normal death */
232     else
233         fatal_protocol_perror( current, "reply write" );
234 }
235
236 /* call a request handler */
237 static void call_req_handler( struct thread *thread )
238 {
239     union generic_reply reply;
240     enum request req = thread->req.request_header.req;
241
242     current = thread;
243     current->reply_size = 0;
244     clear_error();
245     memset( &reply, 0, sizeof(reply) );
246
247     if (debug_level) trace_request();
248
249     if (req < REQ_NB_REQUESTS)
250     {
251         req_handlers[req]( &current->req, &reply );
252         if (current)
253         {
254             reply.reply_header.error = current->error;
255             reply.reply_header.reply_size = current->reply_size;
256             if (debug_level) trace_reply( req, &reply );
257             send_reply( &reply );
258         }
259         current = NULL;
260         return;
261     }
262     fatal_protocol_error( current, "bad request %d\n", req );
263 }
264
265 /* read a request from a thread */
266 void read_request( struct thread *thread )
267 {
268     int ret;
269
270     if (!thread->req_toread)  /* no pending request */
271     {
272         if ((ret = read( thread->obj.fd, &thread->req,
273                          sizeof(thread->req) )) != sizeof(thread->req)) goto error;
274         if (!(thread->req_toread = thread->req.request_header.request_size))
275         {
276             /* no data, handle request at once */
277             call_req_handler( thread );
278             return;
279         }
280         if (!(thread->req_data = malloc( thread->req_toread )))
281             fatal_protocol_error( thread, "no memory for %d bytes request\n", thread->req_toread );
282     }
283
284     /* read the variable sized data */
285     for (;;)
286     {
287         ret = read( thread->obj.fd, ((char *)thread->req_data +
288                                      thread->req.request_header.request_size - thread->req_toread),
289                     thread->req_toread );
290         if (ret <= 0) break;
291         if (!(thread->req_toread -= ret))
292         {
293             call_req_handler( thread );
294             free( thread->req_data );
295             thread->req_data = NULL;
296             return;
297         }
298     }
299
300 error:
301     if (!ret)  /* closed pipe */
302         kill_thread( thread, 0 );
303     else if (ret > 0)
304         fatal_protocol_error( thread, "partial read %d\n", ret );
305     else if (errno != EWOULDBLOCK && errno != EAGAIN)
306         fatal_protocol_perror( thread, "read" );
307 }
308
309 /* receive a file descriptor on the process socket */
310 int receive_fd( struct process *process )
311 {
312     struct send_fd data;
313     int fd, ret;
314
315 #ifdef HAVE_MSGHDR_ACCRIGHTS
316     msghdr.msg_accrightslen = sizeof(int);
317     msghdr.msg_accrights = (void *)&fd;
318 #else  /* HAVE_MSGHDR_ACCRIGHTS */
319     msghdr.msg_control    = &cmsg;
320     msghdr.msg_controllen = sizeof(cmsg);
321     cmsg.fd = -1;
322 #endif  /* HAVE_MSGHDR_ACCRIGHTS */
323
324     myiovec.iov_base = (void *)&data;
325     myiovec.iov_len  = sizeof(data);
326
327     ret = recvmsg( process->obj.fd, &msghdr, 0 );
328 #ifndef HAVE_MSGHDR_ACCRIGHTS
329     fd = cmsg.fd;
330 #endif
331
332     if (ret == sizeof(data))
333     {
334         struct thread *thread;
335
336         if (data.tid) thread = get_thread_from_id( data.tid );
337         else thread = (struct thread *)grab_object( process->thread_list );
338
339         if (!thread || thread->process != process)
340         {
341             if (debug_level)
342                 fprintf( stderr, "%08x: *fd* %d <- %d bad thread id\n",
343                          (unsigned int)data.tid, data.fd, fd );
344             close( fd );
345         }
346         else
347         {
348             if (debug_level)
349                 fprintf( stderr, "%08x: *fd* %d <- %d\n",
350                          (unsigned int)thread, data.fd, fd );
351             thread_add_inflight_fd( thread, data.fd, fd );
352         }
353         if (thread) release_object( thread );
354         return 0;
355     }
356
357     if (ret >= 0)
358     {
359         if (ret > 0)
360             fprintf( stderr, "Protocol error: process %p: partial recvmsg %d for fd\n",
361                      process, ret );
362         kill_process( process, NULL, 1 );
363     }
364     else
365     {
366         if (errno != EWOULDBLOCK && errno != EAGAIN)
367         {
368             fprintf( stderr, "Protocol error: process %p: ", process );
369             perror( "recvmsg" );
370             kill_process( process, NULL, 1 );
371         }
372     }
373     return -1;
374 }
375
376 /* send an fd to a client */
377 int send_client_fd( struct process *process, int fd, handle_t handle )
378 {
379     int ret;
380
381     if (debug_level)
382         fprintf( stderr, "%08x: *fd* %d -> %d\n", (unsigned int)current, handle, fd );
383
384 #ifdef HAVE_MSGHDR_ACCRIGHTS
385     msghdr.msg_accrightslen = sizeof(fd);
386     msghdr.msg_accrights = (void *)&fd;
387 #else  /* HAVE_MSGHDR_ACCRIGHTS */
388     msghdr.msg_control    = &cmsg;
389     msghdr.msg_controllen = sizeof(cmsg);
390     cmsg.fd = fd;
391 #endif  /* HAVE_MSGHDR_ACCRIGHTS */
392
393     myiovec.iov_base = (void *)&handle;
394     myiovec.iov_len  = sizeof(handle);
395
396     ret = sendmsg( process->obj.fd, &msghdr, 0 );
397
398     if (ret == sizeof(handle)) return 0;
399
400     if (ret >= 0)
401     {
402         if (ret > 0)
403             fprintf( stderr, "Protocol error: process %p: partial sendmsg %d\n", process, ret );
404         kill_process( process, NULL, 1 );
405     }
406     else
407     {
408         fprintf( stderr, "Protocol error: process %p: ", process );
409         perror( "sendmsg" );
410         kill_process( process, NULL, 1 );
411     }
412     return -1;
413 }
414
415 /* get current tick count to return to client */
416 unsigned int get_tick_count(void)
417 {
418     struct timeval t;
419     gettimeofday( &t, NULL );
420     return (t.tv_sec * 1000) + (t.tv_usec / 1000) - server_start_ticks;
421 }
422
423 static void master_socket_dump( struct object *obj, int verbose )
424 {
425     struct master_socket *sock = (struct master_socket *)obj;
426     assert( obj->ops == &master_socket_ops );
427     fprintf( stderr, "Master socket fd=%d\n", sock->obj.fd );
428 }
429
430 /* handle a socket event */
431 static void master_socket_poll_event( struct object *obj, int event )
432 {
433     struct master_socket *sock = (struct master_socket *)obj;
434     assert( obj->ops == &master_socket_ops );
435
436     assert( sock == master_socket );  /* there is only one master socket */
437
438     if (event & (POLLERR | POLLHUP))
439     {
440         /* this is not supposed to happen */
441         fprintf( stderr, "wineserver: Error on master socket\n" );
442         release_object( obj );
443     }
444     else if (event & POLLIN)
445     {
446         struct sockaddr_un dummy;
447         int len = sizeof(dummy);
448         int client = accept( master_socket->obj.fd, (struct sockaddr *) &dummy, &len );
449         if (client == -1) return;
450         fcntl( client, F_SETFL, O_NONBLOCK );
451         create_process( client );
452     }
453 }
454
455 /* remove the socket upon exit */
456 static void socket_cleanup(void)
457 {
458     static int do_it_once;
459     if (!do_it_once++) unlink( SOCKETNAME );
460 }
461
462 static void master_socket_destroy( struct object *obj )
463 {
464     socket_cleanup();
465 }
466
467 /* return the configuration directory ($WINEPREFIX or $HOME/.wine) */
468 const char *get_config_dir(void)
469 {
470     static char *confdir;
471     if (!confdir)
472     {
473         const char *prefix = getenv( "WINEPREFIX" );
474         if (prefix)
475         {
476             int len = strlen(prefix);
477             if (!(confdir = strdup( prefix ))) fatal_error( "out of memory\n" );
478             if (len > 1 && confdir[len-1] == '/') confdir[len-1] = 0;
479         }
480         else
481         {
482             const char *home = getenv( "HOME" );
483             if (!home)
484             {
485                 struct passwd *pwd = getpwuid( getuid() );
486                 if (!pwd) fatal_error( "could not find your home directory\n" );
487                 home = pwd->pw_dir;
488             }
489             if (!(confdir = malloc( strlen(home) + strlen(CONFDIR) + 1 )))
490                 fatal_error( "out of memory\n" );
491             strcpy( confdir, home );
492             strcat( confdir, CONFDIR );
493         }
494     }
495     return confdir;
496 }
497
498 /* create the server directory and chdir to it */
499 static void create_server_dir(void)
500 {
501     char hostname[64];
502     char *serverdir;
503     const char *confdir = get_config_dir();
504     struct stat st;
505
506     if (gethostname( hostname, sizeof(hostname) ) == -1) fatal_perror( "gethostname" );
507
508     if (!(serverdir = malloc( strlen(SERVERDIR) + strlen(hostname) + 1 )))
509         fatal_error( "out of memory\n" );
510
511     if (chdir( confdir ) == -1) fatal_perror( "chdir %s", confdir );
512
513     strcpy( serverdir, SERVERDIR );
514     strcat( serverdir, hostname );
515
516     if (chdir( serverdir ) == -1)
517     {
518         if (errno != ENOENT) fatal_perror( "chdir %s", serverdir );
519         if (mkdir( serverdir, 0700 ) == -1) fatal_perror( "mkdir %s", serverdir );
520         if (chdir( serverdir ) == -1) fatal_perror( "chdir %s", serverdir );
521     }
522     if (stat( ".", &st ) == -1) fatal_perror( "stat %s", serverdir );
523     if (!S_ISDIR(st.st_mode)) fatal_error( "%s is not a directory\n", serverdir );
524     if (st.st_uid != getuid()) fatal_error( "%s is not owned by you\n", serverdir );
525     if (st.st_mode & 077) fatal_error( "%s must not be accessible by other users\n", serverdir );
526 }
527
528 /* open the master server socket and start waiting for new clients */
529 void open_master_socket(void)
530 {
531     struct sockaddr_un addr;
532     int fd, slen;
533
534     /* make sure no request is larger than the maximum size */
535     assert( sizeof(union generic_request) == sizeof(struct request_max_size) );
536     assert( sizeof(union generic_reply) == sizeof(struct request_max_size) );
537
538     create_server_dir();
539     if ((fd = socket( AF_UNIX, SOCK_STREAM, 0 )) == -1) fatal_perror( "socket" );
540     addr.sun_family = AF_UNIX;
541     strcpy( addr.sun_path, SOCKETNAME );
542     slen = sizeof(addr) - sizeof(addr.sun_path) + strlen(addr.sun_path) + 1;
543 #ifdef HAVE_SOCKADDR_SUN_LEN
544     addr.sun_len = slen;
545 #endif
546     if (bind( fd, (struct sockaddr *)&addr, slen ) == -1)
547     {
548         if ((errno == EEXIST) || (errno == EADDRINUSE))
549             exit(0);  /* pretend we succeeded to start */
550         else
551             fatal_perror( "bind" );
552     }
553     atexit( socket_cleanup );
554
555     chmod( SOCKETNAME, 0600 );  /* make sure no other user can connect */
556     if (listen( fd, 5 ) == -1) fatal_perror( "listen" );
557
558     if (!(master_socket = alloc_object( &master_socket_ops, fd )))
559         fatal_error( "out of memory\n" );
560     set_select_events( &master_socket->obj, POLLIN );
561
562     /* setup msghdr structure constant fields */
563     msghdr.msg_name    = NULL;
564     msghdr.msg_namelen = 0;
565     msghdr.msg_iov     = &myiovec;
566     msghdr.msg_iovlen  = 1;
567
568     /* init startup ticks */
569     server_start_ticks = get_tick_count();
570
571     /* go in the background */
572     switch(fork())
573     {
574     case -1:
575         fatal_perror( "fork" );
576     case 0:
577         setsid();
578         break;
579     default:
580         _exit(0);  /* do not call atexit functions */
581     }
582 }
583
584 /* close the master socket and stop waiting for new clients */
585 void close_master_socket(void)
586 {
587     /* if a new client is waiting, we keep on running */
588     if (!check_select_events( master_socket->obj.fd, POLLIN ))
589         release_object( master_socket );
590 }
591
592 /* lock/unlock the master socket to stop accepting new clients */
593 void lock_master_socket( int locked )
594 {
595     set_select_events( &master_socket->obj, locked ? 0 : POLLIN );
596 }