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 fd *fd, 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_destroy /* destroy */
95 static const struct fd_ops master_socket_fd_ops =
97 NULL, /* get_poll_events */
98 master_socket_poll_event, /* poll_event */
100 no_get_file_info, /* get_file_info */
101 no_queue_async /* queue_async */
105 struct thread *current = NULL; /* thread handling the current request */
106 unsigned int global_error = 0; /* global error code for when no thread is current */
107 unsigned int server_start_ticks = 0; /* tick count offset from server startup */
109 static struct master_socket *master_socket; /* the master socket object */
111 /* socket communication static structures */
112 static struct iovec myiovec;
113 static struct msghdr msghdr;
114 #ifndef HAVE_MSGHDR_ACCRIGHTS
117 int len; /* sizeof structure */
118 int level; /* SOL_SOCKET */
119 int type; /* SCM_RIGHTS */
120 int fd; /* fd to pass */
122 static struct cmsg_fd cmsg = { sizeof(cmsg), SOL_SOCKET, SCM_RIGHTS, -1 };
123 #endif /* HAVE_MSGHDR_ACCRIGHTS */
125 /* complain about a protocol error and terminate the client connection */
126 void fatal_protocol_error( struct thread *thread, const char *err, ... )
130 va_start( args, err );
131 fprintf( stderr, "Protocol error:%p: ", thread );
132 vfprintf( stderr, err, args );
134 thread->exit_code = 1;
135 kill_thread( thread, 1 );
138 /* complain about a protocol error and terminate the client connection */
139 void fatal_protocol_perror( struct thread *thread, const char *err, ... )
143 va_start( args, err );
144 fprintf( stderr, "Protocol error:%p: ", thread );
145 vfprintf( stderr, err, args );
148 thread->exit_code = 1;
149 kill_thread( thread, 1 );
152 /* die on a fatal error */
153 void fatal_error( const char *err, ... )
157 va_start( args, err );
158 fprintf( stderr, "wineserver: " );
159 vfprintf( stderr, err, args );
164 /* die on a fatal error */
165 void fatal_perror( const char *err, ... )
169 va_start( args, err );
170 fprintf( stderr, "wineserver: " );
171 vfprintf( stderr, err, args );
177 /* allocate the reply data */
178 void *set_reply_data_size( size_t size )
180 assert( size <= get_reply_max_size() );
181 if (size && !(current->reply_data = mem_alloc( size ))) size = 0;
182 current->reply_size = size;
183 return current->reply_data;
186 /* write the remaining part of the reply */
187 void write_reply( struct thread *thread )
191 if ((ret = write( thread->reply_fd,
192 (char *)thread->reply_data + thread->reply_size - thread->reply_towrite,
193 thread->reply_towrite )) >= 0)
195 if (!(thread->reply_towrite -= ret))
197 free( thread->reply_data );
198 thread->reply_data = NULL;
199 /* sent everything, can go back to waiting for requests */
200 change_select_fd( &thread->obj, thread->request_fd, POLLIN );
205 kill_thread( thread, 0 ); /* normal death */
206 else if (errno != EWOULDBLOCK && errno != EAGAIN)
207 fatal_protocol_perror( thread, "reply write" );
210 /* send a reply to the current thread */
211 static void send_reply( union generic_reply *reply )
215 if (!current->reply_size)
217 if ((ret = write( current->reply_fd, reply, sizeof(*reply) )) != sizeof(*reply)) goto error;
223 vec[0].iov_base = (void *)reply;
224 vec[0].iov_len = sizeof(*reply);
225 vec[1].iov_base = current->reply_data;
226 vec[1].iov_len = current->reply_size;
228 if ((ret = writev( current->reply_fd, vec, 2 )) < sizeof(*reply)) goto error;
230 if ((current->reply_towrite = current->reply_size - (ret - sizeof(*reply))))
232 /* couldn't write it all, wait for POLLOUT */
233 change_select_fd( ¤t->obj, current->reply_fd, POLLOUT );
237 if (current->reply_data)
239 free( current->reply_data );
240 current->reply_data = NULL;
246 fatal_protocol_error( current, "partial write %d\n", ret );
247 else if (errno == EPIPE)
248 kill_thread( current, 0 ); /* normal death */
250 fatal_protocol_perror( current, "reply write" );
253 /* call a request handler */
254 static void call_req_handler( struct thread *thread )
256 union generic_reply reply;
257 enum request req = thread->req.request_header.req;
260 current->reply_size = 0;
262 memset( &reply, 0, sizeof(reply) );
264 if (debug_level) trace_request();
266 if (req < REQ_NB_REQUESTS)
268 req_handlers[req]( ¤t->req, &reply );
271 reply.reply_header.error = current->error;
272 reply.reply_header.reply_size = current->reply_size;
273 if (debug_level) trace_reply( req, &reply );
274 send_reply( &reply );
279 fatal_protocol_error( current, "bad request %d\n", req );
282 /* read a request from a thread */
283 void read_request( struct thread *thread )
287 if (!thread->req_toread) /* no pending request */
289 if ((ret = read( thread->obj.fd, &thread->req,
290 sizeof(thread->req) )) != sizeof(thread->req)) goto error;
291 if (!(thread->req_toread = thread->req.request_header.request_size))
293 /* no data, handle request at once */
294 call_req_handler( thread );
297 if (!(thread->req_data = malloc( thread->req_toread )))
298 fatal_protocol_error( thread, "no memory for %d bytes request\n", thread->req_toread );
301 /* read the variable sized data */
304 ret = read( thread->obj.fd, ((char *)thread->req_data +
305 thread->req.request_header.request_size - thread->req_toread),
306 thread->req_toread );
308 if (!(thread->req_toread -= ret))
310 call_req_handler( thread );
311 free( thread->req_data );
312 thread->req_data = NULL;
318 if (!ret) /* closed pipe */
319 kill_thread( thread, 0 );
321 fatal_protocol_error( thread, "partial read %d\n", ret );
322 else if (errno != EWOULDBLOCK && errno != EAGAIN)
323 fatal_protocol_perror( thread, "read" );
326 /* receive a file descriptor on the process socket */
327 int receive_fd( struct process *process )
332 #ifdef HAVE_MSGHDR_ACCRIGHTS
333 msghdr.msg_accrightslen = sizeof(int);
334 msghdr.msg_accrights = (void *)&fd;
335 #else /* HAVE_MSGHDR_ACCRIGHTS */
336 msghdr.msg_control = &cmsg;
337 msghdr.msg_controllen = sizeof(cmsg);
339 #endif /* HAVE_MSGHDR_ACCRIGHTS */
341 myiovec.iov_base = (void *)&data;
342 myiovec.iov_len = sizeof(data);
344 ret = recvmsg( process->obj.fd, &msghdr, 0 );
345 #ifndef HAVE_MSGHDR_ACCRIGHTS
349 if (ret == sizeof(data))
351 struct thread *thread;
353 if (data.tid) thread = get_thread_from_id( data.tid );
354 else thread = (struct thread *)grab_object( process->thread_list );
356 if (!thread || thread->process != process || thread->state == TERMINATED)
359 fprintf( stderr, "%04x: *fd* %d <- %d bad thread id\n",
360 data.tid, data.fd, fd );
366 fprintf( stderr, "%04x: *fd* %d <- %d\n",
367 thread->id, data.fd, fd );
368 thread_add_inflight_fd( thread, data.fd, fd );
370 if (thread) release_object( thread );
377 fprintf( stderr, "Protocol error: process %p: partial recvmsg %d for fd\n",
379 kill_process( process, NULL, 1 );
383 if (errno != EWOULDBLOCK && errno != EAGAIN)
385 fprintf( stderr, "Protocol error: process %p: ", process );
387 kill_process( process, NULL, 1 );
393 /* send an fd to a client */
394 int send_client_fd( struct process *process, int fd, obj_handle_t handle )
399 fprintf( stderr, "%04x: *fd* %p -> %d\n",
400 current ? current->id : process->id, handle, fd );
402 #ifdef HAVE_MSGHDR_ACCRIGHTS
403 msghdr.msg_accrightslen = sizeof(fd);
404 msghdr.msg_accrights = (void *)&fd;
405 #else /* HAVE_MSGHDR_ACCRIGHTS */
406 msghdr.msg_control = &cmsg;
407 msghdr.msg_controllen = sizeof(cmsg);
409 #endif /* HAVE_MSGHDR_ACCRIGHTS */
411 myiovec.iov_base = (void *)&handle;
412 myiovec.iov_len = sizeof(handle);
414 ret = sendmsg( process->obj.fd, &msghdr, 0 );
416 if (ret == sizeof(handle)) return 0;
420 fprintf( stderr, "Protocol error: process %p: partial sendmsg %d\n", process, ret );
421 kill_process( process, NULL, 1 );
423 else if (errno == EPIPE)
425 kill_process( process, NULL, 0 );
429 fprintf( stderr, "Protocol error: process %p: ", process );
431 kill_process( process, NULL, 1 );
436 /* get current tick count to return to client */
437 unsigned int get_tick_count(void)
440 gettimeofday( &t, NULL );
441 return (t.tv_sec * 1000) + (t.tv_usec / 1000) - server_start_ticks;
444 static void master_socket_dump( struct object *obj, int verbose )
446 struct master_socket *sock = (struct master_socket *)obj;
447 assert( obj->ops == &master_socket_ops );
448 fprintf( stderr, "Master socket fd=%p\n", sock->obj.fd_obj );
451 /* handle a socket event */
452 static void master_socket_poll_event( struct fd *fd, int event )
454 struct master_socket *sock = get_fd_user( fd );
455 assert( master_socket->obj.ops == &master_socket_ops );
457 assert( sock == master_socket ); /* there is only one master socket */
459 if (event & (POLLERR | POLLHUP))
461 /* this is not supposed to happen */
462 fprintf( stderr, "wineserver: Error on master socket\n" );
463 release_object( sock );
465 else if (event & POLLIN)
467 struct sockaddr_un dummy;
468 int len = sizeof(dummy);
469 int client = accept( master_socket->obj.fd, (struct sockaddr *) &dummy, &len );
470 if (client == -1) return;
473 remove_timeout_user( sock->timeout );
474 sock->timeout = NULL;
476 fcntl( client, F_SETFL, O_NONBLOCK );
477 create_process( client );
481 /* remove the socket upon exit */
482 static void socket_cleanup(void)
484 static int do_it_once;
485 if (!do_it_once++) unlink( server_socket_name );
488 /* create a directory and check its permissions */
489 static void create_dir( const char *name, struct stat *st )
491 if (lstat( name, st ) == -1)
493 if (errno != ENOENT) fatal_perror( "lstat %s", name );
494 if (mkdir( name, 0700 ) == -1) fatal_perror( "mkdir %s", name );
495 if (lstat( name, st ) == -1) fatal_perror( "lstat %s", name );
497 if (!S_ISDIR(st->st_mode)) fatal_error( "%s is not a directory\n", name );
498 if (st->st_uid != getuid()) fatal_error( "%s is not owned by you\n", name );
499 if (st->st_mode & 077) fatal_error( "%s must not be accessible by other users\n", name );
502 /* create the server directory and chdir to it */
503 static void create_server_dir(void)
505 char *p, *server_dir;
508 if (!(server_dir = strdup( wine_get_server_dir() ))) fatal_error( "out of memory\n" );
510 /* first create the base directory if needed */
512 p = strrchr( server_dir, '/' );
514 create_dir( server_dir, &st );
516 /* now create the server directory */
519 create_dir( server_dir, &st );
521 if (chdir( server_dir ) == -1) fatal_perror( "chdir %s", server_dir );
522 if (stat( ".", &st2 ) == -1) fatal_perror( "stat %s", server_dir );
523 if (st.st_dev != st2.st_dev || st.st_ino != st2.st_ino)
524 fatal_error( "chdir did not end up in %s\n", server_dir );
529 /* create the lock file and return its file descriptor */
530 static int create_server_lock(void)
535 if (lstat( server_lock_name, &st ) == -1)
538 fatal_perror( "lstat %s/%s", wine_get_server_dir(), server_lock_name );
542 if (!S_ISREG(st.st_mode))
543 fatal_error( "%s/%s is not a regular file\n", wine_get_server_dir(), server_lock_name );
546 if ((fd = open( server_lock_name, O_CREAT|O_TRUNC|O_WRONLY, 0600 )) == -1)
547 fatal_perror( "error creating %s/%s", wine_get_server_dir(), server_lock_name );
551 /* wait for the server lock */
552 int wait_for_lock(void)
558 fd = create_server_lock();
561 fl.l_whence = SEEK_SET;
564 r = fcntl( fd, F_SETLKW, &fl );
570 /* kill the wine server holding the lock */
571 int kill_lock_owner( int sig )
578 fd = create_server_lock();
580 for (i = 0; i < 10; i++)
583 fl.l_whence = SEEK_SET;
586 if (fcntl( fd, F_GETLK, &fl ) == -1) goto done;
587 if (fl.l_type != F_WRLCK) goto done; /* the file is not locked */
588 if (!pid) /* first time around */
590 if (!(pid = fl.l_pid)) goto done; /* shouldn't happen */
593 if (kill( pid, SIGINT ) == -1) goto done;
594 kill( pid, SIGCONT );
597 else /* just send the specified signal and return */
599 ret = (kill( pid, sig ) != -1);
603 else if (fl.l_pid != pid) goto done; /* no longer the same process */
606 /* waited long enough, now kill it */
607 kill( pid, SIGKILL );
614 /* acquire the main server lock */
615 static void acquire_lock(void)
617 struct sockaddr_un addr;
620 int fd, slen, got_lock = 0;
622 fd = create_server_lock();
625 fl.l_whence = SEEK_SET;
628 if (fcntl( fd, F_SETLK, &fl ) != -1)
630 /* check for crashed server */
631 if (stat( server_socket_name, &st ) != -1 && /* there is a leftover socket */
632 stat( "core", &st ) != -1 && st.st_size) /* and there is a non-empty core file */
635 "Warning: a previous instance of the wine server seems to have crashed.\n"
636 "Please run 'gdb %s %s/core',\n"
637 "type 'backtrace' at the gdb prompt and report the results. Thanks.\n\n",
638 server_argv0, wine_get_server_dir() );
640 unlink( server_socket_name ); /* we got the lock, we can safely remove the socket */
642 /* in that case we reuse fd without closing it, this ensures
643 * that we hold the lock until the process exits */
652 /* check whether locks work at all on this file system */
653 if (fcntl( fd, F_GETLK, &fl ) == -1) break;
656 exit(2); /* we didn't get the lock, exit with special status */
658 fatal_perror( "fcntl %s/%s", wine_get_server_dir(), server_lock_name );
660 /* it seems we can't use locks on this fs, so we will use the socket existence as lock */
664 if ((fd = socket( AF_UNIX, SOCK_STREAM, 0 )) == -1) fatal_perror( "socket" );
665 addr.sun_family = AF_UNIX;
666 strcpy( addr.sun_path, server_socket_name );
667 slen = sizeof(addr) - sizeof(addr.sun_path) + strlen(addr.sun_path) + 1;
668 #ifdef HAVE_SOCKADDR_SUN_LEN
671 if (bind( fd, (struct sockaddr *)&addr, slen ) == -1)
673 if ((errno == EEXIST) || (errno == EADDRINUSE))
676 fatal_error( "couldn't bind to the socket even though we hold the lock\n" );
677 exit(2); /* we didn't get the lock, exit with special status */
679 fatal_perror( "bind" );
681 atexit( socket_cleanup );
682 chmod( server_socket_name, 0600 ); /* make sure no other user can connect */
683 if (listen( fd, 5 ) == -1) fatal_perror( "listen" );
685 if (!(master_socket = alloc_fd_object( &master_socket_ops, &master_socket_fd_ops, fd )))
686 fatal_error( "out of memory\n" );
687 master_socket->timeout = NULL;
688 set_select_events( &master_socket->obj, POLLIN );
691 /* open the master server socket and start waiting for new clients */
692 void open_master_socket(void)
694 int pid, status, sync_pipe[2];
697 /* make sure no request is larger than the maximum size */
698 assert( sizeof(union generic_request) == sizeof(struct request_max_size) );
699 assert( sizeof(union generic_reply) == sizeof(struct request_max_size) );
702 if (pipe( sync_pipe ) == -1) fatal_perror( "pipe" );
709 close( sync_pipe[0] );
714 write( sync_pipe[1], &dummy, 1 );
715 close( sync_pipe[1] );
719 fatal_perror( "fork" );
722 default: /* parent */
723 close( sync_pipe[1] );
725 /* wait for child to signal us and then exit */
726 if (read( sync_pipe[0], &dummy, 1 ) == 1) _exit(0);
728 /* child terminated, propagate exit status */
729 wait4( pid, &status, 0, NULL );
730 if (WIFEXITED(status)) _exit( WEXITSTATUS(status) );
734 /* setup msghdr structure constant fields */
735 msghdr.msg_name = NULL;
736 msghdr.msg_namelen = 0;
737 msghdr.msg_iov = &myiovec;
738 msghdr.msg_iovlen = 1;
740 /* init startup ticks */
741 server_start_ticks = get_tick_count();
744 /* master socket timer expiration handler */
745 static void close_socket_timeout( void *arg )
747 master_socket->timeout = NULL;
750 /* if a new client is waiting, we keep on running */
751 if (check_fd_events( master_socket->obj.fd_obj, POLLIN )) return;
753 if (debug_level) fprintf( stderr, "wineserver: exiting (pid=%ld)\n", (long) getpid() );
756 /* shut down everything properly */
757 release_object( master_socket );
758 close_global_hooks();
759 close_global_handles();
767 /* close the master socket and stop waiting for new clients */
768 void close_master_socket(void)
772 if (master_socket_timeout == -1) return; /* just keep running forever */
774 if (master_socket_timeout)
776 gettimeofday( &when, 0 );
777 add_timeout( &when, master_socket_timeout * 1000 );
778 master_socket->timeout = add_timeout_user( &when, close_socket_timeout, NULL );
780 else close_socket_timeout( NULL ); /* close it right away */
783 /* lock/unlock the master socket to stop accepting new clients */
784 void lock_master_socket( int locked )
786 set_select_events( &master_socket->obj, locked ? 0 : POLLIN );