Revert 16bit win95 version back to original value. Fixes InstallShield
[wine] / scheduler / client.c
1 /*
2  * Client part of the client/server communication
3  *
4  * Copyright (C) 1998 Alexandre Julliard
5  */
6
7 #include "wine/port.h"
8
9 #include <assert.h>
10 #include <ctype.h>
11 #include <errno.h>
12 #include <fcntl.h>
13 #include <pwd.h>
14 #include <signal.h>
15 #include <stdio.h>
16 #include <string.h>
17 #include <sys/types.h>
18 #ifdef HAVE_SYS_SOCKET_H
19 # include <sys/socket.h>
20 #endif
21 #ifdef HAVE_SYS_WAIT_H
22 #include <sys/wait.h>
23 #endif
24 #include <sys/un.h>
25 #ifdef HAVE_SYS_MMAN_H
26 #include <sys/mman.h>
27 #endif
28 #include <sys/stat.h>
29 #include <sys/uio.h>
30 #include <unistd.h>
31 #include <stdarg.h>
32
33 #include "thread.h"
34 #include "wine/server.h"
35 #include "winerror.h"
36 #include "options.h"
37
38 /* Some versions of glibc don't define this */
39 #ifndef SCM_RIGHTS
40 #define SCM_RIGHTS 1
41 #endif
42
43 #define CONFDIR    "/.wine"        /* directory for Wine config relative to $HOME */
44 #define SERVERDIR  "/wineserver-"  /* server socket directory (hostname appended) */
45 #define SOCKETNAME "socket"        /* name of the socket file */
46
47 #ifndef HAVE_MSGHDR_ACCRIGHTS
48 /* data structure used to pass an fd with sendmsg/recvmsg */
49 struct cmsg_fd
50 {
51     int len;   /* sizeof structure */
52     int level; /* SOL_SOCKET */
53     int type;  /* SCM_RIGHTS */
54     int fd;    /* fd to pass */
55 };
56 #endif  /* HAVE_MSGHDR_ACCRIGHTS */
57
58 static void *boot_thread_id;
59 static sigset_t block_set;  /* signals to block during server calls */
60 static int fd_socket;  /* socket to exchange file descriptors with the server */
61
62 /* die on a fatal error; use only during initialization */
63 static void fatal_error( const char *err, ... ) WINE_NORETURN;
64 static void fatal_error( const char *err, ... )
65 {
66     va_list args;
67
68     va_start( args, err );
69     fprintf( stderr, "wine: " );
70     vfprintf( stderr, err, args );
71     va_end( args );
72     exit(1);
73 }
74
75 /* die on a fatal error; use only during initialization */
76 static void fatal_perror( const char *err, ... ) WINE_NORETURN;
77 static void fatal_perror( const char *err, ... )
78 {
79     va_list args;
80
81     va_start( args, err );
82     fprintf( stderr, "wine: " );
83     vfprintf( stderr, err, args );
84     perror( " " );
85     va_end( args );
86     exit(1);
87 }
88
89 /***********************************************************************
90  *           server_protocol_error
91  */
92 void server_protocol_error( const char *err, ... )
93 {
94     va_list args;
95
96     va_start( args, err );
97     fprintf( stderr, "wine client error:%p: ", NtCurrentTeb()->tid );
98     vfprintf( stderr, err, args );
99     va_end( args );
100     SYSDEPS_ExitThread(1);
101 }
102
103
104 /***********************************************************************
105  *           server_protocol_perror
106  */
107 void server_protocol_perror( const char *err )
108 {
109     fprintf( stderr, "wine client error:%p: ", NtCurrentTeb()->tid );
110     perror( err );
111     SYSDEPS_ExitThread(1);
112 }
113
114
115 /***********************************************************************
116  *           __wine_server_exception_handler (NTDLL.@)
117  */
118 DWORD __wine_server_exception_handler( PEXCEPTION_RECORD record, EXCEPTION_FRAME *frame,
119                                        CONTEXT *context, EXCEPTION_FRAME **pdispatcher )
120 {
121     struct __server_exception_frame *server_frame = (struct __server_exception_frame *)frame;
122     if ((record->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND)))
123         NtCurrentTeb()->buffer_pos = server_frame->buffer_pos;
124     return ExceptionContinueSearch;
125 }
126
127
128 /***********************************************************************
129  *           wine_server_alloc_req (NTDLL.@)
130  */
131 void wine_server_alloc_req( union generic_request *req, size_t size )
132 {
133     unsigned int pos = NtCurrentTeb()->buffer_pos;
134
135     assert( size <= REQUEST_MAX_VAR_SIZE );
136
137     if (pos + size > NtCurrentTeb()->buffer_size)
138         server_protocol_error( "buffer overflow %d bytes\n",
139                                pos + size - NtCurrentTeb()->buffer_pos );
140
141     NtCurrentTeb()->buffer_pos = pos + size;
142     req->header.var_offset = pos;
143     req->header.var_size = size;
144 }
145
146
147 /***********************************************************************
148  *           send_request
149  *
150  * Send a request to the server.
151  */
152 static void send_request( union generic_request *request )
153 {
154     int ret;
155
156     if ((ret = write( NtCurrentTeb()->request_fd, request, sizeof(*request) )) == sizeof(*request))
157         return;
158     if (ret >= 0) server_protocol_error( "partial write %d\n", ret );
159     if (errno == EPIPE) SYSDEPS_ExitThread(0);
160     server_protocol_perror( "sendmsg" );
161 }
162
163 /***********************************************************************
164  *           wait_reply
165  *
166  * Wait for a reply from the server.
167  */
168 static void wait_reply( union generic_request *req )
169 {
170     int ret;
171
172     for (;;)
173     {
174         if ((ret = read( NtCurrentTeb()->reply_fd, req, sizeof(*req) )) == sizeof(*req))
175             return;
176         if (!ret) break;
177         if (ret > 0) server_protocol_error( "partial read %d\n", ret );
178         if (errno == EINTR) continue;
179         if (errno == EPIPE) break;
180         server_protocol_perror("read");
181     }
182     /* the server closed the connection; time to die... */
183     SYSDEPS_ExitThread(0);
184 }
185
186
187 /***********************************************************************
188  *           wine_server_call (NTDLL.@)
189  *
190  * Perform a server call.
191  */
192 unsigned int wine_server_call( union generic_request *req, size_t size )
193 {
194     sigset_t old_set;
195
196     memset( (char *)req + size, 0, sizeof(*req) - size );
197     sigprocmask( SIG_BLOCK, &block_set, &old_set );
198     send_request( req );
199     wait_reply( req );
200     sigprocmask( SIG_SETMASK, &old_set, NULL );
201     return req->header.error;
202 }
203
204
205 /***********************************************************************
206  *           wine_server_send_fd
207  *
208  * Send a file descriptor to the server.
209  */
210 void wine_server_send_fd( int fd )
211 {
212 #ifndef HAVE_MSGHDR_ACCRIGHTS
213     struct cmsg_fd cmsg;
214 #endif
215     struct send_fd data;
216     struct msghdr msghdr;
217     struct iovec vec;
218     int ret;
219
220     vec.iov_base = (void *)&data;
221     vec.iov_len  = sizeof(data);
222
223     msghdr.msg_name    = NULL;
224     msghdr.msg_namelen = 0;
225     msghdr.msg_iov     = &vec;
226     msghdr.msg_iovlen  = 1;
227
228 #ifdef HAVE_MSGHDR_ACCRIGHTS
229     msghdr.msg_accrights    = (void *)&fd;
230     msghdr.msg_accrightslen = sizeof(fd);
231 #else  /* HAVE_MSGHDR_ACCRIGHTS */
232     cmsg.len   = sizeof(cmsg);
233     cmsg.level = SOL_SOCKET;
234     cmsg.type  = SCM_RIGHTS;
235     cmsg.fd    = fd;
236     msghdr.msg_control    = &cmsg;
237     msghdr.msg_controllen = sizeof(cmsg);
238     msghdr.msg_flags      = 0;
239 #endif  /* HAVE_MSGHDR_ACCRIGHTS */
240
241     data.tid = (void *)GetCurrentThreadId();
242     data.fd  = fd;
243
244     for (;;)
245     {
246         if ((ret = sendmsg( fd_socket, &msghdr, 0 )) == sizeof(data)) return;
247         if (ret >= 0) server_protocol_error( "partial write %d\n", ret );
248         if (errno == EINTR) continue;
249         if (errno == EPIPE) SYSDEPS_ExitThread(0);
250         server_protocol_perror( "sendmsg" );
251     }
252 }
253
254
255 /***********************************************************************
256  *           receive_fd
257  *
258  * Receive a file descriptor passed from the server.
259  */
260 static int receive_fd( handle_t *handle )
261 {
262     struct iovec vec;
263     int ret, fd;
264
265 #ifdef HAVE_MSGHDR_ACCRIGHTS
266     struct msghdr msghdr;
267
268     fd = -1;
269     msghdr.msg_accrights    = (void *)&fd;
270     msghdr.msg_accrightslen = sizeof(fd);
271 #else  /* HAVE_MSGHDR_ACCRIGHTS */
272     struct msghdr msghdr;
273     struct cmsg_fd cmsg;
274
275     cmsg.len   = sizeof(cmsg);
276     cmsg.level = SOL_SOCKET;
277     cmsg.type  = SCM_RIGHTS;
278     cmsg.fd    = -1;
279     msghdr.msg_control    = &cmsg;
280     msghdr.msg_controllen = sizeof(cmsg);
281     msghdr.msg_flags      = 0;
282 #endif  /* HAVE_MSGHDR_ACCRIGHTS */
283
284     msghdr.msg_name    = NULL;
285     msghdr.msg_namelen = 0;
286     msghdr.msg_iov     = &vec;
287     msghdr.msg_iovlen  = 1;
288     vec.iov_base = (void *)handle;
289     vec.iov_len  = sizeof(*handle);
290
291     for (;;)
292     {
293         if ((ret = recvmsg( fd_socket, &msghdr, 0 )) > 0)
294         {
295 #ifndef HAVE_MSGHDR_ACCRIGHTS
296             fd = cmsg.fd;
297 #endif
298             if (fd == -1) server_protocol_error( "no fd received for handle %d\n", *handle );
299             fcntl( fd, F_SETFD, 1 ); /* set close on exec flag */
300             return fd;
301         }
302         if (!ret) break;
303         if (errno == EINTR) continue;
304         if (errno == EPIPE) break;
305         server_protocol_perror("recvmsg");
306     }
307     /* the server closed the connection; time to die... */
308     SYSDEPS_ExitThread(0);
309 }
310
311
312 /***********************************************************************
313  *           wine_server_recv_fd
314  *
315  * Receive a file descriptor passed from the server.
316  * The file descriptor must not be closed.
317  * Return -2 if a race condition stole our file descriptor.
318  */
319 int wine_server_recv_fd( handle_t handle )
320 {
321     handle_t fd_handle;
322
323     int fd = receive_fd( &fd_handle );
324
325     /* now store it in the server fd cache for this handle */
326
327     SERVER_START_REQ( set_handle_info )
328     {
329         req->handle = fd_handle;
330         req->flags  = 0;
331         req->mask   = 0;
332         req->fd     = fd;
333         if (!SERVER_CALL())
334         {
335             if (req->cur_fd != fd)
336             {
337                 /* someone was here before us */
338                 close( fd );
339                 fd = req->cur_fd;
340             }
341         }
342         else
343         {
344             close( fd );
345             fd = -1;
346         }
347     }
348     SERVER_END_REQ;
349
350     if (handle != fd_handle) fd = -2;  /* not the one we expected */
351     return fd;
352 }
353
354
355 /***********************************************************************
356  *           get_config_dir
357  *
358  * Return the configuration directory ($WINEPREFIX or $HOME/.wine)
359  */
360 const char *get_config_dir(void)
361 {
362     static char *confdir;
363     if (!confdir)
364     {
365         const char *prefix = getenv( "WINEPREFIX" );
366         if (prefix)
367         {
368             int len = strlen(prefix);
369             if (!(confdir = strdup( prefix ))) fatal_error( "out of memory\n" );
370             if (len > 1 && confdir[len-1] == '/') confdir[len-1] = 0;
371         }
372         else
373         {
374             const char *home = getenv( "HOME" );
375             if (!home)
376             {
377                 struct passwd *pwd = getpwuid( getuid() );
378                 if (!pwd) fatal_error( "could not find your home directory\n" );
379                 home = pwd->pw_dir;
380             }
381             if (!(confdir = malloc( strlen(home) + strlen(CONFDIR) + 1 )))
382                 fatal_error( "out of memory\n" );
383             strcpy( confdir, home );
384             strcat( confdir, CONFDIR );
385         }
386     }
387     return confdir;
388 }
389
390
391 /***********************************************************************
392  *           start_server
393  *
394  * Start a new wine server.
395  */
396 static void start_server( const char *oldcwd )
397 {
398     static int started;  /* we only try once */
399     char *path, *p;
400     if (!started)
401     {
402         int status;
403         int pid = fork();
404         if (pid == -1) fatal_perror( "fork" );
405         if (!pid)
406         {
407             /* if server is explicitly specified, use this */
408             if ((p = getenv("WINESERVER")))
409             {
410                 if (p[0] != '/' && oldcwd[0] == '/')  /* make it an absolute path */
411                 {
412                     if (!(path = malloc( strlen(oldcwd) + strlen(p) + 1 )))
413                         fatal_error( "out of memory\n" );
414                     sprintf( path, "%s/%s", oldcwd, p );
415                     p = path;
416                 }
417                 execl( p, "wineserver", NULL );
418                 fatal_perror( "could not exec the server '%s'\n"
419                               "    specified in the WINESERVER environment variable", p );
420             }
421
422             /* first try the installation dir */
423             execl( BINDIR "/wineserver", "wineserver", NULL );
424
425             /* now try the dir we were launched from */
426             if (full_argv0)
427             {
428                 if (!(path = malloc( strlen(full_argv0) + 20 )))
429                     fatal_error( "out of memory\n" );
430                 if ((p = strrchr( strcpy( path, full_argv0 ), '/' )))
431                 {
432                     strcpy( p, "/wineserver" );
433                     execl( path, "wineserver", NULL );
434                     strcpy( p, "/server/wineserver" );
435                     execl( path, "wineserver", NULL );
436                 }
437                 free(path);
438             }
439
440             /* now try the path */
441             execlp( "wineserver", "wineserver", NULL );
442
443             /* and finally the current dir */
444             if (!(path = malloc( strlen(oldcwd) + 20 )))
445                 fatal_error( "out of memory\n" );
446             p = strcpy( path, oldcwd ) + strlen( oldcwd );
447             strcpy( p, "/wineserver" );
448             execl( path, "wineserver", NULL );
449             strcpy( p, "/server/wineserver" );
450             execl( path, "wineserver", NULL );
451             free(path);
452             fatal_error( "could not exec wineserver\n" );
453         }
454         started = 1;
455         waitpid( pid, &status, 0 );
456         status = WIFEXITED(status) ? WEXITSTATUS(status) : 1;
457         if (status) exit(status);  /* server failed */
458     }
459 }
460
461 /***********************************************************************
462  *           server_connect
463  *
464  * Attempt to connect to an existing server socket.
465  * We need to be in the server directory already.
466  */
467 static int server_connect( const char *oldcwd, const char *serverdir )
468 {
469     struct sockaddr_un addr;
470     struct stat st;
471     int s, slen, retry;
472
473     /* chdir to the server directory */
474     if (chdir( serverdir ) == -1)
475     {
476         if (errno != ENOENT) fatal_perror( "chdir to %s", serverdir );
477         start_server( "." );
478         if (chdir( serverdir ) == -1) fatal_perror( "chdir to %s", serverdir );
479     }
480
481     /* make sure we are at the right place */
482     if (stat( ".", &st ) == -1) fatal_perror( "stat %s", serverdir );
483     if (st.st_uid != getuid()) fatal_error( "'%s' is not owned by you\n", serverdir );
484     if (st.st_mode & 077) fatal_error( "'%s' must not be accessible by other users\n", serverdir );
485
486     for (retry = 0; retry < 3; retry++)
487     {
488         /* if not the first try, wait a bit to leave the server time to exit */
489         if (retry) usleep( 100000 * retry * retry );
490
491         /* check for an existing socket */
492         if (lstat( SOCKETNAME, &st ) == -1)
493         {
494             if (errno != ENOENT) fatal_perror( "lstat %s/%s", serverdir, SOCKETNAME );
495             start_server( oldcwd );
496             if (lstat( SOCKETNAME, &st ) == -1) fatal_perror( "lstat %s/%s", serverdir, SOCKETNAME );
497         }
498
499         /* make sure the socket is sane (ISFIFO needed for Solaris) */
500         if (!S_ISSOCK(st.st_mode) && !S_ISFIFO(st.st_mode))
501             fatal_error( "'%s/%s' is not a socket\n", serverdir, SOCKETNAME );
502         if (st.st_uid != getuid())
503             fatal_error( "'%s/%s' is not owned by you\n", serverdir, SOCKETNAME );
504
505         /* try to connect to it */
506         addr.sun_family = AF_UNIX;
507         strcpy( addr.sun_path, SOCKETNAME );
508         slen = sizeof(addr) - sizeof(addr.sun_path) + strlen(addr.sun_path) + 1;
509 #ifdef HAVE_SOCKADDR_SUN_LEN
510         addr.sun_len = slen;
511 #endif
512         if ((s = socket( AF_UNIX, SOCK_STREAM, 0 )) == -1) fatal_perror( "socket" );
513         if (connect( s, (struct sockaddr *)&addr, slen ) != -1)
514         {
515             fcntl( s, F_SETFD, 1 ); /* set close on exec flag */
516             return s;
517         }
518         close( s );
519     }
520     fatal_error( "file '%s/%s' exists,\n"
521                  "   but I cannot connect to it; maybe the wineserver has crashed?\n"
522                  "   If this is the case, you should remove this socket file and try again.\n",
523                  serverdir, SOCKETNAME );
524 }
525
526
527 /***********************************************************************
528  *           CLIENT_InitServer
529  *
530  * Start the server and create the initial socket pair.
531  */
532 void CLIENT_InitServer(void)
533 {
534     int size;
535     char hostname[64];
536     char *oldcwd, *serverdir;
537     const char *configdir;
538     handle_t dummy_handle;
539
540     /* retrieve the current directory */
541     for (size = 512; ; size *= 2)
542     {
543         if (!(oldcwd = malloc( size ))) break;
544         if (getcwd( oldcwd, size )) break;
545         free( oldcwd );
546         if (errno == ERANGE) continue;
547         oldcwd = NULL;
548         break;
549     }
550
551     /* if argv[0] is a relative path, make it absolute */
552     full_argv0 = argv0;
553     if (oldcwd && argv0[0] != '/' && strchr( argv0, '/' ))
554     {
555         char *new_argv0 = malloc( strlen(oldcwd) + strlen(argv0) + 2 );
556         if (new_argv0)
557         {
558             strcpy( new_argv0, oldcwd );
559             strcat( new_argv0, "/" );
560             strcat( new_argv0, argv0 );
561             full_argv0 = new_argv0;
562         }
563     }
564
565     /* get the server directory name */
566     if (gethostname( hostname, sizeof(hostname) ) == -1) fatal_perror( "gethostname" );
567     configdir = get_config_dir();
568     serverdir = malloc( strlen(configdir) + strlen(SERVERDIR) + strlen(hostname) + 1 );
569     if (!serverdir) fatal_error( "out of memory\n" );
570     strcpy( serverdir, configdir );
571     strcat( serverdir, SERVERDIR );
572     strcat( serverdir, hostname );
573
574     /* connect to the server */
575     fd_socket = server_connect( oldcwd, serverdir );
576
577     /* switch back to the starting directory */
578     if (oldcwd)
579     {
580         chdir( oldcwd );
581         free( oldcwd );
582     }
583
584     /* setup the signal mask */
585     sigemptyset( &block_set );
586     sigaddset( &block_set, SIGALRM );
587     sigaddset( &block_set, SIGIO );
588     sigaddset( &block_set, SIGINT );
589     sigaddset( &block_set, SIGHUP );
590
591     /* receive the first thread request fd on the main socket */
592     NtCurrentTeb()->request_fd = receive_fd( &dummy_handle );
593
594     CLIENT_InitThread();
595 }
596
597
598 /***********************************************************************
599  *           set_request_buffer
600  */
601 inline static void set_request_buffer(void)
602 {
603     char *name;
604     int fd, ret;
605     unsigned int offset, size;
606
607     /* create a temporary file */
608     do
609     {
610         if (!(name = tmpnam(NULL))) server_protocol_perror( "tmpnam" );
611         fd = open( name, O_CREAT | O_EXCL | O_RDWR, 0600 );
612     } while ((fd == -1) && (errno == EEXIST));
613
614     if (fd == -1) server_protocol_perror( "create" );
615     unlink( name );
616
617     wine_server_send_fd( fd );
618
619     SERVER_START_REQ( set_thread_buffer )
620     {
621         req->fd = fd;
622         ret = SERVER_CALL();
623         offset = req->offset;
624         size = req->size;
625     }
626     SERVER_END_REQ;
627     if (ret) server_protocol_error( "set_thread_buffer failed with status %x\n", ret );
628
629     if ((NtCurrentTeb()->buffer = mmap( 0, size, PROT_READ | PROT_WRITE,
630                                         MAP_SHARED, fd, offset )) == (void*)-1)
631         server_protocol_perror( "mmap" );
632
633     close( fd );
634     NtCurrentTeb()->buffer_pos  = 0;
635     NtCurrentTeb()->buffer_size = size;
636 }
637
638
639 /***********************************************************************
640  *           CLIENT_InitThread
641  *
642  * Send an init thread request. Return 0 if OK.
643  */
644 void CLIENT_InitThread(void)
645 {
646     TEB *teb = NtCurrentTeb();
647     int version, ret;
648     int reply_pipe[2];
649
650     /* ignore SIGPIPE so that we get a EPIPE error instead  */
651     signal( SIGPIPE, SIG_IGN );
652
653     /* create the server->client communication pipes */
654     if (pipe( reply_pipe ) == -1) server_protocol_perror( "pipe" );
655     if (pipe( teb->wait_fd ) == -1) server_protocol_perror( "pipe" );
656     wine_server_send_fd( reply_pipe[1] );
657     wine_server_send_fd( teb->wait_fd[1] );
658     teb->reply_fd = reply_pipe[0];
659
660     /* set close on exec flag */
661     fcntl( teb->reply_fd, F_SETFD, 1 );
662     fcntl( teb->wait_fd[0], F_SETFD, 1 );
663     fcntl( teb->wait_fd[1], F_SETFD, 1 );
664
665     SERVER_START_REQ( init_thread )
666     {
667         req->unix_pid    = getpid();
668         req->teb         = teb;
669         req->entry       = teb->entry_point;
670         req->reply_fd    = reply_pipe[1];
671         req->wait_fd     = teb->wait_fd[1];
672         ret = SERVER_CALL();
673         teb->pid = req->pid;
674         teb->tid = req->tid;
675         version  = req->version;
676         if (req->boot) boot_thread_id = teb->tid;
677         else if (boot_thread_id == teb->tid) boot_thread_id = 0;
678         close( reply_pipe[1] );
679     }
680     SERVER_END_REQ;
681
682     if (ret) server_protocol_error( "init_thread failed with status %x\n", ret );
683     if (version != SERVER_PROTOCOL_VERSION)
684         server_protocol_error( "version mismatch %d/%d.\n"
685                                "Your %s binary was not upgraded correctly,\n"
686                                "or you have an older one somewhere in your PATH.\n"
687                                "Or maybe the wrong wineserver is still running?\n",
688                                version, SERVER_PROTOCOL_VERSION,
689                                (version > SERVER_PROTOCOL_VERSION) ? "wine" : "wineserver" );
690     set_request_buffer();
691 }
692
693
694 /***********************************************************************
695  *           CLIENT_BootDone
696  *
697  * Signal that we have finished booting, and set debug level.
698  */
699 void CLIENT_BootDone( int debug_level )
700 {
701     SERVER_START_REQ( boot_done )
702     {
703         req->debug_level = debug_level;
704         SERVER_CALL();
705     }
706     SERVER_END_REQ;
707 }
708
709
710 /***********************************************************************
711  *           CLIENT_IsBootThread
712  *
713  * Return TRUE if current thread is the boot thread.
714  */
715 int CLIENT_IsBootThread(void)
716 {
717     return (GetCurrentThreadId() == (DWORD)boot_thread_id);
718 }