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