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