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