msvcrt: Share lconv data between threadlocinfo instances.
[wine.git] / server / request.c
blob97bf1a746d23563dce1e9f23b91155f7f0750cce
1 /*
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
21 #include "config.h"
22 #include "wine/port.h"
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 #ifdef __APPLE__
55 # include <mach/mach_time.h>
56 #endif
58 #include "ntstatus.h"
59 #define WIN32_NO_STATUS
60 #include "windef.h"
61 #include "winbase.h"
62 #include "wincon.h"
63 #include "winternl.h"
65 #include "file.h"
66 #include "process.h"
67 #include "thread.h"
68 #include "security.h"
69 #define WANT_REQUEST_HANDLERS
70 #include "request.h"
72 /* Some versions of glibc don't define this */
73 #ifndef SCM_RIGHTS
74 #define SCM_RIGHTS 1
75 #endif
77 /* path names for server master Unix socket */
78 static const char * const server_socket_name = "socket"; /* name of the socket file */
79 static const char * const server_lock_name = "lock"; /* name of the server lock file */
81 struct master_socket
83 struct object obj; /* object header */
84 struct fd *fd; /* file descriptor of the master socket */
87 static void master_socket_dump( struct object *obj, int verbose );
88 static void master_socket_destroy( struct object *obj );
89 static void master_socket_poll_event( struct fd *fd, int event );
91 static const struct object_ops master_socket_ops =
93 sizeof(struct master_socket), /* size */
94 master_socket_dump, /* dump */
95 no_get_type, /* get_type */
96 no_add_queue, /* add_queue */
97 NULL, /* remove_queue */
98 NULL, /* signaled */
99 NULL, /* satisfied */
100 no_signal, /* signal */
101 no_get_fd, /* get_fd */
102 no_map_access, /* map_access */
103 default_get_sd, /* get_sd */
104 default_set_sd, /* set_sd */
105 no_get_full_name, /* get_full_name */
106 no_lookup_name, /* lookup_name */
107 no_link_name, /* link_name */
108 NULL, /* unlink_name */
109 no_open_file, /* open_file */
110 no_kernel_obj_list, /* get_kernel_obj_list */
111 no_close_handle, /* close_handle */
112 master_socket_destroy /* destroy */
115 static const struct fd_ops master_socket_fd_ops =
117 NULL, /* get_poll_events */
118 master_socket_poll_event, /* poll_event */
119 NULL, /* flush */
120 NULL, /* get_fd_type */
121 NULL, /* ioctl */
122 NULL, /* queue_async */
123 NULL /* reselect_async */
127 struct thread *current = NULL; /* thread handling the current request */
128 unsigned int global_error = 0; /* global error code for when no thread is current */
129 timeout_t server_start_time = 0; /* server startup time */
130 char *server_dir = NULL; /* server directory */
131 int server_dir_fd = -1; /* file descriptor for the server dir */
132 int config_dir_fd = -1; /* file descriptor for the config dir */
134 static struct master_socket *master_socket; /* the master socket object */
135 static struct timeout_user *master_timeout;
137 /* complain about a protocol error and terminate the client connection */
138 void fatal_protocol_error( struct thread *thread, const char *err, ... )
140 va_list args;
142 va_start( args, err );
143 fprintf( stderr, "Protocol error:%04x: ", thread->id );
144 vfprintf( stderr, err, args );
145 va_end( args );
146 thread->exit_code = 1;
147 kill_thread( thread, 1 );
150 /* die on a fatal error */
151 void fatal_error( const char *err, ... )
153 va_list args;
155 va_start( args, err );
156 fprintf( stderr, "wineserver: " );
157 vfprintf( stderr, err, args );
158 va_end( args );
159 exit(1);
162 /* allocate the reply data */
163 void *set_reply_data_size( data_size_t size )
165 assert( size <= get_reply_max_size() );
166 if (size && !(current->reply_data = mem_alloc( size ))) size = 0;
167 current->reply_size = size;
168 return current->reply_data;
171 static const struct object_attributes empty_attributes;
173 /* return object attributes from the current request */
174 const struct object_attributes *get_req_object_attributes( const struct security_descriptor **sd,
175 struct unicode_str *name,
176 struct object **root )
178 const struct object_attributes *attr = get_req_data();
179 data_size_t size = get_req_data_size();
181 if (root) *root = NULL;
183 if (!size)
185 *sd = NULL;
186 name->len = 0;
187 return &empty_attributes;
190 if ((size < sizeof(*attr)) || (size - sizeof(*attr) < attr->sd_len) ||
191 (size - sizeof(*attr) - attr->sd_len < attr->name_len))
193 set_error( STATUS_ACCESS_VIOLATION );
194 return NULL;
196 if (attr->sd_len && !sd_is_valid( (const struct security_descriptor *)(attr + 1), attr->sd_len ))
198 set_error( STATUS_INVALID_SECURITY_DESCR );
199 return NULL;
201 if ((attr->name_len & (sizeof(WCHAR) - 1)) || attr->name_len >= 65534)
203 set_error( STATUS_OBJECT_NAME_INVALID );
204 return NULL;
206 if (root && attr->rootdir && attr->name_len)
208 if (!(*root = get_directory_obj( current->process, attr->rootdir ))) return NULL;
210 *sd = attr->sd_len ? (const struct security_descriptor *)(attr + 1) : NULL;
211 name->len = attr->name_len;
212 name->str = (const WCHAR *)(attr + 1) + attr->sd_len / sizeof(WCHAR);
213 return attr;
216 /* return a pointer to the request data following an object attributes structure */
217 const void *get_req_data_after_objattr( const struct object_attributes *attr, data_size_t *len )
219 data_size_t size = (sizeof(*attr) + (attr->sd_len & ~1) + (attr->name_len & ~1) + 3) & ~3;
221 if (attr == &empty_attributes || size >= get_req_data_size())
223 *len = 0;
224 return NULL;
226 *len = get_req_data_size() - size;
227 return (const char *)get_req_data() + size;
230 /* write the remaining part of the reply */
231 void write_reply( struct thread *thread )
233 int ret;
235 if ((ret = write( get_unix_fd( thread->reply_fd ),
236 (char *)thread->reply_data + thread->reply_size - thread->reply_towrite,
237 thread->reply_towrite )) >= 0)
239 if (!(thread->reply_towrite -= ret))
241 free( thread->reply_data );
242 thread->reply_data = NULL;
243 /* sent everything, can go back to waiting for requests */
244 set_fd_events( thread->request_fd, POLLIN );
245 set_fd_events( thread->reply_fd, 0 );
247 return;
249 if (errno == EPIPE)
250 kill_thread( thread, 0 ); /* normal death */
251 else if (errno != EWOULDBLOCK && (EWOULDBLOCK == EAGAIN || errno != EAGAIN))
252 fatal_protocol_error( thread, "reply write: %s\n", strerror( errno ));
255 /* send a reply to the current thread */
256 static void send_reply( union generic_reply *reply )
258 int ret;
260 if (!current->reply_size)
262 if ((ret = write( get_unix_fd( current->reply_fd ),
263 reply, sizeof(*reply) )) != sizeof(*reply)) goto error;
265 else
267 struct iovec vec[2];
269 vec[0].iov_base = (void *)reply;
270 vec[0].iov_len = sizeof(*reply);
271 vec[1].iov_base = current->reply_data;
272 vec[1].iov_len = current->reply_size;
274 if ((ret = writev( get_unix_fd( current->reply_fd ), vec, 2 )) < sizeof(*reply)) goto error;
276 if ((current->reply_towrite = current->reply_size - (ret - sizeof(*reply))))
278 /* couldn't write it all, wait for POLLOUT */
279 set_fd_events( current->reply_fd, POLLOUT );
280 set_fd_events( current->request_fd, 0 );
281 return;
284 free( current->reply_data );
285 current->reply_data = NULL;
286 return;
288 error:
289 if (ret >= 0)
290 fatal_protocol_error( current, "partial write %d\n", ret );
291 else if (errno == EPIPE)
292 kill_thread( current, 0 ); /* normal death */
293 else
294 fatal_protocol_error( current, "reply write: %s\n", strerror( errno ));
297 /* call a request handler */
298 static void call_req_handler( struct thread *thread )
300 union generic_reply reply;
301 enum request req = thread->req.request_header.req;
303 current = thread;
304 current->reply_size = 0;
305 clear_error();
306 memset( &reply, 0, sizeof(reply) );
308 if (debug_level) trace_request();
310 if (req < REQ_NB_REQUESTS)
311 req_handlers[req]( &current->req, &reply );
312 else
313 set_error( STATUS_NOT_IMPLEMENTED );
315 if (current)
317 if (current->reply_fd)
319 reply.reply_header.error = current->error;
320 reply.reply_header.reply_size = current->reply_size;
321 if (debug_level) trace_reply( req, &reply );
322 send_reply( &reply );
324 else
326 current->exit_code = 1;
327 kill_thread( current, 1 ); /* no way to continue without reply fd */
330 current = NULL;
333 /* read a request from a thread */
334 void read_request( struct thread *thread )
336 int ret;
338 if (!thread->req_toread) /* no pending request */
340 if ((ret = read( get_unix_fd( thread->request_fd ), &thread->req,
341 sizeof(thread->req) )) != sizeof(thread->req)) goto error;
342 if (!(thread->req_toread = thread->req.request_header.request_size))
344 /* no data, handle request at once */
345 call_req_handler( thread );
346 return;
348 if (!(thread->req_data = malloc( thread->req_toread )))
350 fatal_protocol_error( thread, "no memory for %u bytes request %d\n",
351 thread->req_toread, thread->req.request_header.req );
352 return;
356 /* read the variable sized data */
357 for (;;)
359 ret = read( get_unix_fd( thread->request_fd ),
360 (char *)thread->req_data + thread->req.request_header.request_size
361 - thread->req_toread,
362 thread->req_toread );
363 if (ret <= 0) break;
364 if (!(thread->req_toread -= ret))
366 call_req_handler( thread );
367 free( thread->req_data );
368 thread->req_data = NULL;
369 return;
373 error:
374 if (!ret) /* closed pipe */
375 kill_thread( thread, 0 );
376 else if (ret > 0)
377 fatal_protocol_error( thread, "partial read %d\n", ret );
378 else if (errno != EWOULDBLOCK && (EWOULDBLOCK == EAGAIN || errno != EAGAIN))
379 fatal_protocol_error( thread, "read: %s\n", strerror( errno ));
382 /* receive a file descriptor on the process socket */
383 int receive_fd( struct process *process )
385 struct iovec vec;
386 struct send_fd data;
387 struct msghdr msghdr;
388 int fd = -1, ret;
390 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
391 msghdr.msg_accrightslen = sizeof(int);
392 msghdr.msg_accrights = (void *)&fd;
393 #else /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
394 char cmsg_buffer[256];
395 msghdr.msg_control = cmsg_buffer;
396 msghdr.msg_controllen = sizeof(cmsg_buffer);
397 msghdr.msg_flags = 0;
398 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
400 msghdr.msg_name = NULL;
401 msghdr.msg_namelen = 0;
402 msghdr.msg_iov = &vec;
403 msghdr.msg_iovlen = 1;
404 vec.iov_base = (void *)&data;
405 vec.iov_len = sizeof(data);
407 ret = recvmsg( get_unix_fd( process->msg_fd ), &msghdr, 0 );
409 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
410 if (ret > 0)
412 struct cmsghdr *cmsg;
413 for (cmsg = CMSG_FIRSTHDR( &msghdr ); cmsg; cmsg = CMSG_NXTHDR( &msghdr, cmsg ))
415 if (cmsg->cmsg_level != SOL_SOCKET) continue;
416 if (cmsg->cmsg_type == SCM_RIGHTS) fd = *(int *)CMSG_DATA(cmsg);
419 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
421 if (ret == sizeof(data))
423 struct thread *thread;
425 if (data.tid) thread = get_thread_from_id( data.tid );
426 else thread = (struct thread *)grab_object( get_process_first_thread( process ));
428 if (!thread || thread->process != process || thread->state == TERMINATED)
430 if (debug_level)
431 fprintf( stderr, "%04x: *fd* %d <- %d bad thread id\n",
432 data.tid, data.fd, fd );
433 close( fd );
435 else
437 if (debug_level)
438 fprintf( stderr, "%04x: *fd* %d <- %d\n",
439 thread->id, data.fd, fd );
440 thread_add_inflight_fd( thread, data.fd, fd );
442 if (thread) release_object( thread );
443 return 0;
446 if (!ret)
448 kill_process( process, 0 );
450 else if (ret > 0)
452 fprintf( stderr, "Protocol error: process %04x: partial recvmsg %d for fd\n",
453 process->id, ret );
454 if (fd != -1) close( fd );
455 kill_process( process, 1 );
457 else
459 if (errno != EWOULDBLOCK && (EWOULDBLOCK == EAGAIN || errno != EAGAIN))
461 fprintf( stderr, "Protocol error: process %04x: ", process->id );
462 perror( "recvmsg" );
463 kill_process( process, 1 );
466 return -1;
469 /* send an fd to a client */
470 int send_client_fd( struct process *process, int fd, obj_handle_t handle )
472 struct iovec vec;
473 struct msghdr msghdr;
474 int ret;
476 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
477 msghdr.msg_accrightslen = sizeof(fd);
478 msghdr.msg_accrights = (void *)&fd;
479 #else /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
480 char cmsg_buffer[256];
481 struct cmsghdr *cmsg;
482 msghdr.msg_control = cmsg_buffer;
483 msghdr.msg_controllen = sizeof(cmsg_buffer);
484 msghdr.msg_flags = 0;
485 cmsg = CMSG_FIRSTHDR( &msghdr );
486 cmsg->cmsg_len = CMSG_LEN( sizeof(fd) );
487 cmsg->cmsg_level = SOL_SOCKET;
488 cmsg->cmsg_type = SCM_RIGHTS;
489 *(int *)CMSG_DATA(cmsg) = fd;
490 msghdr.msg_controllen = cmsg->cmsg_len;
491 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
493 msghdr.msg_name = NULL;
494 msghdr.msg_namelen = 0;
495 msghdr.msg_iov = &vec;
496 msghdr.msg_iovlen = 1;
498 vec.iov_base = (void *)&handle;
499 vec.iov_len = sizeof(handle);
501 if (debug_level)
502 fprintf( stderr, "%04x: *fd* %04x -> %d\n", current ? current->id : process->id, handle, fd );
504 ret = sendmsg( get_unix_fd( process->msg_fd ), &msghdr, 0 );
506 if (ret == sizeof(handle)) return 0;
508 if (ret >= 0)
510 fprintf( stderr, "Protocol error: process %04x: partial sendmsg %d\n", process->id, ret );
511 kill_process( process, 1 );
513 else if (errno == EPIPE)
515 kill_process( process, 0 );
517 else
519 fprintf( stderr, "Protocol error: process %04x: ", process->id );
520 perror( "sendmsg" );
521 kill_process( process, 1 );
523 return -1;
526 /* return a monotonic time counter */
527 timeout_t monotonic_counter(void)
529 #ifdef __APPLE__
530 static mach_timebase_info_data_t timebase;
532 if (!timebase.denom) mach_timebase_info( &timebase );
533 #ifdef HAVE_MACH_CONTINUOUS_TIME
534 if (&mach_continuous_time != NULL)
535 return mach_continuous_time() * timebase.numer / timebase.denom / 100;
536 #endif
537 return mach_absolute_time() * timebase.numer / timebase.denom / 100;
538 #elif defined(HAVE_CLOCK_GETTIME)
539 struct timespec ts;
540 #ifdef CLOCK_MONOTONIC_RAW
541 if (!clock_gettime( CLOCK_MONOTONIC_RAW, &ts ))
542 return (timeout_t)ts.tv_sec * TICKS_PER_SEC + ts.tv_nsec / 100;
543 #endif
544 if (!clock_gettime( CLOCK_MONOTONIC, &ts ))
545 return (timeout_t)ts.tv_sec * TICKS_PER_SEC + ts.tv_nsec / 100;
546 #endif
547 return current_time - server_start_time;
550 static void master_socket_dump( struct object *obj, int verbose )
552 struct master_socket *sock = (struct master_socket *)obj;
553 assert( obj->ops == &master_socket_ops );
554 fprintf( stderr, "Master socket fd=%p\n", sock->fd );
557 static void master_socket_destroy( struct object *obj )
559 struct master_socket *sock = (struct master_socket *)obj;
560 assert( obj->ops == &master_socket_ops );
561 release_object( sock->fd );
564 /* handle a socket event */
565 static void master_socket_poll_event( struct fd *fd, int event )
567 struct master_socket *sock = get_fd_user( fd );
568 assert( master_socket->obj.ops == &master_socket_ops );
570 assert( sock == master_socket ); /* there is only one master socket */
572 if (event & (POLLERR | POLLHUP))
574 /* this is not supposed to happen */
575 fprintf( stderr, "wineserver: Error on master socket\n" );
576 set_fd_events( sock->fd, -1 );
578 else if (event & POLLIN)
580 struct process *process;
581 struct sockaddr_un dummy;
582 socklen_t len = sizeof(dummy);
583 int client = accept( get_unix_fd( master_socket->fd ), (struct sockaddr *) &dummy, &len );
584 if (client == -1) return;
585 fcntl( client, F_SETFL, O_NONBLOCK );
586 if ((process = create_process( client, NULL, 0, NULL, NULL, NULL, 0, NULL )))
588 create_thread( -1, process, NULL );
589 release_object( process );
594 /* remove the socket upon exit */
595 static void socket_cleanup(void)
597 static int do_it_once;
598 if (!do_it_once++) unlink( server_socket_name );
601 /* create a directory and check its permissions */
602 static void create_dir( const char *name, struct stat *st )
604 if (lstat( name, st ) == -1)
606 if (errno != ENOENT)
607 fatal_error( "lstat %s: %s\n", name, strerror( errno ));
608 if (mkdir( name, 0700 ) == -1 && errno != EEXIST)
609 fatal_error( "mkdir %s: %s\n", name, strerror( errno ));
610 if (lstat( name, st ) == -1)
611 fatal_error( "lstat %s: %s\n", name, strerror( errno ));
613 if (!S_ISDIR(st->st_mode)) fatal_error( "%s is not a directory\n", name );
614 if (st->st_uid != getuid()) fatal_error( "%s is not owned by you\n", name );
615 if (st->st_mode & 077) fatal_error( "%s must not be accessible by other users\n", name );
618 /* create the server directory and chdir to it */
619 static char *create_server_dir( int force )
621 const char *prefix = getenv( "WINEPREFIX" );
622 char *p, *config_dir;
623 struct stat st, st2;
624 size_t len = sizeof("/server-") + 2 * sizeof(st.st_dev) + 2 * sizeof(st.st_ino) + 2;
626 /* open the configuration directory */
628 if (prefix)
630 if (!(config_dir = strdup( prefix ))) fatal_error( "out of memory\n" );
631 for (p = config_dir + strlen(config_dir); p > config_dir; p--) if (p[-1] != '/') break;
632 if (p > config_dir) *p = 0;
633 if (config_dir[0] != '/')
634 fatal_error( "invalid directory %s in WINEPREFIX: not an absolute path\n", prefix );
636 else
638 const char *home = getenv( "HOME" );
639 if (!home)
641 struct passwd *pwd = getpwuid( getuid() );
642 if (pwd) home = pwd->pw_dir;
644 if (!home) fatal_error( "could not determine your home directory\n" );
645 if (home[0] != '/') fatal_error( "your home directory %s is not an absolute path\n", home );
646 if (!(config_dir = malloc( strlen(home) + sizeof("/.wine") ))) fatal_error( "out of memory\n" );
647 strcpy( config_dir, home );
648 for (p = config_dir + strlen(config_dir); p > config_dir; p--) if (p[-1] != '/') break;
649 strcpy( p, "/.wine" );
652 if (chdir( config_dir ) == -1)
654 if (errno != ENOENT || force) fatal_error( "chdir to %s: %s\n", config_dir, strerror( errno ));
655 return NULL;
657 if ((config_dir_fd = open( ".", O_RDONLY )) == -1)
658 fatal_error( "open %s: %s\n", config_dir, strerror( errno ));
659 if (fstat( config_dir_fd, &st ) == -1)
660 fatal_error( "stat %s: %s\n", config_dir, strerror( errno ));
661 if (st.st_uid != getuid())
662 fatal_error( "%s is not owned by you\n", config_dir );
664 /* create the base directory if needed */
666 #ifdef __ANDROID__ /* there's no /tmp dir on Android */
667 len += strlen( config_dir ) + sizeof("/.wineserver");
668 if (!(server_dir = malloc( len ))) fatal_error( "out of memory\n" );
669 strcpy( server_dir, config_dir );
670 strcat( server_dir, "/.wineserver" );
671 #else
672 len += sizeof("/tmp/.wine-") + 12;
673 if (!(server_dir = malloc( len ))) fatal_error( "out of memory\n" );
674 sprintf( server_dir, "/tmp/.wine-%u", getuid() );
675 #endif
676 create_dir( server_dir, &st2 );
678 /* now create the server directory */
680 strcat( server_dir, "/server-" );
681 p = server_dir + strlen(server_dir);
683 if (st.st_dev != (unsigned long)st.st_dev)
684 p += sprintf( p, "%lx%08lx-", (unsigned long)((unsigned long long)st.st_dev >> 32),
685 (unsigned long)st.st_dev );
686 else
687 p += sprintf( p, "%lx-", (unsigned long)st.st_dev );
689 if (st.st_ino != (unsigned long)st.st_ino)
690 sprintf( p, "%lx%08lx", (unsigned long)((unsigned long long)st.st_ino >> 32),
691 (unsigned long)st.st_ino );
692 else
693 sprintf( p, "%lx", (unsigned long)st.st_ino );
695 create_dir( server_dir, &st );
697 if (chdir( server_dir ) == -1)
698 fatal_error( "chdir %s: %s\n", server_dir, strerror( errno ));
699 if ((server_dir_fd = open( ".", O_RDONLY )) == -1)
700 fatal_error( "open %s: %s\n", server_dir, strerror( errno ));
701 if (fstat( server_dir_fd, &st2 ) == -1)
702 fatal_error( "stat %s: %s\n", server_dir, strerror( errno ));
703 if (st.st_dev != st2.st_dev || st.st_ino != st2.st_ino)
704 fatal_error( "chdir did not end up in %s\n", server_dir );
706 free( config_dir );
707 return server_dir;
710 /* create the lock file and return its file descriptor */
711 static int create_server_lock(void)
713 struct stat st;
714 int fd;
716 if (lstat( server_lock_name, &st ) == -1)
718 if (errno != ENOENT)
719 fatal_error( "lstat %s/%s: %s\n", server_dir, server_lock_name, strerror( errno ));
721 else
723 if (!S_ISREG(st.st_mode))
724 fatal_error( "%s/%s is not a regular file\n", server_dir, server_lock_name );
727 if ((fd = open( server_lock_name, O_CREAT|O_TRUNC|O_WRONLY, 0600 )) == -1)
728 fatal_error( "error creating %s/%s: %s\n", server_dir, server_lock_name, strerror( errno ));
729 return fd;
732 /* wait for the server lock */
733 int wait_for_lock(void)
735 int fd, r;
736 struct flock fl;
738 server_dir = create_server_dir( 0 );
739 if (!server_dir) return 0; /* no server dir, so no lock to wait on */
741 fd = create_server_lock();
743 fl.l_type = F_WRLCK;
744 fl.l_whence = SEEK_SET;
745 fl.l_start = 0;
746 fl.l_len = 1;
747 r = fcntl( fd, F_SETLKW, &fl );
748 close(fd);
750 return r;
753 /* kill the wine server holding the lock */
754 int kill_lock_owner( int sig )
756 int fd, i, ret = 0;
757 pid_t pid = 0;
758 struct flock fl;
760 server_dir = create_server_dir( 0 );
761 if (!server_dir) return 0; /* no server dir, nothing to do */
763 fd = create_server_lock();
765 for (i = 1; i <= 20; i++)
767 fl.l_type = F_WRLCK;
768 fl.l_whence = SEEK_SET;
769 fl.l_start = 0;
770 fl.l_len = 1;
771 if (fcntl( fd, F_GETLK, &fl ) == -1) goto done;
772 if (fl.l_type != F_WRLCK) goto done; /* the file is not locked */
773 if (!pid) /* first time around */
775 if (!(pid = fl.l_pid)) goto done; /* shouldn't happen */
776 if (sig == -1)
778 if (kill( pid, SIGINT ) == -1) goto done;
779 kill( pid, SIGCONT );
780 ret = 1;
782 else /* just send the specified signal and return */
784 ret = (kill( pid, sig ) != -1);
785 goto done;
788 else if (fl.l_pid != pid) goto done; /* no longer the same process */
789 usleep( 50000 * i );
791 /* waited long enough, now kill it */
792 kill( pid, SIGKILL );
794 done:
795 close( fd );
796 return ret;
799 /* acquire the main server lock */
800 static void acquire_lock(void)
802 struct sockaddr_un addr;
803 struct stat st;
804 struct flock fl;
805 int fd, slen, got_lock = 0;
807 fd = create_server_lock();
809 fl.l_type = F_WRLCK;
810 fl.l_whence = SEEK_SET;
811 fl.l_start = 0;
812 fl.l_len = 1;
813 if (fcntl( fd, F_SETLK, &fl ) != -1)
815 /* check for crashed server */
816 if (stat( server_socket_name, &st ) != -1 && /* there is a leftover socket */
817 stat( "core", &st ) != -1 && st.st_size) /* and there is a non-empty core file */
819 fprintf( stderr,
820 "Warning: a previous instance of the wine server seems to have crashed.\n"
821 "Please run 'gdb %s %s/core',\n"
822 "type 'backtrace' at the gdb prompt and report the results. Thanks.\n\n",
823 server_argv0, server_dir );
825 unlink( server_socket_name ); /* we got the lock, we can safely remove the socket */
826 got_lock = 1;
827 /* in that case we reuse fd without closing it, this ensures
828 * that we hold the lock until the process exits */
830 else
832 switch(errno)
834 case ENOLCK:
835 break;
836 case EACCES:
837 /* check whether locks work at all on this file system */
838 if (fcntl( fd, F_GETLK, &fl ) == -1) break;
839 /* fall through */
840 case EAGAIN:
841 exit(2); /* we didn't get the lock, exit with special status */
842 default:
843 fatal_error( "fcntl %s/%s: %s\n", server_dir, server_lock_name, strerror( errno ));
845 /* it seems we can't use locks on this fs, so we will use the socket existence as lock */
846 close( fd );
849 if ((fd = socket( AF_UNIX, SOCK_STREAM, 0 )) == -1) fatal_error( "socket: %s\n", strerror( errno ));
850 addr.sun_family = AF_UNIX;
851 strcpy( addr.sun_path, server_socket_name );
852 slen = sizeof(addr) - sizeof(addr.sun_path) + strlen(addr.sun_path) + 1;
853 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
854 addr.sun_len = slen;
855 #endif
856 if (bind( fd, (struct sockaddr *)&addr, slen ) == -1)
858 if ((errno == EEXIST) || (errno == EADDRINUSE))
860 if (got_lock)
861 fatal_error( "couldn't bind to the socket even though we hold the lock\n" );
862 exit(2); /* we didn't get the lock, exit with special status */
864 fatal_error( "bind: %s\n", strerror( errno ));
866 atexit( socket_cleanup );
867 chmod( server_socket_name, 0600 ); /* make sure no other user can connect */
868 if (listen( fd, 5 ) == -1) fatal_error( "listen: %s\n", strerror( errno ));
870 if (!(master_socket = alloc_object( &master_socket_ops )) ||
871 !(master_socket->fd = create_anonymous_fd( &master_socket_fd_ops, fd, &master_socket->obj, 0 )))
872 fatal_error( "out of memory\n" );
873 set_fd_events( master_socket->fd, POLLIN );
874 make_object_permanent( &master_socket->obj );
877 /* open the master server socket and start waiting for new clients */
878 void open_master_socket(void)
880 int fd, pid, status, sync_pipe[2];
881 char dummy;
883 /* make sure no request is larger than the maximum size */
884 assert( sizeof(union generic_request) == sizeof(struct request_max_size) );
885 assert( sizeof(union generic_reply) == sizeof(struct request_max_size) );
887 /* make sure the stdio fds are open */
888 fd = open( "/dev/null", O_RDWR );
889 while (fd >= 0 && fd <= 2) fd = dup( fd );
891 server_dir = create_server_dir( 1 );
893 if (!foreground)
895 if (pipe( sync_pipe ) == -1) fatal_error( "pipe: %s\n", strerror( errno ));
896 pid = fork();
897 switch( pid )
899 case 0: /* child */
900 setsid();
901 close( sync_pipe[0] );
903 acquire_lock();
905 /* close stdin and stdout */
906 dup2( fd, 0 );
907 dup2( fd, 1 );
909 /* signal parent */
910 dummy = 0;
911 write( sync_pipe[1], &dummy, 1 );
912 close( sync_pipe[1] );
913 break;
915 case -1:
916 fatal_error( "fork: %s\n", strerror( errno ));
917 break;
919 default: /* parent */
920 close( sync_pipe[1] );
922 /* wait for child to signal us and then exit */
923 if (read( sync_pipe[0], &dummy, 1 ) == 1) _exit(0);
925 /* child terminated, propagate exit status */
926 waitpid( pid, &status, 0 );
927 if (WIFEXITED(status)) _exit( WEXITSTATUS(status) );
928 _exit(1);
931 else /* remain in the foreground */
933 acquire_lock();
936 /* init the process tracing mechanism */
937 init_tracing_mechanism();
938 close( fd );
941 /* master socket timer expiration handler */
942 static void close_socket_timeout( void *arg )
944 master_timeout = NULL;
945 flush_registry();
946 if (debug_level) fprintf( stderr, "wineserver: exiting (pid=%ld)\n", (long) getpid() );
948 #ifdef DEBUG_OBJECTS
949 close_objects(); /* shut down everything properly */
950 #endif
951 exit( 0 );
954 /* close the master socket and stop waiting for new clients */
955 void close_master_socket( timeout_t timeout )
957 if (master_socket)
959 release_object( master_socket );
960 master_socket = NULL;
962 if (master_timeout) /* cancel previous timeout */
963 remove_timeout_user( master_timeout );
965 master_timeout = add_timeout_user( timeout, close_socket_timeout, NULL );