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"
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>
55 #include "wine/library.h"
62 #define WANT_REQUEST_HANDLERS
65 /* Some versions of glibc don't define this */
70 /* path names for server master Unix socket */
71 static const char * const server_socket_name = "socket"; /* name of the socket file */
72 static const char * const server_lock_name = "lock"; /* name of the server lock file */
76 struct object obj; /* object header */
77 struct timeout_user *timeout; /* timeout on last process exit */
80 static void master_socket_dump( struct object *obj, int verbose );
81 static void master_socket_poll_event( struct object *obj, int event );
83 static const struct object_ops master_socket_ops =
85 sizeof(struct master_socket), /* size */
86 master_socket_dump, /* dump */
87 no_add_queue, /* add_queue */
88 NULL, /* remove_queue */
91 no_get_fd, /* get_fd */
92 no_get_file_info, /* get_file_info */
93 no_destroy /* destroy */
96 static const struct fd_ops master_socket_fd_ops =
98 NULL, /* get_poll_events */
99 master_socket_poll_event, /* poll_event */
100 no_flush, /* flush */
101 no_get_file_info, /* get_file_info */
102 no_queue_async /* queue_async */
106 struct thread *current = NULL; /* thread handling the current request */
107 unsigned int global_error = 0; /* global error code for when no thread is current */
108 unsigned int server_start_ticks = 0; /* tick count offset from server startup */
110 static struct master_socket *master_socket; /* the master socket object */
112 /* socket communication static structures */
113 static struct iovec myiovec;
114 static struct msghdr msghdr;
115 #ifndef HAVE_MSGHDR_ACCRIGHTS
118 int len; /* sizeof structure */
119 int level; /* SOL_SOCKET */
120 int type; /* SCM_RIGHTS */
121 int fd; /* fd to pass */
123 static struct cmsg_fd cmsg = { sizeof(cmsg), SOL_SOCKET, SCM_RIGHTS, -1 };
124 #endif /* HAVE_MSGHDR_ACCRIGHTS */
126 /* complain about a protocol error and terminate the client connection */
127 void fatal_protocol_error( struct thread *thread, const char *err, ... )
131 va_start( args, err );
132 fprintf( stderr, "Protocol error:%p: ", thread );
133 vfprintf( stderr, err, args );
135 thread->exit_code = 1;
136 kill_thread( thread, 1 );
139 /* complain about a protocol error and terminate the client connection */
140 void fatal_protocol_perror( struct thread *thread, const char *err, ... )
144 va_start( args, err );
145 fprintf( stderr, "Protocol error:%p: ", thread );
146 vfprintf( stderr, err, args );
149 thread->exit_code = 1;
150 kill_thread( thread, 1 );
153 /* die on a fatal error */
154 void fatal_error( const char *err, ... )
158 va_start( args, err );
159 fprintf( stderr, "wineserver: " );
160 vfprintf( stderr, err, args );
165 /* die on a fatal error */
166 void fatal_perror( const char *err, ... )
170 va_start( args, err );
171 fprintf( stderr, "wineserver: " );
172 vfprintf( stderr, err, args );
178 /* allocate the reply data */
179 void *set_reply_data_size( size_t size )
181 assert( size <= get_reply_max_size() );
182 if (size && !(current->reply_data = mem_alloc( size ))) size = 0;
183 current->reply_size = size;
184 return current->reply_data;
187 /* write the remaining part of the reply */
188 void write_reply( struct thread *thread )
192 if ((ret = write( thread->reply_fd,
193 (char *)thread->reply_data + thread->reply_size - thread->reply_towrite,
194 thread->reply_towrite )) >= 0)
196 if (!(thread->reply_towrite -= ret))
198 free( thread->reply_data );
199 thread->reply_data = NULL;
200 /* sent everything, can go back to waiting for requests */
201 change_select_fd( &thread->obj, thread->request_fd, POLLIN );
206 kill_thread( thread, 0 ); /* normal death */
207 else if (errno != EWOULDBLOCK && errno != EAGAIN)
208 fatal_protocol_perror( thread, "reply write" );
211 /* send a reply to the current thread */
212 static void send_reply( union generic_reply *reply )
216 if (!current->reply_size)
218 if ((ret = write( current->reply_fd, reply, sizeof(*reply) )) != sizeof(*reply)) goto error;
224 vec[0].iov_base = (void *)reply;
225 vec[0].iov_len = sizeof(*reply);
226 vec[1].iov_base = current->reply_data;
227 vec[1].iov_len = current->reply_size;
229 if ((ret = writev( current->reply_fd, vec, 2 )) < sizeof(*reply)) goto error;
231 if ((current->reply_towrite = current->reply_size - (ret - sizeof(*reply))))
233 /* couldn't write it all, wait for POLLOUT */
234 change_select_fd( ¤t->obj, current->reply_fd, POLLOUT );
238 if (current->reply_data)
240 free( current->reply_data );
241 current->reply_data = NULL;
247 fatal_protocol_error( current, "partial write %d\n", ret );
248 else if (errno == EPIPE)
249 kill_thread( current, 0 ); /* normal death */
251 fatal_protocol_perror( current, "reply write" );
254 /* call a request handler */
255 static void call_req_handler( struct thread *thread )
257 union generic_reply reply;
258 enum request req = thread->req.request_header.req;
261 current->reply_size = 0;
263 memset( &reply, 0, sizeof(reply) );
265 if (debug_level) trace_request();
267 if (req < REQ_NB_REQUESTS)
269 req_handlers[req]( ¤t->req, &reply );
272 reply.reply_header.error = current->error;
273 reply.reply_header.reply_size = current->reply_size;
274 if (debug_level) trace_reply( req, &reply );
275 send_reply( &reply );
280 fatal_protocol_error( current, "bad request %d\n", req );
283 /* read a request from a thread */
284 void read_request( struct thread *thread )
288 if (!thread->req_toread) /* no pending request */
290 if ((ret = read( thread->obj.fd, &thread->req,
291 sizeof(thread->req) )) != sizeof(thread->req)) goto error;
292 if (!(thread->req_toread = thread->req.request_header.request_size))
294 /* no data, handle request at once */
295 call_req_handler( thread );
298 if (!(thread->req_data = malloc( thread->req_toread )))
299 fatal_protocol_error( thread, "no memory for %d bytes request\n", thread->req_toread );
302 /* read the variable sized data */
305 ret = read( thread->obj.fd, ((char *)thread->req_data +
306 thread->req.request_header.request_size - thread->req_toread),
307 thread->req_toread );
309 if (!(thread->req_toread -= ret))
311 call_req_handler( thread );
312 free( thread->req_data );
313 thread->req_data = NULL;
319 if (!ret) /* closed pipe */
320 kill_thread( thread, 0 );
322 fatal_protocol_error( thread, "partial read %d\n", ret );
323 else if (errno != EWOULDBLOCK && errno != EAGAIN)
324 fatal_protocol_perror( thread, "read" );
327 /* receive a file descriptor on the process socket */
328 int receive_fd( struct process *process )
333 #ifdef HAVE_MSGHDR_ACCRIGHTS
334 msghdr.msg_accrightslen = sizeof(int);
335 msghdr.msg_accrights = (void *)&fd;
336 #else /* HAVE_MSGHDR_ACCRIGHTS */
337 msghdr.msg_control = &cmsg;
338 msghdr.msg_controllen = sizeof(cmsg);
340 #endif /* HAVE_MSGHDR_ACCRIGHTS */
342 myiovec.iov_base = (void *)&data;
343 myiovec.iov_len = sizeof(data);
345 ret = recvmsg( process->obj.fd, &msghdr, 0 );
346 #ifndef HAVE_MSGHDR_ACCRIGHTS
350 if (ret == sizeof(data))
352 struct thread *thread;
354 if (data.tid) thread = get_thread_from_id( data.tid );
355 else thread = (struct thread *)grab_object( process->thread_list );
357 if (!thread || thread->process != process || thread->state == TERMINATED)
360 fprintf( stderr, "%04x: *fd* %d <- %d bad thread id\n",
361 data.tid, data.fd, fd );
367 fprintf( stderr, "%04x: *fd* %d <- %d\n",
368 thread->id, data.fd, fd );
369 thread_add_inflight_fd( thread, data.fd, fd );
371 if (thread) release_object( thread );
378 fprintf( stderr, "Protocol error: process %p: partial recvmsg %d for fd\n",
380 kill_process( process, NULL, 1 );
384 if (errno != EWOULDBLOCK && errno != EAGAIN)
386 fprintf( stderr, "Protocol error: process %p: ", process );
388 kill_process( process, NULL, 1 );
394 /* send an fd to a client */
395 int send_client_fd( struct process *process, int fd, obj_handle_t handle )
400 fprintf( stderr, "%04x: *fd* %p -> %d\n",
401 current ? current->id : process->id, handle, fd );
403 #ifdef HAVE_MSGHDR_ACCRIGHTS
404 msghdr.msg_accrightslen = sizeof(fd);
405 msghdr.msg_accrights = (void *)&fd;
406 #else /* HAVE_MSGHDR_ACCRIGHTS */
407 msghdr.msg_control = &cmsg;
408 msghdr.msg_controllen = sizeof(cmsg);
410 #endif /* HAVE_MSGHDR_ACCRIGHTS */
412 myiovec.iov_base = (void *)&handle;
413 myiovec.iov_len = sizeof(handle);
415 ret = sendmsg( process->obj.fd, &msghdr, 0 );
417 if (ret == sizeof(handle)) return 0;
421 fprintf( stderr, "Protocol error: process %p: partial sendmsg %d\n", process, ret );
422 kill_process( process, NULL, 1 );
424 else if (errno == EPIPE)
426 kill_process( process, NULL, 0 );
430 fprintf( stderr, "Protocol error: process %p: ", process );
432 kill_process( process, NULL, 1 );
437 /* get current tick count to return to client */
438 unsigned int get_tick_count(void)
441 gettimeofday( &t, NULL );
442 return (t.tv_sec * 1000) + (t.tv_usec / 1000) - server_start_ticks;
445 static void master_socket_dump( struct object *obj, int verbose )
447 struct master_socket *sock = (struct master_socket *)obj;
448 assert( obj->ops == &master_socket_ops );
449 fprintf( stderr, "Master socket fd=%d\n", sock->obj.fd );
452 /* handle a socket event */
453 static void master_socket_poll_event( struct object *obj, int event )
455 struct master_socket *sock = (struct master_socket *)obj;
456 assert( obj->ops == &master_socket_ops );
458 assert( sock == master_socket ); /* there is only one master socket */
460 if (event & (POLLERR | POLLHUP))
462 /* this is not supposed to happen */
463 fprintf( stderr, "wineserver: Error on master socket\n" );
464 release_object( obj );
466 else if (event & POLLIN)
468 struct sockaddr_un dummy;
469 int len = sizeof(dummy);
470 int client = accept( master_socket->obj.fd, (struct sockaddr *) &dummy, &len );
471 if (client == -1) return;
474 remove_timeout_user( sock->timeout );
475 sock->timeout = NULL;
477 fcntl( client, F_SETFL, O_NONBLOCK );
478 create_process( client );
482 /* remove the socket upon exit */
483 static void socket_cleanup(void)
485 static int do_it_once;
486 if (!do_it_once++) unlink( server_socket_name );
489 /* create a directory and check its permissions */
490 static void create_dir( const char *name, struct stat *st )
492 if (lstat( name, st ) == -1)
494 if (errno != ENOENT) fatal_perror( "lstat %s", name );
495 if (mkdir( name, 0700 ) == -1) fatal_perror( "mkdir %s", name );
496 if (lstat( name, st ) == -1) fatal_perror( "lstat %s", name );
498 if (!S_ISDIR(st->st_mode)) fatal_error( "%s is not a directory\n", name );
499 if (st->st_uid != getuid()) fatal_error( "%s is not owned by you\n", name );
500 if (st->st_mode & 077) fatal_error( "%s must not be accessible by other users\n", name );
503 /* create the server directory and chdir to it */
504 static void create_server_dir(void)
506 char *p, *server_dir;
509 if (!(server_dir = strdup( wine_get_server_dir() ))) fatal_error( "out of memory\n" );
511 /* first create the base directory if needed */
513 p = strrchr( server_dir, '/' );
515 create_dir( server_dir, &st );
517 /* now create the server directory */
520 create_dir( server_dir, &st );
522 if (chdir( server_dir ) == -1) fatal_perror( "chdir %s", server_dir );
523 if (stat( ".", &st2 ) == -1) fatal_perror( "stat %s", server_dir );
524 if (st.st_dev != st2.st_dev || st.st_ino != st2.st_ino)
525 fatal_error( "chdir did not end up in %s\n", server_dir );
530 /* create the lock file and return its file descriptor */
531 static int create_server_lock(void)
536 if (lstat( server_lock_name, &st ) == -1)
539 fatal_perror( "lstat %s/%s", wine_get_server_dir(), server_lock_name );
543 if (!S_ISREG(st.st_mode))
544 fatal_error( "%s/%s is not a regular file\n", wine_get_server_dir(), server_lock_name );
547 if ((fd = open( server_lock_name, O_CREAT|O_TRUNC|O_WRONLY, 0600 )) == -1)
548 fatal_perror( "error creating %s/%s", wine_get_server_dir(), server_lock_name );
552 /* wait for the server lock */
553 int wait_for_lock(void)
559 fd = create_server_lock();
562 fl.l_whence = SEEK_SET;
565 r = fcntl( fd, F_SETLKW, &fl );
571 /* kill the wine server holding the lock */
572 int kill_lock_owner( int sig )
579 fd = create_server_lock();
581 for (i = 0; i < 10; i++)
584 fl.l_whence = SEEK_SET;
587 if (fcntl( fd, F_GETLK, &fl ) == -1) goto done;
588 if (fl.l_type != F_WRLCK) goto done; /* the file is not locked */
589 if (!pid) /* first time around */
591 if (!(pid = fl.l_pid)) goto done; /* shouldn't happen */
594 if (kill( pid, SIGINT ) == -1) goto done;
595 kill( pid, SIGCONT );
598 else /* just send the specified signal and return */
600 ret = (kill( pid, sig ) != -1);
604 else if (fl.l_pid != pid) goto done; /* no longer the same process */
607 /* waited long enough, now kill it */
608 kill( pid, SIGKILL );
615 /* acquire the main server lock */
616 static void acquire_lock(void)
618 struct sockaddr_un addr;
621 int fd, slen, got_lock = 0;
623 fd = create_server_lock();
626 fl.l_whence = SEEK_SET;
629 if (fcntl( fd, F_SETLK, &fl ) != -1)
631 /* check for crashed server */
632 if (stat( server_socket_name, &st ) != -1 && /* there is a leftover socket */
633 stat( "core", &st ) != -1 && st.st_size) /* and there is a non-empty core file */
636 "Warning: a previous instance of the wine server seems to have crashed.\n"
637 "Please run 'gdb %s %s/core',\n"
638 "type 'backtrace' at the gdb prompt and report the results. Thanks.\n\n",
639 server_argv0, wine_get_server_dir() );
641 unlink( server_socket_name ); /* we got the lock, we can safely remove the socket */
643 /* in that case we reuse fd without closing it, this ensures
644 * that we hold the lock until the process exits */
653 /* check whether locks work at all on this file system */
654 if (fcntl( fd, F_GETLK, &fl ) == -1) break;
657 exit(2); /* we didn't get the lock, exit with special status */
659 fatal_perror( "fcntl %s/%s", wine_get_server_dir(), server_lock_name );
661 /* it seems we can't use locks on this fs, so we will use the socket existence as lock */
665 if ((fd = socket( AF_UNIX, SOCK_STREAM, 0 )) == -1) fatal_perror( "socket" );
666 addr.sun_family = AF_UNIX;
667 strcpy( addr.sun_path, server_socket_name );
668 slen = sizeof(addr) - sizeof(addr.sun_path) + strlen(addr.sun_path) + 1;
669 #ifdef HAVE_SOCKADDR_SUN_LEN
672 if (bind( fd, (struct sockaddr *)&addr, slen ) == -1)
674 if ((errno == EEXIST) || (errno == EADDRINUSE))
677 fatal_error( "couldn't bind to the socket even though we hold the lock\n" );
678 exit(2); /* we didn't get the lock, exit with special status */
680 fatal_perror( "bind" );
682 atexit( socket_cleanup );
683 chmod( server_socket_name, 0600 ); /* make sure no other user can connect */
684 if (listen( fd, 5 ) == -1) fatal_perror( "listen" );
686 if (!(master_socket = alloc_fd_object( &master_socket_ops, &master_socket_fd_ops, fd )))
687 fatal_error( "out of memory\n" );
688 master_socket->timeout = NULL;
689 set_select_events( &master_socket->obj, POLLIN );
692 /* open the master server socket and start waiting for new clients */
693 void open_master_socket(void)
695 int pid, status, sync_pipe[2];
698 /* make sure no request is larger than the maximum size */
699 assert( sizeof(union generic_request) == sizeof(struct request_max_size) );
700 assert( sizeof(union generic_reply) == sizeof(struct request_max_size) );
703 if (pipe( sync_pipe ) == -1) fatal_perror( "pipe" );
710 close( sync_pipe[0] );
715 write( sync_pipe[1], &dummy, 1 );
716 close( sync_pipe[1] );
720 fatal_perror( "fork" );
723 default: /* parent */
724 close( sync_pipe[1] );
726 /* wait for child to signal us and then exit */
727 if (read( sync_pipe[0], &dummy, 1 ) == 1) _exit(0);
729 /* child terminated, propagate exit status */
730 wait4( pid, &status, 0, NULL );
731 if (WIFEXITED(status)) _exit( WEXITSTATUS(status) );
735 /* setup msghdr structure constant fields */
736 msghdr.msg_name = NULL;
737 msghdr.msg_namelen = 0;
738 msghdr.msg_iov = &myiovec;
739 msghdr.msg_iovlen = 1;
741 /* init startup ticks */
742 server_start_ticks = get_tick_count();
745 /* master socket timer expiration handler */
746 static void close_socket_timeout( void *arg )
748 master_socket->timeout = NULL;
751 /* if a new client is waiting, we keep on running */
752 if (check_select_events( master_socket->obj.fd, POLLIN )) return;
754 if (debug_level) fprintf( stderr, "wineserver: exiting (pid=%ld)\n", (long) getpid() );
757 /* shut down everything properly */
758 release_object( master_socket );
759 close_global_hooks();
760 close_global_handles();
768 /* close the master socket and stop waiting for new clients */
769 void close_master_socket(void)
773 if (master_socket_timeout == -1) return; /* just keep running forever */
775 if (master_socket_timeout)
777 gettimeofday( &when, 0 );
778 add_timeout( &when, master_socket_timeout * 1000 );
779 master_socket->timeout = add_timeout_user( &when, close_socket_timeout, NULL );
781 else close_socket_timeout( NULL ); /* close it right away */
784 /* lock/unlock the master socket to stop accepting new clients */
785 void lock_master_socket( int locked )
787 set_select_events( &master_socket->obj, locked ? 0 : POLLIN );