chiark / gitweb /
243a333c5fe29af9a7e9528e813dce02fd68c070
[userv.git] / client.c
1 /*
2  * userv - client.c
3  * client code
4  *
5  * Copyright (C)1996-1997 Ian Jackson
6  *
7  * This is free software; you can redistribute it and/or modify it
8  * under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with userv; if not, write to the Free Software
19  * Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20  */
21
22 /*
23  * Here too, we do some horrible asynchronous stuff with signals.
24  *
25  * The following objects &c. are used in signal handlers and so
26  * must be protected by calls to blocksignals if they are used in
27  * the main program:
28  *  stderr
29  *  swfile
30  *
31  * The following objects are used in the main program unprotected
32  * and so must not be used in signal handlers:
33  *  srfile
34  *  fdsetup[].copyfd
35  *  fdsetup[].pipefd
36  *
37  * The following objects/functions are not modified/called after the
38  * asynchronicity starts:
39  *  malloc
40  *  fdsetupsize
41  *  fdsetup[].mods
42  *  fdsetup[].filename
43  *  fdsetup[].oflags
44  *  results of argument parsing
45  *
46  * systemerror, swfile, fdsetup[].catpid and fdsetup[].killed are used
47  * for communication between the main thread and the signal handlers.
48  *
49  * All the signal handlers save errno so that is OK too.
50  */
51
52 #include <fcntl.h>
53 #include <stdarg.h>
54 #include <errno.h>
55 #include <stdio.h>
56 #include <stdlib.h>
57 #include <string.h>
58 #include <assert.h>
59 #include <unistd.h>
60 #include <ctype.h>
61 #include <pwd.h>
62 #include <grp.h>
63 #include <signal.h>
64 #include <limits.h>
65 #include <sys/time.h>
66 #include <sys/types.h>
67 #include <sys/stat.h>
68 #include <sys/socket.h>
69 #include <sys/un.h>
70 #include <sys/resource.h>
71 #include <sys/wait.h>
72
73 #include "config.h"
74 #include "common.h"
75 #include "both.h"
76 #include "version.h"
77
78 enum fdmodifiervalues {
79   fdm_read=       00001,
80   fdm_write=      00002,
81   fdm_create=     00004,
82   fdm_exclusive=  00010,
83   fdm_truncate=   00020,
84   fdm_append=     00040,
85   fdm_sync=       00100,
86   fdm_fd=         00200,
87   fdm_wait=       01000,
88   fdm_nowait=     02000,
89   fdm_close=      04000,
90 };
91
92 struct fdmodifierinfo {
93   const char *string;
94   int implies;
95   int conflicts;
96   int oflags;
97 };
98
99 struct fdsetupstate {
100   const char *filename; /* non-null iff this fd has been specified */
101   int copyfd; /* fd to copy, -1 unless mods & fdm_fd */
102   int mods, oflags, pipefd, killed; /* 0,0,-1,0 unless otherwise set */
103   pid_t catpid; /* -1 indicates no cat process */
104 };
105
106 enum signalsexitspecials { se_number=-100, se_numbernocore, se_highbit, se_stdout };
107 enum overridetypes { ot_none, ot_string, ot_file, ot_builtin };
108
109 struct constkeyvaluepair { const char *key, *value; };
110
111 /* Variables from command-line arguments */
112 static const char *serviceuser;
113 static uid_t serviceuid;
114 static struct fdsetupstate *fdsetup;
115 static int fdsetupsize;
116 static struct constkeyvaluepair *defvararray;
117 static int defvaravail, defvarused;
118 static unsigned long timeout;
119 static int signalsexit=254;
120 static int sigpipeok, hidecwd;
121 static int overridetype= ot_none;
122 static const char *overridevalue, *spoofuser=0;
123
124 /* Other state variables */
125 static FILE *srfile, *swfile;
126 static pid_t mypid;
127 static uid_t myuid, spoofuid;
128 static gid_t mygid, spoofgid, *gidarray;
129 static int ngids;
130 static struct opening_msg opening_mbuf;
131 static const char *logname;
132 static char *cwdbuf;
133 static size_t cwdbufsize;
134 static char *ovbuf;
135 static int ovused, systemerror;
136
137 static void blocksignals(int how) {
138   sigset_t set;
139   static const char blockerrmsg[]= "userv: failed to [un]block signals: ";
140   const char *str;
141
142   sigemptyset(&set);
143   sigaddset(&set,SIGCHLD);
144   sigaddset(&set,SIGALRM);
145   if (sigprocmask(how,&set,0)) {
146     str= strerror(errno);
147     write(2,blockerrmsg,sizeof(blockerrmsg)-1);
148     write(2,str,strlen(str));
149     write(2,"\n",1);
150     exit(-1);
151   }
152 }
153
154 /* Functions which may be called either from signal handlers or from
155  * the main thread.  They block signals in case they are on the main
156  * thread, and may only use signal handler objects.  None of them
157  * return.  If they did they'd have to restore the signal mask.
158  */
159
160 static void NONRETURNPRINTFFORMAT(1,2) miscerror(const char *fmt, ...) {
161   va_list al;
162
163   blocksignals(SIG_BLOCK);
164   va_start(al,fmt);
165   fprintf(stderr,"userv: failure: ");
166   vfprintf(stderr,fmt,al);
167   fprintf(stderr,"\n");
168   exit(-1);
169 }
170
171 static void NONRETURNPRINTFFORMAT(1,2) syscallerror(const char *fmt, ...) {
172   va_list al;
173   int e;
174
175   e= errno;
176   blocksignals(SIG_BLOCK);
177   va_start(al,fmt);
178   fprintf(stderr,"userv: system call failure: ");
179   vfprintf(stderr,fmt,al);
180   fprintf(stderr,": %s\n",strerror(e));
181   exit(-1);
182 }
183
184 static void NONRETURNING protoreaderror(FILE *file, const char *where) {
185   int e;
186
187   e= errno;
188   blocksignals(SIG_BLOCK);
189   if (ferror(file)) {
190     fprintf(stderr,"userv: failure: read error %s: %s\n",where,strerror(e));
191   } else {
192     assert(feof(file));
193     fprintf(stderr,"userv: internal failure: EOF from server %s\n",where);
194   }
195   exit(-1);
196 }
197
198 static void NONRETURNPRINTFFORMAT(1,2) protoerror(const char *fmt, ...) {
199   va_list al;
200
201   blocksignals(SIG_BLOCK);
202   va_start(al,fmt);
203   fprintf(stderr,"userv: internal failure: protocol error: ");
204   vfprintf(stderr,fmt,al);
205   fprintf(stderr,"\n");
206   exit(-1);
207 }
208
209 /*
210  * General-purpose functions; these do nothing special about signals,
211  * except that they can call error-handlers which may block them
212  * to print error messages.
213  */
214
215 static void xfread(void *p, size_t sz, FILE *file) {
216   size_t nr;
217   nr= working_fread(p,sz,file);
218   if (nr != sz) protoreaderror(file,"in data");
219 }
220
221 static void xfwrite(const void *p, size_t sz, FILE *file) {
222   size_t nr;
223   nr= fwrite(p,1,sz,file); if (nr == sz) return;
224   syscallerror("writing to server");
225 }
226
227 static void xfflush(FILE *file) {
228   if (fflush(file)) syscallerror("flush server socket");
229 }
230
231 /* Functions which may be called only from the main thread.  These may
232  * use main-thread objects and must block signals before using signal
233  * handler objects.
234  */
235
236 #ifdef DEBUG
237 static void priv_suspend(void) { }
238 static void priv_resume(void) { }
239 static void priv_permanentlyrevokesuspended(void) { }
240 #else
241 static void priv_suspend(void) {
242   if (setreuid(0,myuid) != 0) syscallerror("suspend root setreuid(0,myuid)");
243 }
244 static void priv_resume(void) {
245   if (setreuid(myuid,0) != 0) syscallerror("resume root setreuid(myuid,0)");
246 }
247 static void priv_permanentlyrevokesuspended(void) {
248   if (setreuid(myuid,myuid) != 0) syscallerror("revoke root setreuid(myuid,myuid)");
249   if (setreuid(myuid,myuid) != 0) syscallerror("rerevoke root setreuid(myuid,myuid)");
250   if (myuid) {
251     if (!setreuid(myuid,0)) miscerror("revoked root but setreuid(0,0) succeeded !");
252     if (errno != EPERM) syscallerror("revoked and setreuid(myuid,0) unexpected error");
253   }
254 }
255 #endif
256
257 static void checkmagic(unsigned long was, unsigned long should, const char *when) {
258   if (was != should)
259     protoerror("magic number %s was %08lx, expected %08lx",when,was,should);
260 }
261
262 static void getprogress(struct progress_msg *progress_r, FILE *file) {
263   int i, c;
264   unsigned long ul;
265
266   for (;;) {
267     xfread(progress_r,sizeof(struct progress_msg),file);
268     checkmagic(progress_r->magic,PROGRESS_MAGIC,"in progress message");
269     switch (progress_r->type) {
270     case pt_failed:
271       blocksignals(SIG_BLOCK);
272       fputs("userv: uservd reports that service failed\n",stderr);
273       exit(-1);
274     case pt_errmsg:
275       blocksignals(SIG_BLOCK);
276       fputs("uservd: ",stderr);
277       if (progress_r->data.errmsg.messagelen>MAX_ERRMSG_STRING)
278         protoerror("stderr message length %d is far too long",
279                    progress_r->data.errmsg.messagelen);
280       for (i=0; i<progress_r->data.errmsg.messagelen; i++) {
281         c= working_getc(file);
282         if (c==EOF) protoreaderror(file,"in error message");
283         if (isprint(c)) putc(c,stderr);
284         else fprintf(stderr,"\\x%02x",(unsigned char)c);
285       }
286       putc('\n',stderr);
287       if (ferror(stderr)) syscallerror("printing error message");
288       xfread(&ul,sizeof(ul),file);
289       checkmagic(ul,PROGRESS_ERRMSG_END_MAGIC,"after error message");
290       blocksignals(SIG_UNBLOCK);
291       break;
292     default:
293       return;
294     }
295   }
296 }
297
298 /*
299  * Functions which are called only during setup, before
300  * the signal asynchronicity starts.  They can do anything they like.
301  */
302
303 static void *xmalloc(size_t s) {
304   void *p;
305   p= malloc(s?s:1);
306   if (!p) syscallerror("malloc (%lu bytes)",(unsigned long)s);
307   return p;
308 }
309
310 static void *xrealloc(void *p, size_t s) {
311   p= realloc(p,s);
312   if (!p) syscallerror("realloc (%lu bytes)",(unsigned long)s);
313   return p;
314 }
315
316 static void xfwritestring(const char *s, FILE *file) {
317   int l;
318   l= strlen(s);
319   assert(l<=MAX_GENERAL_STRING);
320   xfwrite(&l,sizeof(l),file);
321   xfwrite(s,sizeof(*s)*l,file);
322 }
323
324 static void xfwritefds(int modifier, int expected, FILE *file) {
325   int i, fdcount;
326
327   for (i=0, fdcount=0; i<fdsetupsize; i++) {
328     if (!(fdsetup[i].filename && (fdsetup[i].mods & modifier)))
329       continue;
330     xfwrite(&i,sizeof(int),file); fdcount++;
331   }
332   assert(fdcount == expected);
333 }
334
335 /* Functions which may be called from signal handlers.  These
336  * may use signal-handler objects.  The main program may only
337  * call them with signals blocked, and they may not use any
338  * main-thread objects.
339  */
340
341 static void disconnect(void) /* DOES return, unlike in daemon */ {
342   struct event_msg event_mbuf;
343   int r;
344
345   if (swfile) {
346     memset(&event_mbuf,0,sizeof(event_mbuf));
347     event_mbuf.magic= EVENT_MAGIC;
348     event_mbuf.type= et_disconnect;
349     r= fwrite(&event_mbuf,1,sizeof(event_mbuf),swfile);
350     if ((r != sizeof(event_mbuf) || fflush(swfile)) && errno != EPIPE)
351       syscallerror("write to server when disconnecting\n");
352   }
353   systemerror= 1;
354 }
355
356 static void sighandler_alrm(int ignored) /* DOES return, unlike in daemon */ {
357   int es;
358   es= errno;
359   fputs("userv: timeout\n",stderr);
360   disconnect();
361   errno= es;
362 }
363
364 static void sighandler_chld(int ignored) /* DOES return, unlike in daemon */ {
365   struct event_msg event_mbuf;
366   pid_t child;
367   int status, fd, r, es;
368
369   es= errno;
370   for (;;) {
371     child= wait3(&status,WNOHANG,0);
372     if (child == 0 || (child == -1 && errno == ECHILD)) break;
373     if (child == -1) syscallerror("wait for child process (in sigchld handler)");
374     for (fd=0; fd<fdsetupsize && fdsetup[fd].catpid != child; fd++);
375     if (fd>=fdsetupsize) continue; /* perhaps the caller gave us children */
376     if ((WIFEXITED(status) && WEXITSTATUS(status)==0) ||
377         (WIFSIGNALED(status) && WTERMSIG(status)==SIGPIPE) ||
378         (fdsetup[fd].killed && WIFSIGNALED(status) && WTERMSIG(status)==SIGKILL)) {
379       if (swfile && fdsetup[fd].mods & fdm_read) {
380         memset(&event_mbuf,0,sizeof(event_mbuf));
381         event_mbuf.magic= EVENT_MAGIC;
382         event_mbuf.type= et_closereadfd;
383         event_mbuf.data.closereadfd.fd= fd;
384         r= fwrite(&event_mbuf,1,sizeof(event_mbuf),swfile);
385         if (r != sizeof(event_mbuf) || fflush(swfile))
386           if (errno != EPIPE) syscallerror("inform service of closed read fd");
387       }
388     } else {
389       if (WIFEXITED(status))
390         fprintf(stderr,"userv: cat for fd %d exited with error exit status %d\n",
391                 fd,WEXITSTATUS(status));
392       else if (WIFSIGNALED(status))
393         if (WCOREDUMP(status))
394           fprintf(stderr,"userv: cat for fd %d dumped core due to signal %s (%d)\n",
395                   fd,strsignal(WTERMSIG(status)),WTERMSIG(status));
396         else
397           fprintf(stderr,"userv: cat for fd %d terminated by signal %s (%d)\n",
398                   fd,strsignal(WTERMSIG(status)),WTERMSIG(status));
399       else
400         fprintf(stderr,"userv: cat for fd %d gave unknown wait status %d\n",
401                 fd,status);
402       disconnect();
403     }
404     fdsetup[fd].catpid= -1;
405   }
406   errno= es;
407 }
408
409 /*
410  * Argument parsing.  These functions which are called only during
411  * setup, before the signal asynchronicity starts.
412  */
413
414 struct optioninfo;
415
416 typedef void optionfunction(const struct optioninfo*, const char *value, char *key);
417
418 struct optioninfo {
419   int abbrev;
420   const char *full;
421   int values; /* 0: no value; 1: single value; 2: key and value */
422   optionfunction *fn;
423 };
424
425 static void usage(void) {
426   if (fputs(
427     "usage: userv <options> [--] <service-user> <service-name> [<argument> ...]\n"
428     "usage: userv <options> -B|--builtin [--] <builtin-service> [<info-argument> ...]\n"
429     "options: -f|--file <fd>[<fdmodifiers>]=<filename>\n"
430     "         -D|--defvar <name>=<value>\n"
431     "         -t|--timeout <seconds>\n"
432     "         -S|--signals <status>|number|number-nocore|highbit|stdout\n"
433     "         -w|--fdwait <fd>=wait|nowait|close\n"
434     "         -P|--sigpipe  -H|--hidecwd  -h|--help  --copyright\n"
435     "         --override <configuration-data> } available only\n"
436     "         --override-file <filename>      }  to root\n"
437     "         --spoof-user <username>         }  or same user\n"
438     "fdmodifiers:            read    write  overwrite    trunc[ate]\n"
439     "(separate with commas)  append  sync   excl[usive]  creat[e]  fd\n\n"
440     "userv and uservd version " VERSION VEREXT "; copyright (C)1996-1997 Ian Jackson.\n"
441     "there is NO WARRANTY; type `userv --copyright' for details.\n",
442             stderr) < 0)
443     syscallerror("write usage to stderr");
444 }
445
446 static void NONRETURNPRINTFFORMAT(1,2) usageerror(const char *fmt, ...) {
447   va_list al;
448   va_start(al,fmt);
449   fputs("userv: ",stderr);
450   vfprintf(stderr,fmt,al);
451   fputs("\n\n",stderr);
452   usage();
453   exit(-1);
454 }
455
456 static const struct fdmodifierinfo fdmodifierinfos[]= {
457   { "read",      fdm_read,
458                  fdm_write,
459                  O_RDONLY                                                         },
460   { "write",     fdm_write,
461                  fdm_read,
462                  O_WRONLY                                                         },
463   { "overwrite", fdm_write|fdm_create|fdm_truncate,
464                  fdm_read|fdm_fd|fdm_exclusive,
465                  O_WRONLY|O_CREAT|O_TRUNC                                         },
466   { "create",    fdm_write|fdm_create,
467                  fdm_read|fdm_fd,
468                  O_WRONLY|O_CREAT                                                 },
469   { "creat",     fdm_write|fdm_create,
470                  fdm_read|fdm_fd,
471                  O_WRONLY|O_CREAT                                                 },
472   { "exclusive", fdm_write|fdm_create|fdm_exclusive,
473                  fdm_read|fdm_fd|fdm_truncate,
474                  O_WRONLY|O_CREAT|O_EXCL                                          },
475   { "excl",      fdm_write|fdm_create|fdm_exclusive,
476                  fdm_read|fdm_fd|fdm_truncate,
477                  O_WRONLY|O_CREAT|O_EXCL                                          },
478   { "truncate",  fdm_write|fdm_truncate,
479                  fdm_read|fdm_fd|fdm_exclusive,
480                  O_WRONLY|O_CREAT|O_EXCL                                          },
481   { "trunc",     fdm_write|fdm_truncate,
482                  fdm_read|fdm_fd|fdm_exclusive,
483                  O_WRONLY|O_CREAT|O_EXCL                                          },
484   { "append",    fdm_write|fdm_append,
485                  fdm_read|fdm_fd,
486                  O_WRONLY|O_CREAT|O_APPEND                                        },
487   { "sync",      fdm_write|fdm_sync,
488                  fdm_read|fdm_fd,
489                  O_WRONLY|O_CREAT|O_SYNC                                          },
490   { "wait",      fdm_wait,
491                  fdm_nowait|fdm_close,
492                  0                                                                },
493   { "nowait",    fdm_nowait,
494                  fdm_wait|fdm_close,
495                  0                                                                },
496   { "close",     fdm_close,
497                  fdm_wait|fdm_nowait,
498                  0                                                                },
499   { "fd",        fdm_fd,
500                  fdm_create|fdm_exclusive|fdm_truncate|fdm_append|fdm_sync,
501                  0                                                                },
502   {  0                                                                            }
503 };
504
505 static void addfdmodifier(int fd, const char *key) {
506   const struct fdmodifierinfo *fdmip;
507   
508   if (!*key) return;
509   for (fdmip= fdmodifierinfos; fdmip->string && strcmp(fdmip->string,key); fdmip++);
510   if (!fdmip->string) usageerror("unknown fdmodifer `%s' for fd %d",key,fd);
511   if (fdmip->conflicts & fdsetup[fd].mods)
512     usageerror("fdmodifier `%s' conflicts with another for fd %d",key,fd);
513   fdsetup[fd].mods |= fdmip->implies;
514   fdsetup[fd].oflags |= fdmip->oflags;
515 }
516
517 static int fdstdnumber(const char *string) {
518   if (!strcmp(string,"stdin")) return 0;
519   else if (!strcmp(string,"stdout")) return 1;
520   else if (!strcmp(string,"stderr")) return 2;
521   else return -1;
522 }
523
524 static void of_file(const struct optioninfo *oip, const char *value, char *key) {
525   unsigned long fd, copyfd;
526   struct stat stab;
527   int oldarraysize, r;
528   char *delim;
529
530   fd= strtoul(key,&delim,10);
531   if (delim == key) {
532     delim= strchr(key,',');
533     if (delim) *delim++= 0;
534     fd= fdstdnumber(key);
535     if (fd<0) usageerror("first part of argument to -f or --file must be numeric "
536                          "file descriptor or `stdin', `stdout' or `stderr' - `%s' "
537                          "is not recognized",key);
538   }
539   if (fd > MAX_ALLOW_FD)
540     usageerror("file descriptor specified (%lu) is larger than maximum allowed (%d)",
541                fd,MAX_ALLOW_FD);
542   if (fd >= fdsetupsize) {
543     oldarraysize= fdsetupsize;
544     fdsetupsize+=2; fdsetupsize<<=1;
545     fdsetup= xrealloc(fdsetup,sizeof(struct fdsetupstate)*fdsetupsize);
546     while (oldarraysize < fdsetupsize) {
547       fdsetup[oldarraysize].filename= 0;
548       fdsetup[oldarraysize].pipefd= -1;
549       fdsetup[oldarraysize].copyfd= -1;
550       fdsetup[oldarraysize].mods= 0;
551       fdsetup[oldarraysize].oflags= 0;
552       fdsetup[oldarraysize].catpid= -1;
553       fdsetup[oldarraysize].killed= 0;
554       fdsetup[oldarraysize].filename= 0;
555       oldarraysize++;
556     }
557   }
558   fdsetup[fd].filename= value;
559   fdsetup[fd].oflags= 0;
560   fdsetup[fd].mods= 0;
561   fdsetup[fd].copyfd= -1;
562   while (delim && *delim) {
563     key= delim;
564     delim= strchr(key,',');
565     if (delim) *delim++= 0;
566     addfdmodifier(fd,key);
567   }
568   if (!(fdsetup[fd].mods & (fdm_read|fdm_write))) {
569     if (fd == 0) {
570       addfdmodifier(fd,"read");
571     } else if (fdsetup[fd].mods & fdm_fd) {
572       addfdmodifier(fd,"write");
573     } else {
574       addfdmodifier(fd,"overwrite");
575     }
576   }
577   if (fdsetup[fd].mods & fdm_fd) {
578     copyfd= fdstdnumber(value);
579     if (copyfd<0) {
580       copyfd= strtoul(value,&delim,0);
581       if (*delim)
582         usageerror("value part of argument to --file with fd modifier must be "
583                    "numeric or fd name - `%s' is not recognised",value);
584       else if (copyfd > MAX_ALLOW_FD)
585         usageerror("file descriptor %lu named as target of file descriptor redirection"
586                    " (for file descriptor %lu) is larger than maximum allowed (%d)",
587                    copyfd,fd,MAX_ALLOW_FD);
588     }
589     r= fstat(copyfd,&stab);
590     if (r) {
591       if (oip) syscallerror("check filedescriptor %lu (named as target of file "
592                             "descriptor redirection for %lu)",copyfd,fd);
593       else syscallerror("check basic filedescriptor %lu at program start",copyfd);
594     }
595     fdsetup[fd].copyfd= copyfd;
596   }
597 }
598
599 static void of_fdwait(const struct optioninfo *oip, const char *value, char *key) {
600   const struct fdmodifierinfo *fdmip;
601   unsigned long ul;
602   int fd;
603   char *delim;
604   
605   fd= fdstdnumber(key);
606   if (fd<0) {
607     ul= strtoul(key,&delim,0);
608     if (*delim) usageerror("first part of argument to --fdwait must be "
609                            "numeric or fd name - `%s' is not recognised",key);
610     if (ul>MAX_ALLOW_FD) usageerror("first part of argument to --fdwait is too large");
611     fd= ul;
612   }
613   if (fd >= fdsetupsize || !fdsetup[fd].filename)
614     usageerror("file descriptor %d specified in --fdwait option is not open",fd);
615   for (fdmip= fdmodifierinfos; fdmip->string && strcmp(fdmip->string,value); fdmip++);
616   if (!fdmip->string || !(fdmip->implies & (fdm_wait|fdm_nowait|fdm_close)))
617     usageerror("value for --fdwait must be `wait', `nowait' or `close', not `%s'",value);
618   fdsetup[fd].mods &= ~(fdm_wait|fdm_nowait|fdm_close);
619   fdsetup[fd].mods |= fdmip->implies;
620 }
621
622 static void of_defvar(const struct optioninfo *oip, const char *value, char *key) {
623   int i;
624
625   if (!key[0])
626     usageerror("empty string not allowed as variable name");
627   if (strlen(key)>MAX_GENERAL_STRING)
628     usageerror("variable name `%s' is far too long",key);
629   if (strlen(value)>MAX_GENERAL_STRING)
630     usageerror("variable `%s' has value `%s' which is far too long",key,value);
631   for (i=0; i<defvarused && strcmp(defvararray[i].key,key); i++);
632   if (defvarused >= MAX_ARGSDEFVAR) usageerror("far too many --defvar or -D options");
633   if (i>=defvaravail) {
634     defvaravail+=10; defvaravail<<=1;
635     defvararray= xrealloc(defvararray,sizeof(struct constkeyvaluepair)*defvaravail);
636   }
637   if (i==defvarused) defvarused++;
638   defvararray[i].key= key;
639   defvararray[i].value= value;
640 }
641
642 static void of_timeout(const struct optioninfo *oip, const char *value, char *key) {
643   char *endp;
644   unsigned long ul;
645   
646   ul= strtoul(value,&endp,0);
647   if (*endp) usageerror("timeout value `%s' must be a plain decimal string",value);
648   if (ul>INT_MAX) usageerror("timeout value %lu too large",ul);
649   timeout= ul;
650 }
651
652 static void of_signals(const struct optioninfo *oip, const char *value, char *key) {
653   unsigned long numvalue;
654   char *endp;
655   
656   numvalue= strtoul(value,&endp,0);
657   if (*endp) {
658     if (!strcmp(value,"number")) signalsexit= se_number;
659     else if (!strcmp(value,"number-nocore")) signalsexit= se_numbernocore;
660     else if (!strcmp(value,"highbit")) signalsexit= se_highbit;
661     else if (!strcmp(value,"stdout")) signalsexit= se_stdout;
662     else usageerror("value `%s' for --signals not understood",value);
663   } else {
664     if (numvalue<0 || numvalue>255)
665       usageerror("value %lu for --signals not 0...255",numvalue);
666     signalsexit= numvalue;
667   }
668 }
669
670 static void of_sigpipe(const struct optioninfo *oip, const char *value, char *key) {
671   sigpipeok=1;
672 }
673
674 static void of_hidecwd(const struct optioninfo *oip, const char *value, char *key) {
675   hidecwd=1;
676 }
677
678 static void of_help(const struct optioninfo *oip, const char *value, char *key) {
679   usage();
680   exit(0);
681 }
682
683 static void of_copyright(const struct optioninfo *oip, const char *value, char *key) {
684   if (fputs(
685 " userv - user service daemon and client; copyright (C)1996-1997 Ian Jackson\n\n"
686 " This is free software; you can redistribute it and/or modify it under the\n"
687 " terms of the GNU General Public License as published by the Free Software\n"
688 " Foundation; either version 2 of the License, or (at your option) any\n"
689 " later version.\n\n"
690 " This program is distributed in the hope that it will be useful, but\n"
691 " WITHOUT ANY WARRANTY; without even the implied warranty of\n"
692 " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General\n"
693 " Public License for more details.\n\n"
694 " You should have received a copy of the GNU General Public License along\n"
695 " with userv; if not, write to Ian Jackson <ian@chiark.greenend.org.uk> or\n"
696 " to the Free Software Foundation, 59 Temple Place - Suite 330, Boston,\n"
697 " MA 02111-1307, USA.\n",
698             stdout) < 0) syscallerror("write usage to stderr");
699   exit(0);
700 }
701
702 static void of_builtin(const struct optioninfo *oip, const char *value, char *key) {
703   overridetype= ot_builtin;
704 }
705
706 static void of_override(const struct optioninfo *oip, const char *value, char *key) {
707   overridetype= ot_string;
708   overridevalue= value;
709 }
710
711 static void of_overridefile(const struct optioninfo *oip,
712                             const char *value, char *key) {
713   overridetype= ot_file;
714   overridevalue= value;
715 }
716
717 static void of_spoofuser(const struct optioninfo *oip,
718                          const char *value, char *key) {
719   spoofuser= value;
720 }
721
722 const struct optioninfo optioninfos[]= {
723   { 'f', "file",          2, of_file         },
724   { 'w', "fdwait",        2, of_fdwait       },
725   { 'D', "defvar",        2, of_defvar       },
726   { 't', "timeout",       1, of_timeout      },
727   { 'S', "signals",       1, of_signals      },
728   { 'P', "sigpipe",       0, of_sigpipe      },
729   { 'H', "hidecwd",       0, of_hidecwd      },
730   { 'B', "builtin",       0, of_builtin      },
731   { 'h', "help",          0, of_help         },
732   {  0,  "copyright",     0, of_copyright    },
733   {  0,  "override",      1, of_override     },
734   {  0,  "override-file", 1, of_overridefile },
735   {  0,  "spoof-user",    1, of_spoofuser    },
736   {  0,   0                                  }
737 };
738
739 static void callvalueoption(const struct optioninfo *oip, char *arg) {
740   char *equals;
741   if (oip->values == 2) {
742     equals= strchr(arg,'=');
743     if (!equals) {
744       if (oip->abbrev)
745         usageerror("option --%s (-%c) passed argument `%s' with no `='",
746                    oip->full,oip->abbrev,arg);
747       else
748         usageerror("option --%s passed argument `%s' with no `='",
749                    oip->full,arg);
750     }
751     *equals++= 0;
752     (oip->fn)(oip,equals,arg);
753   } else {
754     (oip->fn)(oip,arg,0);
755   }
756 }
757
758 /*
759  * Main thread main processing functions - in order of execution.
760  */
761
762 static void security_init(void) {
763   /* May not open any file descriptors. */
764   
765   mypid= getpid(); if (mypid == (pid_t)-1) syscallerror("getpid");
766   myuid= getuid(); if (myuid == (uid_t)-1) syscallerror("getuid");
767   mygid= getgid(); if (mygid == (gid_t)-1) syscallerror("getgid");
768   ngids= getgroups(0,0); if (ngids == (gid_t)-1) syscallerror("getgroups(0,0)");
769   gidarray= xmalloc(sizeof(gid_t)*ngids);
770   if (getgroups(ngids,gidarray) != ngids) syscallerror("getgroups(ngids,)");
771   
772   priv_suspend();
773
774   if (ngids > MAX_GIDS) miscerror("caller is in far too many gids");
775 }
776
777 static void parse_arguments(int *argcp, char *const **argvp) {
778   static char fd0key[]= "stdin,fd,read";
779   static char fd1key[]= "stdout,fd,write";
780   static char fd2key[]= "stderr,fd,write";
781
782   char *const *argpp;
783   char *argp;
784   const struct optioninfo *oip;
785   int fd;
786
787   assert((*argvp)[0]);
788   of_file(0,"stdin",fd0key);
789   of_file(0,"stdout",fd1key);
790   of_file(0,"stderr",fd2key);
791
792   for (argpp= *argvp+1;
793        (argp= *argpp) && *argp == '-' && argp[1];
794        argpp++) {
795     if (!*++argp) usageerror("unknown option/argument `%s'",*argpp);
796     if (*argp == '-') { /* Two hyphens */
797       if (!*++argp) { argpp++; break; /* End of options. */ }
798       for (oip= optioninfos; oip->full && strcmp(oip->full,argp); oip++);
799       if (!oip->full) usageerror("unknown long option `%s'",*argpp);
800       if (oip->values) {
801         if (!argpp[1]) usageerror("long option `%s' needs a value",*argpp);
802         callvalueoption(oip,*++argpp);
803       } else {
804         (oip->fn)(oip,0,0);
805       }
806     } else {
807       for (; *argp; argp++) {
808         for (oip= optioninfos; oip->full && oip->abbrev != *argp; oip++);
809         if (!oip->full) usageerror("unknown short option `-%c' in argument `%s'",
810                                     *argp, *argpp);
811         if (oip->values) {
812           if (argp[1]) {
813             argp++;
814           } else {
815             if (!argpp[1]) usageerror("short option `-%c' in argument `%s' needs"
816                                       " a value",*argp,*argpp);
817             argp= *++argpp;
818           }
819           callvalueoption(oip,argp);
820           break; /* No more options in this argument, go on to the next one. */
821         } else {
822           (oip->fn)(oip,0,0);
823         }
824       }
825     }
826   }
827   if (overridetype == ot_builtin) {
828     serviceuser= "-";
829   } else {
830     if (!*argpp) usageerror("no service user given after options");
831     serviceuser= *argpp++;
832   }
833   if (!*argpp) usageerror(overridetype == ot_builtin ?
834                           "no service name given after options and service user" :
835                           "no builtin service given after options");
836
837   *argcp-= (argpp-*argvp);
838   *argvp= argpp;
839
840   if (*argcp > MAX_ARGSDEFVAR) usageerror("far too many arguments");
841   
842   for (fd=0; fd<fdsetupsize; fd++) {
843     if (!fdsetup[fd].filename) continue;
844     if (fdsetup[fd].mods & (fdm_wait|fdm_nowait|fdm_close)) continue;
845     assert(fdsetup[fd].mods & (fdm_read|fdm_write));
846     fdsetup[fd].mods |= (fdsetup[fd].mods & fdm_read) ? fdm_close : fdm_wait;
847   }
848 }
849
850 static void determine_users(void) {
851   int ngidssize;
852   char **mem;
853   struct passwd *pw;
854   struct group *gr;
855   
856   spoofuid= myuid;
857   spoofgid= mygid;
858   logname= getenv("LOGNAME");
859   if (!logname) logname= getenv("USER");
860   if (logname) {
861     pw= getpwnam(logname);
862     if (!pw || pw->pw_uid != myuid) logname= 0;
863   }
864   if (!logname) {
865     pw= getpwuid(myuid); if (!pw) miscerror("cannot determine your login name");
866     logname= pw->pw_name;
867   }
868
869   if (!strcmp(serviceuser,"-")) serviceuser= logname;
870   pw= getpwnam(serviceuser);
871   if (!pw) miscerror("requested service user `%s' is not a user",serviceuser);
872   serviceuid= pw->pw_uid;
873
874   if ((overridetype != ot_none || spoofuser) && myuid != 0 && myuid != serviceuid)
875     miscerror("--override and --spoof options only available to root or to"
876               " the user who will be providing the service");
877
878   if (spoofuser) {
879     logname= spoofuser;
880     pw= getpwnam(logname);
881     if (!pw) miscerror("spoofed login name `%s' is not valid",logname);
882     spoofuid= pw->pw_uid;
883     spoofgid= pw->pw_gid;
884     ngidssize= ngids; ngids= 0;
885     if (ngidssize<5) {
886       ngidssize= 5;
887       gidarray= xrealloc(gidarray,sizeof(gid_t)*ngidssize);
888     }
889     gidarray[ngids++]= spoofgid;
890     while ((gr= getgrent())) { /* ouch! getgrent has no error behaviour! */
891       for (mem= gr->gr_mem; *mem && strcmp(*mem,logname); mem++);
892       if (!*mem) continue;
893       if (ngids>=ngidssize) {
894       if (ngids>=MAX_GIDS) miscerror("spoofed user is member of too many groups");
895         ngidssize= (ngids+5)<<1;
896         gidarray= xrealloc(gidarray,sizeof(gid_t)*ngidssize);
897       }
898       gidarray[ngids++]= gr->gr_gid;
899     }
900   }
901 }
902
903 static void determine_cwd(void) {
904   cwdbufsize= 0; cwdbuf= 0;
905
906   if (hidecwd) return;
907   
908   for (;;) {
909     if (cwdbufsize > MAX_GENERAL_STRING) { cwdbufsize= 0; free(cwdbuf); break; }
910     cwdbufsize <<= 1; cwdbufsize+= 100;
911     cwdbuf= xrealloc(cwdbuf,cwdbufsize);
912     cwdbuf[cwdbufsize-1]= 0;
913     if (getcwd(cwdbuf,cwdbufsize-1)) { cwdbufsize= strlen(cwdbuf); break; }
914     if (errno != ERANGE) { cwdbufsize= 0; free(cwdbuf); break; }
915   }
916 }
917
918 static void process_override(const char *servicename) {
919   FILE *ovfile;
920   int ovavail, l, c;
921
922   switch (overridetype) {
923   case ot_none:
924     ovused= -1;
925     ovbuf= 0;
926     break;
927   case ot_builtin:
928     l= strlen(servicename);
929     if (l >= MAX_OVERRIDE_LEN-20)
930       miscerror("builtin service string is too long (%d, max is %d)",
931                 l,MAX_OVERRIDE_LEN-21);
932     l+= 20;
933     ovbuf= xmalloc(l);
934     snprintf(ovbuf,l,"execute-builtin %s\n",servicename);
935     ovused= strlen(ovbuf);
936     break;
937   case ot_string:
938     l= strlen(overridevalue);
939     if (l >= MAX_OVERRIDE_LEN)
940       miscerror("override string is too long (%d, max is %d)",l,MAX_OVERRIDE_LEN-1);
941     ovbuf= xmalloc(l+2);
942     snprintf(ovbuf,l+2,"%s\n",overridevalue);
943     ovused= l+1;
944     break;
945   case ot_file:
946     ovfile= fopen(overridevalue,"r");
947     if (!ovfile) syscallerror("open overriding configuration file `%s'",overridevalue);
948     ovbuf= 0; ovavail= ovused= 0;
949     while ((c= getc(ovfile)) != EOF) {
950       if (!c) miscerror("overriding config file `%s' contains null(s)",overridevalue);
951       if (ovused >= MAX_OVERRIDE_LEN)
952         miscerror("override file is too long (max is %d)",MAX_OVERRIDE_LEN);
953       if (ovused >= ovavail) {
954         ovavail+=80; ovavail<<=2; ovbuf= xrealloc(ovbuf,ovavail);
955       }
956       ovbuf[ovused++]= c;
957     }
958     if (ferror(ovfile) || fclose(ovfile))
959       syscallerror("read overriding configuration file `%s'",overridevalue);
960     ovbuf= xrealloc(ovbuf,ovused+1);
961     ovbuf[ovused]= 0;
962     break;
963   default:
964     abort();
965   }
966 }
967
968 static int server_connect(void) {
969   struct sockaddr_un ssockname;
970   int sfd;
971   struct sigaction sig;
972   sigset_t sset;
973
974   sigemptyset(&sset);
975   sigaddset(&sset,SIGCHLD);
976   sigaddset(&sset,SIGALRM);
977   sigaddset(&sset,SIGPIPE);
978   if (sigprocmask(SIG_UNBLOCK,&sset,0)) syscallerror("preliminarily unblock signals");
979
980   sig.sa_handler= SIG_IGN;
981   sigemptyset(&sig.sa_mask);
982   sig.sa_flags= 0;
983   if (sigaction(SIGPIPE,&sig,0)) syscallerror("ignore sigpipe");
984
985   sfd= socket(AF_UNIX,SOCK_STREAM,0);
986   if (!sfd) syscallerror("create client socket");
987
988   assert(sizeof(ssockname.sun_path) > sizeof(RENDEZVOUSPATH));
989   ssockname.sun_family= AF_UNIX;
990   strcpy(ssockname.sun_path,RENDEZVOUSPATH);
991   priv_resume();
992   while (connect(sfd,(struct sockaddr*)&ssockname,sizeof(ssockname))) {
993     if (errno == ECONNREFUSED || errno == ENOENT)
994       syscallerror("uservd daemon is not running - service not available");
995     if (errno != EINTR)
996       syscallerror("unable to connect to uservd daemon: %m");
997   }
998
999   return sfd;
1000 }
1001
1002 static void server_handshake(int sfd) {
1003   srfile= fdopen(sfd,"r");
1004   if (!srfile) syscallerror("turn socket fd into FILE* for read");
1005   if (setvbuf(srfile,0,_IOFBF,BUFSIZ)) syscallerror("set buffering on socket reads");
1006
1007   swfile= fdopen(sfd,"w");
1008   if (!swfile) syscallerror("turn socket fd into FILE* for write");
1009   if (setvbuf(swfile,0,_IOFBF,BUFSIZ)) syscallerror("set buffering on socket writes");
1010
1011   xfread(&opening_mbuf,sizeof(opening_mbuf),srfile);
1012   checkmagic(opening_mbuf.magic,OPENING_MAGIC,"in opening message");
1013   if (memcmp(protocolchecksumversion,opening_mbuf.protocolchecksumversion,PCSUMSIZE))
1014     protoerror("protocol version checksum mismatch - server not same as client");
1015 }
1016
1017 static void server_preparepipes(void) {
1018   char pipepathbuf[PIPEPATHMAXLEN+2];
1019   int fd, tempfd;
1020   
1021   for (fd=0; fd<fdsetupsize; fd++) {
1022     if (!fdsetup[fd].filename) continue;
1023     pipepathbuf[PIPEPATHMAXLEN]= 0;
1024     sprintf(pipepathbuf, PIPEPATHFORMAT,
1025             (unsigned long)mypid, (unsigned long)opening_mbuf.serverpid, fd);
1026     assert(!pipepathbuf[PIPEPATHMAXLEN]);
1027     priv_resume();
1028     if (unlink(pipepathbuf) && errno != ENOENT)
1029       syscallerror("remove any old pipe `%s'",pipepathbuf);
1030     if (mkfifo(pipepathbuf,0600)) /* permissions are irrelevant */
1031       syscallerror("create pipe `%s'",pipepathbuf);
1032     tempfd= open(pipepathbuf,O_RDWR);
1033     if (tempfd<0) syscallerror("prelim open pipe `%s' for read+write",pipepathbuf);
1034     assert(fdsetup[fd].mods & (fdm_read|fdm_write));
1035     fdsetup[fd].pipefd=
1036       open(pipepathbuf, (fdsetup[fd].mods & fdm_read) ? O_WRONLY : O_RDONLY);
1037     if (fdsetup[fd].pipefd<0) syscallerror("real open pipe `%s'",pipepathbuf);
1038     if (close(tempfd)) syscallerror("close prelim fd onto pipe `%s'",pipepathbuf);
1039     priv_suspend();
1040   }
1041 }
1042
1043 static void server_sendrequest(int argc, char *const *argv) {
1044   struct request_msg request_mbuf;
1045   unsigned long ul;
1046   int fd, i;
1047   
1048   memset(&request_mbuf,0,sizeof(request_mbuf));
1049   request_mbuf.magic= REQUEST_MAGIC;
1050   request_mbuf.clientpid= getpid();
1051   request_mbuf.serviceuserlen= strlen(serviceuser);
1052   request_mbuf.servicelen= strlen(argv[0]);
1053   request_mbuf.lognamelen= strlen(logname);
1054   request_mbuf.spoofed= spoofuser ? 1 : 0;
1055   request_mbuf.cwdlen= cwdbufsize;
1056   request_mbuf.callinguid= spoofuid;
1057   request_mbuf.ngids= ngids+1;
1058   request_mbuf.nreadfds= 0;
1059   request_mbuf.nwritefds= 0;
1060   for (fd=0; fd<fdsetupsize; fd++) {
1061     if (!fdsetup[fd].filename) continue;
1062     assert(fdsetup[fd].mods & (fdm_write|fdm_read));
1063     if (fdsetup[fd].mods & fdm_write) request_mbuf.nwritefds++;
1064     else request_mbuf.nreadfds++;
1065   }
1066   request_mbuf.nargs= argc-1;
1067   request_mbuf.nvars= defvarused;
1068   request_mbuf.overridelen= ovused;
1069   xfwrite(&request_mbuf,sizeof(request_mbuf),swfile);
1070   xfwrite(serviceuser,sizeof(*serviceuser)*request_mbuf.serviceuserlen,swfile);
1071   xfwrite(argv[0],sizeof(*argv[0])*request_mbuf.servicelen,swfile);
1072   xfwrite(logname,sizeof(*logname)*request_mbuf.lognamelen,swfile);
1073   xfwrite(cwdbuf,sizeof(*cwdbuf)*request_mbuf.cwdlen,swfile);
1074   if (ovused>=0) xfwrite(ovbuf,sizeof(*ovbuf)*ovused,swfile);
1075   xfwrite(&spoofgid,sizeof(gid_t),swfile);
1076   xfwrite(gidarray,sizeof(gid_t)*ngids,swfile);
1077   xfwritefds(fdm_read,request_mbuf.nreadfds,swfile);
1078   xfwritefds(fdm_write,request_mbuf.nwritefds,swfile);
1079   for (i=1; i<argc; i++)
1080     xfwritestring(argv[i],swfile);
1081   for (i=0; i<defvarused; i++) {
1082     xfwritestring(defvararray[i].key,swfile);
1083     xfwritestring(defvararray[i].value,swfile);
1084   }
1085   ul= REQUEST_END_MAGIC; xfwrite(&ul,sizeof(ul),swfile);
1086   xfflush(swfile);
1087 }
1088
1089 static void server_awaitconfirm(void) {
1090   struct progress_msg progress_mbuf;
1091   
1092   getprogress(&progress_mbuf,srfile);
1093   if (progress_mbuf.type != pt_ok)
1094     protoerror("progress message during configuration phase"
1095                " unexpected type %d",progress_mbuf.type);
1096 }
1097
1098 static void prepare_asynchsignals(void) {
1099   static char stderrbuf[BUFSIZ], stdoutbuf[BUFSIZ];
1100   
1101   struct sigaction sig;
1102
1103   if (setvbuf(stderr,stderrbuf,_IOLBF,sizeof(stderrbuf)))
1104     syscallerror("set buffering on stderr");
1105   if (setvbuf(stdout,stdoutbuf,_IOFBF,sizeof(stdoutbuf)))
1106     syscallerror("set buffering on stdout");
1107   
1108   sig.sa_handler= sighandler_chld;
1109   sigemptyset(&sig.sa_mask);
1110   sigaddset(&sig.sa_mask,SIGCHLD);
1111   sigaddset(&sig.sa_mask,SIGALRM);
1112   sig.sa_flags= 0;
1113   if (sigaction(SIGCHLD,&sig,0)) syscallerror("set up sigchld handler");
1114
1115   sig.sa_handler= sighandler_alrm;
1116   if (sigaction(SIGALRM,&sig,0)) syscallerror("set up sigalrm handler");
1117
1118   if (!timeout) return;
1119   if (alarm(timeout)<0) syscallerror("set up timeout alarm");
1120 }
1121
1122 static void catdup(const char *which, int from, int to) {
1123   if (dup2(from,to)<0) {
1124     blocksignals(SIG_BLOCK);
1125     fprintf(stderr,"userv: %s: cannot dup for %s: %s\n",which,
1126             to?"stdout":"stdin", strerror(errno));
1127     exit(-1);
1128   }
1129 }
1130
1131 static void connect_pipes(void) {
1132   struct sigaction sig;
1133   char catnamebuf[sizeof(int)*3+30];
1134   int fd, reading;
1135   pid_t child;
1136   
1137   for (fd=0; fd<fdsetupsize; fd++) {
1138     if (!fdsetup[fd].filename) continue;
1139     if (!(fdsetup[fd].mods & fdm_fd)) {
1140       fdsetup[fd].copyfd=
1141         open(fdsetup[fd].filename,fdsetup[fd].oflags|O_NOCTTY,0777);
1142       if (fdsetup[fd].copyfd<0)
1143         syscallerror("open file `%s' for fd %d",fdsetup[fd].filename,fd);
1144     }
1145     blocksignals(SIG_BLOCK);
1146     child= fork();
1147     fdsetup[fd].catpid= child;
1148     blocksignals(SIG_UNBLOCK);
1149     if (child==-1) syscallerror("fork for cat for fd %d",fd);
1150     if (!child) {
1151       snprintf(catnamebuf,sizeof(catnamebuf),"cat fd%d",fd);
1152       catnamebuf[sizeof(catnamebuf)-1]= 0;
1153       sig.sa_handler= SIG_DFL;
1154       sigemptyset(&sig.sa_mask);
1155       sig.sa_flags= 0;
1156       if (sigaction(SIGPIPE,&sig,0)) {
1157         fprintf(stderr,"userv: %s: reset sigpipe handler for cat: %s",
1158                 catnamebuf,strerror(errno));
1159         exit(-1);
1160       }
1161       reading= fdsetup[fd].mods & fdm_read;
1162       catdup(catnamebuf, fdsetup[fd].copyfd, reading ? 0 : 1);
1163       catdup(catnamebuf, fdsetup[fd].pipefd, reading ? 1 : 0);
1164       execl("/bin/cat",catnamebuf,(char*)0);
1165       fprintf(stderr,"userv: %s: cannot exec `cat': %s\n",catnamebuf,strerror(errno));
1166       exit(-1);
1167     }
1168     if (fdsetup[fd].copyfd>2)
1169       if (close(fdsetup[fd].copyfd)) syscallerror("close real fd for %d",fd);
1170     if (close(fdsetup[fd].pipefd)) syscallerror("close pipe fd for %d",fd);
1171   }
1172 }
1173
1174 static void server_sendconfirm(void) {
1175   struct event_msg event_mbuf;
1176
1177   blocksignals(SIG_BLOCK);
1178   memset(&event_mbuf,0,sizeof(event_mbuf));
1179   event_mbuf.magic= EVENT_MAGIC;
1180   event_mbuf.type= et_confirm;
1181   xfwrite(&event_mbuf,sizeof(event_mbuf),swfile);
1182   xfflush(swfile);
1183   blocksignals(SIG_UNBLOCK);
1184 }
1185
1186 static int server_awaitcompletion(void) {
1187   struct progress_msg progress_mbuf;
1188   
1189   getprogress(&progress_mbuf,srfile);
1190   if (progress_mbuf.type != pt_terminated)
1191     protoerror("progress message during execution phase"
1192                " unexpected type %d",progress_mbuf.type);
1193
1194   swfile= 0;
1195   return progress_mbuf.data.terminated.status;
1196 }
1197
1198 static void dispose_remaining_pipes(void) {
1199   sigset_t sset;
1200   int fd, r;
1201
1202   blocksignals(SIG_BLOCK);
1203   for (fd=0; fd<fdsetupsize; fd++) {
1204     if (!(fdsetup[fd].catpid!=-1 && (fdsetup[fd].mods & fdm_close))) continue;
1205     if (kill(fdsetup[fd].catpid,SIGKILL)) syscallerror("kill cat for %d",fd);
1206     fdsetup[fd].killed= 1;
1207   }
1208   blocksignals(SIG_UNBLOCK);
1209
1210   for (;;) {
1211     blocksignals(SIG_BLOCK);
1212     for (fd=0;
1213          fd<fdsetupsize && !(fdsetup[fd].catpid!=-1 && (fdsetup[fd].mods & fdm_wait));
1214          fd++);
1215     if (fd>=fdsetupsize) break;
1216     sigemptyset(&sset);
1217     r= sigsuspend(&sset);
1218     if (r && errno != EINTR) syscallerror("sigsuspend failed in unexpected way");
1219     blocksignals(SIG_UNBLOCK);
1220   }
1221 }
1222
1223 static void NONRETURNING process_exitstatus(int status) {
1224   blocksignals(SIG_BLOCK);
1225
1226   if (systemerror) _exit(255);
1227
1228   if (sigpipeok && signalsexit != se_stdout && WIFSIGNALED(status) &&
1229       WTERMSIG(status)==SIGPIPE && !WCOREDUMP(status)) status= 0;
1230   
1231   switch (signalsexit) {
1232   case se_number:
1233   case se_numbernocore:
1234     if (WIFEXITED(status))
1235       _exit(WEXITSTATUS(status));
1236     else if (WIFSIGNALED(status))
1237       _exit(WTERMSIG(status) + (signalsexit==se_number && WCOREDUMP(status) ? 128 : 0));
1238     break;
1239   case se_highbit:
1240     if (WIFEXITED(status))
1241       _exit(WEXITSTATUS(status)<=127 ? WEXITSTATUS(status) : 127);
1242     else if (WIFSIGNALED(status) && WTERMSIG(status)<=126)
1243       _exit(WTERMSIG(status)+128);
1244     break;
1245   case se_stdout:
1246     printf("\n%d %d ",(status>>8)&0x0ff,status&0x0ff);
1247     if (WIFEXITED(status))
1248       printf("exited with code %d",WEXITSTATUS(status));
1249     else if (WIFSIGNALED(status))
1250       printf("killed by %s (signal %d)%s",
1251              strsignal(WTERMSIG(status)),WTERMSIG(status),
1252              WCOREDUMP(status) ? ", core dumped " : "");
1253     else
1254       printf("unknown wait status");
1255     putchar('\n');
1256     if (ferror(stdout) || fflush(stdout)) syscallerror("write exit status to stdout");
1257     _exit(0);
1258   default:
1259     if (WIFEXITED(status))
1260       _exit(WEXITSTATUS(status));
1261     else if (WIFSIGNALED(status))
1262       _exit(signalsexit);
1263     break;
1264   }
1265       
1266   fprintf(stderr,"userv: unknown wait status %d\n",status);
1267   _exit(-1);
1268 }
1269
1270 int main(int argc, char *const *argv) {
1271   int status, socketfd;
1272
1273 #ifdef NDEBUG
1274 # error Do not disable assertions in this security-critical code !
1275 #endif
1276
1277   security_init();
1278   parse_arguments(&argc,&argv);
1279   determine_users();
1280   determine_cwd();
1281   process_override(argv[0]);
1282
1283   socketfd= server_connect();
1284   priv_suspend();
1285   server_handshake(socketfd);
1286   server_preparepipes();
1287   server_sendrequest(argc,argv);
1288
1289   priv_permanentlyrevokesuspended();
1290   
1291   server_awaitconfirm();
1292   prepare_asynchsignals();
1293   connect_pipes();
1294   server_sendconfirm();
1295   status= server_awaitcompletion();
1296   
1297   dispose_remaining_pipes();
1298   process_exitstatus(status);
1299 }