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