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