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