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