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 assert(l<=MAX_GENERAL_STRING);
268 xfwrite(&l,sizeof(l),file);
269 xfwrite(s,sizeof(*s)*l,file);
272 static void xfflush(FILE *file) {
273 if (fflush(file)) syscallerror("flush server socket");
276 static void usage(void) {
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");
295 static void NONRETURNPRINTFFORMAT(1,2) usageerror(const char *fmt, ...) {
298 fprintf(stderr,"userv: ");
299 vfprintf(stderr,fmt,al);
300 fprintf(stderr,"\n\n");
305 static void addfdmodifier(struct fdsetupstate *fdsus, int fd, const char *key) {
306 const struct fdmodifierinfo *fdmip;
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;
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;
324 static void of_file(const struct optioninfo *oip, const char *value, char *key) {
325 unsigned long fd, copyfd;
330 fd= strtoul(key,&delim,10);
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);
339 if (fd > MAX_ALLOW_FD)
340 usageerror("file descriptor specified (%lu) is larger than maximum allowed (%d)",
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;
356 fdsetup[fd].filename= value;
357 fdsetup[fd].oflags= 0;
359 fdsetup[fd].copyfd= -1;
360 while (delim && *delim) {
362 delim= strchr(key,',');
363 if (delim) *delim++= 0;
364 addfdmodifier(&fdsetup[fd],fd,key);
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");
372 addfdmodifier(&fdsetup[fd],fd,"overwrite");
375 if (fdsetup[fd].mods & fdm_fd) {
376 copyfd= fdstdnumber(value);
378 copyfd= strtoul(value,&delim,0);
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);
387 do { r= fstat(copyfd,&stab); } while (r && errno==EINTR);
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);
393 fdsetup[fd].copyfd= copyfd;
397 static void of_fdwait(const struct optioninfo *oip, const char *value, char *key) {
398 const struct fdmodifierinfo *fdmip;
403 fd= fdstdnumber(key);
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");
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;
420 static void of_defvar(const struct optioninfo *oip, const char *value, char *key) {
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);
433 if (i==defvarsused) defvarsused++;
434 defvarsarray[i][0]= key;
435 defvarsarray[i][1]= value;
438 static void of_timeout(const struct optioninfo *oip, const char *value, char *key) {
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);
445 static void of_signals(const struct optioninfo *oip, const char *value, char *key) {
446 unsigned long numvalue;
448 numvalue= strtoul(value,&endp,0);
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);
456 if (numvalue<0 || numvalue>255)
457 usageerror("value %lu for --signals not 0...255",numvalue);
458 signalsexit= numvalue;
462 static void of_sigpipe(const struct optioninfo *oip, const char *value, char *key) {
466 static void of_hidecwd(const struct optioninfo *oip, const char *value, char *key) {
470 static void of_help(const struct optioninfo *oip, const char *value, char *key) {
475 static void of_copyright(const struct optioninfo *oip, const char *value, char *key) {
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");
494 static void of_override(const struct optioninfo *oip, const char *value, char *key) {
495 overridetype= ot_string;
496 overridevalue= value;
499 static void of_overridefile(const struct optioninfo *oip,
500 const char *value, char *key) {
501 overridetype= ot_file;
502 overridevalue= value;
505 static void of_spoofuser(const struct optioninfo *oip,
506 const char *value, char *key) {
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 },
526 static void callvalueoption(const struct optioninfo *oip, char *arg) {
528 if (oip->values == 2) {
529 equals= strchr(arg,'=');
532 usageerror("option --%s (-%c) passed argument `%s' with no `='",
533 oip->full,oip->abbrev,arg);
535 usageerror("option --%s passed argument `%s' with no `='",
538 (oip->fn)(oip,equals,arg);
540 (oip->fn)(oip,arg,0);
544 static void checkmagic(unsigned long was, unsigned long should, const char *when) {
546 protoerror("magic number %s was %08lx, expected %08lx",when,was,should);
549 static void getprogress(struct progress_msg *progress_r, FILE *file) {
554 xfread(progress_r,sizeof(struct progress_msg),file);
555 switch (progress_r->type) {
557 blocksignals(SIG_BLOCK);
558 fputs("userv: uservd reports that service failed\n",stderr);
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);
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);
583 static void xfwritefds(int modifier, int expected, FILE *file) {
586 for (i=0, fdcount=0; i<fdsetupsize; i++) {
587 if (!(fdsetup[i].filename && (fdsetup[i].mods & modifier)))
589 xfwrite(&i,sizeof(int),file); fdcount++;
591 assert(fdcount == expected);
594 static void disconnect(void) /* DOES return, unlike in daemon */ {
595 struct event_msg event_mbuf;
598 fputs("userv: failed, after service program terminated\n",stderr);
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);
608 static void sighandler_alrm(int ignored) /* DOES return, unlike in daemon */ {
611 fputs("userv: timeout\n",stderr);
616 static void sighandler_chld(int ignored) /* DOES return, unlike in daemon */ {
617 struct event_msg event_mbuf;
619 int status, fd, r, es;
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");
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));
648 fprintf(stderr,"userv: cat for fd %d terminated by signal %s (%d)\n",
649 fd,strsignal(WTERMSIG(status)),WTERMSIG(status));
651 fprintf(stderr,"userv: cat for fd %d gave unknown wait status %d\n",
655 fdsetup[fd].catpid= -1;
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));
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];
677 const struct optioninfo *oip;
678 struct sockaddr_un ssockname;
679 int sfd, ngids, i, j, tempfd, l, c, reading, fd, r, status, ngidssize;
684 struct opening_msg opening_mbuf;
685 struct request_msg request_mbuf;
686 struct progress_msg progress_mbuf;
687 struct event_msg event_mbuf;
690 gid_t mygid, spoofgid, *gidarray;
697 char pipepathbuf[PIPEPATHMAXLEN], catnamebuf[sizeof(int)*3+30];
698 struct sigaction sig;
701 # error Do not disable assertions in this security-critical code !
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,)");
713 of_file(0,"stdin",fd0key);
714 of_file(0,"stdout",fd1key);
715 of_file(0,"stderr",fd2key);
718 (argp= *argpp) && *argp == '-';
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);
726 if (!argpp[1]) usageerror("long option `%s' needs a value",*argpp);
727 callvalueoption(oip,*++argpp);
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'",
740 if (!argpp[1]) usageerror("short option `-%c' in argument `%s' needs"
741 " a value",*argp,*argpp);
744 callvalueoption(oip,argp);
745 break; /* No more options in this argument, go on to the next one. */
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");
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;
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");
770 if (argc > MAX_ARGSDEFVARS) usageerror("far too many arguments");
771 if (ngids > MAX_GIDS) miscerror("caller is in far too many gids");
773 pw= getpwnam(serviceuser);
774 if (!pw) miscerror("requested service user `%s' is not a user",serviceuser);
775 serviceuid= pw->pw_uid;
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");
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;
790 gidarray= xrealloc(gidarray,sizeof(gid_t)*ngidssize);
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++);
796 if (ngids>=ngidssize) {
797 ngidssize= (ngids+5)<<1;
798 gidarray= xrealloc(gidarray,sizeof(gid_t)*ngidssize);
800 gidarray[ngids++]= gr->gr_gid;
805 logname= getenv("LOGNAME");
806 if (!logname) logname= getenv("USER");
808 pw= getpwnam(logname);
809 if (!pw || pw->pw_uid != myuid) logname= 0;
812 pw= getpwuid(myuid); if (!pw) miscerror("cannot determine your login name");
813 logname= pw->pw_name;
817 cwdbufsize= 0; cwdbuf= 0;
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; }
829 switch (overridetype) {
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);
839 strcpy(ovbuf,overridevalue);
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);
856 if (ferror(ovfile) || fclose(ovfile))
857 syscallerror("read overriding configuration file `%s'",overridevalue);
858 ovbuf= xrealloc(ovbuf,ovused+1);
865 sig.sa_handler= SIG_IGN;
866 sigemptyset(&sig.sa_mask);
868 if (sigaction(SIGPIPE,&sig,0)) syscallerror("ignore sigpipe");
870 sfd= socket(AF_UNIX,SOCK_STREAM,0);
871 if (!sfd) syscallerror("create client socket");
873 assert(sizeof(ssockname.sun_path) > sizeof(RENDEZVOUSPATH));
874 ssockname.sun_family= AF_UNIX;
875 strcpy(ssockname.sun_path,RENDEZVOUSPATH);
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");
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");
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");
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");
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);
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));
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);
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++;
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++)
950 xfwritestring(defvarsarray[i][j],swfile);
951 ul= REQUEST_END_MAGIC; xfwrite(&ul,sizeof(ul),swfile);
954 priv_permanentlyrevokesuspended(); /* Must not do this before we give our real id */
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);
961 sig.sa_handler= sighandler_chld;
962 sigemptyset(&sig.sa_mask);
963 sigaddset(&sig.sa_mask,SIGCHLD);
964 sigaddset(&sig.sa_mask,SIGALRM);
966 if (sigaction(SIGCHLD,&sig,0)) syscallerror("set up sigchld handler");
968 sig.sa_handler= sighandler_alrm;
969 if (sigaction(SIGALRM,&sig,0)) syscallerror("set up sigalrm handler");
971 for (fd=0; fd<fdsetupsize; fd++) {
972 if (!fdsetup[fd].filename) continue;
973 if (!(fdsetup[fd].mods & fdm_fd)) {
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);
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);
987 if (sigaction(SIGPIPE,&sig,0)) {
988 fprintf(stderr,"userv: %s: reset sigpipe handler for cat: %s",
989 catnamebuf,strerror(errno));
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));
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);
1005 if (alarm(timeout)<0) syscallerror("set up timeout alarm");
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);
1013 blocksignals(SIG_UNBLOCK);
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);
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;
1028 blocksignals(SIG_UNBLOCK);
1031 blocksignals(SIG_BLOCK);
1033 fd<fdsetupsize && !(fdsetup[fd].catpid!=-1 && (fdsetup[fd].mods & fdm_wait));
1035 if (fd>=fdsetupsize) break;
1037 r= sigsuspend(&sset);
1038 if (r && errno != EINTR) syscallerror("sigsuspend failed in unexpected way");
1039 blocksignals(SIG_UNBLOCK);
1042 blocksignals(SIG_BLOCK);
1044 status= progress_mbuf.data.terminated.status;
1045 if (sigpipeok && signalsexit != se_stdout && WIFSIGNALED(status) &&
1046 WTERMSIG(status)==SIGPIPE && !WCOREDUMP(status)) status= 0;
1048 switch (signalsexit) {
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));
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);
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 " : "");
1071 printf("unknown wait status");
1073 if (ferror(stdout) || fflush(stdout)) syscallerror("write exit status to stdout");
1076 if (WIFEXITED(status))
1077 _exit(WEXITSTATUS(status));
1078 else if (WIFSIGNALED(status))
1083 fprintf(stderr,"unknown wait status %d\n",status);