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