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