wined3d: Don't return the BO address offset if glMapBuffer() fails.
[wine.git] / server / request.c
blobb7d2713aaa5bd0b98025740615f09c066a9b22b5
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"
23 #include <assert.h>
24 #include <errno.h>
25 #include <fcntl.h>
26 #ifdef HAVE_PWD_H
27 #include <pwd.h>
28 #endif
29 #include <signal.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <stdarg.h>
33 #include <string.h>
34 #include <sys/stat.h>
35 #include <sys/time.h>
36 #include <sys/types.h>
37 #ifdef HAVE_SYS_SOCKET_H
38 # include <sys/socket.h>
39 #endif
40 #ifdef HAVE_SYS_WAIT_H
41 # include <sys/wait.h>
42 #endif
43 #ifdef HAVE_SYS_UIO_H
44 #include <sys/uio.h>
45 #endif
46 #ifdef HAVE_SYS_UN_H
47 #include <sys/un.h>
48 #endif
49 #include <unistd.h>
50 #include <poll.h>
51 #ifdef __APPLE__
52 # include <mach/mach_time.h>
53 #endif
55 #include "ntstatus.h"
56 #define WIN32_NO_STATUS
57 #include "windef.h"
58 #include "winbase.h"
59 #include "wincon.h"
60 #include "winternl.h"
62 #include "file.h"
63 #include "process.h"
64 #include "thread.h"
65 #include "security.h"
66 #include "handle.h"
67 #define WANT_REQUEST_HANDLERS
68 #include "request.h"
70 /* Some versions of glibc don't define this */
71 #ifndef SCM_RIGHTS
72 #define SCM_RIGHTS 1
73 #endif
75 /* path names for server master Unix socket */
76 static const char * const server_socket_name = "socket"; /* name of the socket file */
77 static const char * const server_lock_name = "lock"; /* name of the server lock file */
79 struct master_socket
81 struct object obj; /* object header */
82 struct fd *fd; /* file descriptor of the master socket */
85 static void master_socket_dump( struct object *obj, int verbose );
86 static void master_socket_destroy( struct object *obj );
87 static void master_socket_poll_event( struct fd *fd, int event );
89 static const struct object_ops master_socket_ops =
91 sizeof(struct master_socket), /* size */
92 &no_type, /* type */
93 master_socket_dump, /* dump */
94 no_add_queue, /* add_queue */
95 NULL, /* remove_queue */
96 NULL, /* signaled */
97 NULL, /* satisfied */
98 no_signal, /* signal */
99 no_get_fd, /* get_fd */
100 default_map_access, /* map_access */
101 default_get_sd, /* get_sd */
102 default_set_sd, /* set_sd */
103 no_get_full_name, /* get_full_name */
104 no_lookup_name, /* lookup_name */
105 no_link_name, /* link_name */
106 NULL, /* unlink_name */
107 no_open_file, /* open_file */
108 no_kernel_obj_list, /* get_kernel_obj_list */
109 no_close_handle, /* close_handle */
110 master_socket_destroy /* destroy */
113 static const struct fd_ops master_socket_fd_ops =
115 NULL, /* get_poll_events */
116 master_socket_poll_event, /* poll_event */
117 NULL, /* flush */
118 NULL, /* get_fd_type */
119 NULL, /* ioctl */
120 NULL, /* queue_async */
121 NULL /* reselect_async */
125 struct thread *current = NULL; /* thread handling the current request */
126 unsigned int global_error = 0; /* global error code for when no thread is current */
127 timeout_t server_start_time = 0; /* server startup time */
128 char *server_dir = NULL; /* server directory */
129 int server_dir_fd = -1; /* file descriptor for the server dir */
130 int config_dir_fd = -1; /* file descriptor for the config dir */
132 static struct master_socket *master_socket; /* the master socket object */
133 static struct timeout_user *master_timeout;
135 /* complain about a protocol error and terminate the client connection */
136 void fatal_protocol_error( struct thread *thread, const char *err, ... )
138 va_list args;
140 va_start( args, err );
141 fprintf( stderr, "Protocol error:%04x: ", thread->id );
142 vfprintf( stderr, err, args );
143 va_end( args );
144 thread->exit_code = 1;
145 kill_thread( thread, 1 );
148 /* die on a fatal error */
149 void fatal_error( const char *err, ... )
151 va_list args;
153 va_start( args, err );
154 fprintf( stderr, "wineserver: " );
155 vfprintf( stderr, err, args );
156 va_end( args );
157 exit(1);
160 /* allocate the reply data */
161 void *set_reply_data_size( data_size_t size )
163 assert( size <= get_reply_max_size() );
164 if (size && !(current->reply_data = mem_alloc( size ))) size = 0;
165 current->reply_size = size;
166 return current->reply_data;
169 static const struct object_attributes empty_attributes;
171 /* return object attributes from the current request */
172 const struct object_attributes *get_req_object_attributes( const struct security_descriptor **sd,
173 struct unicode_str *name,
174 struct object **root )
176 const struct object_attributes *attr = get_req_data();
177 data_size_t size = get_req_data_size();
179 if (root) *root = NULL;
181 if (!size)
183 *sd = NULL;
184 name->len = 0;
185 return &empty_attributes;
188 if ((size < sizeof(*attr)) || (size - sizeof(*attr) < attr->sd_len) ||
189 (size - sizeof(*attr) - attr->sd_len < attr->name_len))
191 set_error( STATUS_ACCESS_VIOLATION );
192 return NULL;
194 if (attr->sd_len && !sd_is_valid( (const struct security_descriptor *)(attr + 1), attr->sd_len ))
196 set_error( STATUS_INVALID_SECURITY_DESCR );
197 return NULL;
199 if ((attr->name_len & (sizeof(WCHAR) - 1)) || attr->name_len >= 65534)
201 set_error( STATUS_OBJECT_NAME_INVALID );
202 return NULL;
204 if (root && attr->rootdir && attr->name_len)
206 if (!(*root = get_handle_obj( current->process, attr->rootdir, 0, NULL ))) return NULL;
208 *sd = attr->sd_len ? (const struct security_descriptor *)(attr + 1) : NULL;
209 name->len = attr->name_len;
210 name->str = (const WCHAR *)(attr + 1) + attr->sd_len / sizeof(WCHAR);
211 return attr;
214 /* return a pointer to the request data following an object attributes structure */
215 const void *get_req_data_after_objattr( const struct object_attributes *attr, data_size_t *len )
217 data_size_t size = (sizeof(*attr) + (attr->sd_len & ~1) + (attr->name_len & ~1) + 3) & ~3;
219 if (attr == &empty_attributes || size >= get_req_data_size())
221 *len = 0;
222 return NULL;
224 *len = get_req_data_size() - size;
225 return (const char *)get_req_data() + size;
228 /* write the remaining part of the reply */
229 void write_reply( struct thread *thread )
231 int ret;
233 if ((ret = write( get_unix_fd( thread->reply_fd ),
234 (char *)thread->reply_data + thread->reply_size - thread->reply_towrite,
235 thread->reply_towrite )) >= 0)
237 if (!(thread->reply_towrite -= ret))
239 free( thread->reply_data );
240 thread->reply_data = NULL;
241 /* sent everything, can go back to waiting for requests */
242 set_fd_events( thread->request_fd, POLLIN );
243 set_fd_events( thread->reply_fd, 0 );
245 return;
247 if (errno == EPIPE)
248 kill_thread( thread, 0 ); /* normal death */
249 else if (errno != EWOULDBLOCK && (EWOULDBLOCK == EAGAIN || errno != EAGAIN))
250 fatal_protocol_error( thread, "reply write: %s\n", strerror( errno ));
253 /* send a reply to the current thread */
254 static void send_reply( union generic_reply *reply )
256 int ret;
258 if (!current->reply_size)
260 if ((ret = write( get_unix_fd( current->reply_fd ),
261 reply, sizeof(*reply) )) != sizeof(*reply)) goto error;
263 else
265 struct iovec vec[2];
267 vec[0].iov_base = (void *)reply;
268 vec[0].iov_len = sizeof(*reply);
269 vec[1].iov_base = current->reply_data;
270 vec[1].iov_len = current->reply_size;
272 if ((ret = writev( get_unix_fd( current->reply_fd ), vec, 2 )) < sizeof(*reply)) goto error;
274 if ((current->reply_towrite = current->reply_size - (ret - sizeof(*reply))))
276 /* couldn't write it all, wait for POLLOUT */
277 set_fd_events( current->reply_fd, POLLOUT );
278 set_fd_events( current->request_fd, 0 );
279 return;
282 free( current->reply_data );
283 current->reply_data = NULL;
284 return;
286 error:
287 if (ret >= 0)
288 fatal_protocol_error( current, "partial write %d\n", ret );
289 else if (errno == EPIPE)
290 kill_thread( current, 0 ); /* normal death */
291 else
292 fatal_protocol_error( current, "reply write: %s\n", strerror( errno ));
295 /* call a request handler */
296 static void call_req_handler( struct thread *thread )
298 union generic_reply reply;
299 enum request req = thread->req.request_header.req;
301 current = thread;
302 current->reply_size = 0;
303 clear_error();
304 memset( &reply, 0, sizeof(reply) );
306 if (debug_level) trace_request();
308 if (req < REQ_NB_REQUESTS)
309 req_handlers[req]( &current->req, &reply );
310 else
311 set_error( STATUS_NOT_IMPLEMENTED );
313 if (current)
315 if (current->reply_fd)
317 reply.reply_header.error = current->error;
318 reply.reply_header.reply_size = current->reply_size;
319 if (debug_level) trace_reply( req, &reply );
320 send_reply( &reply );
322 else
324 current->exit_code = 1;
325 kill_thread( current, 1 ); /* no way to continue without reply fd */
328 current = NULL;
331 /* read a request from a thread */
332 void read_request( struct thread *thread )
334 int ret;
336 if (!thread->req_toread) /* no pending request */
338 if ((ret = read( get_unix_fd( thread->request_fd ), &thread->req,
339 sizeof(thread->req) )) != sizeof(thread->req)) goto error;
340 if (!(thread->req_toread = thread->req.request_header.request_size))
342 /* no data, handle request at once */
343 call_req_handler( thread );
344 return;
346 if (!(thread->req_data = malloc( thread->req_toread )))
348 fatal_protocol_error( thread, "no memory for %u bytes request %d\n",
349 thread->req_toread, thread->req.request_header.req );
350 return;
354 /* read the variable sized data */
355 for (;;)
357 ret = read( get_unix_fd( thread->request_fd ),
358 (char *)thread->req_data + thread->req.request_header.request_size
359 - thread->req_toread,
360 thread->req_toread );
361 if (ret <= 0) break;
362 if (!(thread->req_toread -= ret))
364 call_req_handler( thread );
365 free( thread->req_data );
366 thread->req_data = NULL;
367 return;
371 error:
372 if (!ret) /* closed pipe */
373 kill_thread( thread, 0 );
374 else if (ret > 0)
375 fatal_protocol_error( thread, "partial read %d\n", ret );
376 else if (errno != EWOULDBLOCK && (EWOULDBLOCK == EAGAIN || errno != EAGAIN))
377 fatal_protocol_error( thread, "read: %s\n", strerror( errno ));
380 /* receive a file descriptor on the process socket */
381 int receive_fd( struct process *process )
383 struct iovec vec;
384 struct send_fd data;
385 struct msghdr msghdr;
386 int fd = -1, ret;
388 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
389 msghdr.msg_accrightslen = sizeof(int);
390 msghdr.msg_accrights = (void *)&fd;
391 #else /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
392 char cmsg_buffer[256];
393 msghdr.msg_control = cmsg_buffer;
394 msghdr.msg_controllen = sizeof(cmsg_buffer);
395 msghdr.msg_flags = 0;
396 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
398 msghdr.msg_name = NULL;
399 msghdr.msg_namelen = 0;
400 msghdr.msg_iov = &vec;
401 msghdr.msg_iovlen = 1;
402 vec.iov_base = (void *)&data;
403 vec.iov_len = sizeof(data);
405 ret = recvmsg( get_unix_fd( process->msg_fd ), &msghdr, 0 );
407 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
408 if (ret > 0)
410 struct cmsghdr *cmsg;
411 for (cmsg = CMSG_FIRSTHDR( &msghdr ); cmsg; cmsg = CMSG_NXTHDR( &msghdr, cmsg ))
413 if (cmsg->cmsg_level != SOL_SOCKET) continue;
414 if (cmsg->cmsg_type == SCM_RIGHTS) fd = *(int *)CMSG_DATA(cmsg);
417 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
419 if (ret == sizeof(data))
421 struct thread *thread;
423 if (data.tid) thread = get_thread_from_id( data.tid );
424 else thread = (struct thread *)grab_object( get_process_first_thread( process ));
426 if (!thread || thread->process != process || thread->state == TERMINATED)
428 if (debug_level)
429 fprintf( stderr, "%04x: *fd* %d <- %d bad thread id\n",
430 data.tid, data.fd, fd );
431 close( fd );
433 else
435 if (debug_level)
436 fprintf( stderr, "%04x: *fd* %d <- %d\n",
437 thread->id, data.fd, fd );
438 thread_add_inflight_fd( thread, data.fd, fd );
440 if (thread) release_object( thread );
441 return 0;
444 if (!ret)
446 kill_process( process, 0 );
448 else if (ret > 0)
450 fprintf( stderr, "Protocol error: process %04x: partial recvmsg %d for fd\n",
451 process->id, ret );
452 if (fd != -1) close( fd );
453 kill_process( process, 1 );
455 else
457 if (errno != EWOULDBLOCK && (EWOULDBLOCK == EAGAIN || errno != EAGAIN))
459 fprintf( stderr, "Protocol error: process %04x: ", process->id );
460 perror( "recvmsg" );
461 kill_process( process, 1 );
464 return -1;
467 /* send an fd to a client */
468 int send_client_fd( struct process *process, int fd, obj_handle_t handle )
470 struct iovec vec;
471 struct msghdr msghdr;
472 int ret;
474 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
475 msghdr.msg_accrightslen = sizeof(fd);
476 msghdr.msg_accrights = (void *)&fd;
477 #else /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
478 char cmsg_buffer[256];
479 struct cmsghdr *cmsg;
480 msghdr.msg_control = cmsg_buffer;
481 msghdr.msg_controllen = sizeof(cmsg_buffer);
482 msghdr.msg_flags = 0;
483 cmsg = CMSG_FIRSTHDR( &msghdr );
484 cmsg->cmsg_len = CMSG_LEN( sizeof(fd) );
485 cmsg->cmsg_level = SOL_SOCKET;
486 cmsg->cmsg_type = SCM_RIGHTS;
487 *(int *)CMSG_DATA(cmsg) = fd;
488 msghdr.msg_controllen = cmsg->cmsg_len;
489 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
491 msghdr.msg_name = NULL;
492 msghdr.msg_namelen = 0;
493 msghdr.msg_iov = &vec;
494 msghdr.msg_iovlen = 1;
496 vec.iov_base = (void *)&handle;
497 vec.iov_len = sizeof(handle);
499 if (debug_level)
500 fprintf( stderr, "%04x: *fd* %04x -> %d\n", current ? current->id : process->id, handle, fd );
502 ret = sendmsg( get_unix_fd( process->msg_fd ), &msghdr, 0 );
504 if (ret == sizeof(handle)) return 0;
506 if (ret >= 0)
508 fprintf( stderr, "Protocol error: process %04x: partial sendmsg %d\n", process->id, ret );
509 kill_process( process, 1 );
511 else if (errno == EPIPE)
513 kill_process( process, 0 );
515 else
517 fprintf( stderr, "Protocol error: process %04x: ", process->id );
518 perror( "sendmsg" );
519 kill_process( process, 1 );
521 return -1;
524 /* return a monotonic time counter */
525 timeout_t monotonic_counter(void)
527 #ifdef __APPLE__
528 static mach_timebase_info_data_t timebase;
530 if (!timebase.denom) mach_timebase_info( &timebase );
531 #ifdef HAVE_MACH_CONTINUOUS_TIME
532 if (&mach_continuous_time != NULL)
533 return mach_continuous_time() * timebase.numer / timebase.denom / 100;
534 #endif
535 return mach_absolute_time() * timebase.numer / timebase.denom / 100;
536 #elif defined(HAVE_CLOCK_GETTIME)
537 struct timespec ts;
538 #ifdef CLOCK_MONOTONIC_RAW
539 if (!clock_gettime( CLOCK_MONOTONIC_RAW, &ts ))
540 return (timeout_t)ts.tv_sec * TICKS_PER_SEC + ts.tv_nsec / 100;
541 #endif
542 if (!clock_gettime( CLOCK_MONOTONIC, &ts ))
543 return (timeout_t)ts.tv_sec * TICKS_PER_SEC + ts.tv_nsec / 100;
544 #endif
545 return current_time - server_start_time;
548 static void master_socket_dump( struct object *obj, int verbose )
550 struct master_socket *sock = (struct master_socket *)obj;
551 assert( obj->ops == &master_socket_ops );
552 fprintf( stderr, "Master socket fd=%p\n", sock->fd );
555 static void master_socket_destroy( struct object *obj )
557 struct master_socket *sock = (struct master_socket *)obj;
558 assert( obj->ops == &master_socket_ops );
559 release_object( sock->fd );
562 /* handle a socket event */
563 static void master_socket_poll_event( struct fd *fd, int event )
565 struct master_socket *sock = get_fd_user( fd );
566 assert( master_socket->obj.ops == &master_socket_ops );
568 assert( sock == master_socket ); /* there is only one master socket */
570 if (event & (POLLERR | POLLHUP))
572 /* this is not supposed to happen */
573 fprintf( stderr, "wineserver: Error on master socket\n" );
574 set_fd_events( sock->fd, -1 );
576 else if (event & POLLIN)
578 struct process *process;
579 struct sockaddr_un dummy;
580 socklen_t len = sizeof(dummy);
581 int client = accept( get_unix_fd( master_socket->fd ), (struct sockaddr *) &dummy, &len );
582 if (client == -1) return;
583 fcntl( client, F_SETFL, O_NONBLOCK );
584 if ((process = create_process( client, NULL, 0, NULL, NULL, NULL, 0, NULL )))
586 create_thread( -1, process, NULL );
587 release_object( process );
592 /* remove the socket upon exit */
593 static void socket_cleanup(void)
595 static int do_it_once;
596 if (!do_it_once++) unlink( server_socket_name );
599 /* create a directory and check its permissions */
600 static void create_dir( const char *name, struct stat *st )
602 if (lstat( name, st ) == -1)
604 if (errno != ENOENT)
605 fatal_error( "lstat %s: %s\n", name, strerror( errno ));
606 if (mkdir( name, 0700 ) == -1 && errno != EEXIST)
607 fatal_error( "mkdir %s: %s\n", name, strerror( errno ));
608 if (lstat( name, st ) == -1)
609 fatal_error( "lstat %s: %s\n", name, strerror( errno ));
611 if (!S_ISDIR(st->st_mode)) fatal_error( "%s is not a directory\n", name );
612 if (st->st_uid != getuid()) fatal_error( "%s is not owned by you\n", name );
613 if (st->st_mode & 077) fatal_error( "%s must not be accessible by other users\n", name );
616 /* create the server directory and chdir to it */
617 static char *create_server_dir( int force )
619 const char *prefix = getenv( "WINEPREFIX" );
620 char *p, *config_dir;
621 struct stat st, st2;
622 size_t len = sizeof("/server-") + 2 * sizeof(st.st_dev) + 2 * sizeof(st.st_ino) + 2;
624 /* open the configuration directory */
626 if (prefix)
628 if (!(config_dir = strdup( prefix ))) fatal_error( "out of memory\n" );
629 for (p = config_dir + strlen(config_dir); p > config_dir; p--) if (p[-1] != '/') break;
630 if (p > config_dir) *p = 0;
631 if (config_dir[0] != '/')
632 fatal_error( "invalid directory %s in WINEPREFIX: not an absolute path\n", prefix );
634 else
636 const char *home = getenv( "HOME" );
637 if (!home)
639 struct passwd *pwd = getpwuid( getuid() );
640 if (pwd) home = pwd->pw_dir;
642 if (!home) fatal_error( "could not determine your home directory\n" );
643 if (home[0] != '/') fatal_error( "your home directory %s is not an absolute path\n", home );
644 if (!(config_dir = malloc( strlen(home) + sizeof("/.wine") ))) fatal_error( "out of memory\n" );
645 strcpy( config_dir, home );
646 for (p = config_dir + strlen(config_dir); p > config_dir; p--) if (p[-1] != '/') break;
647 strcpy( p, "/.wine" );
650 if (chdir( config_dir ) == -1)
652 if (errno != ENOENT || force) fatal_error( "chdir to %s: %s\n", config_dir, strerror( errno ));
653 return NULL;
655 if ((config_dir_fd = open( ".", O_RDONLY )) == -1)
656 fatal_error( "open %s: %s\n", config_dir, strerror( errno ));
657 if (fstat( config_dir_fd, &st ) == -1)
658 fatal_error( "stat %s: %s\n", config_dir, strerror( errno ));
659 if (st.st_uid != getuid())
660 fatal_error( "%s is not owned by you\n", config_dir );
662 /* create the base directory if needed */
664 #ifdef __ANDROID__ /* there's no /tmp dir on Android */
665 len += strlen( config_dir ) + sizeof("/.wineserver");
666 if (!(server_dir = malloc( len ))) fatal_error( "out of memory\n" );
667 strcpy( server_dir, config_dir );
668 strcat( server_dir, "/.wineserver" );
669 #else
670 len += sizeof("/tmp/.wine-") + 12;
671 if (!(server_dir = malloc( len ))) fatal_error( "out of memory\n" );
672 sprintf( server_dir, "/tmp/.wine-%u", getuid() );
673 #endif
674 create_dir( server_dir, &st2 );
676 /* now create the server directory */
678 strcat( server_dir, "/server-" );
679 p = server_dir + strlen(server_dir);
681 if (st.st_dev != (unsigned long)st.st_dev)
682 p += sprintf( p, "%lx%08lx-", (unsigned long)((unsigned long long)st.st_dev >> 32),
683 (unsigned long)st.st_dev );
684 else
685 p += sprintf( p, "%lx-", (unsigned long)st.st_dev );
687 if (st.st_ino != (unsigned long)st.st_ino)
688 sprintf( p, "%lx%08lx", (unsigned long)((unsigned long long)st.st_ino >> 32),
689 (unsigned long)st.st_ino );
690 else
691 sprintf( p, "%lx", (unsigned long)st.st_ino );
693 create_dir( server_dir, &st );
695 if (chdir( server_dir ) == -1)
696 fatal_error( "chdir %s: %s\n", server_dir, strerror( errno ));
697 if ((server_dir_fd = open( ".", O_RDONLY )) == -1)
698 fatal_error( "open %s: %s\n", server_dir, strerror( errno ));
699 if (fstat( server_dir_fd, &st2 ) == -1)
700 fatal_error( "stat %s: %s\n", server_dir, strerror( errno ));
701 if (st.st_dev != st2.st_dev || st.st_ino != st2.st_ino)
702 fatal_error( "chdir did not end up in %s\n", server_dir );
704 free( config_dir );
705 return server_dir;
708 /* create the lock file and return its file descriptor */
709 static int create_server_lock(void)
711 struct stat st;
712 int fd;
714 if (lstat( server_lock_name, &st ) == -1)
716 if (errno != ENOENT)
717 fatal_error( "lstat %s/%s: %s\n", server_dir, server_lock_name, strerror( errno ));
719 else
721 if (!S_ISREG(st.st_mode))
722 fatal_error( "%s/%s is not a regular file\n", server_dir, server_lock_name );
725 if ((fd = open( server_lock_name, O_CREAT|O_TRUNC|O_WRONLY, 0600 )) == -1)
726 fatal_error( "error creating %s/%s: %s\n", server_dir, server_lock_name, strerror( errno ));
727 return fd;
730 /* wait for the server lock */
731 int wait_for_lock(void)
733 int fd, r;
734 struct flock fl;
736 server_dir = create_server_dir( 0 );
737 if (!server_dir) return 0; /* no server dir, so no lock to wait on */
739 fd = create_server_lock();
741 fl.l_type = F_WRLCK;
742 fl.l_whence = SEEK_SET;
743 fl.l_start = 0;
744 fl.l_len = 1;
745 r = fcntl( fd, F_SETLKW, &fl );
746 close(fd);
748 return r;
751 /* kill the wine server holding the lock */
752 int kill_lock_owner( int sig )
754 int fd, i, ret = 0;
755 pid_t pid = 0;
756 struct flock fl;
758 server_dir = create_server_dir( 0 );
759 if (!server_dir) return 0; /* no server dir, nothing to do */
761 fd = create_server_lock();
763 for (i = 1; i <= 20; i++)
765 fl.l_type = F_WRLCK;
766 fl.l_whence = SEEK_SET;
767 fl.l_start = 0;
768 fl.l_len = 1;
769 if (fcntl( fd, F_GETLK, &fl ) == -1) goto done;
770 if (fl.l_type != F_WRLCK) goto done; /* the file is not locked */
771 if (!pid) /* first time around */
773 if (!(pid = fl.l_pid)) goto done; /* shouldn't happen */
774 if (sig == -1)
776 if (kill( pid, SIGINT ) == -1) goto done;
777 kill( pid, SIGCONT );
778 ret = 1;
780 else /* just send the specified signal and return */
782 ret = (kill( pid, sig ) != -1);
783 goto done;
786 else if (fl.l_pid != pid) goto done; /* no longer the same process */
787 usleep( 50000 * i );
789 /* waited long enough, now kill it */
790 kill( pid, SIGKILL );
792 done:
793 close( fd );
794 return ret;
797 /* acquire the main server lock */
798 static void acquire_lock(void)
800 struct sockaddr_un addr;
801 struct stat st;
802 struct flock fl;
803 int fd, slen, got_lock = 0;
805 fd = create_server_lock();
807 fl.l_type = F_WRLCK;
808 fl.l_whence = SEEK_SET;
809 fl.l_start = 0;
810 fl.l_len = 1;
811 if (fcntl( fd, F_SETLK, &fl ) != -1)
813 /* check for crashed server */
814 if (stat( server_socket_name, &st ) != -1 && /* there is a leftover socket */
815 stat( "core", &st ) != -1 && st.st_size) /* and there is a non-empty core file */
817 fprintf( stderr,
818 "Warning: a previous instance of the wine server seems to have crashed.\n"
819 "Please run 'gdb %s %s/core',\n"
820 "type 'backtrace' at the gdb prompt and report the results. Thanks.\n\n",
821 server_argv0, server_dir );
823 unlink( server_socket_name ); /* we got the lock, we can safely remove the socket */
824 got_lock = 1;
825 /* in that case we reuse fd without closing it, this ensures
826 * that we hold the lock until the process exits */
828 else
830 switch(errno)
832 case ENOLCK:
833 break;
834 case EACCES:
835 /* check whether locks work at all on this file system */
836 if (fcntl( fd, F_GETLK, &fl ) == -1) break;
837 /* fall through */
838 case EAGAIN:
839 exit(2); /* we didn't get the lock, exit with special status */
840 default:
841 fatal_error( "fcntl %s/%s: %s\n", server_dir, server_lock_name, strerror( errno ));
843 /* it seems we can't use locks on this fs, so we will use the socket existence as lock */
844 close( fd );
847 if ((fd = socket( AF_UNIX, SOCK_STREAM, 0 )) == -1) fatal_error( "socket: %s\n", strerror( errno ));
848 addr.sun_family = AF_UNIX;
849 strcpy( addr.sun_path, server_socket_name );
850 slen = sizeof(addr) - sizeof(addr.sun_path) + strlen(addr.sun_path) + 1;
851 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
852 addr.sun_len = slen;
853 #endif
854 if (bind( fd, (struct sockaddr *)&addr, slen ) == -1)
856 if ((errno == EEXIST) || (errno == EADDRINUSE))
858 if (got_lock)
859 fatal_error( "couldn't bind to the socket even though we hold the lock\n" );
860 exit(2); /* we didn't get the lock, exit with special status */
862 fatal_error( "bind: %s\n", strerror( errno ));
864 atexit( socket_cleanup );
865 chmod( server_socket_name, 0600 ); /* make sure no other user can connect */
866 if (listen( fd, 5 ) == -1) fatal_error( "listen: %s\n", strerror( errno ));
868 if (!(master_socket = alloc_object( &master_socket_ops )) ||
869 !(master_socket->fd = create_anonymous_fd( &master_socket_fd_ops, fd, &master_socket->obj, 0 )))
870 fatal_error( "out of memory\n" );
871 set_fd_events( master_socket->fd, POLLIN );
872 make_object_permanent( &master_socket->obj );
875 /* open the master server socket and start waiting for new clients */
876 void open_master_socket(void)
878 int fd, pid, status, sync_pipe[2];
879 char dummy;
881 /* make sure no request is larger than the maximum size */
882 assert( sizeof(union generic_request) == sizeof(struct request_max_size) );
883 assert( sizeof(union generic_reply) == sizeof(struct request_max_size) );
885 /* make sure the stdio fds are open */
886 fd = open( "/dev/null", O_RDWR );
887 while (fd >= 0 && fd <= 2) fd = dup( fd );
889 server_dir = create_server_dir( 1 );
891 if (!foreground)
893 if (pipe( sync_pipe ) == -1) fatal_error( "pipe: %s\n", strerror( errno ));
894 pid = fork();
895 switch( pid )
897 case 0: /* child */
898 setsid();
899 close( sync_pipe[0] );
901 acquire_lock();
903 /* close stdin and stdout */
904 dup2( fd, 0 );
905 dup2( fd, 1 );
907 /* signal parent */
908 dummy = 0;
909 write( sync_pipe[1], &dummy, 1 );
910 close( sync_pipe[1] );
911 break;
913 case -1:
914 fatal_error( "fork: %s\n", strerror( errno ));
915 break;
917 default: /* parent */
918 close( sync_pipe[1] );
920 /* wait for child to signal us and then exit */
921 if (read( sync_pipe[0], &dummy, 1 ) == 1) _exit(0);
923 /* child terminated, propagate exit status */
924 waitpid( pid, &status, 0 );
925 if (WIFEXITED(status)) _exit( WEXITSTATUS(status) );
926 _exit(1);
929 else /* remain in the foreground */
931 acquire_lock();
934 /* init the process tracing mechanism */
935 init_tracing_mechanism();
936 close( fd );
939 /* master socket timer expiration handler */
940 static void close_socket_timeout( void *arg )
942 master_timeout = NULL;
943 flush_registry();
944 if (debug_level) fprintf( stderr, "wineserver: exiting (pid=%ld)\n", (long) getpid() );
946 #ifdef DEBUG_OBJECTS
947 close_objects(); /* shut down everything properly */
948 #endif
949 exit( 0 );
952 /* close the master socket and stop waiting for new clients */
953 void close_master_socket( timeout_t timeout )
955 if (master_socket)
957 release_object( master_socket );
958 master_socket = NULL;
960 if (master_timeout) /* cancel previous timeout */
961 remove_timeout_user( master_timeout );
963 master_timeout = add_timeout_user( timeout, close_socket_timeout, NULL );