2 * Server-side request handling
4 * Copyright (C) 1998 Alexandre Julliard
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.
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.
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 #include "wine/port.h"
35 #include <sys/types.h>
36 #ifdef HAVE_SYS_SOCKET_H
37 # include <sys/socket.h>
39 #ifdef HAVE_SYS_WAIT_H
40 # include <sys/wait.h>
49 #include "wine/library.h"
56 #define WANT_REQUEST_HANDLERS
59 /* Some versions of glibc don't define this */
64 /* path names for server master Unix socket */
65 static const char * const server_socket_name = "socket"; /* name of the socket file */
66 static const char * const server_lock_name = "lock"; /* name of the server lock file */
70 struct object obj; /* object header */
71 struct timeout_user *timeout; /* timeout on last process exit */
74 static void master_socket_dump( struct object *obj, int verbose );
75 static void master_socket_poll_event( struct object *obj, int event );
77 static const struct object_ops master_socket_ops =
79 sizeof(struct master_socket), /* size */
80 master_socket_dump, /* dump */
81 no_add_queue, /* add_queue */
82 NULL, /* remove_queue */
85 no_get_fd, /* get_fd */
86 no_get_file_info, /* get_file_info */
87 no_destroy /* destroy */
90 static const struct fd_ops master_socket_fd_ops =
92 NULL, /* get_poll_events */
93 master_socket_poll_event, /* poll_event */
95 no_get_file_info, /* get_file_info */
96 no_queue_async /* queue_async */
100 struct thread *current = NULL; /* thread handling the current request */
101 unsigned int global_error = 0; /* global error code for when no thread is current */
102 unsigned int server_start_ticks = 0; /* tick count offset from server startup */
104 static struct master_socket *master_socket; /* the master socket object */
106 /* socket communication static structures */
107 static struct iovec myiovec;
108 static struct msghdr msghdr;
109 #ifndef HAVE_MSGHDR_ACCRIGHTS
112 int len; /* sizeof structure */
113 int level; /* SOL_SOCKET */
114 int type; /* SCM_RIGHTS */
115 int fd; /* fd to pass */
117 static struct cmsg_fd cmsg = { sizeof(cmsg), SOL_SOCKET, SCM_RIGHTS, -1 };
118 #endif /* HAVE_MSGHDR_ACCRIGHTS */
120 /* complain about a protocol error and terminate the client connection */
121 void fatal_protocol_error( struct thread *thread, const char *err, ... )
125 va_start( args, err );
126 fprintf( stderr, "Protocol error:%p: ", thread );
127 vfprintf( stderr, err, args );
129 thread->exit_code = 1;
130 kill_thread( thread, 1 );
133 /* complain about a protocol error and terminate the client connection */
134 void fatal_protocol_perror( struct thread *thread, const char *err, ... )
138 va_start( args, err );
139 fprintf( stderr, "Protocol error:%p: ", thread );
140 vfprintf( stderr, err, args );
143 thread->exit_code = 1;
144 kill_thread( thread, 1 );
147 /* die on a fatal error */
148 void fatal_error( const char *err, ... )
152 va_start( args, err );
153 fprintf( stderr, "wineserver: " );
154 vfprintf( stderr, err, args );
159 /* die on a fatal error */
160 void fatal_perror( const char *err, ... )
164 va_start( args, err );
165 fprintf( stderr, "wineserver: " );
166 vfprintf( stderr, err, args );
172 /* allocate the reply data */
173 void *set_reply_data_size( size_t size )
175 assert( size <= get_reply_max_size() );
176 if (size && !(current->reply_data = mem_alloc( size ))) size = 0;
177 current->reply_size = size;
178 return current->reply_data;
181 /* write the remaining part of the reply */
182 void write_reply( struct thread *thread )
186 if ((ret = write( thread->reply_fd,
187 (char *)thread->reply_data + thread->reply_size - thread->reply_towrite,
188 thread->reply_towrite )) >= 0)
190 if (!(thread->reply_towrite -= ret))
192 free( thread->reply_data );
193 thread->reply_data = NULL;
194 /* sent everything, can go back to waiting for requests */
195 change_select_fd( &thread->obj, thread->request_fd, POLLIN );
200 kill_thread( thread, 0 ); /* normal death */
201 else if (errno != EWOULDBLOCK && errno != EAGAIN)
202 fatal_protocol_perror( thread, "reply write" );
205 /* send a reply to the current thread */
206 static void send_reply( union generic_reply *reply )
210 if (!current->reply_size)
212 if ((ret = write( current->reply_fd, reply, sizeof(*reply) )) != sizeof(*reply)) goto error;
218 vec[0].iov_base = (void *)reply;
219 vec[0].iov_len = sizeof(*reply);
220 vec[1].iov_base = current->reply_data;
221 vec[1].iov_len = current->reply_size;
223 if ((ret = writev( current->reply_fd, vec, 2 )) < sizeof(*reply)) goto error;
225 if ((current->reply_towrite = current->reply_size - (ret - sizeof(*reply))))
227 /* couldn't write it all, wait for POLLOUT */
228 change_select_fd( ¤t->obj, current->reply_fd, POLLOUT );
232 if (current->reply_data)
234 free( current->reply_data );
235 current->reply_data = NULL;
241 fatal_protocol_error( current, "partial write %d\n", ret );
242 else if (errno == EPIPE)
243 kill_thread( current, 0 ); /* normal death */
245 fatal_protocol_perror( current, "reply write" );
248 /* call a request handler */
249 static void call_req_handler( struct thread *thread )
251 union generic_reply reply;
252 enum request req = thread->req.request_header.req;
255 current->reply_size = 0;
257 memset( &reply, 0, sizeof(reply) );
259 if (debug_level) trace_request();
261 if (req < REQ_NB_REQUESTS)
263 req_handlers[req]( ¤t->req, &reply );
266 reply.reply_header.error = current->error;
267 reply.reply_header.reply_size = current->reply_size;
268 if (debug_level) trace_reply( req, &reply );
269 send_reply( &reply );
274 fatal_protocol_error( current, "bad request %d\n", req );
277 /* read a request from a thread */
278 void read_request( struct thread *thread )
282 if (!thread->req_toread) /* no pending request */
284 if ((ret = read( thread->obj.fd, &thread->req,
285 sizeof(thread->req) )) != sizeof(thread->req)) goto error;
286 if (!(thread->req_toread = thread->req.request_header.request_size))
288 /* no data, handle request at once */
289 call_req_handler( thread );
292 if (!(thread->req_data = malloc( thread->req_toread )))
293 fatal_protocol_error( thread, "no memory for %d bytes request\n", thread->req_toread );
296 /* read the variable sized data */
299 ret = read( thread->obj.fd, ((char *)thread->req_data +
300 thread->req.request_header.request_size - thread->req_toread),
301 thread->req_toread );
303 if (!(thread->req_toread -= ret))
305 call_req_handler( thread );
306 free( thread->req_data );
307 thread->req_data = NULL;
313 if (!ret) /* closed pipe */
314 kill_thread( thread, 0 );
316 fatal_protocol_error( thread, "partial read %d\n", ret );
317 else if (errno != EWOULDBLOCK && errno != EAGAIN)
318 fatal_protocol_perror( thread, "read" );
321 /* receive a file descriptor on the process socket */
322 int receive_fd( struct process *process )
327 #ifdef HAVE_MSGHDR_ACCRIGHTS
328 msghdr.msg_accrightslen = sizeof(int);
329 msghdr.msg_accrights = (void *)&fd;
330 #else /* HAVE_MSGHDR_ACCRIGHTS */
331 msghdr.msg_control = &cmsg;
332 msghdr.msg_controllen = sizeof(cmsg);
334 #endif /* HAVE_MSGHDR_ACCRIGHTS */
336 myiovec.iov_base = (void *)&data;
337 myiovec.iov_len = sizeof(data);
339 ret = recvmsg( process->obj.fd, &msghdr, 0 );
340 #ifndef HAVE_MSGHDR_ACCRIGHTS
344 if (ret == sizeof(data))
346 struct thread *thread;
348 if (data.tid) thread = get_thread_from_id( data.tid );
349 else thread = (struct thread *)grab_object( process->thread_list );
351 if (!thread || thread->process != process || thread->state == TERMINATED)
354 fprintf( stderr, "%08x: *fd* %d <- %d bad thread id\n",
355 (unsigned int)data.tid, data.fd, fd );
361 fprintf( stderr, "%08x: *fd* %d <- %d\n",
362 (unsigned int)thread, data.fd, fd );
363 thread_add_inflight_fd( thread, data.fd, fd );
365 if (thread) release_object( thread );
372 fprintf( stderr, "Protocol error: process %p: partial recvmsg %d for fd\n",
374 kill_process( process, NULL, 1 );
378 if (errno != EWOULDBLOCK && errno != EAGAIN)
380 fprintf( stderr, "Protocol error: process %p: ", process );
382 kill_process( process, NULL, 1 );
388 /* send an fd to a client */
389 int send_client_fd( struct process *process, int fd, obj_handle_t handle )
394 fprintf( stderr, "%08x: *fd* %p -> %d\n", (unsigned int)current, handle, fd );
396 #ifdef HAVE_MSGHDR_ACCRIGHTS
397 msghdr.msg_accrightslen = sizeof(fd);
398 msghdr.msg_accrights = (void *)&fd;
399 #else /* HAVE_MSGHDR_ACCRIGHTS */
400 msghdr.msg_control = &cmsg;
401 msghdr.msg_controllen = sizeof(cmsg);
403 #endif /* HAVE_MSGHDR_ACCRIGHTS */
405 myiovec.iov_base = (void *)&handle;
406 myiovec.iov_len = sizeof(handle);
408 ret = sendmsg( process->obj.fd, &msghdr, 0 );
410 if (ret == sizeof(handle)) return 0;
414 fprintf( stderr, "Protocol error: process %p: partial sendmsg %d\n", process, ret );
415 kill_process( process, NULL, 1 );
417 else if (errno == EPIPE)
419 kill_process( process, NULL, 0 );
423 fprintf( stderr, "Protocol error: process %p: ", process );
425 kill_process( process, NULL, 1 );
430 /* get current tick count to return to client */
431 unsigned int get_tick_count(void)
434 gettimeofday( &t, NULL );
435 return (t.tv_sec * 1000) + (t.tv_usec / 1000) - server_start_ticks;
438 static void master_socket_dump( struct object *obj, int verbose )
440 struct master_socket *sock = (struct master_socket *)obj;
441 assert( obj->ops == &master_socket_ops );
442 fprintf( stderr, "Master socket fd=%d\n", sock->obj.fd );
445 /* handle a socket event */
446 static void master_socket_poll_event( struct object *obj, int event )
448 struct master_socket *sock = (struct master_socket *)obj;
449 assert( obj->ops == &master_socket_ops );
451 assert( sock == master_socket ); /* there is only one master socket */
453 if (event & (POLLERR | POLLHUP))
455 /* this is not supposed to happen */
456 fprintf( stderr, "wineserver: Error on master socket\n" );
457 release_object( obj );
459 else if (event & POLLIN)
461 struct sockaddr_un dummy;
462 int len = sizeof(dummy);
463 int client = accept( master_socket->obj.fd, (struct sockaddr *) &dummy, &len );
464 if (client == -1) return;
467 remove_timeout_user( sock->timeout );
468 sock->timeout = NULL;
470 fcntl( client, F_SETFL, O_NONBLOCK );
471 create_process( client );
475 /* remove the socket upon exit */
476 static void socket_cleanup(void)
478 static int do_it_once;
479 if (!do_it_once++) unlink( server_socket_name );
482 /* create a directory and check its permissions */
483 static void create_dir( const char *name, struct stat *st )
485 if (lstat( name, st ) == -1)
487 if (errno != ENOENT) fatal_perror( "lstat %s", name );
488 if (mkdir( name, 0700 ) == -1) fatal_perror( "mkdir %s", name );
489 if (lstat( name, st ) == -1) fatal_perror( "lstat %s", name );
491 if (!S_ISDIR(st->st_mode)) fatal_error( "%s is not a directory\n", name );
492 if (st->st_uid != getuid()) fatal_error( "%s is not owned by you\n", name );
493 if (st->st_mode & 077) fatal_error( "%s must not be accessible by other users\n", name );
496 /* create the server directory and chdir to it */
497 static void create_server_dir(void)
499 char *p, *server_dir;
502 if (!(server_dir = strdup( wine_get_server_dir() ))) fatal_error( "out of memory\n" );
504 /* first create the base directory if needed */
506 p = strrchr( server_dir, '/' );
508 create_dir( server_dir, &st );
510 /* now create the server directory */
513 create_dir( server_dir, &st );
515 if (chdir( server_dir ) == -1) fatal_perror( "chdir %s", server_dir );
516 if (stat( ".", &st2 ) == -1) fatal_perror( "stat %s", server_dir );
517 if (st.st_dev != st2.st_dev || st.st_ino != st2.st_ino)
518 fatal_error( "chdir did not end up in %s\n", server_dir );
523 /* create the lock file and return its file descriptor */
524 static int create_server_lock(void)
529 if (lstat( server_lock_name, &st ) == -1)
532 fatal_perror( "lstat %s/%s", wine_get_server_dir(), server_lock_name );
536 if (!S_ISREG(st.st_mode))
537 fatal_error( "%s/%s is not a regular file\n", wine_get_server_dir(), server_lock_name );
540 if ((fd = open( server_lock_name, O_CREAT|O_TRUNC|O_WRONLY, 0600 )) == -1)
541 fatal_perror( "error creating %s/%s", wine_get_server_dir(), server_lock_name );
545 /* wait for the server lock */
546 int wait_for_lock(void)
552 fd = create_server_lock();
555 fl.l_whence = SEEK_SET;
558 r = fcntl( fd, F_SETLKW, &fl );
564 /* kill the wine server holding the lock */
565 int kill_lock_owner( int sig )
572 fd = create_server_lock();
574 for (i = 0; i < 10; i++)
577 fl.l_whence = SEEK_SET;
580 if (fcntl( fd, F_GETLK, &fl ) == -1) goto done;
581 if (fl.l_type != F_WRLCK) goto done; /* the file is not locked */
582 if (!pid) /* first time around */
584 if (!(pid = fl.l_pid)) goto done; /* shouldn't happen */
587 if (kill( pid, SIGINT ) == -1) goto done;
588 kill( pid, SIGCONT );
591 else /* just send the specified signal and return */
593 ret = (kill( pid, sig ) != -1);
597 else if (fl.l_pid != pid) goto done; /* no longer the same process */
600 /* waited long enough, now kill it */
601 kill( pid, SIGKILL );
608 /* acquire the main server lock */
609 static void acquire_lock(void)
611 struct sockaddr_un addr;
614 int fd, slen, got_lock = 0;
616 fd = create_server_lock();
619 fl.l_whence = SEEK_SET;
622 if (fcntl( fd, F_SETLK, &fl ) != -1)
624 /* check for crashed server */
625 if (stat( server_socket_name, &st ) != -1 && /* there is a leftover socket */
626 stat( "core", &st ) != -1 && st.st_size) /* and there is a non-empty core file */
629 "Warning: a previous instance of the wine server seems to have crashed.\n"
630 "Please run 'gdb %s %s/core',\n"
631 "type 'backtrace' at the gdb prompt and report the results. Thanks.\n\n",
632 server_argv0, wine_get_server_dir() );
634 unlink( server_socket_name ); /* we got the lock, we can safely remove the socket */
636 /* in that case we reuse fd without closing it, this ensures
637 * that we hold the lock until the process exits */
646 /* check whether locks work at all on this file system */
647 if (fcntl( fd, F_GETLK, &fl ) == -1) break;
650 exit(2); /* we didn't get the lock, exit with special status */
652 fatal_perror( "fcntl %s/%s", wine_get_server_dir(), server_lock_name );
654 /* it seems we can't use locks on this fs, so we will use the socket existence as lock */
658 if ((fd = socket( AF_UNIX, SOCK_STREAM, 0 )) == -1) fatal_perror( "socket" );
659 addr.sun_family = AF_UNIX;
660 strcpy( addr.sun_path, server_socket_name );
661 slen = sizeof(addr) - sizeof(addr.sun_path) + strlen(addr.sun_path) + 1;
662 #ifdef HAVE_SOCKADDR_SUN_LEN
665 if (bind( fd, (struct sockaddr *)&addr, slen ) == -1)
667 if ((errno == EEXIST) || (errno == EADDRINUSE))
670 fatal_error( "couldn't bind to the socket even though we hold the lock\n" );
671 exit(2); /* we didn't get the lock, exit with special status */
673 fatal_perror( "bind" );
675 atexit( socket_cleanup );
676 chmod( server_socket_name, 0600 ); /* make sure no other user can connect */
677 if (listen( fd, 5 ) == -1) fatal_perror( "listen" );
679 if (!(master_socket = alloc_fd_object( &master_socket_ops, &master_socket_fd_ops, fd )))
680 fatal_error( "out of memory\n" );
681 master_socket->timeout = NULL;
682 set_select_events( &master_socket->obj, POLLIN );
685 /* open the master server socket and start waiting for new clients */
686 void open_master_socket(void)
688 int pid, status, sync_pipe[2];
691 /* make sure no request is larger than the maximum size */
692 assert( sizeof(union generic_request) == sizeof(struct request_max_size) );
693 assert( sizeof(union generic_reply) == sizeof(struct request_max_size) );
696 if (pipe( sync_pipe ) == -1) fatal_perror( "pipe" );
703 close( sync_pipe[0] );
708 write( sync_pipe[1], &dummy, 1 );
709 close( sync_pipe[1] );
713 fatal_perror( "fork" );
716 default: /* parent */
717 close( sync_pipe[1] );
719 /* wait for child to signal us and then exit */
720 if (read( sync_pipe[0], &dummy, 1 ) == 1) _exit(0);
722 /* child terminated, propagate exit status */
723 wait4( pid, &status, 0, NULL );
724 if (WIFEXITED(status)) _exit( WEXITSTATUS(status) );
728 /* setup msghdr structure constant fields */
729 msghdr.msg_name = NULL;
730 msghdr.msg_namelen = 0;
731 msghdr.msg_iov = &myiovec;
732 msghdr.msg_iovlen = 1;
734 /* init startup ticks */
735 server_start_ticks = get_tick_count();
738 /* master socket timer expiration handler */
739 static void close_socket_timeout( void *arg )
741 master_socket->timeout = NULL;
744 /* if a new client is waiting, we keep on running */
745 if (check_select_events( master_socket->obj.fd, POLLIN )) return;
747 if (debug_level) fprintf( stderr, "wineserver: exiting (pid=%ld)\n", (long) getpid() );
750 /* shut down everything properly */
751 release_object( master_socket );
752 close_global_hooks();
753 close_global_handles();
761 /* close the master socket and stop waiting for new clients */
762 void close_master_socket(void)
766 if (master_socket_timeout == -1) return; /* just keep running forever */
768 if (master_socket_timeout)
770 gettimeofday( &when, 0 );
771 add_timeout( &when, master_socket_timeout * 1000 );
772 master_socket->timeout = add_timeout_user( &when, close_socket_timeout, NULL );
774 else close_socket_timeout( NULL ); /* close it right away */
777 /* lock/unlock the master socket to stop accepting new clients */
778 void lock_master_socket( int locked )
780 set_select_events( &master_socket->obj, locked ? 0 : POLLIN );