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