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