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