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