server: Store the opening options in the file descriptor instead of in the individual...
[wine] / server / request.c
1 /*
2  * Server-side request handling
3  *
4  * Copyright (C) 1998 Alexandre Julliard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #include "config.h"
22 #include "wine/port.h"
23
24 #include <assert.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #ifdef HAVE_PWD_H
28 #include <pwd.h>
29 #endif
30 #include <signal.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <stdarg.h>
34 #include <string.h>
35 #include <sys/stat.h>
36 #include <sys/time.h>
37 #include <sys/types.h>
38 #ifdef HAVE_SYS_SOCKET_H
39 # include <sys/socket.h>
40 #endif
41 #ifdef HAVE_SYS_WAIT_H
42 # include <sys/wait.h>
43 #endif
44 #ifdef HAVE_SYS_UIO_H
45 #include <sys/uio.h>
46 #endif
47 #ifdef HAVE_SYS_UN_H
48 #include <sys/un.h>
49 #endif
50 #include <unistd.h>
51 #ifdef HAVE_POLL_H
52 #include <poll.h>
53 #endif
54
55 #include "ntstatus.h"
56 #define WIN32_NO_STATUS
57 #include "windef.h"
58 #include "winbase.h"
59 #include "wincon.h"
60 #include "winternl.h"
61 #include "wine/library.h"
62
63 #include "file.h"
64 #include "process.h"
65 #define WANT_REQUEST_HANDLERS
66 #include "request.h"
67
68 /* Some versions of glibc don't define this */
69 #ifndef SCM_RIGHTS
70 #define SCM_RIGHTS 1
71 #endif
72
73 /* path names for server master Unix socket */
74 static const char * const server_socket_name = "socket";   /* name of the socket file */
75 static const char * const server_lock_name = "lock";       /* name of the server lock file */
76
77 struct master_socket
78 {
79     struct object        obj;        /* object header */
80     struct fd           *fd;         /* file descriptor of the master socket */
81     struct timeout_user *timeout;    /* timeout on last process exit */
82 };
83
84 static void master_socket_dump( struct object *obj, int verbose );
85 static void master_socket_destroy( struct object *obj );
86 static void master_socket_poll_event( struct fd *fd, int event );
87
88 static const struct object_ops master_socket_ops =
89 {
90     sizeof(struct master_socket),  /* size */
91     master_socket_dump,            /* dump */
92     no_add_queue,                  /* add_queue */
93     NULL,                          /* remove_queue */
94     NULL,                          /* signaled */
95     NULL,                          /* satisfied */
96     no_signal,                     /* signal */
97     no_get_fd,                     /* get_fd */
98     no_map_access,                 /* map_access */
99     no_lookup_name,                /* lookup_name */
100     no_open_file,                  /* open_file */
101     no_close_handle,               /* close_handle */
102     master_socket_destroy          /* destroy */
103 };
104
105 static const struct fd_ops master_socket_fd_ops =
106 {
107     NULL,                          /* get_poll_events */
108     master_socket_poll_event,      /* poll_event */
109     no_flush,                      /* flush */
110     no_get_file_info,              /* get_file_info */
111     no_queue_async,                /* queue_async */
112     NULL,                          /* reselect_async */
113     no_cancel_async                /* cancel_async */
114 };
115
116
117 struct thread *current = NULL;  /* thread handling the current request */
118 unsigned int global_error = 0;  /* global error code for when no thread is current */
119 struct timeval server_start_time = { 0, 0 };  /* server startup time */
120
121 static struct master_socket *master_socket;  /* the master socket object */
122 static int force_shutdown;
123
124 /* socket communication static structures */
125 static struct iovec myiovec;
126 static struct msghdr msghdr;
127 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
128 struct cmsg_fd
129 {
130     struct
131     {
132         size_t len;   /* size of structure */
133         int    level; /* SOL_SOCKET */
134         int    type;  /* SCM_RIGHTS */
135     } header;
136     int fd;           /* fd to pass */
137 };
138 static struct cmsg_fd cmsg = { { sizeof(cmsg.header) + sizeof(cmsg.fd), SOL_SOCKET, SCM_RIGHTS }, -1 };
139 #endif  /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
140
141 /* complain about a protocol error and terminate the client connection */
142 void fatal_protocol_error( struct thread *thread, const char *err, ... )
143 {
144     va_list args;
145
146     va_start( args, err );
147     fprintf( stderr, "Protocol error:%04x: ", thread->id );
148     vfprintf( stderr, err, args );
149     va_end( args );
150     thread->exit_code = 1;
151     kill_thread( thread, 1 );
152 }
153
154 /* complain about a protocol error and terminate the client connection */
155 void fatal_protocol_perror( struct thread *thread, const char *err, ... )
156 {
157     va_list args;
158
159     va_start( args, err );
160     fprintf( stderr, "Protocol error:%04x: ", thread->id );
161     vfprintf( stderr, err, args );
162     perror( " " );
163     va_end( args );
164     thread->exit_code = 1;
165     kill_thread( thread, 1 );
166 }
167
168 /* die on a fatal error */
169 void fatal_error( const char *err, ... )
170 {
171     va_list args;
172
173     va_start( args, err );
174     fprintf( stderr, "wineserver: " );
175     vfprintf( stderr, err, args );
176     va_end( args );
177     exit(1);
178 }
179
180 /* die on a fatal error */
181 void fatal_perror( const char *err, ... )
182 {
183     va_list args;
184
185     va_start( args, err );
186     fprintf( stderr, "wineserver: " );
187     vfprintf( stderr, err, args );
188     perror( " " );
189     va_end( args );
190     exit(1);
191 }
192
193 /* allocate the reply data */
194 void *set_reply_data_size( data_size_t size )
195 {
196     assert( size <= get_reply_max_size() );
197     if (size && !(current->reply_data = mem_alloc( size ))) size = 0;
198     current->reply_size = size;
199     return current->reply_data;
200 }
201
202 /* write the remaining part of the reply */
203 void write_reply( struct thread *thread )
204 {
205     int ret;
206
207     if ((ret = write( get_unix_fd( thread->reply_fd ),
208                       (char *)thread->reply_data + thread->reply_size - thread->reply_towrite,
209                       thread->reply_towrite )) >= 0)
210     {
211         if (!(thread->reply_towrite -= ret))
212         {
213             free( thread->reply_data );
214             thread->reply_data = NULL;
215             /* sent everything, can go back to waiting for requests */
216             set_fd_events( thread->request_fd, POLLIN );
217             set_fd_events( thread->reply_fd, 0 );
218         }
219         return;
220     }
221     if (errno == EPIPE)
222         kill_thread( thread, 0 );  /* normal death */
223     else if (errno != EWOULDBLOCK && errno != EAGAIN)
224         fatal_protocol_perror( thread, "reply write" );
225 }
226
227 /* send a reply to the current thread */
228 static void send_reply( union generic_reply *reply )
229 {
230     int ret;
231
232     if (!current->reply_size)
233     {
234         if ((ret = write( get_unix_fd( current->reply_fd ),
235                           reply, sizeof(*reply) )) != sizeof(*reply)) goto error;
236     }
237     else
238     {
239         struct iovec vec[2];
240
241         vec[0].iov_base = (void *)reply;
242         vec[0].iov_len  = sizeof(*reply);
243         vec[1].iov_base = current->reply_data;
244         vec[1].iov_len  = current->reply_size;
245
246         if ((ret = writev( get_unix_fd( current->reply_fd ), vec, 2 )) < sizeof(*reply)) goto error;
247
248         if ((current->reply_towrite = current->reply_size - (ret - sizeof(*reply))))
249         {
250             /* couldn't write it all, wait for POLLOUT */
251             set_fd_events( current->reply_fd, POLLOUT );
252             set_fd_events( current->request_fd, 0 );
253             return;
254         }
255     }
256     free( current->reply_data );
257     current->reply_data = NULL;
258     return;
259
260  error:
261     if (ret >= 0)
262         fatal_protocol_error( current, "partial write %d\n", ret );
263     else if (errno == EPIPE)
264         kill_thread( current, 0 );  /* normal death */
265     else
266         fatal_protocol_perror( current, "reply write" );
267 }
268
269 /* call a request handler */
270 static void call_req_handler( struct thread *thread )
271 {
272     union generic_reply reply;
273     enum request req = thread->req.request_header.req;
274
275     current = thread;
276     current->reply_size = 0;
277     clear_error();
278     memset( &reply, 0, sizeof(reply) );
279
280     if (debug_level) trace_request();
281
282     if (req < REQ_NB_REQUESTS)
283         req_handlers[req]( &current->req, &reply );
284     else
285         set_error( STATUS_NOT_IMPLEMENTED );
286
287     if (current)
288     {
289         if (current->reply_fd)
290         {
291             reply.reply_header.error = current->error;
292             reply.reply_header.reply_size = current->reply_size;
293             if (debug_level) trace_reply( req, &reply );
294             send_reply( &reply );
295         }
296         else
297         {
298             current->exit_code = 1;
299             kill_thread( current, 1 );  /* no way to continue without reply fd */
300         }
301     }
302     current = NULL;
303 }
304
305 /* read a request from a thread */
306 void read_request( struct thread *thread )
307 {
308     int ret;
309
310     if (!thread->req_toread)  /* no pending request */
311     {
312         if ((ret = read( get_unix_fd( thread->request_fd ), &thread->req,
313                          sizeof(thread->req) )) != sizeof(thread->req)) goto error;
314         if (!(thread->req_toread = thread->req.request_header.request_size))
315         {
316             /* no data, handle request at once */
317             call_req_handler( thread );
318             return;
319         }
320         if (!(thread->req_data = malloc( thread->req_toread )))
321         {
322             fatal_protocol_error( thread, "no memory for %u bytes request %d\n",
323                                   thread->req_toread, thread->req.request_header.req );
324             return;
325         }
326     }
327
328     /* read the variable sized data */
329     for (;;)
330     {
331         ret = read( get_unix_fd( thread->request_fd ),
332                     (char *)thread->req_data + thread->req.request_header.request_size
333                       - thread->req_toread,
334                     thread->req_toread );
335         if (ret <= 0) break;
336         if (!(thread->req_toread -= ret))
337         {
338             call_req_handler( thread );
339             free( thread->req_data );
340             thread->req_data = NULL;
341             return;
342         }
343     }
344
345 error:
346     if (!ret)  /* closed pipe */
347         kill_thread( thread, 0 );
348     else if (ret > 0)
349         fatal_protocol_error( thread, "partial read %d\n", ret );
350     else if (errno != EWOULDBLOCK && errno != EAGAIN)
351         fatal_protocol_perror( thread, "read" );
352 }
353
354 /* receive a file descriptor on the process socket */
355 int receive_fd( struct process *process )
356 {
357     struct send_fd data;
358     int fd, ret;
359
360 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
361     msghdr.msg_accrightslen = sizeof(int);
362     msghdr.msg_accrights = (void *)&fd;
363 #else  /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
364     msghdr.msg_control    = &cmsg;
365     msghdr.msg_controllen = sizeof(cmsg.header) + sizeof(fd);
366     cmsg.fd = -1;
367 #endif  /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
368
369     myiovec.iov_base = (void *)&data;
370     myiovec.iov_len  = sizeof(data);
371
372     ret = recvmsg( get_unix_fd( process->msg_fd ), &msghdr, 0 );
373 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
374     fd = cmsg.fd;
375 #endif
376
377     if (ret == sizeof(data))
378     {
379         struct thread *thread;
380
381         if (data.tid) thread = get_thread_from_id( data.tid );
382         else thread = (struct thread *)grab_object( get_process_first_thread( process ));
383
384         if (!thread || thread->process != process || thread->state == TERMINATED)
385         {
386             if (debug_level)
387                 fprintf( stderr, "%04x: *fd* %d <- %d bad thread id\n",
388                          data.tid, data.fd, fd );
389             close( fd );
390         }
391         else
392         {
393             if (debug_level)
394                 fprintf( stderr, "%04x: *fd* %d <- %d\n",
395                          thread->id, data.fd, fd );
396             thread_add_inflight_fd( thread, data.fd, fd );
397         }
398         if (thread) release_object( thread );
399         return 0;
400     }
401
402     if (!ret)
403     {
404         kill_process( process, 0 );
405     }
406     else if (ret > 0)
407     {
408         fprintf( stderr, "Protocol error: process %04x: partial recvmsg %d for fd\n",
409                  process->id, ret );
410         kill_process( process, 1 );
411     }
412     else
413     {
414         if (errno != EWOULDBLOCK && errno != EAGAIN)
415         {
416             fprintf( stderr, "Protocol error: process %04x: ", process->id );
417             perror( "recvmsg" );
418             kill_process( process, 1 );
419         }
420     }
421     return -1;
422 }
423
424 /* send an fd to a client */
425 int send_client_fd( struct process *process, int fd, obj_handle_t handle )
426 {
427     int ret;
428
429     if (debug_level)
430         fprintf( stderr, "%04x: *fd* %p -> %d\n",
431                  current ? current->id : process->id, handle, fd );
432
433 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
434     msghdr.msg_accrightslen = sizeof(fd);
435     msghdr.msg_accrights = (void *)&fd;
436 #else  /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
437     msghdr.msg_control    = &cmsg;
438     msghdr.msg_controllen = sizeof(cmsg.header) + sizeof(fd);
439     cmsg.fd = fd;
440 #endif  /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
441
442     myiovec.iov_base = (void *)&handle;
443     myiovec.iov_len  = sizeof(handle);
444
445     ret = sendmsg( get_unix_fd( process->msg_fd ), &msghdr, 0 );
446
447     if (ret == sizeof(handle)) return 0;
448
449     if (ret >= 0)
450     {
451         fprintf( stderr, "Protocol error: process %04x: partial sendmsg %d\n", process->id, ret );
452         kill_process( process, 1 );
453     }
454     else if (errno == EPIPE)
455     {
456         kill_process( process, 0 );
457     }
458     else
459     {
460         fprintf( stderr, "Protocol error: process %04x: ", process->id );
461         perror( "sendmsg" );
462         kill_process( process, 1 );
463     }
464     return -1;
465 }
466
467 /* get current tick count to return to client */
468 unsigned int get_tick_count(void)
469 {
470     return ((current_time.tv_sec - server_start_time.tv_sec) * 1000) +
471            ((current_time.tv_usec - server_start_time.tv_usec) / 1000);
472 }
473
474 static void master_socket_dump( struct object *obj, int verbose )
475 {
476     struct master_socket *sock = (struct master_socket *)obj;
477     assert( obj->ops == &master_socket_ops );
478     fprintf( stderr, "Master socket fd=%p\n", sock->fd );
479 }
480
481 static void master_socket_destroy( struct object *obj )
482 {
483     struct master_socket *sock = (struct master_socket *)obj;
484     assert( obj->ops == &master_socket_ops );
485     release_object( sock->fd );
486 }
487
488 /* handle a socket event */
489 static void master_socket_poll_event( struct fd *fd, int event )
490 {
491     struct master_socket *sock = get_fd_user( fd );
492     assert( master_socket->obj.ops == &master_socket_ops );
493
494     assert( sock == master_socket );  /* there is only one master socket */
495
496     if (event & (POLLERR | POLLHUP))
497     {
498         /* this is not supposed to happen */
499         fprintf( stderr, "wineserver: Error on master socket\n" );
500         set_fd_events( sock->fd, -1 );
501     }
502     else if (event & POLLIN)
503     {
504         struct sockaddr_un dummy;
505         unsigned int len = sizeof(dummy);
506         int client = accept( get_unix_fd( master_socket->fd ), (struct sockaddr *) &dummy, &len );
507         if (client == -1) return;
508         if (sock->timeout)
509         {
510             remove_timeout_user( sock->timeout );
511             sock->timeout = NULL;
512         }
513         fcntl( client, F_SETFL, O_NONBLOCK );
514         create_process( client, NULL, 0 );
515     }
516 }
517
518 /* remove the socket upon exit */
519 static void socket_cleanup(void)
520 {
521     static int do_it_once;
522     if (!do_it_once++) unlink( server_socket_name );
523 }
524
525 /* create a directory and check its permissions */
526 static void create_dir( const char *name, struct stat *st )
527 {
528     if (lstat( name, st ) == -1)
529     {
530         if (errno != ENOENT) fatal_perror( "lstat %s", name );
531         if (mkdir( name, 0700 ) == -1 && errno != EEXIST) fatal_perror( "mkdir %s", name );
532         if (lstat( name, st ) == -1) fatal_perror( "lstat %s", name );
533     }
534     if (!S_ISDIR(st->st_mode)) fatal_error( "%s is not a directory\n", name );
535     if (st->st_uid != getuid()) fatal_error( "%s is not owned by you\n", name );
536     if (st->st_mode & 077) fatal_error( "%s must not be accessible by other users\n", name );
537 }
538
539 /* create the server directory and chdir to it */
540 static void create_server_dir( const char *dir )
541 {
542     char *p, *server_dir;
543     struct stat st, st2;
544
545     if (!(server_dir = strdup( dir ))) fatal_error( "out of memory\n" );
546
547     /* first create the base directory if needed */
548
549     p = strrchr( server_dir, '/' );
550     *p = 0;
551     create_dir( server_dir, &st );
552
553     /* now create the server directory */
554
555     *p = '/';
556     create_dir( server_dir, &st );
557
558     if (chdir( server_dir ) == -1) fatal_perror( "chdir %s", server_dir );
559     if (stat( ".", &st2 ) == -1) fatal_perror( "stat %s", server_dir );
560     if (st.st_dev != st2.st_dev || st.st_ino != st2.st_ino)
561         fatal_error( "chdir did not end up in %s\n", server_dir );
562
563     free( server_dir );
564 }
565
566 /* create the lock file and return its file descriptor */
567 static int create_server_lock(void)
568 {
569     struct stat st;
570     int fd;
571
572     if (lstat( server_lock_name, &st ) == -1)
573     {
574         if (errno != ENOENT)
575             fatal_perror( "lstat %s/%s", wine_get_server_dir(), server_lock_name );
576     }
577     else
578     {
579         if (!S_ISREG(st.st_mode))
580             fatal_error( "%s/%s is not a regular file\n", wine_get_server_dir(), server_lock_name );
581     }
582
583     if ((fd = open( server_lock_name, O_CREAT|O_TRUNC|O_WRONLY, 0600 )) == -1)
584         fatal_perror( "error creating %s/%s", wine_get_server_dir(), server_lock_name );
585     return fd;
586 }
587
588 /* wait for the server lock */
589 int wait_for_lock(void)
590 {
591     const char *server_dir = wine_get_server_dir();
592     int fd, r;
593     struct flock fl;
594
595     if (!server_dir) return 0;  /* no server dir, so no lock to wait on */
596
597     create_server_dir( server_dir );
598     fd = create_server_lock();
599
600     fl.l_type   = F_WRLCK;
601     fl.l_whence = SEEK_SET;
602     fl.l_start  = 0;
603     fl.l_len    = 1;
604     r = fcntl( fd, F_SETLKW, &fl );
605     close(fd);
606
607     return r;
608 }
609
610 /* kill the wine server holding the lock */
611 int kill_lock_owner( int sig )
612 {
613     const char *server_dir = wine_get_server_dir();
614     int fd, i, ret = 0;
615     pid_t pid = 0;
616     struct flock fl;
617
618     if (!server_dir) return 0;  /* no server dir, nothing to do */
619
620     create_server_dir( server_dir );
621     fd = create_server_lock();
622
623     for (i = 0; i < 10; i++)
624     {
625         fl.l_type   = F_WRLCK;
626         fl.l_whence = SEEK_SET;
627         fl.l_start  = 0;
628         fl.l_len    = 1;
629         if (fcntl( fd, F_GETLK, &fl ) == -1) goto done;
630         if (fl.l_type != F_WRLCK) goto done;  /* the file is not locked */
631         if (!pid)  /* first time around */
632         {
633             if (!(pid = fl.l_pid)) goto done;  /* shouldn't happen */
634             if (sig == -1)
635             {
636                 if (kill( pid, SIGINT ) == -1) goto done;
637                 kill( pid, SIGCONT );
638                 ret = 1;
639             }
640             else  /* just send the specified signal and return */
641             {
642                 ret = (kill( pid, sig ) != -1);
643                 goto done;
644             }
645         }
646         else if (fl.l_pid != pid) goto done;  /* no longer the same process */
647         sleep( 1 );
648     }
649     /* waited long enough, now kill it */
650     kill( pid, SIGKILL );
651
652  done:
653     close( fd );
654     return ret;
655 }
656
657 /* acquire the main server lock */
658 static void acquire_lock(void)
659 {
660     struct sockaddr_un addr;
661     struct stat st;
662     struct flock fl;
663     int fd, slen, got_lock = 0;
664
665     fd = create_server_lock();
666
667     fl.l_type   = F_WRLCK;
668     fl.l_whence = SEEK_SET;
669     fl.l_start  = 0;
670     fl.l_len    = 1;
671     if (fcntl( fd, F_SETLK, &fl ) != -1)
672     {
673         /* check for crashed server */
674         if (stat( server_socket_name, &st ) != -1 &&   /* there is a leftover socket */
675             stat( "core", &st ) != -1 && st.st_size)   /* and there is a non-empty core file */
676         {
677             fprintf( stderr,
678                      "Warning: a previous instance of the wine server seems to have crashed.\n"
679                      "Please run 'gdb %s %s/core',\n"
680                      "type 'backtrace' at the gdb prompt and report the results. Thanks.\n\n",
681                      server_argv0, wine_get_server_dir() );
682         }
683         unlink( server_socket_name ); /* we got the lock, we can safely remove the socket */
684         got_lock = 1;
685         /* in that case we reuse fd without closing it, this ensures
686          * that we hold the lock until the process exits */
687     }
688     else
689     {
690         switch(errno)
691         {
692         case ENOLCK:
693             break;
694         case EACCES:
695             /* check whether locks work at all on this file system */
696             if (fcntl( fd, F_GETLK, &fl ) == -1) break;
697             /* fall through */
698         case EAGAIN:
699             exit(2); /* we didn't get the lock, exit with special status */
700         default:
701             fatal_perror( "fcntl %s/%s", wine_get_server_dir(), server_lock_name );
702         }
703         /* it seems we can't use locks on this fs, so we will use the socket existence as lock */
704         close( fd );
705     }
706
707     if ((fd = socket( AF_UNIX, SOCK_STREAM, 0 )) == -1) fatal_perror( "socket" );
708     addr.sun_family = AF_UNIX;
709     strcpy( addr.sun_path, server_socket_name );
710     slen = sizeof(addr) - sizeof(addr.sun_path) + strlen(addr.sun_path) + 1;
711 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
712     addr.sun_len = slen;
713 #endif
714     if (bind( fd, (struct sockaddr *)&addr, slen ) == -1)
715     {
716         if ((errno == EEXIST) || (errno == EADDRINUSE))
717         {
718             if (got_lock)
719                 fatal_error( "couldn't bind to the socket even though we hold the lock\n" );
720             exit(2); /* we didn't get the lock, exit with special status */
721         }
722         fatal_perror( "bind" );
723     }
724     atexit( socket_cleanup );
725     chmod( server_socket_name, 0600 );  /* make sure no other user can connect */
726     if (listen( fd, 5 ) == -1) fatal_perror( "listen" );
727
728     if (!(master_socket = alloc_object( &master_socket_ops )) ||
729         !(master_socket->fd = create_anonymous_fd( &master_socket_fd_ops, fd, &master_socket->obj, 0 )))
730         fatal_error( "out of memory\n" );
731     master_socket->timeout = NULL;
732     set_fd_events( master_socket->fd, POLLIN );
733     make_object_static( &master_socket->obj );
734 }
735
736 /* open the master server socket and start waiting for new clients */
737 void open_master_socket(void)
738 {
739     const char *server_dir = wine_get_server_dir();
740     int fd, pid, status, sync_pipe[2];
741     char dummy;
742
743     /* make sure no request is larger than the maximum size */
744     assert( sizeof(union generic_request) == sizeof(struct request_max_size) );
745     assert( sizeof(union generic_reply) == sizeof(struct request_max_size) );
746
747     if (!server_dir) fatal_error( "directory %s cannot be accessed\n", wine_get_config_dir() );
748     create_server_dir( server_dir );
749
750     if (!foreground)
751     {
752         if (pipe( sync_pipe ) == -1) fatal_perror( "pipe" );
753         pid = fork();
754         switch( pid )
755         {
756         case 0:  /* child */
757             setsid();
758             close( sync_pipe[0] );
759
760             acquire_lock();
761
762             /* close stdin and stdout */
763             if ((fd = open( "/dev/null", O_RDWR )) != -1)
764             {
765                 dup2( fd, 0 );
766                 dup2( fd, 1 );
767                 close( fd );
768             }
769
770             /* signal parent */
771             dummy = 0;
772             write( sync_pipe[1], &dummy, 1 );
773             close( sync_pipe[1] );
774             break;
775
776         case -1:
777             fatal_perror( "fork" );
778             break;
779
780         default:  /* parent */
781             close( sync_pipe[1] );
782
783             /* wait for child to signal us and then exit */
784             if (read( sync_pipe[0], &dummy, 1 ) == 1) _exit(0);
785
786             /* child terminated, propagate exit status */
787             wait4( pid, &status, 0, NULL );
788             if (WIFEXITED(status)) _exit( WEXITSTATUS(status) );
789             _exit(1);
790         }
791     }
792     else  /* remain in the foreground */
793     {
794         acquire_lock();
795     }
796
797     /* setup msghdr structure constant fields */
798     msghdr.msg_name    = NULL;
799     msghdr.msg_namelen = 0;
800     msghdr.msg_iov     = &myiovec;
801     msghdr.msg_iovlen  = 1;
802
803     /* init startup time */
804     gettimeofday( &server_start_time, NULL );
805
806     /* init the process tracing mechanism */
807     init_tracing_mechanism();
808 }
809
810 /* master socket timer expiration handler */
811 static void close_socket_timeout( void *arg )
812 {
813     master_socket->timeout = NULL;
814     flush_registry();
815
816     /* if a new client is waiting, we keep on running */
817     if (!force_shutdown && check_fd_events( master_socket->fd, POLLIN )) return;
818
819     if (debug_level) fprintf( stderr, "wineserver: exiting (pid=%ld)\n", (long) getpid() );
820
821 #ifdef DEBUG_OBJECTS
822     close_objects();  /* shut down everything properly */
823 #endif
824     exit( force_shutdown );
825 }
826
827 /* close the master socket and stop waiting for new clients */
828 void close_master_socket(void)
829 {
830     if (master_socket_timeout == -1) return;  /* just keep running forever */
831
832     if (master_socket_timeout)
833     {
834         struct timeval when = current_time;
835         add_timeout( &when, master_socket_timeout * 1000 );
836         master_socket->timeout = add_timeout_user( &when, close_socket_timeout, NULL );
837     }
838     else close_socket_timeout( NULL );  /* close it right away */
839 }
840
841 /* forced shutdown, used for wineserver -k */
842 void shutdown_master_socket(void)
843 {
844     force_shutdown = 1;
845     master_socket_timeout = 0;
846     if (master_socket->timeout)
847     {
848         remove_timeout_user( master_socket->timeout );
849         close_socket_timeout( NULL );
850     }
851     set_fd_events( master_socket->fd, -1 ); /* stop waiting for new clients */
852 }