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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 #include "wine/port.h"
37 #include <sys/types.h>
38 #ifdef HAVE_SYS_SOCKET_H
39 # include <sys/socket.h>
41 #ifdef HAVE_SYS_WAIT_H
42 # include <sys/wait.h>
56 #define WIN32_NO_STATUS
61 #include "wine/library.h"
65 #define WANT_REQUEST_HANDLERS
68 /* Some versions of glibc don't define this */
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 */
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 */
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 );
88 static const struct object_ops master_socket_ops =
90 sizeof(struct master_socket), /* size */
91 master_socket_dump, /* dump */
92 no_add_queue, /* add_queue */
93 NULL, /* remove_queue */
96 no_signal, /* signal */
97 no_get_fd, /* get_fd */
98 no_map_access, /* map_access */
99 no_lookup_name, /* lookup_name */
100 no_open_file, /* open_file */
101 no_close_handle, /* close_handle */
102 master_socket_destroy /* destroy */
105 static const struct fd_ops master_socket_fd_ops =
107 NULL, /* get_poll_events */
108 master_socket_poll_event, /* poll_event */
109 no_flush, /* flush */
110 no_get_file_info, /* get_file_info */
111 no_queue_async, /* queue_async */
112 no_cancel_async /* cancel_async */
116 struct thread *current = NULL; /* thread handling the current request */
117 unsigned int global_error = 0; /* global error code for when no thread is current */
118 struct timeval server_start_time = { 0, 0 }; /* server startup time */
120 static struct master_socket *master_socket; /* the master socket object */
121 static int force_shutdown;
123 /* socket communication static structures */
124 static struct iovec myiovec;
125 static struct msghdr msghdr;
126 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
131 size_t len; /* size of structure */
132 int level; /* SOL_SOCKET */
133 int type; /* SCM_RIGHTS */
135 int fd; /* fd to pass */
137 static struct cmsg_fd cmsg = { { sizeof(cmsg.header) + sizeof(cmsg.fd), SOL_SOCKET, SCM_RIGHTS }, -1 };
138 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
140 /* complain about a protocol error and terminate the client connection */
141 void fatal_protocol_error( struct thread *thread, const char *err, ... )
145 va_start( args, err );
146 fprintf( stderr, "Protocol error:%04x: ", thread->id );
147 vfprintf( stderr, err, args );
149 thread->exit_code = 1;
150 kill_thread( thread, 1 );
153 /* complain about a protocol error and terminate the client connection */
154 void fatal_protocol_perror( struct thread *thread, const char *err, ... )
158 va_start( args, err );
159 fprintf( stderr, "Protocol error:%04x: ", thread->id );
160 vfprintf( stderr, err, args );
163 thread->exit_code = 1;
164 kill_thread( thread, 1 );
167 /* die on a fatal error */
168 void fatal_error( const char *err, ... )
172 va_start( args, err );
173 fprintf( stderr, "wineserver: " );
174 vfprintf( stderr, err, args );
179 /* die on a fatal error */
180 void fatal_perror( const char *err, ... )
184 va_start( args, err );
185 fprintf( stderr, "wineserver: " );
186 vfprintf( stderr, err, args );
192 /* allocate the reply data */
193 void *set_reply_data_size( data_size_t size )
195 assert( size <= get_reply_max_size() );
196 if (size && !(current->reply_data = mem_alloc( size ))) size = 0;
197 current->reply_size = size;
198 return current->reply_data;
201 /* write the remaining part of the reply */
202 void write_reply( struct thread *thread )
206 if ((ret = write( get_unix_fd( thread->reply_fd ),
207 (char *)thread->reply_data + thread->reply_size - thread->reply_towrite,
208 thread->reply_towrite )) >= 0)
210 if (!(thread->reply_towrite -= ret))
212 free( thread->reply_data );
213 thread->reply_data = NULL;
214 /* sent everything, can go back to waiting for requests */
215 set_fd_events( thread->request_fd, POLLIN );
216 set_fd_events( thread->reply_fd, 0 );
221 kill_thread( thread, 0 ); /* normal death */
222 else if (errno != EWOULDBLOCK && errno != EAGAIN)
223 fatal_protocol_perror( thread, "reply write" );
226 /* send a reply to the current thread */
227 static void send_reply( union generic_reply *reply )
231 if (!current->reply_size)
233 if ((ret = write( get_unix_fd( current->reply_fd ),
234 reply, sizeof(*reply) )) != sizeof(*reply)) goto error;
240 vec[0].iov_base = (void *)reply;
241 vec[0].iov_len = sizeof(*reply);
242 vec[1].iov_base = current->reply_data;
243 vec[1].iov_len = current->reply_size;
245 if ((ret = writev( get_unix_fd( current->reply_fd ), vec, 2 )) < sizeof(*reply)) goto error;
247 if ((current->reply_towrite = current->reply_size - (ret - sizeof(*reply))))
249 /* couldn't write it all, wait for POLLOUT */
250 set_fd_events( current->reply_fd, POLLOUT );
251 set_fd_events( current->request_fd, 0 );
255 free( current->reply_data );
256 current->reply_data = NULL;
261 fatal_protocol_error( current, "partial write %d\n", ret );
262 else if (errno == EPIPE)
263 kill_thread( current, 0 ); /* normal death */
265 fatal_protocol_perror( current, "reply write" );
268 /* call a request handler */
269 static void call_req_handler( struct thread *thread )
271 union generic_reply reply;
272 enum request req = thread->req.request_header.req;
275 current->reply_size = 0;
277 memset( &reply, 0, sizeof(reply) );
279 if (debug_level) trace_request();
281 if (req < REQ_NB_REQUESTS)
282 req_handlers[req]( ¤t->req, &reply );
284 set_error( STATUS_NOT_IMPLEMENTED );
288 if (current->reply_fd)
290 reply.reply_header.error = current->error;
291 reply.reply_header.reply_size = current->reply_size;
292 if (debug_level) trace_reply( req, &reply );
293 send_reply( &reply );
297 current->exit_code = 1;
298 kill_thread( current, 1 ); /* no way to continue without reply fd */
304 /* read a request from a thread */
305 void read_request( struct thread *thread )
309 if (!thread->req_toread) /* no pending request */
311 if ((ret = read( get_unix_fd( thread->request_fd ), &thread->req,
312 sizeof(thread->req) )) != sizeof(thread->req)) goto error;
313 if (!(thread->req_toread = thread->req.request_header.request_size))
315 /* no data, handle request at once */
316 call_req_handler( thread );
319 if (!(thread->req_data = malloc( thread->req_toread )))
321 fatal_protocol_error( thread, "no memory for %u bytes request %d\n",
322 thread->req_toread, thread->req.request_header.req );
327 /* read the variable sized data */
330 ret = read( get_unix_fd( thread->request_fd ),
331 (char *)thread->req_data + thread->req.request_header.request_size
332 - thread->req_toread,
333 thread->req_toread );
335 if (!(thread->req_toread -= ret))
337 call_req_handler( thread );
338 free( thread->req_data );
339 thread->req_data = NULL;
345 if (!ret) /* closed pipe */
346 kill_thread( thread, 0 );
348 fatal_protocol_error( thread, "partial read %d\n", ret );
349 else if (errno != EWOULDBLOCK && errno != EAGAIN)
350 fatal_protocol_perror( thread, "read" );
353 /* receive a file descriptor on the process socket */
354 int receive_fd( struct process *process )
359 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
360 msghdr.msg_accrightslen = sizeof(int);
361 msghdr.msg_accrights = (void *)&fd;
362 #else /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
363 msghdr.msg_control = &cmsg;
364 msghdr.msg_controllen = sizeof(cmsg.header) + sizeof(fd);
366 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
368 myiovec.iov_base = (void *)&data;
369 myiovec.iov_len = sizeof(data);
371 ret = recvmsg( get_unix_fd( process->msg_fd ), &msghdr, 0 );
372 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
376 if (ret == sizeof(data))
378 struct thread *thread;
380 if (data.tid) thread = get_thread_from_id( data.tid );
381 else thread = (struct thread *)grab_object( get_process_first_thread( process ));
383 if (!thread || thread->process != process || thread->state == TERMINATED)
386 fprintf( stderr, "%04x: *fd* %d <- %d bad thread id\n",
387 data.tid, data.fd, fd );
393 fprintf( stderr, "%04x: *fd* %d <- %d\n",
394 thread->id, data.fd, fd );
395 thread_add_inflight_fd( thread, data.fd, fd );
397 if (thread) release_object( thread );
403 kill_process( process, 0 );
407 fprintf( stderr, "Protocol error: process %04x: partial recvmsg %d for fd\n",
409 kill_process( process, 1 );
413 if (errno != EWOULDBLOCK && errno != EAGAIN)
415 fprintf( stderr, "Protocol error: process %04x: ", process->id );
417 kill_process( process, 1 );
423 /* send an fd to a client */
424 int send_client_fd( struct process *process, int fd, obj_handle_t handle )
429 fprintf( stderr, "%04x: *fd* %p -> %d\n",
430 current ? current->id : process->id, handle, fd );
432 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
433 msghdr.msg_accrightslen = sizeof(fd);
434 msghdr.msg_accrights = (void *)&fd;
435 #else /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
436 msghdr.msg_control = &cmsg;
437 msghdr.msg_controllen = sizeof(cmsg.header) + sizeof(fd);
439 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
441 myiovec.iov_base = (void *)&handle;
442 myiovec.iov_len = sizeof(handle);
444 ret = sendmsg( get_unix_fd( process->msg_fd ), &msghdr, 0 );
446 if (ret == sizeof(handle)) return 0;
450 fprintf( stderr, "Protocol error: process %04x: partial sendmsg %d\n", process->id, ret );
451 kill_process( process, 1 );
453 else if (errno == EPIPE)
455 kill_process( process, 0 );
459 fprintf( stderr, "Protocol error: process %04x: ", process->id );
461 kill_process( process, 1 );
466 /* get current tick count to return to client */
467 unsigned int get_tick_count(void)
469 return ((current_time.tv_sec - server_start_time.tv_sec) * 1000) +
470 ((current_time.tv_usec - server_start_time.tv_usec) / 1000);
473 static void master_socket_dump( struct object *obj, int verbose )
475 struct master_socket *sock = (struct master_socket *)obj;
476 assert( obj->ops == &master_socket_ops );
477 fprintf( stderr, "Master socket fd=%p\n", sock->fd );
480 static void master_socket_destroy( struct object *obj )
482 struct master_socket *sock = (struct master_socket *)obj;
483 assert( obj->ops == &master_socket_ops );
484 release_object( sock->fd );
487 /* handle a socket event */
488 static void master_socket_poll_event( struct fd *fd, int event )
490 struct master_socket *sock = get_fd_user( fd );
491 assert( master_socket->obj.ops == &master_socket_ops );
493 assert( sock == master_socket ); /* there is only one master socket */
495 if (event & (POLLERR | POLLHUP))
497 /* this is not supposed to happen */
498 fprintf( stderr, "wineserver: Error on master socket\n" );
499 set_fd_events( sock->fd, -1 );
501 else if (event & POLLIN)
503 struct sockaddr_un dummy;
504 unsigned int len = sizeof(dummy);
505 int client = accept( get_unix_fd( master_socket->fd ), (struct sockaddr *) &dummy, &len );
506 if (client == -1) return;
509 remove_timeout_user( sock->timeout );
510 sock->timeout = NULL;
512 fcntl( client, F_SETFL, O_NONBLOCK );
513 create_process( client, NULL, 0 );
517 /* remove the socket upon exit */
518 static void socket_cleanup(void)
520 static int do_it_once;
521 if (!do_it_once++) unlink( server_socket_name );
524 /* create a directory and check its permissions */
525 static void create_dir( const char *name, struct stat *st )
527 if (lstat( name, st ) == -1)
529 if (errno != ENOENT) fatal_perror( "lstat %s", name );
530 if (mkdir( name, 0700 ) == -1 && errno != EEXIST) fatal_perror( "mkdir %s", name );
531 if (lstat( name, st ) == -1) fatal_perror( "lstat %s", name );
533 if (!S_ISDIR(st->st_mode)) fatal_error( "%s is not a directory\n", name );
534 if (st->st_uid != getuid()) fatal_error( "%s is not owned by you\n", name );
535 if (st->st_mode & 077) fatal_error( "%s must not be accessible by other users\n", name );
538 /* create the server directory and chdir to it */
539 static void create_server_dir( const char *dir )
541 char *p, *server_dir;
544 if (!(server_dir = strdup( dir ))) fatal_error( "out of memory\n" );
546 /* first create the base directory if needed */
548 p = strrchr( server_dir, '/' );
550 create_dir( server_dir, &st );
552 /* now create the server directory */
555 create_dir( server_dir, &st );
557 if (chdir( server_dir ) == -1) fatal_perror( "chdir %s", server_dir );
558 if (stat( ".", &st2 ) == -1) fatal_perror( "stat %s", server_dir );
559 if (st.st_dev != st2.st_dev || st.st_ino != st2.st_ino)
560 fatal_error( "chdir did not end up in %s\n", server_dir );
565 /* create the lock file and return its file descriptor */
566 static int create_server_lock(void)
571 if (lstat( server_lock_name, &st ) == -1)
574 fatal_perror( "lstat %s/%s", wine_get_server_dir(), server_lock_name );
578 if (!S_ISREG(st.st_mode))
579 fatal_error( "%s/%s is not a regular file\n", wine_get_server_dir(), server_lock_name );
582 if ((fd = open( server_lock_name, O_CREAT|O_TRUNC|O_WRONLY, 0600 )) == -1)
583 fatal_perror( "error creating %s/%s", wine_get_server_dir(), server_lock_name );
587 /* wait for the server lock */
588 int wait_for_lock(void)
590 const char *server_dir = wine_get_server_dir();
594 if (!server_dir) return 0; /* no server dir, so no lock to wait on */
596 create_server_dir( server_dir );
597 fd = create_server_lock();
600 fl.l_whence = SEEK_SET;
603 r = fcntl( fd, F_SETLKW, &fl );
609 /* kill the wine server holding the lock */
610 int kill_lock_owner( int sig )
612 const char *server_dir = wine_get_server_dir();
617 if (!server_dir) return 0; /* no server dir, nothing to do */
619 create_server_dir( server_dir );
620 fd = create_server_lock();
622 for (i = 0; i < 10; i++)
625 fl.l_whence = SEEK_SET;
628 if (fcntl( fd, F_GETLK, &fl ) == -1) goto done;
629 if (fl.l_type != F_WRLCK) goto done; /* the file is not locked */
630 if (!pid) /* first time around */
632 if (!(pid = fl.l_pid)) goto done; /* shouldn't happen */
635 if (kill( pid, SIGINT ) == -1) goto done;
636 kill( pid, SIGCONT );
639 else /* just send the specified signal and return */
641 ret = (kill( pid, sig ) != -1);
645 else if (fl.l_pid != pid) goto done; /* no longer the same process */
648 /* waited long enough, now kill it */
649 kill( pid, SIGKILL );
656 /* acquire the main server lock */
657 static void acquire_lock(void)
659 struct sockaddr_un addr;
662 int fd, slen, got_lock = 0;
664 fd = create_server_lock();
667 fl.l_whence = SEEK_SET;
670 if (fcntl( fd, F_SETLK, &fl ) != -1)
672 /* check for crashed server */
673 if (stat( server_socket_name, &st ) != -1 && /* there is a leftover socket */
674 stat( "core", &st ) != -1 && st.st_size) /* and there is a non-empty core file */
677 "Warning: a previous instance of the wine server seems to have crashed.\n"
678 "Please run 'gdb %s %s/core',\n"
679 "type 'backtrace' at the gdb prompt and report the results. Thanks.\n\n",
680 server_argv0, wine_get_server_dir() );
682 unlink( server_socket_name ); /* we got the lock, we can safely remove the socket */
684 /* in that case we reuse fd without closing it, this ensures
685 * that we hold the lock until the process exits */
694 /* check whether locks work at all on this file system */
695 if (fcntl( fd, F_GETLK, &fl ) == -1) break;
698 exit(2); /* we didn't get the lock, exit with special status */
700 fatal_perror( "fcntl %s/%s", wine_get_server_dir(), server_lock_name );
702 /* it seems we can't use locks on this fs, so we will use the socket existence as lock */
706 if ((fd = socket( AF_UNIX, SOCK_STREAM, 0 )) == -1) fatal_perror( "socket" );
707 addr.sun_family = AF_UNIX;
708 strcpy( addr.sun_path, server_socket_name );
709 slen = sizeof(addr) - sizeof(addr.sun_path) + strlen(addr.sun_path) + 1;
710 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
713 if (bind( fd, (struct sockaddr *)&addr, slen ) == -1)
715 if ((errno == EEXIST) || (errno == EADDRINUSE))
718 fatal_error( "couldn't bind to the socket even though we hold the lock\n" );
719 exit(2); /* we didn't get the lock, exit with special status */
721 fatal_perror( "bind" );
723 atexit( socket_cleanup );
724 chmod( server_socket_name, 0600 ); /* make sure no other user can connect */
725 if (listen( fd, 5 ) == -1) fatal_perror( "listen" );
727 if (!(master_socket = alloc_object( &master_socket_ops )) ||
728 !(master_socket->fd = create_anonymous_fd( &master_socket_fd_ops, fd, &master_socket->obj )))
729 fatal_error( "out of memory\n" );
730 master_socket->timeout = NULL;
731 set_fd_events( master_socket->fd, POLLIN );
732 make_object_static( &master_socket->obj );
735 /* open the master server socket and start waiting for new clients */
736 void open_master_socket(void)
738 const char *server_dir = wine_get_server_dir();
739 int fd, pid, status, sync_pipe[2];
742 /* make sure no request is larger than the maximum size */
743 assert( sizeof(union generic_request) == sizeof(struct request_max_size) );
744 assert( sizeof(union generic_reply) == sizeof(struct request_max_size) );
746 if (!server_dir) fatal_error( "directory %s cannot be accessed\n", wine_get_config_dir() );
747 create_server_dir( server_dir );
751 if (pipe( sync_pipe ) == -1) fatal_perror( "pipe" );
757 close( sync_pipe[0] );
761 /* close stdin and stdout */
762 if ((fd = open( "/dev/null", O_RDWR )) != -1)
771 write( sync_pipe[1], &dummy, 1 );
772 close( sync_pipe[1] );
776 fatal_perror( "fork" );
779 default: /* parent */
780 close( sync_pipe[1] );
782 /* wait for child to signal us and then exit */
783 if (read( sync_pipe[0], &dummy, 1 ) == 1) _exit(0);
785 /* child terminated, propagate exit status */
786 wait4( pid, &status, 0, NULL );
787 if (WIFEXITED(status)) _exit( WEXITSTATUS(status) );
791 else /* remain in the foreground */
796 /* setup msghdr structure constant fields */
797 msghdr.msg_name = NULL;
798 msghdr.msg_namelen = 0;
799 msghdr.msg_iov = &myiovec;
800 msghdr.msg_iovlen = 1;
802 /* init startup time */
803 gettimeofday( &server_start_time, NULL );
805 /* init the process tracing mechanism */
806 init_tracing_mechanism();
809 /* master socket timer expiration handler */
810 static void close_socket_timeout( void *arg )
812 master_socket->timeout = NULL;
815 /* if a new client is waiting, we keep on running */
816 if (!force_shutdown && check_fd_events( master_socket->fd, POLLIN )) return;
818 if (debug_level) fprintf( stderr, "wineserver: exiting (pid=%ld)\n", (long) getpid() );
821 close_objects(); /* shut down everything properly */
823 exit( force_shutdown );
826 /* close the master socket and stop waiting for new clients */
827 void close_master_socket(void)
829 if (master_socket_timeout == -1) return; /* just keep running forever */
831 if (master_socket_timeout)
833 struct timeval when = current_time;
834 add_timeout( &when, master_socket_timeout * 1000 );
835 master_socket->timeout = add_timeout_user( &when, close_socket_timeout, NULL );
837 else close_socket_timeout( NULL ); /* close it right away */
840 /* forced shutdown, used for wineserver -k */
841 void shutdown_master_socket(void)
844 master_socket_timeout = 0;
845 if (master_socket->timeout)
847 remove_timeout_user( master_socket->timeout );
848 close_socket_timeout( NULL );
850 set_fd_events( master_socket->fd, -1 ); /* stop waiting for new clients */