5 * Copyright (C)1996-1997 Ian Jackson
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.
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.
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.
36 #include <sys/types.h>
38 #include <sys/socket.h>
40 #include <sys/resource.h>
49 typedef void optionfunction(const struct optioninfo*, const char *value, char *key);
54 int values; /* 0: no value; 1: single value; 2: key and value */
58 enum fdmodifiervalues {
72 struct fdmodifierinfo {
79 const struct fdmodifierinfo fdmodifierinfos[]= {
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,
92 { "creat", fdm_write|fdm_create,
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,
109 O_WRONLY|O_CREAT|O_APPEND },
110 { "sync", fdm_write|fdm_sync,
112 O_WRONLY|O_CREAT|O_SYNC },
114 fdm_nowait|fdm_close,
116 { "nowait", fdm_nowait,
119 { "close", fdm_close,
123 fdm_create|fdm_exclusive|fdm_truncate|fdm_append|fdm_sync,
128 struct fdsetupstate {
129 const char *filename;
131 int mods, oflags, pipefd, killed;
135 enum signalsexitspecials { se_number=-100, se_numbernocore, se_highbit, se_stdout };
136 enum overridetypes { ot_none, ot_string, ot_file };
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;
150 static FILE *srfile, *swfile;
152 static void blocksignals(int how) {
154 static const char blockerrmsg[]= "userv: failed to [un]block signals: ";
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));
169 static void NONRETURNPRINTFFORMAT(1,2) miscerror(const char *fmt, ...) {
172 blocksignals(SIG_BLOCK);
174 fprintf(stderr,"userv: failure: ");
175 vfprintf(stderr,fmt,al);
176 fprintf(stderr,"\n");
180 static void NONRETURNPRINTFFORMAT(1,2) syscallerror(const char *fmt, ...) {
185 blocksignals(SIG_BLOCK);
187 fprintf(stderr,"userv: system call failure: ");
188 vfprintf(stderr,fmt,al);
189 fprintf(stderr,": %s\n",strerror(e));
193 static void NONRETURNING protoreaderror(FILE *file, const char *where) {
197 blocksignals(SIG_BLOCK);
199 fprintf(stderr,"userv: failure: read error %s: %s\n",where,strerror(e));
202 fprintf(stderr,"userv: internal failure: EOF from server %s\n",where);
207 static void NONRETURNPRINTFFORMAT(1,2) protoerror(const char *fmt, ...) {
210 blocksignals(SIG_BLOCK);
212 fprintf(stderr,"userv: internal failure: protocol error: ");
213 vfprintf(stderr,fmt,al);
214 fprintf(stderr,"\n");
219 static void priv_suspend(void) { }
220 static void priv_resume(void) { }
221 static void priv_permanentlyrevokesuspended(void) { }
223 static void priv_suspend(void) {
224 if (setreuid(0,myuid) != 0) syscallerror("suspend root setreuid(0,myuid)");
226 static void priv_resume(void) {
227 if (setreuid(myuid,0) != 0) syscallerror("resume root setreuid(myuid,0)");
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)");
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");
239 static void *xmalloc(size_t s) {
242 if (!p) syscallerror("malloc (%lu bytes)",(unsigned long)s);
246 static void *xrealloc(void *p, size_t s) {
248 if (!p) syscallerror("realloc (%lu bytes)",(unsigned long)s);
252 static void xfread(void *p, size_t sz, FILE *file) {
254 nr= fread(p,1,sz,file);
255 if (nr != sz) protoreaderror(file,"in data");
258 static void xfwrite(const void *p, size_t sz, FILE *file) {
260 nr= fwrite(p,1,sz,file); if (nr == sz) return;
261 syscallerror("writing to server");
264 static void xfwritestring(const char *s, FILE *file) {
267 xfwrite(&l,sizeof(l),file);
268 xfwrite(s,sizeof(*s)*l,file);
271 static void xfflush(FILE *file) {
272 if (fflush(file)) syscallerror("flush server socket");
275 static void usage(void) {
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");
294 static void NONRETURNPRINTFFORMAT(1,2) usageerror(const char *fmt, ...) {
297 fprintf(stderr,"userv: ");
298 vfprintf(stderr,fmt,al);
299 fprintf(stderr,"\n\n");
304 static void addfdmodifier(struct fdsetupstate *fdsus, int fd, const char *key) {
305 const struct fdmodifierinfo *fdmip;
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;
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;
323 static void of_file(const struct optioninfo *oip, const char *value, char *key) {
324 unsigned long fd, copyfd;
329 fd= strtoul(key,&delim,10);
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);
338 if (fd > MAX_ALLOW_FD)
339 usageerror("file descriptor specified (%lu) is larger than maximum allowed (%d)",
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;
355 fdsetup[fd].filename= value;
356 fdsetup[fd].oflags= 0;
358 fdsetup[fd].copyfd= -1;
359 while (delim && *delim) {
361 delim= strchr(key,',');
362 if (delim) *delim++= 0;
363 addfdmodifier(&fdsetup[fd],fd,key);
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");
371 addfdmodifier(&fdsetup[fd],fd,"overwrite");
374 if (fdsetup[fd].mods & fdm_fd) {
375 copyfd= fdstdnumber(value);
377 copyfd= strtoul(value,&delim,0);
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);
386 do { r= fstat(copyfd,&stab); } while (r && errno==EINTR);
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);
392 fdsetup[fd].copyfd= copyfd;
396 static void of_fdwait(const struct optioninfo *oip, const char *value, char *key) {
397 const struct fdmodifierinfo *fdmip;
402 fd= fdstdnumber(key);
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");
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;
419 static void of_defvar(const struct optioninfo *oip, const char *value, char *key) {
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);
427 if (i==defvarsused) defvarsused++;
428 defvarsarray[i][0]= key;
429 defvarsarray[i][1]= value;
432 static void of_timeout(const struct optioninfo *oip, const char *value, char *key) {
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);
439 static void of_signals(const struct optioninfo *oip, const char *value, char *key) {
440 unsigned long numvalue;
442 numvalue= strtoul(value,&endp,0);
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);
450 if (numvalue<0 || numvalue>255)
451 usageerror("value %lu for --signals not 0...255",numvalue);
452 signalsexit= numvalue;
456 static void of_sigpipe(const struct optioninfo *oip, const char *value, char *key) {
460 static void of_hidecwd(const struct optioninfo *oip, const char *value, char *key) {
464 static void of_help(const struct optioninfo *oip, const char *value, char *key) {
469 static void of_copyright(const struct optioninfo *oip, const char *value, char *key) {
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");
488 static void of_override(const struct optioninfo *oip, const char *value, char *key) {
489 overridetype= ot_string;
490 overridevalue= value;
493 static void of_overridefile(const struct optioninfo *oip,
494 const char *value, char *key) {
495 overridetype= ot_file;
496 overridevalue= value;
499 static void of_spoofuser(const struct optioninfo *oip,
500 const char *value, char *key) {
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 },
520 static void callvalueoption(const struct optioninfo *oip, char *arg) {
522 if (oip->values == 2) {
523 equals= strchr(arg,'=');
526 usageerror("option --%s (-%c) passed argument `%s' with no `='",
527 oip->full,oip->abbrev,arg);
529 usageerror("option --%s passed argument `%s' with no `='",
532 (oip->fn)(oip,equals,arg);
534 (oip->fn)(oip,arg,0);
538 static void checkmagic(unsigned long was, unsigned long should, const char *when) {
540 protoerror("magic number %s was %08lx, expected %08lx",when,was,should);
543 static void getprogress(struct progress_msg *progress_r, FILE *file) {
548 xfread(progress_r,sizeof(struct progress_msg),file);
549 switch (progress_r->type) {
551 blocksignals(SIG_BLOCK);
552 fputs("userv: uservd reports that service failed\n",stderr);
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);
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);
577 static void xfwritefds(int modifier, int expected, FILE *file) {
580 for (i=0, fdcount=0; i<fdsetupsize; i++) {
581 if (!(fdsetup[i].filename && (fdsetup[i].mods & modifier)))
583 xfwrite(&i,sizeof(int),file); fdcount++;
585 assert(fdcount == expected);
588 static void disconnect(void) /* DOES return, unlike in daemon */ {
589 struct event_msg event_mbuf;
592 fputs("userv: failed, after service program terminated\n",stderr);
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);
602 static void sighandler_alrm(int ignored) /* DOES return, unlike in daemon */ {
605 fputs("userv: timeout\n",stderr);
610 static void sighandler_chld(int ignored) /* DOES return, unlike in daemon */ {
611 struct event_msg event_mbuf;
613 int status, fd, r, es;
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");
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));
642 fprintf(stderr,"userv: cat for fd %d terminated by signal %s (%d)\n",
643 fd,strsignal(WTERMSIG(status)),WTERMSIG(status));
645 fprintf(stderr,"userv: cat for fd %d gave unknown wait status %d\n",
649 fdsetup[fd].catpid= -1;
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));
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];
671 const struct optioninfo *oip;
672 struct sockaddr_un ssockname;
673 int sfd, ngids, i, j, tempfd, l, c, reading, fd, r, status, ngidssize;
678 struct opening_msg opening_mbuf;
679 struct request_msg request_mbuf;
680 struct progress_msg progress_mbuf;
681 struct event_msg event_mbuf;
684 gid_t mygid, spoofgid, *gidarray;
691 char pipepathbuf[PIPEPATHMAXLEN], catnamebuf[sizeof(int)*3+30];
692 struct sigaction sig;
695 # error Do not disable assertions in this security-critical code !
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,)");
707 of_file(0,"stdin",fd0key);
708 of_file(0,"stdout",fd1key);
709 of_file(0,"stderr",fd2key);
712 (argp= *argpp) && *argp == '-';
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);
720 if (!argpp[1]) usageerror("long option `%s' needs a value",*argpp);
721 callvalueoption(oip,*++argpp);
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'",
734 if (!argpp[1]) usageerror("short option `-%c' in argument `%s' needs"
735 " a value",*argp,*argpp);
738 callvalueoption(oip,argp);
739 break; /* No more options in this argument, go on to the next one. */
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");
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;
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");
765 pw= getpwnam(serviceuser);
766 if (!pw) miscerror("requested service user `%s' is not a user",serviceuser);
767 serviceuid= pw->pw_uid;
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");
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;
782 gidarray= xrealloc(gidarray,sizeof(gid_t)*ngidssize);
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++);
788 if (ngids>=ngidssize) {
789 ngidssize= (ngids+5)<<1;
790 gidarray= xrealloc(gidarray,sizeof(gid_t)*ngidssize);
792 gidarray[ngids++]= gr->gr_gid;
797 logname= getenv("LOGNAME");
798 if (!logname) logname= getenv("USER");
800 pw= getpwnam(logname);
801 if (!pw || pw->pw_uid != myuid) logname= 0;
804 pw= getpwuid(myuid); if (!pw) miscerror("cannot determine your login name");
805 logname= pw->pw_name;
809 cwdbufsize= 0; cwdbuf= 0;
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; }
821 switch (overridetype) {
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);
831 strcpy(ovbuf,overridevalue);
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);
848 if (ferror(ovfile) || fclose(ovfile))
849 syscallerror("read overriding configuration file `%s'",overridevalue);
850 ovbuf= xrealloc(ovbuf,ovused+1);
857 sig.sa_handler= SIG_IGN;
858 sigemptyset(&sig.sa_mask);
860 if (sigaction(SIGPIPE,&sig,0)) syscallerror("ignore sigpipe");
862 sfd= socket(AF_UNIX,SOCK_STREAM,0);
863 if (!sfd) syscallerror("create client socket");
865 assert(sizeof(ssockname.sun_path) > sizeof(RENDEZVOUSPATH));
866 ssockname.sun_family= AF_UNIX;
867 strcpy(ssockname.sun_path,RENDEZVOUSPATH);
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");
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");
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");
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");
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);
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));
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);
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++;
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++)
942 xfwritestring(defvarsarray[i][j],swfile);
943 ul= REQUEST_END_MAGIC; xfwrite(&ul,sizeof(ul),swfile);
946 priv_permanentlyrevokesuspended(); /* Must not do this before we give our real id */
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);
953 sig.sa_handler= sighandler_chld;
954 sigemptyset(&sig.sa_mask);
955 sigaddset(&sig.sa_mask,SIGCHLD);
956 sigaddset(&sig.sa_mask,SIGALRM);
958 if (sigaction(SIGCHLD,&sig,0)) syscallerror("set up sigchld handler");
960 sig.sa_handler= sighandler_alrm;
961 if (sigaction(SIGALRM,&sig,0)) syscallerror("set up sigalrm handler");
963 for (fd=0; fd<fdsetupsize; fd++) {
964 if (!fdsetup[fd].filename) continue;
965 if (!(fdsetup[fd].mods & fdm_fd)) {
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);
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);
978 if (sigaction(SIGPIPE,&sig,0)) {
979 fprintf(stderr,"userv: %s: reset sigpipe handler for cat: %s",
980 catnamebuf,strerror(errno));
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));
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);
997 if (alarm(timeout)<0) syscallerror("set up timeout alarm");
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);
1005 blocksignals(SIG_UNBLOCK);
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);
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;
1020 blocksignals(SIG_UNBLOCK);
1023 blocksignals(SIG_BLOCK);
1025 fd<fdsetupsize && !(fdsetup[fd].catpid!=-1 && (fdsetup[fd].mods & fdm_wait));
1027 if (fd>=fdsetupsize) break;
1029 r= sigsuspend(&sset);
1030 if (r && errno != EINTR) syscallerror("sigsuspend failed in unexpected way");
1031 blocksignals(SIG_UNBLOCK);
1034 blocksignals(SIG_BLOCK);
1036 status= progress_mbuf.data.terminated.status;
1037 if (sigpipeok && signalsexit != se_stdout && WIFSIGNALED(status) &&
1038 WTERMSIG(status)==SIGPIPE && !WCOREDUMP(status)) status= 0;
1040 switch (signalsexit) {
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));
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);
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 " : "");
1063 printf("unknown wait status");
1065 if (ferror(stdout) || fflush(stdout)) syscallerror("write exit status to stdout");
1068 if (WIFEXITED(status))
1069 _exit(WEXITSTATUS(status));
1070 else if (WIFSIGNALED(status))
1075 fprintf(stderr,"unknown wait status %d\n",status);