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