server: Add functions for conversions between server object handles and pointer-style...
[wine] / dlls / ntdll / server.c
1 /*
2  * Wine server communication
3  *
4  * Copyright (C) 1998 Alexandre Julliard
5  *
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.
10  *
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.
15  *
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
19  */
20
21 #include "config.h"
22 #include "wine/port.h"
23
24 #include <assert.h>
25 #include <ctype.h>
26 #ifdef HAVE_DIRENT_H
27 # include <dirent.h>
28 #endif
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <signal.h>
32 #include <stdarg.h>
33 #include <stdio.h>
34 #include <string.h>
35 #include <sys/types.h>
36 #ifdef HAVE_SYS_SOCKET_H
37 # include <sys/socket.h>
38 #endif
39 #ifdef HAVE_SYS_WAIT_H
40 #include <sys/wait.h>
41 #endif
42 #ifdef HAVE_SYS_UN_H
43 #include <sys/un.h>
44 #endif
45 #ifdef HAVE_SYS_MMAN_H
46 #include <sys/mman.h>
47 #endif
48 #ifdef HAVE_SYS_STAT_H
49 # include <sys/stat.h>
50 #endif
51 #ifdef HAVE_SYS_UIO_H
52 #include <sys/uio.h>
53 #endif
54 #ifdef HAVE_UNISTD_H
55 # include <unistd.h>
56 #endif
57
58 #include "ntstatus.h"
59 #define WIN32_NO_STATUS
60 #include "wine/library.h"
61 #include "wine/pthread.h"
62 #include "wine/server.h"
63 #include "wine/debug.h"
64 #include "ntdll_misc.h"
65
66 WINE_DEFAULT_DEBUG_CHANNEL(server);
67
68 /* Some versions of glibc don't define this */
69 #ifndef SCM_RIGHTS
70 #define SCM_RIGHTS 1
71 #endif
72
73 #define SOCKETNAME "socket"        /* name of the socket file */
74 #define LOCKNAME   "lock"          /* name of the lock file */
75
76 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
77 /* data structure used to pass an fd with sendmsg/recvmsg */
78 struct cmsg_fd
79 {
80     struct
81     {
82         size_t len;   /* size of structure */
83         int    level; /* SOL_SOCKET */
84         int    type;  /* SCM_RIGHTS */
85     } header;
86     int fd;          /* fd to pass */
87 };
88 #endif  /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
89
90 timeout_t server_start_time = 0;  /* time of server startup */
91
92 extern struct wine_pthread_functions pthread_functions;
93
94 sigset_t server_block_set;  /* signals to block during server calls */
95 static int fd_socket = -1;  /* socket to exchange file descriptors with the server */
96
97 static RTL_CRITICAL_SECTION fd_cache_section;
98 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
99 {
100     0, 0, &fd_cache_section,
101     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
102       0, 0, { (DWORD_PTR)(__FILE__ ": fd_cache_section") }
103 };
104 static RTL_CRITICAL_SECTION fd_cache_section = { &critsect_debug, -1, 0, 0, 0, 0 };
105
106
107 #ifdef __GNUC__
108 static void fatal_error( const char *err, ... ) __attribute__((noreturn, format(printf,1,2)));
109 static void fatal_perror( const char *err, ... ) __attribute__((noreturn, format(printf,1,2)));
110 static void server_connect_error( const char *serverdir ) __attribute__((noreturn));
111 #endif
112
113 /* die on a fatal error; use only during initialization */
114 static void fatal_error( const char *err, ... )
115 {
116     va_list args;
117
118     va_start( args, err );
119     fprintf( stderr, "wine: " );
120     vfprintf( stderr, err, args );
121     va_end( args );
122     exit(1);
123 }
124
125 /* die on a fatal error; use only during initialization */
126 static void fatal_perror( const char *err, ... )
127 {
128     va_list args;
129
130     va_start( args, err );
131     fprintf( stderr, "wine: " );
132     vfprintf( stderr, err, args );
133     perror( " " );
134     va_end( args );
135     exit(1);
136 }
137
138
139 /***********************************************************************
140  *           server_exit_thread
141  */
142 void server_exit_thread( int status )
143 {
144     struct wine_pthread_thread_info info;
145     int fds[4];
146
147     RtlAcquirePebLock();
148     RemoveEntryList( &NtCurrentTeb()->TlsLinks );
149     RtlReleasePebLock();
150     RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots );
151     RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots );
152
153     info.stack_base  = NtCurrentTeb()->DeallocationStack;
154     info.teb_base    = NtCurrentTeb();
155     info.teb_sel     = wine_get_fs();
156     info.exit_status = status;
157
158     fds[0] = ntdll_get_thread_data()->wait_fd[0];
159     fds[1] = ntdll_get_thread_data()->wait_fd[1];
160     fds[2] = ntdll_get_thread_data()->reply_fd;
161     fds[3] = ntdll_get_thread_data()->request_fd;
162     pthread_functions.sigprocmask( SIG_BLOCK, &server_block_set, NULL );
163
164     info.stack_size = virtual_free_system_view( &info.stack_base );
165     info.teb_size = virtual_free_system_view( &info.teb_base );
166
167     close( fds[0] );
168     close( fds[1] );
169     close( fds[2] );
170     close( fds[3] );
171     pthread_functions.exit_thread( &info );
172 }
173
174
175 /***********************************************************************
176  *           server_abort_thread
177  */
178 void server_abort_thread( int status )
179 {
180     pthread_functions.sigprocmask( SIG_BLOCK, &server_block_set, NULL );
181     close( ntdll_get_thread_data()->wait_fd[0] );
182     close( ntdll_get_thread_data()->wait_fd[1] );
183     close( ntdll_get_thread_data()->reply_fd );
184     close( ntdll_get_thread_data()->request_fd );
185     pthread_functions.abort_thread( status );
186 }
187
188
189 /***********************************************************************
190  *           server_protocol_error
191  */
192 void server_protocol_error( const char *err, ... )
193 {
194     va_list args;
195
196     va_start( args, err );
197     fprintf( stderr, "wine client error:%x: ", GetCurrentThreadId() );
198     vfprintf( stderr, err, args );
199     va_end( args );
200     server_abort_thread(1);
201 }
202
203
204 /***********************************************************************
205  *           server_protocol_perror
206  */
207 void server_protocol_perror( const char *err )
208 {
209     fprintf( stderr, "wine client error:%x: ", GetCurrentThreadId() );
210     perror( err );
211     server_abort_thread(1);
212 }
213
214
215 /***********************************************************************
216  *           send_request
217  *
218  * Send a request to the server.
219  */
220 static unsigned int send_request( const struct __server_request_info *req )
221 {
222     unsigned int i;
223     int ret;
224
225     if (!req->u.req.request_header.request_size)
226     {
227         if ((ret = write( ntdll_get_thread_data()->request_fd, &req->u.req,
228                           sizeof(req->u.req) )) == sizeof(req->u.req)) return STATUS_SUCCESS;
229
230     }
231     else
232     {
233         struct iovec vec[__SERVER_MAX_DATA+1];
234
235         vec[0].iov_base = (void *)&req->u.req;
236         vec[0].iov_len = sizeof(req->u.req);
237         for (i = 0; i < req->data_count; i++)
238         {
239             vec[i+1].iov_base = (void *)req->data[i].ptr;
240             vec[i+1].iov_len = req->data[i].size;
241         }
242         if ((ret = writev( ntdll_get_thread_data()->request_fd, vec, i+1 )) ==
243             req->u.req.request_header.request_size + sizeof(req->u.req)) return STATUS_SUCCESS;
244     }
245
246     if (ret >= 0) server_protocol_error( "partial write %d\n", ret );
247     if (errno == EPIPE) server_abort_thread(0);
248     if (errno == EFAULT) return STATUS_ACCESS_VIOLATION;
249     server_protocol_perror( "write" );
250 }
251
252
253 /***********************************************************************
254  *           read_reply_data
255  *
256  * Read data from the reply buffer; helper for wait_reply.
257  */
258 static void read_reply_data( void *buffer, size_t size )
259 {
260     int ret;
261
262     for (;;)
263     {
264         if ((ret = read( ntdll_get_thread_data()->reply_fd, buffer, size )) > 0)
265         {
266             if (!(size -= ret)) return;
267             buffer = (char *)buffer + ret;
268             continue;
269         }
270         if (!ret) break;
271         if (errno == EINTR) continue;
272         if (errno == EPIPE) break;
273         server_protocol_perror("read");
274     }
275     /* the server closed the connection; time to die... */
276     server_abort_thread(0);
277 }
278
279
280 /***********************************************************************
281  *           wait_reply
282  *
283  * Wait for a reply from the server.
284  */
285 static inline unsigned int wait_reply( struct __server_request_info *req )
286 {
287     read_reply_data( &req->u.reply, sizeof(req->u.reply) );
288     if (req->u.reply.reply_header.reply_size)
289         read_reply_data( req->reply_data, req->u.reply.reply_header.reply_size );
290     return req->u.reply.reply_header.error;
291 }
292
293
294 /***********************************************************************
295  *           wine_server_call (NTDLL.@)
296  *
297  * Perform a server call.
298  *
299  * PARAMS
300  *     req_ptr [I/O] Function dependent data
301  *
302  * RETURNS
303  *     Depends on server function being called, but usually an NTSTATUS code.
304  *
305  * NOTES
306  *     Use the SERVER_START_REQ and SERVER_END_REQ to help you fill out the
307  *     server request structure for the particular call. E.g:
308  *|     SERVER_START_REQ( event_op )
309  *|     {
310  *|         req->handle = handle;
311  *|         req->op     = SET_EVENT;
312  *|         ret = wine_server_call( req );
313  *|     }
314  *|     SERVER_END_REQ;
315  */
316 unsigned int wine_server_call( void *req_ptr )
317 {
318     struct __server_request_info * const req = req_ptr;
319     sigset_t old_set;
320     unsigned int ret;
321
322     pthread_functions.sigprocmask( SIG_BLOCK, &server_block_set, &old_set );
323     ret = send_request( req );
324     if (!ret) ret = wait_reply( req );
325     pthread_functions.sigprocmask( SIG_SETMASK, &old_set, NULL );
326     return ret;
327 }
328
329
330 /***********************************************************************
331  *           server_enter_uninterrupted_section
332  */
333 void server_enter_uninterrupted_section( RTL_CRITICAL_SECTION *cs, sigset_t *sigset )
334 {
335     pthread_functions.sigprocmask( SIG_BLOCK, &server_block_set, sigset );
336     RtlEnterCriticalSection( cs );
337 }
338
339
340 /***********************************************************************
341  *           server_leave_uninterrupted_section
342  */
343 void server_leave_uninterrupted_section( RTL_CRITICAL_SECTION *cs, sigset_t *sigset )
344 {
345     RtlLeaveCriticalSection( cs );
346     pthread_functions.sigprocmask( SIG_SETMASK, sigset, NULL );
347 }
348
349
350 /***********************************************************************
351  *           wine_server_send_fd   (NTDLL.@)
352  *
353  * Send a file descriptor to the server.
354  *
355  * PARAMS
356  *     fd [I] file descriptor to send
357  *
358  * RETURNS
359  *     nothing
360  */
361 void wine_server_send_fd( int fd )
362 {
363 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
364     struct cmsg_fd cmsg;
365 #endif
366     struct send_fd data;
367     struct msghdr msghdr;
368     struct iovec vec;
369     int ret;
370
371     vec.iov_base = (void *)&data;
372     vec.iov_len  = sizeof(data);
373
374     msghdr.msg_name    = NULL;
375     msghdr.msg_namelen = 0;
376     msghdr.msg_iov     = &vec;
377     msghdr.msg_iovlen  = 1;
378
379 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
380     msghdr.msg_accrights    = (void *)&fd;
381     msghdr.msg_accrightslen = sizeof(fd);
382 #else  /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
383     cmsg.header.len   = sizeof(cmsg.header) + sizeof(fd);
384     cmsg.header.level = SOL_SOCKET;
385     cmsg.header.type  = SCM_RIGHTS;
386     cmsg.fd           = fd;
387     msghdr.msg_control    = &cmsg;
388     msghdr.msg_controllen = sizeof(cmsg.header) + sizeof(fd);
389     msghdr.msg_flags      = 0;
390 #endif  /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
391
392     data.tid = GetCurrentThreadId();
393     data.fd  = fd;
394
395     for (;;)
396     {
397         if ((ret = sendmsg( fd_socket, &msghdr, 0 )) == sizeof(data)) return;
398         if (ret >= 0) server_protocol_error( "partial write %d\n", ret );
399         if (errno == EINTR) continue;
400         if (errno == EPIPE) server_abort_thread(0);
401         server_protocol_perror( "sendmsg" );
402     }
403 }
404
405
406 /***********************************************************************
407  *           receive_fd
408  *
409  * Receive a file descriptor passed from the server.
410  */
411 static int receive_fd( obj_handle_t *handle )
412 {
413     struct iovec vec;
414     int ret, fd;
415
416 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
417     struct msghdr msghdr;
418
419     fd = -1;
420     msghdr.msg_accrights    = (void *)&fd;
421     msghdr.msg_accrightslen = sizeof(fd);
422 #else  /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
423     struct msghdr msghdr;
424     struct cmsg_fd cmsg;
425
426     cmsg.header.len   = sizeof(cmsg.header) + sizeof(fd);
427     cmsg.header.level = SOL_SOCKET;
428     cmsg.header.type  = SCM_RIGHTS;
429     cmsg.fd           = -1;
430     msghdr.msg_control    = &cmsg;
431     msghdr.msg_controllen = sizeof(cmsg.header) + sizeof(fd);
432     msghdr.msg_flags      = 0;
433 #endif  /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
434
435     msghdr.msg_name    = NULL;
436     msghdr.msg_namelen = 0;
437     msghdr.msg_iov     = &vec;
438     msghdr.msg_iovlen  = 1;
439     vec.iov_base = (void *)handle;
440     vec.iov_len  = sizeof(*handle);
441
442     for (;;)
443     {
444         if ((ret = recvmsg( fd_socket, &msghdr, 0 )) > 0)
445         {
446 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
447             fd = cmsg.fd;
448 #endif
449             if (fd != -1) fcntl( fd, F_SETFD, 1 ); /* set close on exec flag */
450             return fd;
451         }
452         if (!ret) break;
453         if (errno == EINTR) continue;
454         if (errno == EPIPE) break;
455         server_protocol_perror("recvmsg");
456     }
457     /* the server closed the connection; time to die... */
458     server_abort_thread(0);
459 }
460
461
462 /***********************************************************************/
463 /* fd cache support */
464
465 struct fd_cache_entry
466 {
467     int fd;
468     enum server_fd_type type : 6;
469     unsigned int        access : 2;
470     unsigned int        options : 24;
471 };
472
473 #define FD_CACHE_BLOCK_SIZE  (65536 / sizeof(struct fd_cache_entry))
474 #define FD_CACHE_ENTRIES     128
475
476 static struct fd_cache_entry *fd_cache[FD_CACHE_ENTRIES];
477 static struct fd_cache_entry fd_cache_initial_block[FD_CACHE_BLOCK_SIZE];
478
479 static inline unsigned int handle_to_index( HANDLE handle, unsigned int *entry )
480 {
481     unsigned int idx = (wine_server_obj_handle(handle) >> 2) - 1;
482     *entry = idx / FD_CACHE_BLOCK_SIZE;
483     return idx % FD_CACHE_BLOCK_SIZE;
484 }
485
486
487 /***********************************************************************
488  *           add_fd_to_cache
489  *
490  * Caller must hold fd_cache_section.
491  */
492 static int add_fd_to_cache( HANDLE handle, int fd, enum server_fd_type type,
493                             unsigned int access, unsigned int options )
494 {
495     unsigned int entry, idx = handle_to_index( handle, &entry );
496     int prev_fd;
497
498     if (entry >= FD_CACHE_ENTRIES)
499     {
500         FIXME( "too many allocated handles, not caching %p\n", handle );
501         return 0;
502     }
503
504     if (!fd_cache[entry])  /* do we need to allocate a new block of entries? */
505     {
506         if (!entry) fd_cache[0] = fd_cache_initial_block;
507         else
508         {
509             void *ptr = wine_anon_mmap( NULL, FD_CACHE_BLOCK_SIZE * sizeof(struct fd_cache_entry),
510                                         PROT_READ | PROT_WRITE, 0 );
511             if (ptr == MAP_FAILED) return 0;
512             fd_cache[entry] = ptr;
513         }
514     }
515     /* store fd+1 so that 0 can be used as the unset value */
516     prev_fd = interlocked_xchg( &fd_cache[entry][idx].fd, fd + 1 ) - 1;
517     fd_cache[entry][idx].type = type;
518     fd_cache[entry][idx].access = access;
519     fd_cache[entry][idx].options = options;
520     if (prev_fd != -1) close( prev_fd );
521     return 1;
522 }
523
524
525 /***********************************************************************
526  *           get_cached_fd
527  *
528  * Caller must hold fd_cache_section.
529  */
530 static inline int get_cached_fd( HANDLE handle, enum server_fd_type *type,
531                                  unsigned int *access, unsigned int *options )
532 {
533     unsigned int entry, idx = handle_to_index( handle, &entry );
534     int fd = -1;
535
536     if (entry < FD_CACHE_ENTRIES && fd_cache[entry])
537     {
538         fd = fd_cache[entry][idx].fd - 1;
539         if (type) *type = fd_cache[entry][idx].type;
540         if (access) *access = fd_cache[entry][idx].access;
541         if (options) *options = fd_cache[entry][idx].options;
542     }
543     return fd;
544 }
545
546
547 /***********************************************************************
548  *           server_remove_fd_from_cache
549  */
550 int server_remove_fd_from_cache( HANDLE handle )
551 {
552     unsigned int entry, idx = handle_to_index( handle, &entry );
553     int fd = -1;
554
555     if (entry < FD_CACHE_ENTRIES && fd_cache[entry])
556         fd = interlocked_xchg( &fd_cache[entry][idx].fd, 0 ) - 1;
557
558     return fd;
559 }
560
561
562 /***********************************************************************
563  *           server_get_unix_fd
564  *
565  * The returned unix_fd should be closed iff needs_close is non-zero.
566  */
567 int server_get_unix_fd( HANDLE handle, unsigned int wanted_access, int *unix_fd,
568                         int *needs_close, enum server_fd_type *type, unsigned int *options )
569 {
570     sigset_t sigset;
571     obj_handle_t fd_handle;
572     int ret = 0, fd;
573     unsigned int access = 0;
574
575     *unix_fd = -1;
576     *needs_close = 0;
577     wanted_access &= FILE_READ_DATA | FILE_WRITE_DATA;
578
579     server_enter_uninterrupted_section( &fd_cache_section, &sigset );
580
581     fd = get_cached_fd( handle, type, &access, options );
582     if (fd != -1) goto done;
583
584     SERVER_START_REQ( get_handle_fd )
585     {
586         req->handle = wine_server_obj_handle( handle );
587         if (!(ret = wine_server_call( req )))
588         {
589             if (type) *type = reply->type;
590             if (options) *options = reply->options;
591             access = reply->access;
592             if ((fd = receive_fd( &fd_handle )) != -1)
593             {
594                 assert( wine_server_ptr_handle(fd_handle) == handle );
595                 *needs_close = (reply->removable ||
596                                 !add_fd_to_cache( handle, fd, reply->type,
597                                                   reply->access, reply->options ));
598             }
599             else ret = STATUS_TOO_MANY_OPENED_FILES;
600         }
601     }
602     SERVER_END_REQ;
603
604 done:
605     server_leave_uninterrupted_section( &fd_cache_section, &sigset );
606     if (!ret && ((access & wanted_access) != wanted_access))
607     {
608         ret = STATUS_ACCESS_DENIED;
609         if (*needs_close) close( fd );
610     }
611     if (!ret) *unix_fd = fd;
612     return ret;
613 }
614
615
616 /***********************************************************************
617  *           wine_server_fd_to_handle   (NTDLL.@)
618  *
619  * Allocate a file handle for a Unix file descriptor.
620  *
621  * PARAMS
622  *     fd      [I] Unix file descriptor.
623  *     access  [I] Win32 access flags.
624  *     attributes [I] Object attributes.
625  *     handle  [O] Address where Wine file handle will be stored.
626  *
627  * RETURNS
628  *     NTSTATUS code
629  */
630 int wine_server_fd_to_handle( int fd, unsigned int access, unsigned int attributes, HANDLE *handle )
631 {
632     int ret;
633
634     *handle = 0;
635     wine_server_send_fd( fd );
636
637     SERVER_START_REQ( alloc_file_handle )
638     {
639         req->access     = access;
640         req->attributes = attributes;
641         req->fd         = fd;
642         if (!(ret = wine_server_call( req ))) *handle = wine_server_ptr_handle( reply->handle );
643     }
644     SERVER_END_REQ;
645     return ret;
646 }
647
648
649 /***********************************************************************
650  *           wine_server_handle_to_fd   (NTDLL.@)
651  *
652  * Retrieve the file descriptor corresponding to a file handle.
653  *
654  * PARAMS
655  *     handle  [I] Wine file handle.
656  *     access  [I] Win32 file access rights requested.
657  *     unix_fd [O] Address where Unix file descriptor will be stored.
658  *     options [O] Address where the file open options will be stored. Optional.
659  *
660  * RETURNS
661  *     NTSTATUS code
662  */
663 int wine_server_handle_to_fd( HANDLE handle, unsigned int access, int *unix_fd,
664                               unsigned int *options )
665 {
666     int needs_close, ret = server_get_unix_fd( handle, access, unix_fd, &needs_close, NULL, options );
667
668     if (!ret && !needs_close)
669     {
670         if ((*unix_fd = dup(*unix_fd)) == -1) ret = FILE_GetNtStatus();
671     }
672     return ret;
673 }
674
675
676 /***********************************************************************
677  *           wine_server_release_fd   (NTDLL.@)
678  *
679  * Release the Unix file descriptor returned by wine_server_handle_to_fd.
680  *
681  * PARAMS
682  *     handle  [I] Wine file handle.
683  *     unix_fd [I] Unix file descriptor to release.
684  *
685  * RETURNS
686  *     nothing
687  */
688 void wine_server_release_fd( HANDLE handle, int unix_fd )
689 {
690     close( unix_fd );
691 }
692
693
694 /***********************************************************************
695  *           start_server
696  *
697  * Start a new wine server.
698  */
699 static void start_server(void)
700 {
701     static int started;  /* we only try once */
702     char *argv[3];
703     static char wineserver[] = "server/wineserver";
704     static char debug[] = "-d";
705
706     if (!started)
707     {
708         int status;
709         int pid = fork();
710         if (pid == -1) fatal_perror( "fork" );
711         if (!pid)
712         {
713             argv[0] = wineserver;
714             argv[1] = TRACE_ON(server) ? debug : NULL;
715             argv[2] = NULL;
716             wine_exec_wine_binary( argv[0], argv, getenv("WINESERVER") );
717             fatal_error( "could not exec wineserver\n" );
718         }
719         waitpid( pid, &status, 0 );
720         status = WIFEXITED(status) ? WEXITSTATUS(status) : 1;
721         if (status == 2) return;  /* server lock held by someone else, will retry later */
722         if (status) exit(status);  /* server failed */
723         started = 1;
724     }
725 }
726
727
728 /***********************************************************************
729  *           setup_config_dir
730  *
731  * Setup the wine configuration dir.
732  */
733 static void setup_config_dir(void)
734 {
735     const char *p, *config_dir = wine_get_config_dir();
736
737     if (chdir( config_dir ) == -1)
738     {
739         if (errno != ENOENT) fatal_perror( "chdir to %s\n", config_dir );
740
741         if ((p = strrchr( config_dir, '/' )) && p != config_dir)
742         {
743             struct stat st;
744             char *tmp_dir;
745
746             if (!(tmp_dir = malloc( p + 1 - config_dir ))) fatal_error( "out of memory\n" );
747             memcpy( tmp_dir, config_dir, p - config_dir );
748             tmp_dir[p - config_dir] = 0;
749             if (!stat( tmp_dir, &st ) && st.st_uid != getuid())
750                 fatal_error( "'%s' is not owned by you, refusing to create a configuration directory there\n",
751                              tmp_dir );
752             free( tmp_dir );
753         }
754
755         mkdir( config_dir, 0777 );
756         if (chdir( config_dir ) == -1) fatal_perror( "chdir to %s\n", config_dir );
757         MESSAGE( "wine: created the configuration directory '%s'\n", config_dir );
758     }
759
760     if (mkdir( "dosdevices", 0777 ) == -1)
761     {
762         if (errno == EEXIST) return;
763         fatal_perror( "cannot create %s/dosdevices\n", config_dir );
764     }
765
766     /* create the drive symlinks */
767
768     mkdir( "drive_c", 0777 );
769     symlink( "../drive_c", "dosdevices/c:" );
770     symlink( "/", "dosdevices/z:" );
771 }
772
773
774 /***********************************************************************
775  *           server_connect_error
776  *
777  * Try to display a meaningful explanation of why we couldn't connect
778  * to the server.
779  */
780 static void server_connect_error( const char *serverdir )
781 {
782     int fd;
783     struct flock fl;
784
785     if ((fd = open( LOCKNAME, O_WRONLY )) == -1)
786         fatal_error( "for some mysterious reason, the wine server never started.\n" );
787
788     fl.l_type   = F_WRLCK;
789     fl.l_whence = SEEK_SET;
790     fl.l_start  = 0;
791     fl.l_len    = 1;
792     if (fcntl( fd, F_GETLK, &fl ) != -1)
793     {
794         if (fl.l_type == F_WRLCK)  /* the file is locked */
795             fatal_error( "a wine server seems to be running, but I cannot connect to it.\n"
796                          "   You probably need to kill that process (it might be pid %d).\n",
797                          (int)fl.l_pid );
798         fatal_error( "for some mysterious reason, the wine server failed to run.\n" );
799     }
800     fatal_error( "the file system of '%s' doesn't support locks,\n"
801           "   and there is a 'socket' file in that directory that prevents wine from starting.\n"
802           "   You should make sure no wine server is running, remove that file and try again.\n",
803                  serverdir );
804 }
805
806
807 /***********************************************************************
808  *           server_connect
809  *
810  * Attempt to connect to an existing server socket.
811  * We need to be in the server directory already.
812  */
813 static int server_connect(void)
814 {
815     const char *serverdir;
816     struct sockaddr_un addr;
817     struct stat st;
818     int s, slen, retry, fd_cwd;
819
820     /* retrieve the current directory */
821     fd_cwd = open( ".", O_RDONLY );
822     if (fd_cwd != -1) fcntl( fd_cwd, F_SETFD, 1 ); /* set close on exec flag */
823
824     setup_config_dir();
825     serverdir = wine_get_server_dir();
826
827     /* chdir to the server directory */
828     if (chdir( serverdir ) == -1)
829     {
830         if (errno != ENOENT) fatal_perror( "chdir to %s", serverdir );
831         start_server();
832         if (chdir( serverdir ) == -1) fatal_perror( "chdir to %s", serverdir );
833     }
834
835     /* make sure we are at the right place */
836     if (stat( ".", &st ) == -1) fatal_perror( "stat %s", serverdir );
837     if (st.st_uid != getuid()) fatal_error( "'%s' is not owned by you\n", serverdir );
838     if (st.st_mode & 077) fatal_error( "'%s' must not be accessible by other users\n", serverdir );
839
840     for (retry = 0; retry < 6; retry++)
841     {
842         /* if not the first try, wait a bit to leave the previous server time to exit */
843         if (retry)
844         {
845             usleep( 100000 * retry * retry );
846             start_server();
847             if (lstat( SOCKETNAME, &st ) == -1) continue;  /* still no socket, wait a bit more */
848         }
849         else if (lstat( SOCKETNAME, &st ) == -1) /* check for an already existing socket */
850         {
851             if (errno != ENOENT) fatal_perror( "lstat %s/%s", serverdir, SOCKETNAME );
852             start_server();
853             if (lstat( SOCKETNAME, &st ) == -1) continue;  /* still no socket, wait a bit more */
854         }
855
856         /* make sure the socket is sane (ISFIFO needed for Solaris) */
857         if (!S_ISSOCK(st.st_mode) && !S_ISFIFO(st.st_mode))
858             fatal_error( "'%s/%s' is not a socket\n", serverdir, SOCKETNAME );
859         if (st.st_uid != getuid())
860             fatal_error( "'%s/%s' is not owned by you\n", serverdir, SOCKETNAME );
861
862         /* try to connect to it */
863         addr.sun_family = AF_UNIX;
864         strcpy( addr.sun_path, SOCKETNAME );
865         slen = sizeof(addr) - sizeof(addr.sun_path) + strlen(addr.sun_path) + 1;
866 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
867         addr.sun_len = slen;
868 #endif
869         if ((s = socket( AF_UNIX, SOCK_STREAM, 0 )) == -1) fatal_perror( "socket" );
870         if (connect( s, (struct sockaddr *)&addr, slen ) != -1)
871         {
872             /* switch back to the starting directory */
873             if (fd_cwd != -1)
874             {
875                 fchdir( fd_cwd );
876                 close( fd_cwd );
877             }
878             fcntl( s, F_SETFD, 1 ); /* set close on exec flag */
879             return s;
880         }
881         close( s );
882     }
883     server_connect_error( serverdir );
884 }
885
886
887 #ifdef __APPLE__
888 #include <mach/mach.h>
889 #include <mach/mach_error.h>
890 #include <servers/bootstrap.h>
891
892 /* send our task port to the server */
893 static void send_server_task_port(void)
894 {
895     mach_port_t bootstrap_port, wineserver_port;
896     kern_return_t kret;
897
898     struct {
899         mach_msg_header_t           header;
900         mach_msg_body_t             body;
901         mach_msg_port_descriptor_t  task_port;
902     } msg;
903
904     if (task_get_bootstrap_port(mach_task_self(), &bootstrap_port) != KERN_SUCCESS) return;
905
906     kret = bootstrap_look_up(bootstrap_port, (char*)wine_get_server_dir(), &wineserver_port);
907     if (kret != KERN_SUCCESS)
908         fatal_error( "cannot find the server port: 0x%08x\n", kret );
909
910     mach_port_deallocate(mach_task_self(), bootstrap_port);
911
912     msg.header.msgh_bits        = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0) | MACH_MSGH_BITS_COMPLEX;
913     msg.header.msgh_size        = sizeof(msg);
914     msg.header.msgh_remote_port = wineserver_port;
915     msg.header.msgh_local_port  = MACH_PORT_NULL;
916
917     msg.body.msgh_descriptor_count  = 1;
918     msg.task_port.name              = mach_task_self();
919     msg.task_port.disposition       = MACH_MSG_TYPE_COPY_SEND;
920     msg.task_port.type              = MACH_MSG_PORT_DESCRIPTOR;
921
922     kret = mach_msg_send(&msg.header);
923     if (kret != KERN_SUCCESS)
924         server_protocol_error( "mach_msg_send failed: 0x%08x\n", kret );
925
926     mach_port_deallocate(mach_task_self(), wineserver_port);
927 }
928 #endif  /* __APPLE__ */
929
930 /***********************************************************************
931  *           server_init_process
932  *
933  * Start the server and create the initial socket pair.
934  */
935 void server_init_process(void)
936 {
937     obj_handle_t dummy_handle;
938     const char *env_socket = getenv( "WINESERVERSOCKET" );
939
940     if (env_socket)
941     {
942         fd_socket = atoi( env_socket );
943         if (fcntl( fd_socket, F_SETFD, 1 ) == -1)
944             fatal_perror( "Bad server socket %d", fd_socket );
945         unsetenv( "WINESERVERSOCKET" );
946     }
947     else fd_socket = server_connect();
948
949     /* setup the signal mask */
950     sigemptyset( &server_block_set );
951     sigaddset( &server_block_set, SIGALRM );
952     sigaddset( &server_block_set, SIGIO );
953     sigaddset( &server_block_set, SIGINT );
954     sigaddset( &server_block_set, SIGHUP );
955     sigaddset( &server_block_set, SIGUSR1 );
956     sigaddset( &server_block_set, SIGUSR2 );
957     sigaddset( &server_block_set, SIGCHLD );
958     pthread_functions.sigprocmask( SIG_BLOCK, &server_block_set, NULL );
959
960     /* receive the first thread request fd on the main socket */
961     ntdll_get_thread_data()->request_fd = receive_fd( &dummy_handle );
962
963 #ifdef __APPLE__
964     send_server_task_port();
965 #endif
966 }
967
968
969 /***********************************************************************
970  *           server_init_process_done
971  */
972 NTSTATUS server_init_process_done(void)
973 {
974     PEB *peb = NtCurrentTeb()->Peb;
975     IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
976     NTSTATUS status;
977
978     /* Install signal handlers; this cannot be done earlier, since we cannot
979      * send exceptions to the debugger before the create process event that
980      * is sent by REQ_INIT_PROCESS_DONE.
981      * We do need the handlers in place by the time the request is over, so
982      * we set them up here. If we segfault between here and the server call
983      * something is very wrong... */
984     signal_init_process();
985
986     /* Signal the parent process to continue */
987     SERVER_START_REQ( init_process_done )
988     {
989         req->module = peb->ImageBaseAddress;
990         req->entry  = (char *)peb->ImageBaseAddress + nt->OptionalHeader.AddressOfEntryPoint;
991         req->gui    = (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_WINDOWS_CUI);
992         status = wine_server_call( req );
993     }
994     SERVER_END_REQ;
995
996     return status;
997 }
998
999
1000 /***********************************************************************
1001  *           server_init_thread
1002  *
1003  * Send an init thread request. Return 0 if OK.
1004  */
1005 size_t server_init_thread( int unix_pid, int unix_tid, void *entry_point )
1006 {
1007     int version, ret;
1008     int reply_pipe[2];
1009     struct sigaction sig_act;
1010     size_t info_size;
1011
1012     sig_act.sa_handler = SIG_IGN;
1013     sig_act.sa_flags   = 0;
1014     sigemptyset( &sig_act.sa_mask );
1015
1016     /* ignore SIGPIPE so that we get an EPIPE error instead  */
1017     sigaction( SIGPIPE, &sig_act, NULL );
1018     /* automatic child reaping to avoid zombies */
1019 #ifdef SA_NOCLDWAIT
1020     sig_act.sa_flags |= SA_NOCLDWAIT;
1021 #endif
1022     sigaction( SIGCHLD, &sig_act, NULL );
1023
1024     /* create the server->client communication pipes */
1025     if (pipe( reply_pipe ) == -1) server_protocol_perror( "pipe" );
1026     if (pipe( ntdll_get_thread_data()->wait_fd ) == -1) server_protocol_perror( "pipe" );
1027     wine_server_send_fd( reply_pipe[1] );
1028     wine_server_send_fd( ntdll_get_thread_data()->wait_fd[1] );
1029     ntdll_get_thread_data()->reply_fd = reply_pipe[0];
1030     close( reply_pipe[1] );
1031
1032     /* set close on exec flag */
1033     fcntl( ntdll_get_thread_data()->reply_fd, F_SETFD, 1 );
1034     fcntl( ntdll_get_thread_data()->wait_fd[0], F_SETFD, 1 );
1035     fcntl( ntdll_get_thread_data()->wait_fd[1], F_SETFD, 1 );
1036
1037     SERVER_START_REQ( init_thread )
1038     {
1039         req->unix_pid    = unix_pid;
1040         req->unix_tid    = unix_tid;
1041         req->teb         = NtCurrentTeb();
1042         req->peb         = NtCurrentTeb()->Peb;
1043         req->entry       = entry_point;
1044         req->ldt_copy    = &wine_ldt_copy;
1045         req->reply_fd    = reply_pipe[1];
1046         req->wait_fd     = ntdll_get_thread_data()->wait_fd[1];
1047         req->debug_level = (TRACE_ON(server) != 0);
1048         ret = wine_server_call( req );
1049         NtCurrentTeb()->ClientId.UniqueProcess = ULongToHandle(reply->pid);
1050         NtCurrentTeb()->ClientId.UniqueThread  = ULongToHandle(reply->tid);
1051         info_size         = reply->info_size;
1052         version           = reply->version;
1053         server_start_time = reply->server_start;
1054     }
1055     SERVER_END_REQ;
1056
1057     if (ret) server_protocol_error( "init_thread failed with status %x\n", ret );
1058     if (version != SERVER_PROTOCOL_VERSION)
1059         server_protocol_error( "version mismatch %d/%d.\n"
1060                                "Your %s binary was not upgraded correctly,\n"
1061                                "or you have an older one somewhere in your PATH.\n"
1062                                "Or maybe the wrong wineserver is still running?\n",
1063                                version, SERVER_PROTOCOL_VERSION,
1064                                (version > SERVER_PROTOCOL_VERSION) ? "wine" : "wineserver" );
1065     return info_size;
1066 }