kernel32: Get rid of the last parameter to PROFILE_CopyEntry().
[wine.git] / server / request.c
blob4c1f30a5fe7c9859a5e93710908c79c136b2534e
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_lookup_name, /* lookup_name */
106 no_link_name, /* link_name */
107 NULL, /* unlink_name */
108 no_open_file, /* open_file */
109 no_kernel_obj_list, /* get_kernel_obj_list */
110 no_close_handle, /* close_handle */
111 master_socket_destroy /* destroy */
114 static const struct fd_ops master_socket_fd_ops =
116 NULL, /* get_poll_events */
117 master_socket_poll_event, /* poll_event */
118 NULL, /* flush */
119 NULL, /* get_fd_type */
120 NULL, /* ioctl */
121 NULL, /* queue_async */
122 NULL /* reselect_async */
126 struct thread *current = NULL; /* thread handling the current request */
127 unsigned int global_error = 0; /* global error code for when no thread is current */
128 timeout_t server_start_time = 0; /* server startup time */
129 char *server_dir = NULL; /* server directory */
130 int server_dir_fd = -1; /* file descriptor for the server dir */
131 int config_dir_fd = -1; /* file descriptor for the config dir */
133 static struct master_socket *master_socket; /* the master socket object */
134 static struct timeout_user *master_timeout;
136 /* complain about a protocol error and terminate the client connection */
137 void fatal_protocol_error( struct thread *thread, const char *err, ... )
139 va_list args;
141 va_start( args, err );
142 fprintf( stderr, "Protocol error:%04x: ", thread->id );
143 vfprintf( stderr, err, args );
144 va_end( args );
145 thread->exit_code = 1;
146 kill_thread( thread, 1 );
149 /* die on a fatal error */
150 void fatal_error( const char *err, ... )
152 va_list args;
154 va_start( args, err );
155 fprintf( stderr, "wineserver: " );
156 vfprintf( stderr, err, args );
157 va_end( args );
158 exit(1);
161 /* allocate the reply data */
162 void *set_reply_data_size( data_size_t size )
164 assert( size <= get_reply_max_size() );
165 if (size && !(current->reply_data = mem_alloc( size ))) size = 0;
166 current->reply_size = size;
167 return current->reply_data;
170 static const struct object_attributes empty_attributes;
172 /* return object attributes from the current request */
173 const struct object_attributes *get_req_object_attributes( const struct security_descriptor **sd,
174 struct unicode_str *name,
175 struct object **root )
177 const struct object_attributes *attr = get_req_data();
178 data_size_t size = get_req_data_size();
180 if (root) *root = NULL;
182 if (!size)
184 *sd = NULL;
185 name->len = 0;
186 return &empty_attributes;
189 if ((size < sizeof(*attr)) || (size - sizeof(*attr) < attr->sd_len) ||
190 (size - sizeof(*attr) - attr->sd_len < attr->name_len))
192 set_error( STATUS_ACCESS_VIOLATION );
193 return NULL;
195 if (attr->sd_len && !sd_is_valid( (const struct security_descriptor *)(attr + 1), attr->sd_len ))
197 set_error( STATUS_INVALID_SECURITY_DESCR );
198 return NULL;
200 if ((attr->name_len & (sizeof(WCHAR) - 1)) || attr->name_len >= 65534)
202 set_error( STATUS_OBJECT_NAME_INVALID );
203 return NULL;
205 if (root && attr->rootdir && attr->name_len)
207 if (!(*root = get_directory_obj( current->process, attr->rootdir ))) return NULL;
209 *sd = attr->sd_len ? (const struct security_descriptor *)(attr + 1) : NULL;
210 name->len = attr->name_len;
211 name->str = (const WCHAR *)(attr + 1) + attr->sd_len / sizeof(WCHAR);
212 return attr;
215 /* return a pointer to the request data following an object attributes structure */
216 const void *get_req_data_after_objattr( const struct object_attributes *attr, data_size_t *len )
218 data_size_t size = (sizeof(*attr) + (attr->sd_len & ~1) + (attr->name_len & ~1) + 3) & ~3;
220 if (attr == &empty_attributes || size >= get_req_data_size())
222 *len = 0;
223 return NULL;
225 *len = get_req_data_size() - size;
226 return (const char *)get_req_data() + size;
229 /* write the remaining part of the reply */
230 void write_reply( struct thread *thread )
232 int ret;
234 if ((ret = write( get_unix_fd( thread->reply_fd ),
235 (char *)thread->reply_data + thread->reply_size - thread->reply_towrite,
236 thread->reply_towrite )) >= 0)
238 if (!(thread->reply_towrite -= ret))
240 free( thread->reply_data );
241 thread->reply_data = NULL;
242 /* sent everything, can go back to waiting for requests */
243 set_fd_events( thread->request_fd, POLLIN );
244 set_fd_events( thread->reply_fd, 0 );
246 return;
248 if (errno == EPIPE)
249 kill_thread( thread, 0 ); /* normal death */
250 else if (errno != EWOULDBLOCK && (EWOULDBLOCK == EAGAIN || errno != EAGAIN))
251 fatal_protocol_error( thread, "reply write: %s\n", strerror( errno ));
254 /* send a reply to the current thread */
255 static void send_reply( union generic_reply *reply )
257 int ret;
259 if (!current->reply_size)
261 if ((ret = write( get_unix_fd( current->reply_fd ),
262 reply, sizeof(*reply) )) != sizeof(*reply)) goto error;
264 else
266 struct iovec vec[2];
268 vec[0].iov_base = (void *)reply;
269 vec[0].iov_len = sizeof(*reply);
270 vec[1].iov_base = current->reply_data;
271 vec[1].iov_len = current->reply_size;
273 if ((ret = writev( get_unix_fd( current->reply_fd ), vec, 2 )) < sizeof(*reply)) goto error;
275 if ((current->reply_towrite = current->reply_size - (ret - sizeof(*reply))))
277 /* couldn't write it all, wait for POLLOUT */
278 set_fd_events( current->reply_fd, POLLOUT );
279 set_fd_events( current->request_fd, 0 );
280 return;
283 free( current->reply_data );
284 current->reply_data = NULL;
285 return;
287 error:
288 if (ret >= 0)
289 fatal_protocol_error( current, "partial write %d\n", ret );
290 else if (errno == EPIPE)
291 kill_thread( current, 0 ); /* normal death */
292 else
293 fatal_protocol_error( current, "reply write: %s\n", strerror( errno ));
296 /* call a request handler */
297 static void call_req_handler( struct thread *thread )
299 union generic_reply reply;
300 enum request req = thread->req.request_header.req;
302 current = thread;
303 current->reply_size = 0;
304 clear_error();
305 memset( &reply, 0, sizeof(reply) );
307 if (debug_level) trace_request();
309 if (req < REQ_NB_REQUESTS)
310 req_handlers[req]( &current->req, &reply );
311 else
312 set_error( STATUS_NOT_IMPLEMENTED );
314 if (current)
316 if (current->reply_fd)
318 reply.reply_header.error = current->error;
319 reply.reply_header.reply_size = current->reply_size;
320 if (debug_level) trace_reply( req, &reply );
321 send_reply( &reply );
323 else
325 current->exit_code = 1;
326 kill_thread( current, 1 ); /* no way to continue without reply fd */
329 current = NULL;
332 /* read a request from a thread */
333 void read_request( struct thread *thread )
335 int ret;
337 if (!thread->req_toread) /* no pending request */
339 if ((ret = read( get_unix_fd( thread->request_fd ), &thread->req,
340 sizeof(thread->req) )) != sizeof(thread->req)) goto error;
341 if (!(thread->req_toread = thread->req.request_header.request_size))
343 /* no data, handle request at once */
344 call_req_handler( thread );
345 return;
347 if (!(thread->req_data = malloc( thread->req_toread )))
349 fatal_protocol_error( thread, "no memory for %u bytes request %d\n",
350 thread->req_toread, thread->req.request_header.req );
351 return;
355 /* read the variable sized data */
356 for (;;)
358 ret = read( get_unix_fd( thread->request_fd ),
359 (char *)thread->req_data + thread->req.request_header.request_size
360 - thread->req_toread,
361 thread->req_toread );
362 if (ret <= 0) break;
363 if (!(thread->req_toread -= ret))
365 call_req_handler( thread );
366 free( thread->req_data );
367 thread->req_data = NULL;
368 return;
372 error:
373 if (!ret) /* closed pipe */
374 kill_thread( thread, 0 );
375 else if (ret > 0)
376 fatal_protocol_error( thread, "partial read %d\n", ret );
377 else if (errno != EWOULDBLOCK && (EWOULDBLOCK == EAGAIN || errno != EAGAIN))
378 fatal_protocol_error( thread, "read: %s\n", strerror( errno ));
381 /* receive a file descriptor on the process socket */
382 int receive_fd( struct process *process )
384 struct iovec vec;
385 struct send_fd data;
386 struct msghdr msghdr;
387 int fd = -1, ret;
389 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
390 msghdr.msg_accrightslen = sizeof(int);
391 msghdr.msg_accrights = (void *)&fd;
392 #else /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
393 char cmsg_buffer[256];
394 msghdr.msg_control = cmsg_buffer;
395 msghdr.msg_controllen = sizeof(cmsg_buffer);
396 msghdr.msg_flags = 0;
397 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
399 msghdr.msg_name = NULL;
400 msghdr.msg_namelen = 0;
401 msghdr.msg_iov = &vec;
402 msghdr.msg_iovlen = 1;
403 vec.iov_base = (void *)&data;
404 vec.iov_len = sizeof(data);
406 ret = recvmsg( get_unix_fd( process->msg_fd ), &msghdr, 0 );
408 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
409 if (ret > 0)
411 struct cmsghdr *cmsg;
412 for (cmsg = CMSG_FIRSTHDR( &msghdr ); cmsg; cmsg = CMSG_NXTHDR( &msghdr, cmsg ))
414 if (cmsg->cmsg_level != SOL_SOCKET) continue;
415 if (cmsg->cmsg_type == SCM_RIGHTS) fd = *(int *)CMSG_DATA(cmsg);
418 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
420 if (ret == sizeof(data))
422 struct thread *thread;
424 if (data.tid) thread = get_thread_from_id( data.tid );
425 else thread = (struct thread *)grab_object( get_process_first_thread( process ));
427 if (!thread || thread->process != process || thread->state == TERMINATED)
429 if (debug_level)
430 fprintf( stderr, "%04x: *fd* %d <- %d bad thread id\n",
431 data.tid, data.fd, fd );
432 close( fd );
434 else
436 if (debug_level)
437 fprintf( stderr, "%04x: *fd* %d <- %d\n",
438 thread->id, data.fd, fd );
439 thread_add_inflight_fd( thread, data.fd, fd );
441 if (thread) release_object( thread );
442 return 0;
445 if (!ret)
447 kill_process( process, 0 );
449 else if (ret > 0)
451 fprintf( stderr, "Protocol error: process %04x: partial recvmsg %d for fd\n",
452 process->id, ret );
453 if (fd != -1) close( fd );
454 kill_process( process, 1 );
456 else
458 if (errno != EWOULDBLOCK && (EWOULDBLOCK == EAGAIN || errno != EAGAIN))
460 fprintf( stderr, "Protocol error: process %04x: ", process->id );
461 perror( "recvmsg" );
462 kill_process( process, 1 );
465 return -1;
468 /* send an fd to a client */
469 int send_client_fd( struct process *process, int fd, obj_handle_t handle )
471 struct iovec vec;
472 struct msghdr msghdr;
473 int ret;
475 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
476 msghdr.msg_accrightslen = sizeof(fd);
477 msghdr.msg_accrights = (void *)&fd;
478 #else /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
479 char cmsg_buffer[256];
480 struct cmsghdr *cmsg;
481 msghdr.msg_control = cmsg_buffer;
482 msghdr.msg_controllen = sizeof(cmsg_buffer);
483 msghdr.msg_flags = 0;
484 cmsg = CMSG_FIRSTHDR( &msghdr );
485 cmsg->cmsg_len = CMSG_LEN( sizeof(fd) );
486 cmsg->cmsg_level = SOL_SOCKET;
487 cmsg->cmsg_type = SCM_RIGHTS;
488 *(int *)CMSG_DATA(cmsg) = fd;
489 msghdr.msg_controllen = cmsg->cmsg_len;
490 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
492 msghdr.msg_name = NULL;
493 msghdr.msg_namelen = 0;
494 msghdr.msg_iov = &vec;
495 msghdr.msg_iovlen = 1;
497 vec.iov_base = (void *)&handle;
498 vec.iov_len = sizeof(handle);
500 if (debug_level)
501 fprintf( stderr, "%04x: *fd* %04x -> %d\n", current ? current->id : process->id, handle, fd );
503 ret = sendmsg( get_unix_fd( process->msg_fd ), &msghdr, 0 );
505 if (ret == sizeof(handle)) return 0;
507 if (ret >= 0)
509 fprintf( stderr, "Protocol error: process %04x: partial sendmsg %d\n", process->id, ret );
510 kill_process( process, 1 );
512 else if (errno == EPIPE)
514 kill_process( process, 0 );
516 else
518 fprintf( stderr, "Protocol error: process %04x: ", process->id );
519 perror( "sendmsg" );
520 kill_process( process, 1 );
522 return -1;
525 /* return a monotonic time counter */
526 timeout_t monotonic_counter(void)
528 #ifdef __APPLE__
529 static mach_timebase_info_data_t timebase;
531 if (!timebase.denom) mach_timebase_info( &timebase );
532 #ifdef HAVE_MACH_CONTINUOUS_TIME
533 if (&mach_continuous_time != NULL)
534 return mach_continuous_time() * timebase.numer / timebase.denom / 100;
535 #endif
536 return mach_absolute_time() * timebase.numer / timebase.denom / 100;
537 #elif defined(HAVE_CLOCK_GETTIME)
538 struct timespec ts;
539 #ifdef CLOCK_MONOTONIC_RAW
540 if (!clock_gettime( CLOCK_MONOTONIC_RAW, &ts ))
541 return (timeout_t)ts.tv_sec * TICKS_PER_SEC + ts.tv_nsec / 100;
542 #endif
543 if (!clock_gettime( CLOCK_MONOTONIC, &ts ))
544 return (timeout_t)ts.tv_sec * TICKS_PER_SEC + ts.tv_nsec / 100;
545 #endif
546 return current_time - server_start_time;
549 static void master_socket_dump( struct object *obj, int verbose )
551 struct master_socket *sock = (struct master_socket *)obj;
552 assert( obj->ops == &master_socket_ops );
553 fprintf( stderr, "Master socket fd=%p\n", sock->fd );
556 static void master_socket_destroy( struct object *obj )
558 struct master_socket *sock = (struct master_socket *)obj;
559 assert( obj->ops == &master_socket_ops );
560 release_object( sock->fd );
563 /* handle a socket event */
564 static void master_socket_poll_event( struct fd *fd, int event )
566 struct master_socket *sock = get_fd_user( fd );
567 assert( master_socket->obj.ops == &master_socket_ops );
569 assert( sock == master_socket ); /* there is only one master socket */
571 if (event & (POLLERR | POLLHUP))
573 /* this is not supposed to happen */
574 fprintf( stderr, "wineserver: Error on master socket\n" );
575 set_fd_events( sock->fd, -1 );
577 else if (event & POLLIN)
579 struct process *process;
580 struct sockaddr_un dummy;
581 socklen_t len = sizeof(dummy);
582 int client = accept( get_unix_fd( master_socket->fd ), (struct sockaddr *) &dummy, &len );
583 if (client == -1) return;
584 fcntl( client, F_SETFL, O_NONBLOCK );
585 if ((process = create_process( client, NULL, 0, NULL )))
587 create_thread( -1, process, NULL );
588 release_object( process );
593 /* remove the socket upon exit */
594 static void socket_cleanup(void)
596 static int do_it_once;
597 if (!do_it_once++) unlink( server_socket_name );
600 /* create a directory and check its permissions */
601 static void create_dir( const char *name, struct stat *st )
603 if (lstat( name, st ) == -1)
605 if (errno != ENOENT)
606 fatal_error( "lstat %s: %s\n", name, strerror( errno ));
607 if (mkdir( name, 0700 ) == -1 && errno != EEXIST)
608 fatal_error( "mkdir %s: %s\n", name, strerror( errno ));
609 if (lstat( name, st ) == -1)
610 fatal_error( "lstat %s: %s\n", name, strerror( errno ));
612 if (!S_ISDIR(st->st_mode)) fatal_error( "%s is not a directory\n", name );
613 if (st->st_uid != getuid()) fatal_error( "%s is not owned by you\n", name );
614 if (st->st_mode & 077) fatal_error( "%s must not be accessible by other users\n", name );
617 /* create the server directory and chdir to it */
618 static char *create_server_dir( int force )
620 const char *prefix = getenv( "WINEPREFIX" );
621 char *p, *config_dir;
622 struct stat st, st2;
623 size_t len = sizeof("/server-") + 2 * sizeof(st.st_dev) + 2 * sizeof(st.st_ino) + 2;
625 /* open the configuration directory */
627 if (prefix)
629 if (!(config_dir = strdup( prefix ))) fatal_error( "out of memory\n" );
630 for (p = config_dir + strlen(config_dir); p > config_dir; p--) if (p[-1] != '/') break;
631 if (p > config_dir) *p = 0;
632 if (config_dir[0] != '/')
633 fatal_error( "invalid directory %s in WINEPREFIX: not an absolute path\n", prefix );
635 else
637 const char *home = getenv( "HOME" );
638 if (!home)
640 struct passwd *pwd = getpwuid( getuid() );
641 if (pwd) home = pwd->pw_dir;
643 if (!home) fatal_error( "could not determine your home directory\n" );
644 if (home[0] != '/') fatal_error( "your home directory %s is not an absolute path\n", home );
645 if (!(config_dir = malloc( strlen(home) + sizeof("/.wine") ))) fatal_error( "out of memory\n" );
646 strcpy( config_dir, home );
647 for (p = config_dir + strlen(config_dir); p > config_dir; p--) if (p[-1] != '/') break;
648 strcpy( p, "/.wine" );
651 if (chdir( config_dir ) == -1)
653 if (errno != ENOENT || force) fatal_error( "chdir to %s: %s\n", config_dir, strerror( errno ));
654 return NULL;
656 if ((config_dir_fd = open( ".", O_RDONLY )) == -1)
657 fatal_error( "open %s: %s\n", config_dir, strerror( errno ));
658 if (fstat( config_dir_fd, &st ) == -1)
659 fatal_error( "stat %s: %s\n", config_dir, strerror( errno ));
660 if (st.st_uid != getuid())
661 fatal_error( "%s is not owned by you\n", config_dir );
663 /* create the base directory if needed */
665 #ifdef __ANDROID__ /* there's no /tmp dir on Android */
666 len += strlen( config_dir ) + sizeof("/.wineserver");
667 if (!(server_dir = malloc( len ))) fatal_error( "out of memory\n" );
668 strcpy( server_dir, config_dir );
669 strcat( server_dir, "/.wineserver" );
670 #else
671 len += sizeof("/tmp/.wine-") + 12;
672 if (!(server_dir = malloc( len ))) fatal_error( "out of memory\n" );
673 sprintf( server_dir, "/tmp/.wine-%u", getuid() );
674 #endif
675 create_dir( server_dir, &st2 );
677 /* now create the server directory */
679 strcat( server_dir, "/server-" );
680 p = server_dir + strlen(server_dir);
682 if (st.st_dev != (unsigned long)st.st_dev)
683 p += sprintf( p, "%lx%08lx-", (unsigned long)((unsigned long long)st.st_dev >> 32),
684 (unsigned long)st.st_dev );
685 else
686 p += sprintf( p, "%lx-", (unsigned long)st.st_dev );
688 if (st.st_ino != (unsigned long)st.st_ino)
689 sprintf( p, "%lx%08lx", (unsigned long)((unsigned long long)st.st_ino >> 32),
690 (unsigned long)st.st_ino );
691 else
692 sprintf( p, "%lx", (unsigned long)st.st_ino );
694 create_dir( server_dir, &st );
696 if (chdir( server_dir ) == -1)
697 fatal_error( "chdir %s: %s\n", server_dir, strerror( errno ));
698 if ((server_dir_fd = open( ".", O_RDONLY )) == -1)
699 fatal_error( "open %s: %s\n", server_dir, strerror( errno ));
700 if (fstat( server_dir_fd, &st2 ) == -1)
701 fatal_error( "stat %s: %s\n", server_dir, strerror( errno ));
702 if (st.st_dev != st2.st_dev || st.st_ino != st2.st_ino)
703 fatal_error( "chdir did not end up in %s\n", server_dir );
705 free( config_dir );
706 return server_dir;
709 /* create the lock file and return its file descriptor */
710 static int create_server_lock(void)
712 struct stat st;
713 int fd;
715 if (lstat( server_lock_name, &st ) == -1)
717 if (errno != ENOENT)
718 fatal_error( "lstat %s/%s: %s\n", server_dir, server_lock_name, strerror( errno ));
720 else
722 if (!S_ISREG(st.st_mode))
723 fatal_error( "%s/%s is not a regular file\n", server_dir, server_lock_name );
726 if ((fd = open( server_lock_name, O_CREAT|O_TRUNC|O_WRONLY, 0600 )) == -1)
727 fatal_error( "error creating %s/%s: %s\n", server_dir, server_lock_name, strerror( errno ));
728 return fd;
731 /* wait for the server lock */
732 int wait_for_lock(void)
734 int fd, r;
735 struct flock fl;
737 server_dir = create_server_dir( 0 );
738 if (!server_dir) return 0; /* no server dir, so no lock to wait on */
740 fd = create_server_lock();
742 fl.l_type = F_WRLCK;
743 fl.l_whence = SEEK_SET;
744 fl.l_start = 0;
745 fl.l_len = 1;
746 r = fcntl( fd, F_SETLKW, &fl );
747 close(fd);
749 return r;
752 /* kill the wine server holding the lock */
753 int kill_lock_owner( int sig )
755 int fd, i, ret = 0;
756 pid_t pid = 0;
757 struct flock fl;
759 server_dir = create_server_dir( 0 );
760 if (!server_dir) return 0; /* no server dir, nothing to do */
762 fd = create_server_lock();
764 for (i = 1; i <= 20; i++)
766 fl.l_type = F_WRLCK;
767 fl.l_whence = SEEK_SET;
768 fl.l_start = 0;
769 fl.l_len = 1;
770 if (fcntl( fd, F_GETLK, &fl ) == -1) goto done;
771 if (fl.l_type != F_WRLCK) goto done; /* the file is not locked */
772 if (!pid) /* first time around */
774 if (!(pid = fl.l_pid)) goto done; /* shouldn't happen */
775 if (sig == -1)
777 if (kill( pid, SIGINT ) == -1) goto done;
778 kill( pid, SIGCONT );
779 ret = 1;
781 else /* just send the specified signal and return */
783 ret = (kill( pid, sig ) != -1);
784 goto done;
787 else if (fl.l_pid != pid) goto done; /* no longer the same process */
788 usleep( 50000 * i );
790 /* waited long enough, now kill it */
791 kill( pid, SIGKILL );
793 done:
794 close( fd );
795 return ret;
798 /* acquire the main server lock */
799 static void acquire_lock(void)
801 struct sockaddr_un addr;
802 struct stat st;
803 struct flock fl;
804 int fd, slen, got_lock = 0;
806 fd = create_server_lock();
808 fl.l_type = F_WRLCK;
809 fl.l_whence = SEEK_SET;
810 fl.l_start = 0;
811 fl.l_len = 1;
812 if (fcntl( fd, F_SETLK, &fl ) != -1)
814 /* check for crashed server */
815 if (stat( server_socket_name, &st ) != -1 && /* there is a leftover socket */
816 stat( "core", &st ) != -1 && st.st_size) /* and there is a non-empty core file */
818 fprintf( stderr,
819 "Warning: a previous instance of the wine server seems to have crashed.\n"
820 "Please run 'gdb %s %s/core',\n"
821 "type 'backtrace' at the gdb prompt and report the results. Thanks.\n\n",
822 server_argv0, server_dir );
824 unlink( server_socket_name ); /* we got the lock, we can safely remove the socket */
825 got_lock = 1;
826 /* in that case we reuse fd without closing it, this ensures
827 * that we hold the lock until the process exits */
829 else
831 switch(errno)
833 case ENOLCK:
834 break;
835 case EACCES:
836 /* check whether locks work at all on this file system */
837 if (fcntl( fd, F_GETLK, &fl ) == -1) break;
838 /* fall through */
839 case EAGAIN:
840 exit(2); /* we didn't get the lock, exit with special status */
841 default:
842 fatal_error( "fcntl %s/%s: %s\n", server_dir, server_lock_name, strerror( errno ));
844 /* it seems we can't use locks on this fs, so we will use the socket existence as lock */
845 close( fd );
848 if ((fd = socket( AF_UNIX, SOCK_STREAM, 0 )) == -1) fatal_error( "socket: %s\n", strerror( errno ));
849 addr.sun_family = AF_UNIX;
850 strcpy( addr.sun_path, server_socket_name );
851 slen = sizeof(addr) - sizeof(addr.sun_path) + strlen(addr.sun_path) + 1;
852 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
853 addr.sun_len = slen;
854 #endif
855 if (bind( fd, (struct sockaddr *)&addr, slen ) == -1)
857 if ((errno == EEXIST) || (errno == EADDRINUSE))
859 if (got_lock)
860 fatal_error( "couldn't bind to the socket even though we hold the lock\n" );
861 exit(2); /* we didn't get the lock, exit with special status */
863 fatal_error( "bind: %s\n", strerror( errno ));
865 atexit( socket_cleanup );
866 chmod( server_socket_name, 0600 ); /* make sure no other user can connect */
867 if (listen( fd, 5 ) == -1) fatal_error( "listen: %s\n", strerror( errno ));
869 if (!(master_socket = alloc_object( &master_socket_ops )) ||
870 !(master_socket->fd = create_anonymous_fd( &master_socket_fd_ops, fd, &master_socket->obj, 0 )))
871 fatal_error( "out of memory\n" );
872 set_fd_events( master_socket->fd, POLLIN );
873 make_object_static( &master_socket->obj );
876 /* open the master server socket and start waiting for new clients */
877 void open_master_socket(void)
879 int fd, pid, status, sync_pipe[2];
880 char dummy;
882 /* make sure no request is larger than the maximum size */
883 assert( sizeof(union generic_request) == sizeof(struct request_max_size) );
884 assert( sizeof(union generic_reply) == sizeof(struct request_max_size) );
886 /* make sure the stdio fds are open */
887 fd = open( "/dev/null", O_RDWR );
888 while (fd >= 0 && fd <= 2) fd = dup( fd );
890 server_dir = create_server_dir( 1 );
892 if (!foreground)
894 if (pipe( sync_pipe ) == -1) fatal_error( "pipe: %s\n", strerror( errno ));
895 pid = fork();
896 switch( pid )
898 case 0: /* child */
899 setsid();
900 close( sync_pipe[0] );
902 acquire_lock();
904 /* close stdin and stdout */
905 dup2( fd, 0 );
906 dup2( fd, 1 );
908 /* signal parent */
909 dummy = 0;
910 write( sync_pipe[1], &dummy, 1 );
911 close( sync_pipe[1] );
912 break;
914 case -1:
915 fatal_error( "fork: %s\n", strerror( errno ));
916 break;
918 default: /* parent */
919 close( sync_pipe[1] );
921 /* wait for child to signal us and then exit */
922 if (read( sync_pipe[0], &dummy, 1 ) == 1) _exit(0);
924 /* child terminated, propagate exit status */
925 waitpid( pid, &status, 0 );
926 if (WIFEXITED(status)) _exit( WEXITSTATUS(status) );
927 _exit(1);
930 else /* remain in the foreground */
932 acquire_lock();
935 /* init the process tracing mechanism */
936 init_tracing_mechanism();
937 close( fd );
940 /* master socket timer expiration handler */
941 static void close_socket_timeout( void *arg )
943 master_timeout = NULL;
944 flush_registry();
945 if (debug_level) fprintf( stderr, "wineserver: exiting (pid=%ld)\n", (long) getpid() );
947 #ifdef DEBUG_OBJECTS
948 close_objects(); /* shut down everything properly */
949 #endif
950 exit( 0 );
953 /* close the master socket and stop waiting for new clients */
954 void close_master_socket( timeout_t timeout )
956 if (master_socket)
958 release_object( master_socket );
959 master_socket = NULL;
961 if (master_timeout) /* cancel previous timeout */
962 remove_timeout_user( master_timeout );
964 master_timeout = add_timeout_user( timeout, close_socket_timeout, NULL );