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