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