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