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