Added handle_t type to server interface so that we can make handles
[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 /* die on a fatal error */
133 void fatal_error( const char *err, ... )
134 {
135     va_list args;
136
137     va_start( args, err );
138     fprintf( stderr, "wineserver: " );
139     vfprintf( stderr, err, args );
140     va_end( args );
141     exit(1);
142 }
143
144 /* die on a fatal error */
145 void fatal_perror( const char *err, ... )
146 {
147     va_list args;
148
149     va_start( args, err );
150     fprintf( stderr, "wineserver: " );
151     vfprintf( stderr, err, args );
152     perror( " " );
153     va_end( args );
154     exit(1);
155 }
156
157 /* call a request handler */
158 static inline void call_req_handler( struct thread *thread )
159 {
160     enum request req;
161     current = thread;
162     clear_error();
163
164     req = ((struct request_header *)current->buffer)->req;
165
166     if (debug_level) trace_request( req );
167
168     if (req < REQ_NB_REQUESTS)
169     {
170         req_handlers[req]( current->buffer );
171         if (current && !current->wait) send_reply( current );
172         current = NULL;
173         return;
174     }
175     fatal_protocol_error( current, "bad request %d\n", req );
176 }
177
178 /* send a reply to a thread */
179 void send_reply( struct thread *thread )
180 {
181     assert( !thread->wait );
182     if (debug_level) trace_reply( thread );
183     if (!write_request( thread )) set_select_events( &thread->obj, POLLOUT );
184 }
185
186 /* read a message from a client that has something to say */
187 void read_request( struct thread *thread )
188 {
189     int ret;
190     char dummy[1];
191
192 #ifdef HAVE_MSGHDR_ACCRIGHTS
193     msghdr.msg_accrightslen = sizeof(int);
194     msghdr.msg_accrights = (void *)&thread->pass_fd;
195 #else  /* HAVE_MSGHDR_ACCRIGHTS */
196     msghdr.msg_control    = &cmsg;
197     msghdr.msg_controllen = sizeof(cmsg);
198     cmsg.fd = -1;
199 #endif  /* HAVE_MSGHDR_ACCRIGHTS */
200
201     assert( thread->pass_fd == -1 );
202
203     myiovec.iov_base = dummy;
204     myiovec.iov_len  = 1;
205
206     ret = recvmsg( thread->obj.fd, &msghdr, 0 );
207 #ifndef HAVE_MSGHDR_ACCRIGHTS
208     thread->pass_fd = cmsg.fd;
209 #endif
210
211     if (ret > 0)
212     {
213         call_req_handler( thread );
214         thread->pass_fd = -1;
215         return;
216     }
217     if (!ret)  /* closed pipe */
218     {
219         kill_thread( thread, 0 );
220         return;
221     }
222     perror("recvmsg");
223     thread->exit_code = 1;
224     kill_thread( thread, 1 );
225 }
226
227 /* send a message to a client that is ready to receive something */
228 int write_request( struct thread *thread )
229 {
230     int ret;
231     struct request_header *header = thread->buffer;
232
233     header->error = thread->error;
234
235     assert (thread->pass_fd == -1);
236
237     ret = write( thread->reply_fd, header, 1 );
238     if (ret > 0)
239     {
240         set_select_events( &thread->obj, POLLIN );
241         return 1;
242     }
243     if (errno == EWOULDBLOCK) return 0;  /* not a fatal error */
244     if (errno == EPIPE)
245     {
246         kill_thread( thread, 0 );  /* normal death */
247     }
248     else
249     {
250         perror("sendmsg");
251         thread->exit_code = 1;
252         kill_thread( thread, 1 );
253     }
254     return -1;
255 }
256
257 /* send an fd to a client */
258 int send_client_fd( struct thread *thread, int fd, handle_t handle )
259 {
260     int ret;
261
262     if (debug_level)
263         fprintf( stderr, "%08x: *fd* %d = %d\n", (unsigned int)thread, handle, fd );
264
265 #ifdef HAVE_MSGHDR_ACCRIGHTS
266     msghdr.msg_accrightslen = sizeof(fd);
267     msghdr.msg_accrights = (void *)&fd;
268 #else  /* HAVE_MSGHDR_ACCRIGHTS */
269     msghdr.msg_control    = &cmsg;
270     msghdr.msg_controllen = sizeof(cmsg);
271     cmsg.fd = fd;
272 #endif  /* HAVE_MSGHDR_ACCRIGHTS */
273
274     myiovec.iov_base = (void *)&handle;
275     myiovec.iov_len  = sizeof(handle);
276
277     ret = sendmsg( thread->obj.fd, &msghdr, 0 );
278
279     if (ret > 0) return 0;
280     if (errno == EPIPE)
281     {
282         kill_thread( thread, 0 );  /* normal death */
283     }
284     else
285     {
286         perror("sendmsg");
287         thread->exit_code = 1;
288         kill_thread( thread, 1 );
289     }
290     return -1;
291 }
292
293 static void master_socket_dump( struct object *obj, int verbose )
294 {
295     struct master_socket *sock = (struct master_socket *)obj;
296     assert( obj->ops == &master_socket_ops );
297     fprintf( stderr, "Master socket fd=%d\n", sock->obj.fd );
298 }
299
300 /* handle a socket event */
301 static void master_socket_poll_event( struct object *obj, int event )
302 {
303     struct master_socket *sock = (struct master_socket *)obj;
304     assert( obj->ops == &master_socket_ops );
305
306     assert( sock == master_socket );  /* there is only one master socket */
307
308     if (event & (POLLERR | POLLHUP))
309     {
310         /* this is not supposed to happen */
311         fprintf( stderr, "wineserver: Error on master socket\n" );
312         release_object( obj );
313     }
314     else if (event & POLLIN)
315     {
316         struct sockaddr_un dummy;
317         int len = sizeof(dummy);
318         int client = accept( master_socket->obj.fd, (struct sockaddr *) &dummy, &len );
319         if (client != -1) create_process( client );
320     }
321 }
322
323 /* remove the socket upon exit */
324 static void socket_cleanup(void)
325 {
326     static int do_it_once;
327     if (!do_it_once++) unlink( SOCKETNAME );
328 }
329
330 static void master_socket_destroy( struct object *obj )
331 {
332     socket_cleanup();
333 }
334
335 static void request_socket_dump( struct object *obj, int verbose )
336 {
337     struct request_socket *sock = (struct request_socket *)obj;
338     assert( obj->ops == &request_socket_ops );
339     fprintf( stderr, "Request socket fd=%d thread=%p\n", sock->obj.fd, sock->thread );
340 }
341
342 /* handle a request socket event */
343 static void request_socket_poll_event( struct object *obj, int event )
344 {
345     struct request_socket *sock = (struct request_socket *)obj;
346     assert( obj->ops == &request_socket_ops );
347
348     if (event & (POLLERR | POLLHUP)) kill_thread( sock->thread, 0 );
349     else if (event & POLLIN)
350     {
351         struct thread *thread = sock->thread;
352         int ret;
353         char dummy[1];
354
355         ret = read( sock->obj.fd, &dummy, 1 );
356         if (ret > 0)
357         {
358             call_req_handler( thread );
359             return;
360         }
361         if (!ret)  /* closed pipe */
362         {
363             kill_thread( thread, 0 );
364             return;
365         }
366         perror("read");
367         thread->exit_code = 1;
368         kill_thread( thread, 1 );
369     }
370 }
371
372 /* create a request socket and send the fd to the client thread */
373 struct object *create_request_socket( struct thread *thread )
374 {
375     struct request_socket *sock;
376     int fd[2];
377
378     if (pipe( fd )) return NULL;
379     if (!(sock = alloc_object( &request_socket_ops, fd[0] )))
380     {
381         close( fd[1] );
382         return NULL;
383     }
384     sock->thread = thread;
385     send_client_fd( thread, fd[1], 0 );
386     close( fd[1] );
387     set_select_events( &sock->obj, POLLIN );
388     return &sock->obj;
389 }
390
391 /* return the configuration directory ($WINEPREFIX or $HOME/.wine) */
392 const char *get_config_dir(void)
393 {
394     static char *confdir;
395     if (!confdir)
396     {
397         const char *prefix = getenv( "WINEPREFIX" );
398         if (prefix)
399         {
400             int len = strlen(prefix);
401             if (!(confdir = strdup( prefix ))) fatal_error( "out of memory\n" );
402             if (len > 1 && confdir[len-1] == '/') confdir[len-1] = 0;
403         }
404         else
405         {
406             const char *home = getenv( "HOME" );
407             if (!home)
408             {
409                 struct passwd *pwd = getpwuid( getuid() );
410                 if (!pwd) fatal_error( "could not find your home directory\n" );
411                 home = pwd->pw_dir;
412             }
413             if (!(confdir = malloc( strlen(home) + strlen(CONFDIR) + 1 )))
414                 fatal_error( "out of memory\n" );
415             strcpy( confdir, home );
416             strcat( confdir, CONFDIR );
417         }
418         mkdir( confdir, 0755 );  /* just in case */
419     }
420     return confdir;
421 }
422
423 /* create the server directory and chdir to it */
424 static void create_server_dir(void)
425 {
426     char hostname[64];
427     char *serverdir;
428     const char *confdir = get_config_dir();
429     struct stat st;
430
431     if (gethostname( hostname, sizeof(hostname) ) == -1) fatal_perror( "gethostname" );
432
433     if (!(serverdir = malloc( strlen(confdir) + strlen(SERVERDIR) + strlen(hostname) + 1 )))
434         fatal_error( "out of memory\n" );
435
436     strcpy( serverdir, confdir );
437     strcat( serverdir, SERVERDIR );
438     strcat( serverdir, hostname );
439
440     if (chdir( serverdir ) == -1)
441     {
442         if (errno != ENOENT) fatal_perror( "chdir %s", serverdir );
443         if (mkdir( serverdir, 0700 ) == -1) fatal_perror( "mkdir %s", serverdir );
444         if (chdir( serverdir ) == -1) fatal_perror( "chdir %s", serverdir );
445     }
446     if (stat( ".", &st ) == -1) fatal_perror( "stat %s", serverdir );
447     if (!S_ISDIR(st.st_mode)) fatal_error( "%s is not a directory\n", serverdir );
448     if (st.st_uid != getuid()) fatal_error( "%s is not owned by you\n", serverdir );
449     if (st.st_mode & 077) fatal_error( "%s must not be accessible by other users\n", serverdir );
450 }
451
452 /* open the master server socket and start waiting for new clients */
453 void open_master_socket(void)
454 {
455     struct sockaddr_un addr;
456     int fd, slen;
457
458     /* make sure no request is larger than the maximum size */
459     assert( sizeof(union generic_request) == sizeof(struct request_max_size) );
460
461     create_server_dir();
462     if ((fd = socket( AF_UNIX, SOCK_STREAM, 0 )) == -1) fatal_perror( "socket" );
463     addr.sun_family = AF_UNIX;
464     strcpy( addr.sun_path, SOCKETNAME );
465     slen = sizeof(addr) - sizeof(addr.sun_path) + strlen(addr.sun_path) + 1;
466 #ifdef HAVE_SOCKADDR_SUN_LEN
467     addr.sun_len = slen;
468 #endif
469     if (bind( fd, (struct sockaddr *)&addr, slen ) == -1)
470     {
471         if ((errno == EEXIST) || (errno == EADDRINUSE))
472             exit(0);  /* pretend we succeeded to start */
473         else
474             fatal_perror( "bind" );
475     }
476     atexit( socket_cleanup );
477
478     chmod( SOCKETNAME, 0600 );  /* make sure no other user can connect */
479     if (listen( fd, 5 ) == -1) fatal_perror( "listen" );
480
481     if (!(master_socket = alloc_object( &master_socket_ops, fd )))
482         fatal_error( "out of memory\n" );
483     set_select_events( &master_socket->obj, POLLIN );
484
485     /* setup msghdr structure constant fields */
486     msghdr.msg_name    = NULL;
487     msghdr.msg_namelen = 0;
488     msghdr.msg_iov     = &myiovec;
489     msghdr.msg_iovlen  = 1;
490
491     /* go in the background */
492     switch(fork())
493     {
494     case -1:
495         fatal_perror( "fork" );
496     case 0:
497         setsid();
498         break;
499     default:
500         _exit(0);  /* do not call atexit functions */
501     }
502 }
503
504 /* close the master socket and stop waiting for new clients */
505 void close_master_socket(void)
506 {
507     /* if a new client is waiting, we keep on running */
508     if (!check_select_events( master_socket->obj.fd, POLLIN ))
509         release_object( master_socket );
510 }
511
512 /* lock/unlock the master socket to stop accepting new clients */
513 void lock_master_socket( int locked )
514 {
515     set_select_events( &master_socket->obj, locked ? 0 : POLLIN );
516 }