Added separate server pipe to wait on blocking server calls.
[wine] / server / request.c
1 /*
2  * Server-side request handling
3  *
4  * Copyright (C) 1998 Alexandre Julliard
5  */
6
7 #include "config.h"
8
9 #include <assert.h>
10 #include <errno.h>
11 #include <fcntl.h>
12 #include <pwd.h>
13 #include <signal.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <stdarg.h>
17 #include <string.h>
18 #include <sys/stat.h>
19 #include <sys/time.h>
20 #include <sys/types.h>
21 #ifdef HAVE_SYS_SOCKET_H
22 # include <sys/socket.h>
23 #endif
24 #include <sys/uio.h>
25 #include <sys/un.h>
26 #include <unistd.h>
27
28 #include "winnt.h"
29 #include "winbase.h"
30 #include "wincon.h"
31 #include "thread.h"
32 #include "process.h"
33 #include "server.h"
34 #define WANT_REQUEST_HANDLERS
35 #include "request.h"
36 #include "wine/port.h"
37
38 /* Some versions of glibc don't define this */
39 #ifndef SCM_RIGHTS
40 #define SCM_RIGHTS 1
41 #endif
42
43  /* path names for server master Unix socket */
44 #define CONFDIR    "/.wine"        /* directory for Wine config relative to $HOME */
45 #define SERVERDIR  "/wineserver-"  /* server socket directory (hostname appended) */
46 #define SOCKETNAME "socket"        /* name of the socket file */
47
48 struct master_socket
49 {
50     struct object       obj;         /* object header */
51 };
52
53 static void master_socket_dump( struct object *obj, int verbose );
54 static void master_socket_poll_event( struct object *obj, int event );
55 static void master_socket_destroy( struct object *obj );
56
57 static const struct object_ops master_socket_ops =
58 {
59     sizeof(struct master_socket),  /* size */
60     master_socket_dump,            /* dump */
61     no_add_queue,                  /* add_queue */
62     NULL,                          /* remove_queue */
63     NULL,                          /* signaled */
64     NULL,                          /* satisfied */
65     NULL,                          /* get_poll_events */
66     master_socket_poll_event,      /* poll_event */
67     no_get_fd,                     /* get_fd */
68     no_flush,                      /* flush */
69     no_get_file_info,              /* get_file_info */
70     master_socket_destroy          /* destroy */
71 };
72
73
74 struct request_socket
75 {
76     struct object       obj;         /* object header */
77     struct thread      *thread;      /* owning thread */
78 };
79
80 static void request_socket_dump( struct object *obj, int verbose );
81 static void request_socket_poll_event( struct object *obj, int event );
82
83 static const struct object_ops request_socket_ops =
84 {
85     sizeof(struct request_socket), /* size */
86     request_socket_dump,           /* dump */
87     no_add_queue,                  /* add_queue */
88     NULL,                          /* remove_queue */
89     NULL,                          /* signaled */
90     NULL,                          /* satisfied */
91     NULL,                          /* get_poll_events */
92     request_socket_poll_event,     /* poll_event */
93     no_get_fd,                     /* get_fd */
94     no_flush,                      /* flush */
95     no_get_file_info,              /* get_file_info */
96     no_destroy                     /* destroy */
97 };
98
99
100 struct thread *current = NULL;  /* thread handling the current request */
101 unsigned int global_error = 0;  /* global error code for when no thread is current */
102
103 static struct master_socket *master_socket;  /* the master socket object */
104
105 /* socket communication static structures */
106 static struct iovec myiovec;
107 static struct msghdr msghdr;
108 #ifndef HAVE_MSGHDR_ACCRIGHTS
109 struct cmsg_fd
110 {
111     int len;   /* sizeof structure */
112     int level; /* SOL_SOCKET */
113     int type;  /* SCM_RIGHTS */
114     int fd;    /* fd to pass */
115 };
116 static struct cmsg_fd cmsg = { sizeof(cmsg), SOL_SOCKET, SCM_RIGHTS, -1 };
117 #endif  /* HAVE_MSGHDR_ACCRIGHTS */
118
119 /* complain about a protocol error and terminate the client connection */
120 void fatal_protocol_error( struct thread *thread, const char *err, ... )
121 {
122     va_list args;
123
124     va_start( args, err );
125     fprintf( stderr, "Protocol error:%p: ", thread );
126     vfprintf( stderr, err, args );
127     va_end( args );
128     thread->exit_code = 1;
129     kill_thread( thread, 1 );
130 }
131
132 /* complain about a protocol error and terminate the client connection */
133 void fatal_protocol_perror( struct thread *thread, const char *err, ... )
134 {
135     va_list args;
136
137     va_start( args, err );
138     fprintf( stderr, "Protocol error:%p: ", thread );
139     vfprintf( stderr, err, args );
140     perror( " " );
141     va_end( args );
142     thread->exit_code = 1;
143     kill_thread( thread, 1 );
144 }
145
146 /* die on a fatal error */
147 void fatal_error( const char *err, ... )
148 {
149     va_list args;
150
151     va_start( args, err );
152     fprintf( stderr, "wineserver: " );
153     vfprintf( stderr, err, args );
154     va_end( args );
155     exit(1);
156 }
157
158 /* die on a fatal error */
159 void fatal_perror( const char *err, ... )
160 {
161     va_list args;
162
163     va_start( args, err );
164     fprintf( stderr, "wineserver: " );
165     vfprintf( stderr, err, args );
166     perror( " " );
167     va_end( args );
168     exit(1);
169 }
170
171 /* call a request handler */
172 static inline void call_req_handler( struct thread *thread, union generic_request *request )
173 {
174     enum request req = request->header.req;
175
176     current = thread;
177     clear_error();
178
179     if (debug_level) trace_request( thread, request );
180
181     if ((unsigned int)request->header.var_offset + request->header.var_size > MAX_REQUEST_LENGTH)
182     {
183         fatal_protocol_error( current, "bad request offset/size %d/%d\n",
184                               request->header.var_offset, request->header.var_size );
185     }
186     else if (req < REQ_NB_REQUESTS)
187     {
188         req_handlers[req]( request );
189         if (current) send_reply( current, request );
190         current = NULL;
191         return;
192     }
193     fatal_protocol_error( current, "bad request %d\n", req );
194 }
195
196 /* send a reply to a thread */
197 void send_reply( struct thread *thread, union generic_request *request )
198 {
199     int ret;
200
201     assert (thread->pass_fd == -1);
202
203     if (debug_level) trace_reply( thread, request );
204
205     request->header.error = thread->error;
206
207     if ((ret = write( thread->reply_fd, request, sizeof(*request) )) != sizeof(*request))
208     {
209         if (ret >= 0)
210             fatal_protocol_error( thread, "partial write %d\n", ret );
211         else if (errno == EPIPE)
212             kill_thread( thread, 0 );  /* normal death */
213         else
214             fatal_protocol_perror( thread, "sendmsg" );
215     }
216 }
217
218 /* read a message from a client that has something to say */
219 void read_request( struct thread *thread )
220 {
221     union generic_request req;
222     int ret;
223
224 #ifdef HAVE_MSGHDR_ACCRIGHTS
225     msghdr.msg_accrightslen = sizeof(int);
226     msghdr.msg_accrights = (void *)&thread->pass_fd;
227 #else  /* HAVE_MSGHDR_ACCRIGHTS */
228     msghdr.msg_control    = &cmsg;
229     msghdr.msg_controllen = sizeof(cmsg);
230     cmsg.fd = -1;
231 #endif  /* HAVE_MSGHDR_ACCRIGHTS */
232
233     assert( thread->pass_fd == -1 );
234
235     myiovec.iov_base = &req;
236     myiovec.iov_len  = sizeof(req);
237
238     ret = recvmsg( thread->obj.fd, &msghdr, 0 );
239 #ifndef HAVE_MSGHDR_ACCRIGHTS
240     thread->pass_fd = cmsg.fd;
241 #endif
242
243     if (ret == sizeof(req))
244     {
245         call_req_handler( thread, &req );
246         thread->pass_fd = -1;
247         return;
248     }
249     if (!ret)  /* closed pipe */
250         kill_thread( thread, 0 );
251     else if (ret > 0)
252         fatal_protocol_error( thread, "partial recvmsg %d\n", ret );
253     else
254         fatal_protocol_perror( thread, "recvmsg" );
255 }
256
257 /* send the wakeup signal to a thread */
258 int send_thread_wakeup( struct thread *thread, int signaled )
259 {
260     int ret = write( thread->wait_fd, &signaled, sizeof(signaled) );
261     if (ret == sizeof(signaled)) return 0;
262     if (ret >= 0)
263         fatal_protocol_error( thread, "partial wakeup write %d\n", ret );
264     else if (errno == EPIPE)
265         kill_thread( thread, 0 );  /* normal death */
266     else
267         fatal_protocol_perror( thread, "write" );
268     return -1;
269 }
270
271 /* send an fd to a client */
272 int send_client_fd( struct thread *thread, int fd, handle_t handle )
273 {
274     int ret;
275
276     if (debug_level)
277         fprintf( stderr, "%08x: *fd* %d = %d\n", (unsigned int)thread, handle, fd );
278
279 #ifdef HAVE_MSGHDR_ACCRIGHTS
280     msghdr.msg_accrightslen = sizeof(fd);
281     msghdr.msg_accrights = (void *)&fd;
282 #else  /* HAVE_MSGHDR_ACCRIGHTS */
283     msghdr.msg_control    = &cmsg;
284     msghdr.msg_controllen = sizeof(cmsg);
285     cmsg.fd = fd;
286 #endif  /* HAVE_MSGHDR_ACCRIGHTS */
287
288     myiovec.iov_base = (void *)&handle;
289     myiovec.iov_len  = sizeof(handle);
290
291     ret = sendmsg( thread->obj.fd, &msghdr, 0 );
292
293     if (ret > 0) return 0;
294     if (errno == EPIPE)
295     {
296         kill_thread( thread, 0 );  /* normal death */
297     }
298     else
299     {
300         fatal_protocol_perror( thread, "sendmsg" );
301     }
302     return -1;
303 }
304
305 static void master_socket_dump( struct object *obj, int verbose )
306 {
307     struct master_socket *sock = (struct master_socket *)obj;
308     assert( obj->ops == &master_socket_ops );
309     fprintf( stderr, "Master socket fd=%d\n", sock->obj.fd );
310 }
311
312 /* handle a socket event */
313 static void master_socket_poll_event( struct object *obj, int event )
314 {
315     struct master_socket *sock = (struct master_socket *)obj;
316     assert( obj->ops == &master_socket_ops );
317
318     assert( sock == master_socket );  /* there is only one master socket */
319
320     if (event & (POLLERR | POLLHUP))
321     {
322         /* this is not supposed to happen */
323         fprintf( stderr, "wineserver: Error on master socket\n" );
324         release_object( obj );
325     }
326     else if (event & POLLIN)
327     {
328         struct sockaddr_un dummy;
329         int len = sizeof(dummy);
330         int client = accept( master_socket->obj.fd, (struct sockaddr *) &dummy, &len );
331         if (client != -1) create_process( client );
332     }
333 }
334
335 /* remove the socket upon exit */
336 static void socket_cleanup(void)
337 {
338     static int do_it_once;
339     if (!do_it_once++) unlink( SOCKETNAME );
340 }
341
342 static void master_socket_destroy( struct object *obj )
343 {
344     socket_cleanup();
345 }
346
347 static void request_socket_dump( struct object *obj, int verbose )
348 {
349     struct request_socket *sock = (struct request_socket *)obj;
350     assert( obj->ops == &request_socket_ops );
351     fprintf( stderr, "Request socket fd=%d thread=%p\n", sock->obj.fd, sock->thread );
352 }
353
354 /* handle a request socket event */
355 static void request_socket_poll_event( struct object *obj, int event )
356 {
357     struct request_socket *sock = (struct request_socket *)obj;
358     assert( obj->ops == &request_socket_ops );
359
360     if (event & (POLLERR | POLLHUP)) kill_thread( sock->thread, 0 );
361     else if (event & POLLIN)
362     {
363         struct thread *thread = sock->thread;
364         union generic_request req;
365         int ret;
366
367         if ((ret = read( sock->obj.fd, &req, sizeof(req) )) == sizeof(req))
368         {
369             call_req_handler( thread, &req );
370             return;
371         }
372         if (!ret)  /* closed pipe */
373             kill_thread( thread, 0 );
374         else if (ret > 0)
375             fatal_protocol_error( thread, "partial read %d\n", ret );
376         else
377             fatal_protocol_perror( thread, "read" );
378     }
379 }
380
381 /* create a request socket and send the fd to the client thread */
382 struct object *create_request_socket( struct thread *thread )
383 {
384     struct request_socket *sock;
385     int fd[2];
386
387     if (pipe( fd )) return NULL;
388     if (!(sock = alloc_object( &request_socket_ops, fd[0] )))
389     {
390         close( fd[1] );
391         return NULL;
392     }
393     sock->thread = thread;
394     send_client_fd( thread, fd[1], 0 );
395     close( fd[1] );
396     fcntl( fd[0], F_SETFL, O_NONBLOCK );
397     set_select_events( &sock->obj, POLLIN );
398     return &sock->obj;
399 }
400
401 /* return the configuration directory ($WINEPREFIX or $HOME/.wine) */
402 const char *get_config_dir(void)
403 {
404     static char *confdir;
405     if (!confdir)
406     {
407         const char *prefix = getenv( "WINEPREFIX" );
408         if (prefix)
409         {
410             int len = strlen(prefix);
411             if (!(confdir = strdup( prefix ))) fatal_error( "out of memory\n" );
412             if (len > 1 && confdir[len-1] == '/') confdir[len-1] = 0;
413         }
414         else
415         {
416             const char *home = getenv( "HOME" );
417             if (!home)
418             {
419                 struct passwd *pwd = getpwuid( getuid() );
420                 if (!pwd) fatal_error( "could not find your home directory\n" );
421                 home = pwd->pw_dir;
422             }
423             if (!(confdir = malloc( strlen(home) + strlen(CONFDIR) + 1 )))
424                 fatal_error( "out of memory\n" );
425             strcpy( confdir, home );
426             strcat( confdir, CONFDIR );
427         }
428         mkdir( confdir, 0755 );  /* just in case */
429     }
430     return confdir;
431 }
432
433 /* create the server directory and chdir to it */
434 static void create_server_dir(void)
435 {
436     char hostname[64];
437     char *serverdir;
438     const char *confdir = get_config_dir();
439     struct stat st;
440
441     if (gethostname( hostname, sizeof(hostname) ) == -1) fatal_perror( "gethostname" );
442
443     if (!(serverdir = malloc( strlen(confdir) + strlen(SERVERDIR) + strlen(hostname) + 1 )))
444         fatal_error( "out of memory\n" );
445
446     strcpy( serverdir, confdir );
447     strcat( serverdir, SERVERDIR );
448     strcat( serverdir, hostname );
449
450     if (chdir( serverdir ) == -1)
451     {
452         if (errno != ENOENT) fatal_perror( "chdir %s", serverdir );
453         if (mkdir( serverdir, 0700 ) == -1) fatal_perror( "mkdir %s", serverdir );
454         if (chdir( serverdir ) == -1) fatal_perror( "chdir %s", serverdir );
455     }
456     if (stat( ".", &st ) == -1) fatal_perror( "stat %s", serverdir );
457     if (!S_ISDIR(st.st_mode)) fatal_error( "%s is not a directory\n", serverdir );
458     if (st.st_uid != getuid()) fatal_error( "%s is not owned by you\n", serverdir );
459     if (st.st_mode & 077) fatal_error( "%s must not be accessible by other users\n", serverdir );
460 }
461
462 /* open the master server socket and start waiting for new clients */
463 void open_master_socket(void)
464 {
465     struct sockaddr_un addr;
466     int fd, slen;
467
468     /* make sure no request is larger than the maximum size */
469     assert( sizeof(union generic_request) == sizeof(struct request_max_size) );
470
471     create_server_dir();
472     if ((fd = socket( AF_UNIX, SOCK_STREAM, 0 )) == -1) fatal_perror( "socket" );
473     addr.sun_family = AF_UNIX;
474     strcpy( addr.sun_path, SOCKETNAME );
475     slen = sizeof(addr) - sizeof(addr.sun_path) + strlen(addr.sun_path) + 1;
476 #ifdef HAVE_SOCKADDR_SUN_LEN
477     addr.sun_len = slen;
478 #endif
479     if (bind( fd, (struct sockaddr *)&addr, slen ) == -1)
480     {
481         if ((errno == EEXIST) || (errno == EADDRINUSE))
482             exit(0);  /* pretend we succeeded to start */
483         else
484             fatal_perror( "bind" );
485     }
486     atexit( socket_cleanup );
487
488     chmod( SOCKETNAME, 0600 );  /* make sure no other user can connect */
489     if (listen( fd, 5 ) == -1) fatal_perror( "listen" );
490
491     if (!(master_socket = alloc_object( &master_socket_ops, fd )))
492         fatal_error( "out of memory\n" );
493     set_select_events( &master_socket->obj, POLLIN );
494
495     /* setup msghdr structure constant fields */
496     msghdr.msg_name    = NULL;
497     msghdr.msg_namelen = 0;
498     msghdr.msg_iov     = &myiovec;
499     msghdr.msg_iovlen  = 1;
500
501     /* go in the background */
502     switch(fork())
503     {
504     case -1:
505         fatal_perror( "fork" );
506     case 0:
507         setsid();
508         break;
509     default:
510         _exit(0);  /* do not call atexit functions */
511     }
512 }
513
514 /* close the master socket and stop waiting for new clients */
515 void close_master_socket(void)
516 {
517     /* if a new client is waiting, we keep on running */
518     if (!check_select_events( master_socket->obj.fd, POLLIN ))
519         release_object( master_socket );
520 }
521
522 /* lock/unlock the master socket to stop accepting new clients */
523 void lock_master_socket( int locked )
524 {
525     set_select_events( &master_socket->obj, locked ? 0 : POLLIN );
526 }