server: Use the monotonic time counter also on the server side.
[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 #ifdef __APPLE__
55 # include <mach/mach_time.h>
56 #endif
57
58 #include "ntstatus.h"
59 #define WIN32_NO_STATUS
60 #include "windef.h"
61 #include "winbase.h"
62 #include "wincon.h"
63 #include "winternl.h"
64 #include "wine/library.h"
65
66 #include "file.h"
67 #include "process.h"
68 #define WANT_REQUEST_HANDLERS
69 #include "request.h"
70
71 /* Some versions of glibc don't define this */
72 #ifndef SCM_RIGHTS
73 #define SCM_RIGHTS 1
74 #endif
75
76 /* path names for server master Unix socket */
77 static const char * const server_socket_name = "socket";   /* name of the socket file */
78 static const char * const server_lock_name = "lock";       /* name of the server lock file */
79
80 struct master_socket
81 {
82     struct object        obj;        /* object header */
83     struct fd           *fd;         /* file descriptor of the master socket */
84 };
85
86 static void master_socket_dump( struct object *obj, int verbose );
87 static void master_socket_destroy( struct object *obj );
88 static void master_socket_poll_event( struct fd *fd, int event );
89
90 static const struct object_ops master_socket_ops =
91 {
92     sizeof(struct master_socket),  /* size */
93     master_socket_dump,            /* dump */
94     no_get_type,                   /* get_type */
95     no_add_queue,                  /* add_queue */
96     NULL,                          /* remove_queue */
97     NULL,                          /* signaled */
98     NULL,                          /* satisfied */
99     no_signal,                     /* signal */
100     no_get_fd,                     /* get_fd */
101     no_map_access,                 /* map_access */
102     default_get_sd,                /* get_sd */
103     default_set_sd,                /* set_sd */
104     no_lookup_name,                /* lookup_name */
105     no_open_file,                  /* open_file */
106     no_close_handle,               /* close_handle */
107     master_socket_destroy          /* destroy */
108 };
109
110 static const struct fd_ops master_socket_fd_ops =
111 {
112     NULL,                          /* get_poll_events */
113     master_socket_poll_event,      /* poll_event */
114     NULL,                          /* flush */
115     NULL,                          /* get_fd_type */
116     NULL,                          /* ioctl */
117     NULL,                          /* queue_async */
118     NULL,                          /* reselect_async */
119     NULL                           /* cancel_async */
120 };
121
122
123 struct thread *current = NULL;  /* thread handling the current request */
124 unsigned int global_error = 0;  /* global error code for when no thread is current */
125 timeout_t server_start_time = 0;  /* server startup time */
126 int server_dir_fd = -1;    /* file descriptor for the server dir */
127 int config_dir_fd = -1;    /* file descriptor for the config dir */
128
129 static struct master_socket *master_socket;  /* the master socket object */
130 static struct timeout_user *master_timeout;
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:%04x: ", thread->id );
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:%04x: ", thread->id );
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( data_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     free( current->reply_data );
248     current->reply_data = NULL;
249     return;
250
251  error:
252     if (ret >= 0)
253         fatal_protocol_error( current, "partial write %d\n", ret );
254     else if (errno == EPIPE)
255         kill_thread( current, 0 );  /* normal death */
256     else
257         fatal_protocol_perror( current, "reply write" );
258 }
259
260 /* call a request handler */
261 static void call_req_handler( struct thread *thread )
262 {
263     union generic_reply reply;
264     enum request req = thread->req.request_header.req;
265
266     current = thread;
267     current->reply_size = 0;
268     clear_error();
269     memset( &reply, 0, sizeof(reply) );
270
271     if (debug_level) trace_request();
272
273     if (req < REQ_NB_REQUESTS)
274         req_handlers[req]( &current->req, &reply );
275     else
276         set_error( STATUS_NOT_IMPLEMENTED );
277
278     if (current)
279     {
280         if (current->reply_fd)
281         {
282             reply.reply_header.error = current->error;
283             reply.reply_header.reply_size = current->reply_size;
284             if (debug_level) trace_reply( req, &reply );
285             send_reply( &reply );
286         }
287         else
288         {
289             current->exit_code = 1;
290             kill_thread( current, 1 );  /* no way to continue without reply fd */
291         }
292     }
293     current = NULL;
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         {
313             fatal_protocol_error( thread, "no memory for %u bytes request %d\n",
314                                   thread->req_toread, thread->req.request_header.req );
315             return;
316         }
317     }
318
319     /* read the variable sized data */
320     for (;;)
321     {
322         ret = read( get_unix_fd( thread->request_fd ),
323                     (char *)thread->req_data + thread->req.request_header.request_size
324                       - thread->req_toread,
325                     thread->req_toread );
326         if (ret <= 0) break;
327         if (!(thread->req_toread -= ret))
328         {
329             call_req_handler( thread );
330             free( thread->req_data );
331             thread->req_data = NULL;
332             return;
333         }
334     }
335
336 error:
337     if (!ret)  /* closed pipe */
338         kill_thread( thread, 0 );
339     else if (ret > 0)
340         fatal_protocol_error( thread, "partial read %d\n", ret );
341     else if (errno != EWOULDBLOCK && errno != EAGAIN)
342         fatal_protocol_perror( thread, "read" );
343 }
344
345 /* receive a file descriptor on the process socket */
346 int receive_fd( struct process *process )
347 {
348     struct iovec vec;
349     struct send_fd data;
350     struct msghdr msghdr;
351     int fd = -1, ret;
352
353 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
354     msghdr.msg_accrightslen = sizeof(int);
355     msghdr.msg_accrights = (void *)&fd;
356 #else  /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
357     char cmsg_buffer[256];
358     msghdr.msg_control    = cmsg_buffer;
359     msghdr.msg_controllen = sizeof(cmsg_buffer);
360     msghdr.msg_flags      = 0;
361 #endif  /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
362
363     msghdr.msg_name    = NULL;
364     msghdr.msg_namelen = 0;
365     msghdr.msg_iov     = &vec;
366     msghdr.msg_iovlen  = 1;
367     vec.iov_base = (void *)&data;
368     vec.iov_len  = sizeof(data);
369
370     ret = recvmsg( get_unix_fd( process->msg_fd ), &msghdr, 0 );
371
372 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
373     if (ret > 0)
374     {
375         struct cmsghdr *cmsg;
376         for (cmsg = CMSG_FIRSTHDR( &msghdr ); cmsg; cmsg = CMSG_NXTHDR( &msghdr, cmsg ))
377         {
378             if (cmsg->cmsg_level != SOL_SOCKET) continue;
379             if (cmsg->cmsg_type == SCM_RIGHTS) fd = *(int *)CMSG_DATA(cmsg);
380         }
381     }
382 #endif  /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
383
384     if (ret == sizeof(data))
385     {
386         struct thread *thread;
387
388         if (data.tid) thread = get_thread_from_id( data.tid );
389         else thread = (struct thread *)grab_object( get_process_first_thread( process ));
390
391         if (!thread || thread->process != process || thread->state == TERMINATED)
392         {
393             if (debug_level)
394                 fprintf( stderr, "%04x: *fd* %d <- %d bad thread id\n",
395                          data.tid, data.fd, fd );
396             close( fd );
397         }
398         else
399         {
400             if (debug_level)
401                 fprintf( stderr, "%04x: *fd* %d <- %d\n",
402                          thread->id, data.fd, fd );
403             thread_add_inflight_fd( thread, data.fd, fd );
404         }
405         if (thread) release_object( thread );
406         return 0;
407     }
408
409     if (!ret)
410     {
411         kill_process( process, 0 );
412     }
413     else if (ret > 0)
414     {
415         fprintf( stderr, "Protocol error: process %04x: partial recvmsg %d for fd\n",
416                  process->id, ret );
417         if (fd != -1) close( fd );
418         kill_process( process, 1 );
419     }
420     else
421     {
422         if (errno != EWOULDBLOCK && errno != EAGAIN)
423         {
424             fprintf( stderr, "Protocol error: process %04x: ", process->id );
425             perror( "recvmsg" );
426             kill_process( process, 1 );
427         }
428     }
429     return -1;
430 }
431
432 /* send an fd to a client */
433 int send_client_fd( struct process *process, int fd, obj_handle_t handle )
434 {
435     struct iovec vec;
436     struct msghdr msghdr;
437     int ret;
438
439 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
440     msghdr.msg_accrightslen = sizeof(fd);
441     msghdr.msg_accrights = (void *)&fd;
442 #else  /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
443     char cmsg_buffer[256];
444     struct cmsghdr *cmsg;
445     msghdr.msg_control    = cmsg_buffer;
446     msghdr.msg_controllen = sizeof(cmsg_buffer);
447     msghdr.msg_flags      = 0;
448     cmsg = CMSG_FIRSTHDR( &msghdr );
449     cmsg->cmsg_len   = CMSG_LEN( sizeof(fd) );
450     cmsg->cmsg_level = SOL_SOCKET;
451     cmsg->cmsg_type  = SCM_RIGHTS;
452     *(int *)CMSG_DATA(cmsg) = fd;
453     msghdr.msg_controllen = cmsg->cmsg_len;
454 #endif  /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
455
456     msghdr.msg_name    = NULL;
457     msghdr.msg_namelen = 0;
458     msghdr.msg_iov     = &vec;
459     msghdr.msg_iovlen  = 1;
460
461     vec.iov_base = (void *)&handle;
462     vec.iov_len  = sizeof(handle);
463
464     if (debug_level)
465         fprintf( stderr, "%04x: *fd* %04x -> %d\n", current ? current->id : process->id, handle, fd );
466
467     ret = sendmsg( get_unix_fd( process->msg_fd ), &msghdr, 0 );
468
469     if (ret == sizeof(handle)) return 0;
470
471     if (ret >= 0)
472     {
473         fprintf( stderr, "Protocol error: process %04x: partial sendmsg %d\n", process->id, ret );
474         kill_process( process, 1 );
475     }
476     else if (errno == EPIPE)
477     {
478         kill_process( process, 0 );
479     }
480     else
481     {
482         fprintf( stderr, "Protocol error: process %04x: ", process->id );
483         perror( "sendmsg" );
484         kill_process( process, 1 );
485     }
486     return -1;
487 }
488
489 /* get current tick count to return to client */
490 unsigned int get_tick_count(void)
491 {
492 #ifdef HAVE_CLOCK_GETTIME
493     struct timespec ts;
494 #ifdef CLOCK_MONOTONIC_RAW
495     if (!clock_gettime( CLOCK_MONOTONIC_RAW, &ts ))
496         return ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
497 #endif
498     if (!clock_gettime( CLOCK_MONOTONIC, &ts ))
499         return ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
500 #elif defined(__APPLE__)
501     static mach_timebase_info_data_t timebase;
502
503     if (!timebase.denom) mach_timebase_info( &timebase );
504     return mach_absolute_time() * timebase.numer / timebase.denom / 1000000;
505 #endif
506     return (current_time - server_start_time) / 10000;
507 }
508
509 static void master_socket_dump( struct object *obj, int verbose )
510 {
511     struct master_socket *sock = (struct master_socket *)obj;
512     assert( obj->ops == &master_socket_ops );
513     fprintf( stderr, "Master socket fd=%p\n", sock->fd );
514 }
515
516 static void master_socket_destroy( struct object *obj )
517 {
518     struct master_socket *sock = (struct master_socket *)obj;
519     assert( obj->ops == &master_socket_ops );
520     release_object( sock->fd );
521 }
522
523 /* handle a socket event */
524 static void master_socket_poll_event( struct fd *fd, int event )
525 {
526     struct master_socket *sock = get_fd_user( fd );
527     assert( master_socket->obj.ops == &master_socket_ops );
528
529     assert( sock == master_socket );  /* there is only one master socket */
530
531     if (event & (POLLERR | POLLHUP))
532     {
533         /* this is not supposed to happen */
534         fprintf( stderr, "wineserver: Error on master socket\n" );
535         set_fd_events( sock->fd, -1 );
536     }
537     else if (event & POLLIN)
538     {
539         struct sockaddr_un dummy;
540         unsigned int len = sizeof(dummy);
541         int client = accept( get_unix_fd( master_socket->fd ), (struct sockaddr *) &dummy, &len );
542         if (client == -1) return;
543         fcntl( client, F_SETFL, O_NONBLOCK );
544         create_process( client, NULL, 0 );
545     }
546 }
547
548 /* remove the socket upon exit */
549 static void socket_cleanup(void)
550 {
551     static int do_it_once;
552     if (!do_it_once++) unlink( server_socket_name );
553 }
554
555 /* create a directory and check its permissions */
556 static void create_dir( const char *name, struct stat *st )
557 {
558     if (lstat( name, st ) == -1)
559     {
560         if (errno != ENOENT) fatal_perror( "lstat %s", name );
561         if (mkdir( name, 0700 ) == -1 && errno != EEXIST) fatal_perror( "mkdir %s", name );
562         if (lstat( name, st ) == -1) fatal_perror( "lstat %s", name );
563     }
564     if (!S_ISDIR(st->st_mode)) fatal_error( "%s is not a directory\n", name );
565     if (st->st_uid != getuid()) fatal_error( "%s is not owned by you\n", name );
566     if (st->st_mode & 077) fatal_error( "%s must not be accessible by other users\n", name );
567 }
568
569 /* create the server directory and chdir to it */
570 static void create_server_dir( const char *dir )
571 {
572     char *p, *server_dir;
573     struct stat st, st2;
574
575     if (!(server_dir = strdup( dir ))) fatal_error( "out of memory\n" );
576
577     /* first create the base directory if needed */
578
579     p = strrchr( server_dir, '/' );
580     *p = 0;
581     create_dir( server_dir, &st );
582
583     /* now create the server directory */
584
585     *p = '/';
586     create_dir( server_dir, &st );
587
588     if (chdir( server_dir ) == -1) fatal_perror( "chdir %s", server_dir );
589     if ((server_dir_fd = open( ".", O_RDONLY )) == -1) fatal_perror( "open %s", server_dir );
590     if (fstat( server_dir_fd, &st2 ) == -1) fatal_perror( "stat %s", server_dir );
591     if (st.st_dev != st2.st_dev || st.st_ino != st2.st_ino)
592         fatal_error( "chdir did not end up in %s\n", server_dir );
593
594     free( server_dir );
595 }
596
597 /* create the lock file and return its file descriptor */
598 static int create_server_lock(void)
599 {
600     struct stat st;
601     int fd;
602
603     if (lstat( server_lock_name, &st ) == -1)
604     {
605         if (errno != ENOENT)
606             fatal_perror( "lstat %s/%s", wine_get_server_dir(), server_lock_name );
607     }
608     else
609     {
610         if (!S_ISREG(st.st_mode))
611             fatal_error( "%s/%s is not a regular file\n", wine_get_server_dir(), server_lock_name );
612     }
613
614     if ((fd = open( server_lock_name, O_CREAT|O_TRUNC|O_WRONLY, 0600 )) == -1)
615         fatal_perror( "error creating %s/%s", wine_get_server_dir(), server_lock_name );
616     return fd;
617 }
618
619 /* wait for the server lock */
620 int wait_for_lock(void)
621 {
622     const char *server_dir = wine_get_server_dir();
623     int fd, r;
624     struct flock fl;
625
626     if (!server_dir) return 0;  /* no server dir, so no lock to wait on */
627
628     create_server_dir( server_dir );
629     fd = create_server_lock();
630
631     fl.l_type   = F_WRLCK;
632     fl.l_whence = SEEK_SET;
633     fl.l_start  = 0;
634     fl.l_len    = 1;
635     r = fcntl( fd, F_SETLKW, &fl );
636     close(fd);
637
638     return r;
639 }
640
641 /* kill the wine server holding the lock */
642 int kill_lock_owner( int sig )
643 {
644     const char *server_dir = wine_get_server_dir();
645     int fd, i, ret = 0;
646     pid_t pid = 0;
647     struct flock fl;
648
649     if (!server_dir) return 0;  /* no server dir, nothing to do */
650
651     create_server_dir( server_dir );
652     fd = create_server_lock();
653
654     for (i = 1; i <= 20; i++)
655     {
656         fl.l_type   = F_WRLCK;
657         fl.l_whence = SEEK_SET;
658         fl.l_start  = 0;
659         fl.l_len    = 1;
660         if (fcntl( fd, F_GETLK, &fl ) == -1) goto done;
661         if (fl.l_type != F_WRLCK) goto done;  /* the file is not locked */
662         if (!pid)  /* first time around */
663         {
664             if (!(pid = fl.l_pid)) goto done;  /* shouldn't happen */
665             if (sig == -1)
666             {
667                 if (kill( pid, SIGINT ) == -1) goto done;
668                 kill( pid, SIGCONT );
669                 ret = 1;
670             }
671             else  /* just send the specified signal and return */
672             {
673                 ret = (kill( pid, sig ) != -1);
674                 goto done;
675             }
676         }
677         else if (fl.l_pid != pid) goto done;  /* no longer the same process */
678         usleep( 50000 * i );
679     }
680     /* waited long enough, now kill it */
681     kill( pid, SIGKILL );
682
683  done:
684     close( fd );
685     return ret;
686 }
687
688 /* acquire the main server lock */
689 static void acquire_lock(void)
690 {
691     struct sockaddr_un addr;
692     struct stat st;
693     struct flock fl;
694     int fd, slen, got_lock = 0;
695
696     fd = create_server_lock();
697
698     fl.l_type   = F_WRLCK;
699     fl.l_whence = SEEK_SET;
700     fl.l_start  = 0;
701     fl.l_len    = 1;
702     if (fcntl( fd, F_SETLK, &fl ) != -1)
703     {
704         /* check for crashed server */
705         if (stat( server_socket_name, &st ) != -1 &&   /* there is a leftover socket */
706             stat( "core", &st ) != -1 && st.st_size)   /* and there is a non-empty core file */
707         {
708             fprintf( stderr,
709                      "Warning: a previous instance of the wine server seems to have crashed.\n"
710                      "Please run 'gdb %s %s/core',\n"
711                      "type 'backtrace' at the gdb prompt and report the results. Thanks.\n\n",
712                      server_argv0, wine_get_server_dir() );
713         }
714         unlink( server_socket_name ); /* we got the lock, we can safely remove the socket */
715         got_lock = 1;
716         /* in that case we reuse fd without closing it, this ensures
717          * that we hold the lock until the process exits */
718     }
719     else
720     {
721         switch(errno)
722         {
723         case ENOLCK:
724             break;
725         case EACCES:
726             /* check whether locks work at all on this file system */
727             if (fcntl( fd, F_GETLK, &fl ) == -1) break;
728             /* fall through */
729         case EAGAIN:
730             exit(2); /* we didn't get the lock, exit with special status */
731         default:
732             fatal_perror( "fcntl %s/%s", wine_get_server_dir(), server_lock_name );
733         }
734         /* it seems we can't use locks on this fs, so we will use the socket existence as lock */
735         close( fd );
736     }
737
738     if ((fd = socket( AF_UNIX, SOCK_STREAM, 0 )) == -1) fatal_perror( "socket" );
739     addr.sun_family = AF_UNIX;
740     strcpy( addr.sun_path, server_socket_name );
741     slen = sizeof(addr) - sizeof(addr.sun_path) + strlen(addr.sun_path) + 1;
742 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
743     addr.sun_len = slen;
744 #endif
745     if (bind( fd, (struct sockaddr *)&addr, slen ) == -1)
746     {
747         if ((errno == EEXIST) || (errno == EADDRINUSE))
748         {
749             if (got_lock)
750                 fatal_error( "couldn't bind to the socket even though we hold the lock\n" );
751             exit(2); /* we didn't get the lock, exit with special status */
752         }
753         fatal_perror( "bind" );
754     }
755     atexit( socket_cleanup );
756     chmod( server_socket_name, 0600 );  /* make sure no other user can connect */
757     if (listen( fd, 5 ) == -1) fatal_perror( "listen" );
758
759     if (!(master_socket = alloc_object( &master_socket_ops )) ||
760         !(master_socket->fd = create_anonymous_fd( &master_socket_fd_ops, fd, &master_socket->obj, 0 )))
761         fatal_error( "out of memory\n" );
762     set_fd_events( master_socket->fd, POLLIN );
763     make_object_static( &master_socket->obj );
764 }
765
766 /* open the master server socket and start waiting for new clients */
767 void open_master_socket(void)
768 {
769     const char *server_dir = wine_get_server_dir();
770     const char *config_dir = wine_get_config_dir();
771     int fd, pid, status, sync_pipe[2];
772     char dummy;
773
774     /* make sure no request is larger than the maximum size */
775     assert( sizeof(union generic_request) == sizeof(struct request_max_size) );
776     assert( sizeof(union generic_reply) == sizeof(struct request_max_size) );
777
778     /* make sure the stdio fds are open */
779     fd = open( "/dev/null", O_RDWR );
780     while (fd >= 0 && fd <= 2) fd = dup( fd );
781
782     if (!server_dir) fatal_error( "directory %s cannot be accessed\n", config_dir );
783     if (chdir( config_dir ) == -1) fatal_perror( "chdir to %s", config_dir );
784     if ((config_dir_fd = open( ".", O_RDONLY )) == -1) fatal_perror( "open %s", config_dir );
785
786     create_server_dir( server_dir );
787
788     if (!foreground)
789     {
790         if (pipe( sync_pipe ) == -1) fatal_perror( "pipe" );
791         pid = fork();
792         switch( pid )
793         {
794         case 0:  /* child */
795             setsid();
796             close( sync_pipe[0] );
797
798             acquire_lock();
799
800             /* close stdin and stdout */
801             dup2( fd, 0 );
802             dup2( fd, 1 );
803
804             /* signal parent */
805             dummy = 0;
806             write( sync_pipe[1], &dummy, 1 );
807             close( sync_pipe[1] );
808             break;
809
810         case -1:
811             fatal_perror( "fork" );
812             break;
813
814         default:  /* parent */
815             close( sync_pipe[1] );
816
817             /* wait for child to signal us and then exit */
818             if (read( sync_pipe[0], &dummy, 1 ) == 1) _exit(0);
819
820             /* child terminated, propagate exit status */
821             waitpid( pid, &status, 0 );
822             if (WIFEXITED(status)) _exit( WEXITSTATUS(status) );
823             _exit(1);
824         }
825     }
826     else  /* remain in the foreground */
827     {
828         acquire_lock();
829     }
830
831     /* init the process tracing mechanism */
832     init_tracing_mechanism();
833     close( fd );
834 }
835
836 /* master socket timer expiration handler */
837 static void close_socket_timeout( void *arg )
838 {
839     master_timeout = NULL;
840     flush_registry();
841     if (debug_level) fprintf( stderr, "wineserver: exiting (pid=%ld)\n", (long) getpid() );
842
843 #ifdef DEBUG_OBJECTS
844     close_objects();  /* shut down everything properly */
845 #endif
846     exit( 0 );
847 }
848
849 /* close the master socket and stop waiting for new clients */
850 void close_master_socket( timeout_t timeout )
851 {
852     if (master_socket)
853     {
854         release_object( master_socket );
855         master_socket = NULL;
856     }
857     if (master_timeout)  /* cancel previous timeout */
858         remove_timeout_user( master_timeout );
859
860     master_timeout = add_timeout_user( timeout, close_socket_timeout, NULL );
861 }