dnsapi: Get rid of imported domain name parsing code.
[wine/zf.git] / server / request.c
blob29b63600f15aa22d169327a440d40461d5ce940d
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 #include "handle.h"
70 #define WANT_REQUEST_HANDLERS
71 #include "request.h"
73 /* Some versions of glibc don't define this */
74 #ifndef SCM_RIGHTS
75 #define SCM_RIGHTS 1
76 #endif
78 /* path names for server master Unix socket */
79 static const char * const server_socket_name = "socket"; /* name of the socket file */
80 static const char * const server_lock_name = "lock"; /* name of the server lock file */
82 struct master_socket
84 struct object obj; /* object header */
85 struct fd *fd; /* file descriptor of the master socket */
88 static void master_socket_dump( struct object *obj, int verbose );
89 static void master_socket_destroy( struct object *obj );
90 static void master_socket_poll_event( struct fd *fd, int event );
92 static const struct object_ops master_socket_ops =
94 sizeof(struct master_socket), /* size */
95 &no_type, /* type */
96 master_socket_dump, /* dump */
97 no_add_queue, /* add_queue */
98 NULL, /* remove_queue */
99 NULL, /* signaled */
100 NULL, /* satisfied */
101 no_signal, /* signal */
102 no_get_fd, /* get_fd */
103 default_map_access, /* map_access */
104 default_get_sd, /* get_sd */
105 default_set_sd, /* set_sd */
106 no_get_full_name, /* get_full_name */
107 no_lookup_name, /* lookup_name */
108 no_link_name, /* link_name */
109 NULL, /* unlink_name */
110 no_open_file, /* open_file */
111 no_kernel_obj_list, /* get_kernel_obj_list */
112 no_close_handle, /* close_handle */
113 master_socket_destroy /* destroy */
116 static const struct fd_ops master_socket_fd_ops =
118 NULL, /* get_poll_events */
119 master_socket_poll_event, /* poll_event */
120 NULL, /* flush */
121 NULL, /* get_fd_type */
122 NULL, /* ioctl */
123 NULL, /* queue_async */
124 NULL /* reselect_async */
128 struct thread *current = NULL; /* thread handling the current request */
129 unsigned int global_error = 0; /* global error code for when no thread is current */
130 timeout_t server_start_time = 0; /* server startup time */
131 char *server_dir = NULL; /* server directory */
132 int server_dir_fd = -1; /* file descriptor for the server dir */
133 int config_dir_fd = -1; /* file descriptor for the config dir */
135 static struct master_socket *master_socket; /* the master socket object */
136 static struct timeout_user *master_timeout;
138 /* complain about a protocol error and terminate the client connection */
139 void fatal_protocol_error( struct thread *thread, const char *err, ... )
141 va_list args;
143 va_start( args, err );
144 fprintf( stderr, "Protocol error:%04x: ", thread->id );
145 vfprintf( stderr, err, args );
146 va_end( args );
147 thread->exit_code = 1;
148 kill_thread( thread, 1 );
151 /* die on a fatal error */
152 void fatal_error( const char *err, ... )
154 va_list args;
156 va_start( args, err );
157 fprintf( stderr, "wineserver: " );
158 vfprintf( stderr, err, args );
159 va_end( args );
160 exit(1);
163 /* allocate the reply data */
164 void *set_reply_data_size( data_size_t size )
166 assert( size <= get_reply_max_size() );
167 if (size && !(current->reply_data = mem_alloc( size ))) size = 0;
168 current->reply_size = size;
169 return current->reply_data;
172 static const struct object_attributes empty_attributes;
174 /* return object attributes from the current request */
175 const struct object_attributes *get_req_object_attributes( const struct security_descriptor **sd,
176 struct unicode_str *name,
177 struct object **root )
179 const struct object_attributes *attr = get_req_data();
180 data_size_t size = get_req_data_size();
182 if (root) *root = NULL;
184 if (!size)
186 *sd = NULL;
187 name->len = 0;
188 return &empty_attributes;
191 if ((size < sizeof(*attr)) || (size - sizeof(*attr) < attr->sd_len) ||
192 (size - sizeof(*attr) - attr->sd_len < attr->name_len))
194 set_error( STATUS_ACCESS_VIOLATION );
195 return NULL;
197 if (attr->sd_len && !sd_is_valid( (const struct security_descriptor *)(attr + 1), attr->sd_len ))
199 set_error( STATUS_INVALID_SECURITY_DESCR );
200 return NULL;
202 if ((attr->name_len & (sizeof(WCHAR) - 1)) || attr->name_len >= 65534)
204 set_error( STATUS_OBJECT_NAME_INVALID );
205 return NULL;
207 if (root && attr->rootdir && attr->name_len)
209 if (!(*root = get_handle_obj( current->process, attr->rootdir, 0, NULL ))) return NULL;
211 *sd = attr->sd_len ? (const struct security_descriptor *)(attr + 1) : NULL;
212 name->len = attr->name_len;
213 name->str = (const WCHAR *)(attr + 1) + attr->sd_len / sizeof(WCHAR);
214 return attr;
217 /* return a pointer to the request data following an object attributes structure */
218 const void *get_req_data_after_objattr( const struct object_attributes *attr, data_size_t *len )
220 data_size_t size = (sizeof(*attr) + (attr->sd_len & ~1) + (attr->name_len & ~1) + 3) & ~3;
222 if (attr == &empty_attributes || size >= get_req_data_size())
224 *len = 0;
225 return NULL;
227 *len = get_req_data_size() - size;
228 return (const char *)get_req_data() + size;
231 /* write the remaining part of the reply */
232 void write_reply( struct thread *thread )
234 int ret;
236 if ((ret = write( get_unix_fd( thread->reply_fd ),
237 (char *)thread->reply_data + thread->reply_size - thread->reply_towrite,
238 thread->reply_towrite )) >= 0)
240 if (!(thread->reply_towrite -= ret))
242 free( thread->reply_data );
243 thread->reply_data = NULL;
244 /* sent everything, can go back to waiting for requests */
245 set_fd_events( thread->request_fd, POLLIN );
246 set_fd_events( thread->reply_fd, 0 );
248 return;
250 if (errno == EPIPE)
251 kill_thread( thread, 0 ); /* normal death */
252 else if (errno != EWOULDBLOCK && (EWOULDBLOCK == EAGAIN || errno != EAGAIN))
253 fatal_protocol_error( thread, "reply write: %s\n", strerror( errno ));
256 /* send a reply to the current thread */
257 static void send_reply( union generic_reply *reply )
259 int ret;
261 if (!current->reply_size)
263 if ((ret = write( get_unix_fd( current->reply_fd ),
264 reply, sizeof(*reply) )) != sizeof(*reply)) goto error;
266 else
268 struct iovec vec[2];
270 vec[0].iov_base = (void *)reply;
271 vec[0].iov_len = sizeof(*reply);
272 vec[1].iov_base = current->reply_data;
273 vec[1].iov_len = current->reply_size;
275 if ((ret = writev( get_unix_fd( current->reply_fd ), vec, 2 )) < sizeof(*reply)) goto error;
277 if ((current->reply_towrite = current->reply_size - (ret - sizeof(*reply))))
279 /* couldn't write it all, wait for POLLOUT */
280 set_fd_events( current->reply_fd, POLLOUT );
281 set_fd_events( current->request_fd, 0 );
282 return;
285 free( current->reply_data );
286 current->reply_data = NULL;
287 return;
289 error:
290 if (ret >= 0)
291 fatal_protocol_error( current, "partial write %d\n", ret );
292 else if (errno == EPIPE)
293 kill_thread( current, 0 ); /* normal death */
294 else
295 fatal_protocol_error( current, "reply write: %s\n", strerror( errno ));
298 /* call a request handler */
299 static void call_req_handler( struct thread *thread )
301 union generic_reply reply;
302 enum request req = thread->req.request_header.req;
304 current = thread;
305 current->reply_size = 0;
306 clear_error();
307 memset( &reply, 0, sizeof(reply) );
309 if (debug_level) trace_request();
311 if (req < REQ_NB_REQUESTS)
312 req_handlers[req]( &current->req, &reply );
313 else
314 set_error( STATUS_NOT_IMPLEMENTED );
316 if (current)
318 if (current->reply_fd)
320 reply.reply_header.error = current->error;
321 reply.reply_header.reply_size = current->reply_size;
322 if (debug_level) trace_reply( req, &reply );
323 send_reply( &reply );
325 else
327 current->exit_code = 1;
328 kill_thread( current, 1 ); /* no way to continue without reply fd */
331 current = NULL;
334 /* read a request from a thread */
335 void read_request( struct thread *thread )
337 int ret;
339 if (!thread->req_toread) /* no pending request */
341 if ((ret = read( get_unix_fd( thread->request_fd ), &thread->req,
342 sizeof(thread->req) )) != sizeof(thread->req)) goto error;
343 if (!(thread->req_toread = thread->req.request_header.request_size))
345 /* no data, handle request at once */
346 call_req_handler( thread );
347 return;
349 if (!(thread->req_data = malloc( thread->req_toread )))
351 fatal_protocol_error( thread, "no memory for %u bytes request %d\n",
352 thread->req_toread, thread->req.request_header.req );
353 return;
357 /* read the variable sized data */
358 for (;;)
360 ret = read( get_unix_fd( thread->request_fd ),
361 (char *)thread->req_data + thread->req.request_header.request_size
362 - thread->req_toread,
363 thread->req_toread );
364 if (ret <= 0) break;
365 if (!(thread->req_toread -= ret))
367 call_req_handler( thread );
368 free( thread->req_data );
369 thread->req_data = NULL;
370 return;
374 error:
375 if (!ret) /* closed pipe */
376 kill_thread( thread, 0 );
377 else if (ret > 0)
378 fatal_protocol_error( thread, "partial read %d\n", ret );
379 else if (errno != EWOULDBLOCK && (EWOULDBLOCK == EAGAIN || errno != EAGAIN))
380 fatal_protocol_error( thread, "read: %s\n", strerror( errno ));
383 /* receive a file descriptor on the process socket */
384 int receive_fd( struct process *process )
386 struct iovec vec;
387 struct send_fd data;
388 struct msghdr msghdr;
389 int fd = -1, ret;
391 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
392 msghdr.msg_accrightslen = sizeof(int);
393 msghdr.msg_accrights = (void *)&fd;
394 #else /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
395 char cmsg_buffer[256];
396 msghdr.msg_control = cmsg_buffer;
397 msghdr.msg_controllen = sizeof(cmsg_buffer);
398 msghdr.msg_flags = 0;
399 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
401 msghdr.msg_name = NULL;
402 msghdr.msg_namelen = 0;
403 msghdr.msg_iov = &vec;
404 msghdr.msg_iovlen = 1;
405 vec.iov_base = (void *)&data;
406 vec.iov_len = sizeof(data);
408 ret = recvmsg( get_unix_fd( process->msg_fd ), &msghdr, 0 );
410 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
411 if (ret > 0)
413 struct cmsghdr *cmsg;
414 for (cmsg = CMSG_FIRSTHDR( &msghdr ); cmsg; cmsg = CMSG_NXTHDR( &msghdr, cmsg ))
416 if (cmsg->cmsg_level != SOL_SOCKET) continue;
417 if (cmsg->cmsg_type == SCM_RIGHTS) fd = *(int *)CMSG_DATA(cmsg);
420 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
422 if (ret == sizeof(data))
424 struct thread *thread;
426 if (data.tid) thread = get_thread_from_id( data.tid );
427 else thread = (struct thread *)grab_object( get_process_first_thread( process ));
429 if (!thread || thread->process != process || thread->state == TERMINATED)
431 if (debug_level)
432 fprintf( stderr, "%04x: *fd* %d <- %d bad thread id\n",
433 data.tid, data.fd, fd );
434 close( fd );
436 else
438 if (debug_level)
439 fprintf( stderr, "%04x: *fd* %d <- %d\n",
440 thread->id, data.fd, fd );
441 thread_add_inflight_fd( thread, data.fd, fd );
443 if (thread) release_object( thread );
444 return 0;
447 if (!ret)
449 kill_process( process, 0 );
451 else if (ret > 0)
453 fprintf( stderr, "Protocol error: process %04x: partial recvmsg %d for fd\n",
454 process->id, ret );
455 if (fd != -1) close( fd );
456 kill_process( process, 1 );
458 else
460 if (errno != EWOULDBLOCK && (EWOULDBLOCK == EAGAIN || errno != EAGAIN))
462 fprintf( stderr, "Protocol error: process %04x: ", process->id );
463 perror( "recvmsg" );
464 kill_process( process, 1 );
467 return -1;
470 /* send an fd to a client */
471 int send_client_fd( struct process *process, int fd, obj_handle_t handle )
473 struct iovec vec;
474 struct msghdr msghdr;
475 int ret;
477 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
478 msghdr.msg_accrightslen = sizeof(fd);
479 msghdr.msg_accrights = (void *)&fd;
480 #else /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
481 char cmsg_buffer[256];
482 struct cmsghdr *cmsg;
483 msghdr.msg_control = cmsg_buffer;
484 msghdr.msg_controllen = sizeof(cmsg_buffer);
485 msghdr.msg_flags = 0;
486 cmsg = CMSG_FIRSTHDR( &msghdr );
487 cmsg->cmsg_len = CMSG_LEN( sizeof(fd) );
488 cmsg->cmsg_level = SOL_SOCKET;
489 cmsg->cmsg_type = SCM_RIGHTS;
490 *(int *)CMSG_DATA(cmsg) = fd;
491 msghdr.msg_controllen = cmsg->cmsg_len;
492 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
494 msghdr.msg_name = NULL;
495 msghdr.msg_namelen = 0;
496 msghdr.msg_iov = &vec;
497 msghdr.msg_iovlen = 1;
499 vec.iov_base = (void *)&handle;
500 vec.iov_len = sizeof(handle);
502 if (debug_level)
503 fprintf( stderr, "%04x: *fd* %04x -> %d\n", current ? current->id : process->id, handle, fd );
505 ret = sendmsg( get_unix_fd( process->msg_fd ), &msghdr, 0 );
507 if (ret == sizeof(handle)) return 0;
509 if (ret >= 0)
511 fprintf( stderr, "Protocol error: process %04x: partial sendmsg %d\n", process->id, ret );
512 kill_process( process, 1 );
514 else if (errno == EPIPE)
516 kill_process( process, 0 );
518 else
520 fprintf( stderr, "Protocol error: process %04x: ", process->id );
521 perror( "sendmsg" );
522 kill_process( process, 1 );
524 return -1;
527 /* return a monotonic time counter */
528 timeout_t monotonic_counter(void)
530 #ifdef __APPLE__
531 static mach_timebase_info_data_t timebase;
533 if (!timebase.denom) mach_timebase_info( &timebase );
534 #ifdef HAVE_MACH_CONTINUOUS_TIME
535 if (&mach_continuous_time != NULL)
536 return mach_continuous_time() * timebase.numer / timebase.denom / 100;
537 #endif
538 return mach_absolute_time() * timebase.numer / timebase.denom / 100;
539 #elif defined(HAVE_CLOCK_GETTIME)
540 struct timespec ts;
541 #ifdef CLOCK_MONOTONIC_RAW
542 if (!clock_gettime( CLOCK_MONOTONIC_RAW, &ts ))
543 return (timeout_t)ts.tv_sec * TICKS_PER_SEC + ts.tv_nsec / 100;
544 #endif
545 if (!clock_gettime( CLOCK_MONOTONIC, &ts ))
546 return (timeout_t)ts.tv_sec * TICKS_PER_SEC + ts.tv_nsec / 100;
547 #endif
548 return current_time - server_start_time;
551 static void master_socket_dump( struct object *obj, int verbose )
553 struct master_socket *sock = (struct master_socket *)obj;
554 assert( obj->ops == &master_socket_ops );
555 fprintf( stderr, "Master socket fd=%p\n", sock->fd );
558 static void master_socket_destroy( struct object *obj )
560 struct master_socket *sock = (struct master_socket *)obj;
561 assert( obj->ops == &master_socket_ops );
562 release_object( sock->fd );
565 /* handle a socket event */
566 static void master_socket_poll_event( struct fd *fd, int event )
568 struct master_socket *sock = get_fd_user( fd );
569 assert( master_socket->obj.ops == &master_socket_ops );
571 assert( sock == master_socket ); /* there is only one master socket */
573 if (event & (POLLERR | POLLHUP))
575 /* this is not supposed to happen */
576 fprintf( stderr, "wineserver: Error on master socket\n" );
577 set_fd_events( sock->fd, -1 );
579 else if (event & POLLIN)
581 struct process *process;
582 struct sockaddr_un dummy;
583 socklen_t len = sizeof(dummy);
584 int client = accept( get_unix_fd( master_socket->fd ), (struct sockaddr *) &dummy, &len );
585 if (client == -1) return;
586 fcntl( client, F_SETFL, O_NONBLOCK );
587 if ((process = create_process( client, NULL, 0, NULL, NULL, NULL, 0, NULL )))
589 create_thread( -1, process, NULL );
590 release_object( process );
595 /* remove the socket upon exit */
596 static void socket_cleanup(void)
598 static int do_it_once;
599 if (!do_it_once++) unlink( server_socket_name );
602 /* create a directory and check its permissions */
603 static void create_dir( const char *name, struct stat *st )
605 if (lstat( name, st ) == -1)
607 if (errno != ENOENT)
608 fatal_error( "lstat %s: %s\n", name, strerror( errno ));
609 if (mkdir( name, 0700 ) == -1 && errno != EEXIST)
610 fatal_error( "mkdir %s: %s\n", name, strerror( errno ));
611 if (lstat( name, st ) == -1)
612 fatal_error( "lstat %s: %s\n", name, strerror( errno ));
614 if (!S_ISDIR(st->st_mode)) fatal_error( "%s is not a directory\n", name );
615 if (st->st_uid != getuid()) fatal_error( "%s is not owned by you\n", name );
616 if (st->st_mode & 077) fatal_error( "%s must not be accessible by other users\n", name );
619 /* create the server directory and chdir to it */
620 static char *create_server_dir( int force )
622 const char *prefix = getenv( "WINEPREFIX" );
623 char *p, *config_dir;
624 struct stat st, st2;
625 size_t len = sizeof("/server-") + 2 * sizeof(st.st_dev) + 2 * sizeof(st.st_ino) + 2;
627 /* open the configuration directory */
629 if (prefix)
631 if (!(config_dir = strdup( prefix ))) fatal_error( "out of memory\n" );
632 for (p = config_dir + strlen(config_dir); p > config_dir; p--) if (p[-1] != '/') break;
633 if (p > config_dir) *p = 0;
634 if (config_dir[0] != '/')
635 fatal_error( "invalid directory %s in WINEPREFIX: not an absolute path\n", prefix );
637 else
639 const char *home = getenv( "HOME" );
640 if (!home)
642 struct passwd *pwd = getpwuid( getuid() );
643 if (pwd) home = pwd->pw_dir;
645 if (!home) fatal_error( "could not determine your home directory\n" );
646 if (home[0] != '/') fatal_error( "your home directory %s is not an absolute path\n", home );
647 if (!(config_dir = malloc( strlen(home) + sizeof("/.wine") ))) fatal_error( "out of memory\n" );
648 strcpy( config_dir, home );
649 for (p = config_dir + strlen(config_dir); p > config_dir; p--) if (p[-1] != '/') break;
650 strcpy( p, "/.wine" );
653 if (chdir( config_dir ) == -1)
655 if (errno != ENOENT || force) fatal_error( "chdir to %s: %s\n", config_dir, strerror( errno ));
656 return NULL;
658 if ((config_dir_fd = open( ".", O_RDONLY )) == -1)
659 fatal_error( "open %s: %s\n", config_dir, strerror( errno ));
660 if (fstat( config_dir_fd, &st ) == -1)
661 fatal_error( "stat %s: %s\n", config_dir, strerror( errno ));
662 if (st.st_uid != getuid())
663 fatal_error( "%s is not owned by you\n", config_dir );
665 /* create the base directory if needed */
667 #ifdef __ANDROID__ /* there's no /tmp dir on Android */
668 len += strlen( config_dir ) + sizeof("/.wineserver");
669 if (!(server_dir = malloc( len ))) fatal_error( "out of memory\n" );
670 strcpy( server_dir, config_dir );
671 strcat( server_dir, "/.wineserver" );
672 #else
673 len += sizeof("/tmp/.wine-") + 12;
674 if (!(server_dir = malloc( len ))) fatal_error( "out of memory\n" );
675 sprintf( server_dir, "/tmp/.wine-%u", getuid() );
676 #endif
677 create_dir( server_dir, &st2 );
679 /* now create the server directory */
681 strcat( server_dir, "/server-" );
682 p = server_dir + strlen(server_dir);
684 if (st.st_dev != (unsigned long)st.st_dev)
685 p += sprintf( p, "%lx%08lx-", (unsigned long)((unsigned long long)st.st_dev >> 32),
686 (unsigned long)st.st_dev );
687 else
688 p += sprintf( p, "%lx-", (unsigned long)st.st_dev );
690 if (st.st_ino != (unsigned long)st.st_ino)
691 sprintf( p, "%lx%08lx", (unsigned long)((unsigned long long)st.st_ino >> 32),
692 (unsigned long)st.st_ino );
693 else
694 sprintf( p, "%lx", (unsigned long)st.st_ino );
696 create_dir( server_dir, &st );
698 if (chdir( server_dir ) == -1)
699 fatal_error( "chdir %s: %s\n", server_dir, strerror( errno ));
700 if ((server_dir_fd = open( ".", O_RDONLY )) == -1)
701 fatal_error( "open %s: %s\n", server_dir, strerror( errno ));
702 if (fstat( server_dir_fd, &st2 ) == -1)
703 fatal_error( "stat %s: %s\n", server_dir, strerror( errno ));
704 if (st.st_dev != st2.st_dev || st.st_ino != st2.st_ino)
705 fatal_error( "chdir did not end up in %s\n", server_dir );
707 free( config_dir );
708 return server_dir;
711 /* create the lock file and return its file descriptor */
712 static int create_server_lock(void)
714 struct stat st;
715 int fd;
717 if (lstat( server_lock_name, &st ) == -1)
719 if (errno != ENOENT)
720 fatal_error( "lstat %s/%s: %s\n", server_dir, server_lock_name, strerror( errno ));
722 else
724 if (!S_ISREG(st.st_mode))
725 fatal_error( "%s/%s is not a regular file\n", server_dir, server_lock_name );
728 if ((fd = open( server_lock_name, O_CREAT|O_TRUNC|O_WRONLY, 0600 )) == -1)
729 fatal_error( "error creating %s/%s: %s\n", server_dir, server_lock_name, strerror( errno ));
730 return fd;
733 /* wait for the server lock */
734 int wait_for_lock(void)
736 int fd, r;
737 struct flock fl;
739 server_dir = create_server_dir( 0 );
740 if (!server_dir) return 0; /* no server dir, so no lock to wait on */
742 fd = create_server_lock();
744 fl.l_type = F_WRLCK;
745 fl.l_whence = SEEK_SET;
746 fl.l_start = 0;
747 fl.l_len = 1;
748 r = fcntl( fd, F_SETLKW, &fl );
749 close(fd);
751 return r;
754 /* kill the wine server holding the lock */
755 int kill_lock_owner( int sig )
757 int fd, i, ret = 0;
758 pid_t pid = 0;
759 struct flock fl;
761 server_dir = create_server_dir( 0 );
762 if (!server_dir) return 0; /* no server dir, nothing to do */
764 fd = create_server_lock();
766 for (i = 1; i <= 20; i++)
768 fl.l_type = F_WRLCK;
769 fl.l_whence = SEEK_SET;
770 fl.l_start = 0;
771 fl.l_len = 1;
772 if (fcntl( fd, F_GETLK, &fl ) == -1) goto done;
773 if (fl.l_type != F_WRLCK) goto done; /* the file is not locked */
774 if (!pid) /* first time around */
776 if (!(pid = fl.l_pid)) goto done; /* shouldn't happen */
777 if (sig == -1)
779 if (kill( pid, SIGINT ) == -1) goto done;
780 kill( pid, SIGCONT );
781 ret = 1;
783 else /* just send the specified signal and return */
785 ret = (kill( pid, sig ) != -1);
786 goto done;
789 else if (fl.l_pid != pid) goto done; /* no longer the same process */
790 usleep( 50000 * i );
792 /* waited long enough, now kill it */
793 kill( pid, SIGKILL );
795 done:
796 close( fd );
797 return ret;
800 /* acquire the main server lock */
801 static void acquire_lock(void)
803 struct sockaddr_un addr;
804 struct stat st;
805 struct flock fl;
806 int fd, slen, got_lock = 0;
808 fd = create_server_lock();
810 fl.l_type = F_WRLCK;
811 fl.l_whence = SEEK_SET;
812 fl.l_start = 0;
813 fl.l_len = 1;
814 if (fcntl( fd, F_SETLK, &fl ) != -1)
816 /* check for crashed server */
817 if (stat( server_socket_name, &st ) != -1 && /* there is a leftover socket */
818 stat( "core", &st ) != -1 && st.st_size) /* and there is a non-empty core file */
820 fprintf( stderr,
821 "Warning: a previous instance of the wine server seems to have crashed.\n"
822 "Please run 'gdb %s %s/core',\n"
823 "type 'backtrace' at the gdb prompt and report the results. Thanks.\n\n",
824 server_argv0, server_dir );
826 unlink( server_socket_name ); /* we got the lock, we can safely remove the socket */
827 got_lock = 1;
828 /* in that case we reuse fd without closing it, this ensures
829 * that we hold the lock until the process exits */
831 else
833 switch(errno)
835 case ENOLCK:
836 break;
837 case EACCES:
838 /* check whether locks work at all on this file system */
839 if (fcntl( fd, F_GETLK, &fl ) == -1) break;
840 /* fall through */
841 case EAGAIN:
842 exit(2); /* we didn't get the lock, exit with special status */
843 default:
844 fatal_error( "fcntl %s/%s: %s\n", server_dir, server_lock_name, strerror( errno ));
846 /* it seems we can't use locks on this fs, so we will use the socket existence as lock */
847 close( fd );
850 if ((fd = socket( AF_UNIX, SOCK_STREAM, 0 )) == -1) fatal_error( "socket: %s\n", strerror( errno ));
851 addr.sun_family = AF_UNIX;
852 strcpy( addr.sun_path, server_socket_name );
853 slen = sizeof(addr) - sizeof(addr.sun_path) + strlen(addr.sun_path) + 1;
854 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
855 addr.sun_len = slen;
856 #endif
857 if (bind( fd, (struct sockaddr *)&addr, slen ) == -1)
859 if ((errno == EEXIST) || (errno == EADDRINUSE))
861 if (got_lock)
862 fatal_error( "couldn't bind to the socket even though we hold the lock\n" );
863 exit(2); /* we didn't get the lock, exit with special status */
865 fatal_error( "bind: %s\n", strerror( errno ));
867 atexit( socket_cleanup );
868 chmod( server_socket_name, 0600 ); /* make sure no other user can connect */
869 if (listen( fd, 5 ) == -1) fatal_error( "listen: %s\n", strerror( errno ));
871 if (!(master_socket = alloc_object( &master_socket_ops )) ||
872 !(master_socket->fd = create_anonymous_fd( &master_socket_fd_ops, fd, &master_socket->obj, 0 )))
873 fatal_error( "out of memory\n" );
874 set_fd_events( master_socket->fd, POLLIN );
875 make_object_permanent( &master_socket->obj );
878 /* open the master server socket and start waiting for new clients */
879 void open_master_socket(void)
881 int fd, pid, status, sync_pipe[2];
882 char dummy;
884 /* make sure no request is larger than the maximum size */
885 assert( sizeof(union generic_request) == sizeof(struct request_max_size) );
886 assert( sizeof(union generic_reply) == sizeof(struct request_max_size) );
888 /* make sure the stdio fds are open */
889 fd = open( "/dev/null", O_RDWR );
890 while (fd >= 0 && fd <= 2) fd = dup( fd );
892 server_dir = create_server_dir( 1 );
894 if (!foreground)
896 if (pipe( sync_pipe ) == -1) fatal_error( "pipe: %s\n", strerror( errno ));
897 pid = fork();
898 switch( pid )
900 case 0: /* child */
901 setsid();
902 close( sync_pipe[0] );
904 acquire_lock();
906 /* close stdin and stdout */
907 dup2( fd, 0 );
908 dup2( fd, 1 );
910 /* signal parent */
911 dummy = 0;
912 write( sync_pipe[1], &dummy, 1 );
913 close( sync_pipe[1] );
914 break;
916 case -1:
917 fatal_error( "fork: %s\n", strerror( errno ));
918 break;
920 default: /* parent */
921 close( sync_pipe[1] );
923 /* wait for child to signal us and then exit */
924 if (read( sync_pipe[0], &dummy, 1 ) == 1) _exit(0);
926 /* child terminated, propagate exit status */
927 waitpid( pid, &status, 0 );
928 if (WIFEXITED(status)) _exit( WEXITSTATUS(status) );
929 _exit(1);
932 else /* remain in the foreground */
934 acquire_lock();
937 /* init the process tracing mechanism */
938 init_tracing_mechanism();
939 close( fd );
942 /* master socket timer expiration handler */
943 static void close_socket_timeout( void *arg )
945 master_timeout = NULL;
946 flush_registry();
947 if (debug_level) fprintf( stderr, "wineserver: exiting (pid=%ld)\n", (long) getpid() );
949 #ifdef DEBUG_OBJECTS
950 close_objects(); /* shut down everything properly */
951 #endif
952 exit( 0 );
955 /* close the master socket and stop waiting for new clients */
956 void close_master_socket( timeout_t timeout )
958 if (master_socket)
960 release_object( master_socket );
961 master_socket = NULL;
963 if (master_timeout) /* cancel previous timeout */
964 remove_timeout_user( master_timeout );
966 master_timeout = add_timeout_user( timeout, close_socket_timeout, NULL );