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.
23 * Here too, we do some horrible asynchronous stuff with signals.
25 * The following objects &c. are used in signal handlers and so
26 * must be protected by calls to blocksignals if they are used in
31 * The following objects are used in the main program unprotected
32 * and so must not be used in signal handlers:
37 * The following objects/functions are not modified/called after the
38 * asynchronicity starts:
44 * results of argument parsing
46 * systemerror, swfile, fdsetup[].catpid and fdsetup[].killed are used
47 * for communication between the main thread and the signal handlers.
49 * All the signal handlers save errno so that is OK too.
66 #include <sys/types.h>
68 #include <sys/socket.h>
70 #include <sys/resource.h>
77 enum fdmodifiervalues {
91 struct fdmodifierinfo {
99 const char *filename; /* non-null iff this fd has been specified */
100 int copyfd; /* fd to copy, -1 unless mods & fdm_fd */
101 int mods, oflags, pipefd, killed; /* 0,0,-1,0 unless otherwise set */
102 pid_t catpid; /* -1 indicates no cat process */
105 enum signalsexitspecials { se_number=-100, se_numbernocore, se_highbit, se_stdout };
106 enum overridetypes { ot_none, ot_string, ot_file, ot_builtin };
108 struct constkeyvaluepair { const char *key, *value; };
110 /* Variables from command-line arguments */
111 static const char *serviceuser;
112 static uid_t serviceuid;
113 static struct fdsetupstate *fdsetup;
114 static int fdsetupsize;
115 static struct constkeyvaluepair *defvararray;
116 static int defvaravail, defvarused;
117 static unsigned long timeout;
118 static int signalsexit=254;
119 static int sigpipeok, hidecwd;
120 static int overridetype= ot_none;
121 static const char *overridevalue, *spoofuser=0;
123 /* Other state variables */
124 static FILE *srfile, *swfile;
126 static uid_t myuid, spoofuid;
127 static gid_t mygid, spoofgid, *gidarray;
129 static struct opening_msg opening_mbuf;
130 static const char *logname;
132 static size_t cwdbufsize;
134 static int ovused, systemerror;
136 static void blocksignals(int how) {
138 static const char blockerrmsg[]= "userv: failed to [un]block signals: ";
142 sigaddset(&set,SIGCHLD);
143 sigaddset(&set,SIGALRM);
144 if (sigprocmask(how,&set,0)) {
145 str= strerror(errno);
146 write(2,blockerrmsg,sizeof(blockerrmsg)-1);
147 write(2,str,strlen(str));
153 /* Functions which may be called either from signal handlers or from
154 * the main thread. They block signals in case they are on the main
155 * thread, and may only use signal handler objects. None of them
156 * return. If they did they'd have to restore the signal mask.
159 static void NONRETURNPRINTFFORMAT(1,2) miscerror(const char *fmt, ...) {
162 blocksignals(SIG_BLOCK);
164 fprintf(stderr,"userv: failure: ");
165 vfprintf(stderr,fmt,al);
166 fprintf(stderr,"\n");
170 static void NONRETURNPRINTFFORMAT(1,2) syscallerror(const char *fmt, ...) {
175 blocksignals(SIG_BLOCK);
177 fprintf(stderr,"userv: system call failure: ");
178 vfprintf(stderr,fmt,al);
179 fprintf(stderr,": %s\n",strerror(e));
183 static void NONRETURNING protoreaderror(FILE *file, const char *where) {
187 blocksignals(SIG_BLOCK);
189 fprintf(stderr,"userv: failure: read error %s: %s\n",where,strerror(e));
192 fprintf(stderr,"userv: internal failure: EOF from server %s\n",where);
197 static void NONRETURNPRINTFFORMAT(1,2) protoerror(const char *fmt, ...) {
200 blocksignals(SIG_BLOCK);
202 fprintf(stderr,"userv: internal failure: protocol error: ");
203 vfprintf(stderr,fmt,al);
204 fprintf(stderr,"\n");
209 * General-purpose functions; these do nothing special about signals,
210 * except that they can call error-handlers which may block them
211 * to print error messages.
214 static void xfread(void *p, size_t sz, FILE *file) {
216 nr= fread(p,1,sz,file);
217 if (nr != sz) protoreaderror(file,"in data");
220 static void xfwrite(const void *p, size_t sz, FILE *file) {
222 nr= fwrite(p,1,sz,file); if (nr == sz) return;
223 syscallerror("writing to server");
226 static void xfflush(FILE *file) {
227 if (fflush(file)) syscallerror("flush server socket");
230 /* Functions which may be called only from the main thread. These may
231 * use main-thread objects and must block signals before using signal
236 static void priv_suspend(void) { }
237 static void priv_resume(void) { }
238 static void priv_permanentlyrevokesuspended(void) { }
240 static void priv_suspend(void) {
241 if (setreuid(0,myuid) != 0) syscallerror("suspend root setreuid(0,myuid)");
243 static void priv_resume(void) {
244 if (setreuid(myuid,0) != 0) syscallerror("resume root setreuid(myuid,0)");
246 static void priv_permanentlyrevokesuspended(void) {
247 if (setreuid(myuid,myuid) != 0) syscallerror("revoke root setreuid(myuid,myuid)");
248 if (setreuid(myuid,myuid) != 0) syscallerror("rerevoke root setreuid(myuid,myuid)");
250 if (!setreuid(myuid,0)) miscerror("revoked root but setreuid(0,0) succeeded !");
251 if (errno != EPERM) syscallerror("revoked and setreuid(myuid,0) unexpected error");
256 static void checkmagic(unsigned long was, unsigned long should, const char *when) {
258 protoerror("magic number %s was %08lx, expected %08lx",when,was,should);
261 static void getprogress(struct progress_msg *progress_r, FILE *file) {
266 xfread(progress_r,sizeof(struct progress_msg),file);
267 checkmagic(progress_r->magic,PROGRESS_MAGIC,"in progress message");
268 switch (progress_r->type) {
270 blocksignals(SIG_BLOCK);
271 fputs("userv: uservd reports that service failed\n",stderr);
274 blocksignals(SIG_BLOCK);
275 fputs("uservd: ",stderr);
276 if (progress_r->data.errmsg.messagelen>MAX_ERRMSG_STRING)
277 protoerror("stderr message length %d is far too long",
278 progress_r->data.errmsg.messagelen);
279 for (i=0; i<progress_r->data.errmsg.messagelen; i++) {
280 c= getc(file); if (c==EOF) protoreaderror(file,"in error message");
281 if (isprint(c)) putc(c,stderr);
282 else fprintf(stderr,"\\x%02x",(unsigned char)c);
285 if (ferror(stderr)) syscallerror("printing error message");
286 xfread(&ul,sizeof(ul),file);
287 checkmagic(ul,PROGRESS_ERRMSG_END_MAGIC,"after error message");
288 blocksignals(SIG_UNBLOCK);
297 * Functions which are called only during setup, before
298 * the signal asynchronicity starts. They can do anything they like.
301 static void *xmalloc(size_t s) {
304 if (!p) syscallerror("malloc (%lu bytes)",(unsigned long)s);
308 static void *xrealloc(void *p, size_t s) {
310 if (!p) syscallerror("realloc (%lu bytes)",(unsigned long)s);
314 static void xfwritestring(const char *s, FILE *file) {
317 assert(l<=MAX_GENERAL_STRING);
318 xfwrite(&l,sizeof(l),file);
319 xfwrite(s,sizeof(*s)*l,file);
322 static void xfwritefds(int modifier, int expected, FILE *file) {
325 for (i=0, fdcount=0; i<fdsetupsize; i++) {
326 if (!(fdsetup[i].filename && (fdsetup[i].mods & modifier)))
328 xfwrite(&i,sizeof(int),file); fdcount++;
330 assert(fdcount == expected);
333 /* Functions which may be called from signal handlers. These
334 * may use signal-handler objects. The main program may only
335 * call them with signals blocked, and they may not use any
336 * main-thread objects.
339 static void disconnect(void) /* DOES return, unlike in daemon */ {
340 struct event_msg event_mbuf;
344 memset(&event_mbuf,0,sizeof(event_mbuf));
345 event_mbuf.magic= EVENT_MAGIC;
346 event_mbuf.type= et_disconnect;
347 r= fwrite(&event_mbuf,1,sizeof(event_mbuf),swfile);
348 if ((r != sizeof(event_mbuf) || fflush(swfile)) && errno != EPIPE)
349 syscallerror("write to server when disconnecting\n");
354 static void sighandler_alrm(int ignored) /* DOES return, unlike in daemon */ {
357 fputs("userv: timeout\n",stderr);
362 static void sighandler_chld(int ignored) /* DOES return, unlike in daemon */ {
363 struct event_msg event_mbuf;
365 int status, fd, r, es;
369 child= wait3(&status,WNOHANG,0);
370 if (child == 0 || (child == -1 && errno == ECHILD)) break;
371 if (child == -1) syscallerror("wait for child process (in sigchld handler)");
372 for (fd=0; fd<fdsetupsize && fdsetup[fd].catpid != child; fd++);
373 if (fd>=fdsetupsize) continue; /* perhaps the caller gave us children */
374 if ((WIFEXITED(status) && WEXITSTATUS(status)==0) ||
375 (WIFSIGNALED(status) && WTERMSIG(status)==SIGPIPE) ||
376 (fdsetup[fd].killed && WIFSIGNALED(status) && WTERMSIG(status)==SIGKILL)) {
377 if (swfile && fdsetup[fd].mods & fdm_read) {
378 memset(&event_mbuf,0,sizeof(event_mbuf));
379 event_mbuf.magic= EVENT_MAGIC;
380 event_mbuf.type= et_closereadfd;
381 event_mbuf.data.closereadfd.fd= fd;
382 r= fwrite(&event_mbuf,1,sizeof(event_mbuf),swfile);
383 if (r != sizeof(event_mbuf) || fflush(swfile))
384 if (errno != EPIPE) syscallerror("inform service of closed read fd");
387 if (WIFEXITED(status))
388 fprintf(stderr,"userv: cat for fd %d exited with error exit status %d\n",
389 fd,WEXITSTATUS(status));
390 else if (WIFSIGNALED(status))
391 if (WCOREDUMP(status))
392 fprintf(stderr,"userv: cat for fd %d dumped core due to signal %s (%d)\n",
393 fd,strsignal(WTERMSIG(status)),WTERMSIG(status));
395 fprintf(stderr,"userv: cat for fd %d terminated by signal %s (%d)\n",
396 fd,strsignal(WTERMSIG(status)),WTERMSIG(status));
398 fprintf(stderr,"userv: cat for fd %d gave unknown wait status %d\n",
402 fdsetup[fd].catpid= -1;
408 * Argument parsing. These functions which are called only during
409 * setup, before the signal asynchronicity starts.
414 typedef void optionfunction(const struct optioninfo*, const char *value, char *key);
419 int values; /* 0: no value; 1: single value; 2: key and value */
423 static void usage(void) {
425 "usage: userv <options> [--] <service-user> <service-name> [<argument> ...]\n"
426 "usage: userv <options> -B|--builtin [--] <builtin-service> [<info-argument> ...]\n"
427 "options: -f|--file <fd>[<fdmodifiers>]=<filename>\n"
428 " -D|--defvar <name>=<value>\n"
429 " -t|--timeout <seconds>\n"
430 " -S|--signals <status>|number|number-nocore|highbit|stdout\n"
431 " -w|--fdwait <fd>=wait|nowait|close\n"
432 " -P|--sigpipe -H|--hidecwd -h|--help --copyright\n"
433 " --override <configuration-data> } available only\n"
434 " --override-file <filename> } to root\n"
435 " --spoof-user <username> } or same user\n"
436 "fdmodifiers: read write overwrite trunc[ate]\n"
437 "(separate with commas) append sync excl[usive] creat[e] fd\n\n"
438 "userv and uservd version " VERSION VEREXT "; copyright (C)1996-1997 Ian Jackson.\n"
439 "there is NO WARRANTY; type `userv --copyright' for details.\n",
441 syscallerror("write usage to stderr");
444 static void NONRETURNPRINTFFORMAT(1,2) usageerror(const char *fmt, ...) {
447 fputs("userv: ",stderr);
448 vfprintf(stderr,fmt,al);
449 fputs("\n\n",stderr);
454 static const struct fdmodifierinfo fdmodifierinfos[]= {
458 { "write", fdm_write,
461 { "overwrite", fdm_write|fdm_create|fdm_truncate,
462 fdm_read|fdm_fd|fdm_exclusive,
463 O_WRONLY|O_CREAT|O_TRUNC },
464 { "create", fdm_write|fdm_create,
467 { "creat", fdm_write|fdm_create,
470 { "exclusive", fdm_write|fdm_create|fdm_exclusive,
471 fdm_read|fdm_fd|fdm_truncate,
472 O_WRONLY|O_CREAT|O_EXCL },
473 { "excl", fdm_write|fdm_create|fdm_exclusive,
474 fdm_read|fdm_fd|fdm_truncate,
475 O_WRONLY|O_CREAT|O_EXCL },
476 { "truncate", fdm_write|fdm_truncate,
477 fdm_read|fdm_fd|fdm_exclusive,
478 O_WRONLY|O_CREAT|O_EXCL },
479 { "trunc", fdm_write|fdm_truncate,
480 fdm_read|fdm_fd|fdm_exclusive,
481 O_WRONLY|O_CREAT|O_EXCL },
482 { "append", fdm_write|fdm_append,
484 O_WRONLY|O_CREAT|O_APPEND },
485 { "sync", fdm_write|fdm_sync,
487 O_WRONLY|O_CREAT|O_SYNC },
489 fdm_nowait|fdm_close,
491 { "nowait", fdm_nowait,
494 { "close", fdm_close,
498 fdm_create|fdm_exclusive|fdm_truncate|fdm_append|fdm_sync,
503 static void addfdmodifier(int fd, const char *key) {
504 const struct fdmodifierinfo *fdmip;
507 for (fdmip= fdmodifierinfos; fdmip->string && strcmp(fdmip->string,key); fdmip++);
508 if (!fdmip->string) usageerror("unknown fdmodifer `%s' for fd %d",key,fd);
509 if (fdmip->conflicts & fdsetup[fd].mods)
510 usageerror("fdmodifier `%s' conflicts with another for fd %d",key,fd);
511 fdsetup[fd].mods |= fdmip->implies;
512 fdsetup[fd].oflags |= fdmip->oflags;
515 static int fdstdnumber(const char *string) {
516 if (!strcmp(string,"stdin")) return 0;
517 else if (!strcmp(string,"stdout")) return 1;
518 else if (!strcmp(string,"stderr")) return 2;
522 static void of_file(const struct optioninfo *oip, const char *value, char *key) {
523 unsigned long fd, copyfd;
528 fd= strtoul(key,&delim,10);
530 delim= strchr(key,',');
531 if (delim) *delim++= 0;
532 fd= fdstdnumber(key);
533 if (fd<0) usageerror("first part of argument to -f or --file must be numeric "
534 "file descriptor or `stdin', `stdout' or `stderr' - `%s' "
535 "is not recognized",key);
537 if (fd > MAX_ALLOW_FD)
538 usageerror("file descriptor specified (%lu) is larger than maximum allowed (%d)",
540 if (fd >= fdsetupsize) {
541 oldarraysize= fdsetupsize;
542 fdsetupsize+=2; fdsetupsize<<=1;
543 fdsetup= xrealloc(fdsetup,sizeof(struct fdsetupstate)*fdsetupsize);
544 while (oldarraysize < fdsetupsize) {
545 fdsetup[oldarraysize].filename= 0;
546 fdsetup[oldarraysize].pipefd= -1;
547 fdsetup[oldarraysize].copyfd= -1;
548 fdsetup[oldarraysize].mods= 0;
549 fdsetup[oldarraysize].oflags= 0;
550 fdsetup[oldarraysize].catpid= -1;
551 fdsetup[oldarraysize].killed= 0;
552 fdsetup[oldarraysize].filename= 0;
556 fdsetup[fd].filename= value;
557 fdsetup[fd].oflags= 0;
559 fdsetup[fd].copyfd= -1;
560 while (delim && *delim) {
562 delim= strchr(key,',');
563 if (delim) *delim++= 0;
564 addfdmodifier(fd,key);
566 if (!(fdsetup[fd].mods & (fdm_read|fdm_write))) {
568 addfdmodifier(fd,"read");
569 } else if (fdsetup[fd].mods & fdm_fd) {
570 addfdmodifier(fd,"write");
572 addfdmodifier(fd,"overwrite");
575 if (fdsetup[fd].mods & fdm_fd) {
576 copyfd= fdstdnumber(value);
578 copyfd= strtoul(value,&delim,0);
580 usageerror("value part of argument to --file with fd modifier must be "
581 "numeric or fd name - `%s' is not recognised",value);
582 else if (copyfd > MAX_ALLOW_FD)
583 usageerror("file descriptor %lu named as target of file descriptor redirection"
584 " (for file descriptor %lu) is larger than maximum allowed (%d)",
585 copyfd,fd,MAX_ALLOW_FD);
587 r= fstat(copyfd,&stab);
589 if (oip) syscallerror("check filedescriptor %lu (named as target of file "
590 "descriptor redirection for %lu)",copyfd,fd);
591 else syscallerror("check basic filedescriptor %lu at program start",copyfd);
593 fdsetup[fd].copyfd= copyfd;
597 static void of_fdwait(const struct optioninfo *oip, const char *value, char *key) {
598 const struct fdmodifierinfo *fdmip;
603 fd= fdstdnumber(key);
605 ul= strtoul(key,&delim,0);
606 if (*delim) usageerror("first part of argument to --fdwait must be "
607 "numeric or fd name - `%s' is not recognised",key);
608 if (ul>MAX_ALLOW_FD) usageerror("first part of argument to --fdwait is too large");
611 if (fd >= fdsetupsize || !fdsetup[fd].filename)
612 usageerror("file descriptor %d specified in --fdwait option is not open",fd);
613 for (fdmip= fdmodifierinfos; fdmip->string && strcmp(fdmip->string,value); fdmip++);
614 if (!fdmip->string || !(fdmip->implies & (fdm_wait|fdm_nowait|fdm_close)))
615 usageerror("value for --fdwait must be `wait', `nowait' or `close', not `%s'",value);
616 fdsetup[fd].mods &= ~(fdm_wait|fdm_nowait|fdm_close);
617 fdsetup[fd].mods |= fdmip->implies;
620 static void of_defvar(const struct optioninfo *oip, const char *value, char *key) {
624 usageerror("empty string not allowed as variable name");
625 if (strlen(key)>MAX_GENERAL_STRING)
626 usageerror("variable name `%s' is far too long",key);
627 if (strlen(value)>MAX_GENERAL_STRING)
628 usageerror("variable `%s' has value `%s' which is far too long",key,value);
629 for (i=0; i<defvarused && strcmp(defvararray[i].key,key); i++);
630 if (defvarused >= MAX_ARGSDEFVAR) usageerror("far too many --defvar or -D options");
631 if (i>=defvaravail) {
632 defvaravail+=10; defvaravail<<=1;
633 defvararray= xrealloc(defvararray,sizeof(struct constkeyvaluepair)*defvaravail);
635 if (i==defvarused) defvarused++;
636 defvararray[i].key= key;
637 defvararray[i].value= value;
640 static void of_timeout(const struct optioninfo *oip, const char *value, char *key) {
644 ul= strtoul(value,&endp,0);
645 if (*endp) usageerror("timeout value `%s' must be a plain decimal string",value);
646 if (ul>INT_MAX) usageerror("timeout value %lu too large",ul);
650 static void of_signals(const struct optioninfo *oip, const char *value, char *key) {
651 unsigned long numvalue;
654 numvalue= strtoul(value,&endp,0);
656 if (!strcmp(value,"number")) signalsexit= se_number;
657 else if (!strcmp(value,"number-nocore")) signalsexit= se_numbernocore;
658 else if (!strcmp(value,"highbit")) signalsexit= se_highbit;
659 else if (!strcmp(value,"stdout")) signalsexit= se_stdout;
660 else usageerror("value `%s' for --signals not understood",value);
662 if (numvalue<0 || numvalue>255)
663 usageerror("value %lu for --signals not 0...255",numvalue);
664 signalsexit= numvalue;
668 static void of_sigpipe(const struct optioninfo *oip, const char *value, char *key) {
672 static void of_hidecwd(const struct optioninfo *oip, const char *value, char *key) {
676 static void of_help(const struct optioninfo *oip, const char *value, char *key) {
681 static void of_copyright(const struct optioninfo *oip, const char *value, char *key) {
683 " userv - user service daemon and client; copyright (C)1996-1997 Ian Jackson\n\n"
684 " This is free software; you can redistribute it and/or modify it under the\n"
685 " terms of the GNU General Public License as published by the Free Software\n"
686 " Foundation; either version 2 of the License, or (at your option) any\n"
687 " later version.\n\n"
688 " This program is distributed in the hope that it will be useful, but\n"
689 " WITHOUT ANY WARRANTY; without even the implied warranty of\n"
690 " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\n"
691 " Public License for more details.\n\n"
692 " You should have received a copy of the GNU General Public License along\n"
693 " with userv; if not, write to Ian Jackson <ian@chiark.greenend.org.uk> or\n"
694 " to the Free Software Foundation, 59 Temple Place - Suite 330, Boston,\n"
695 " MA 02111-1307, USA.\n",
696 stdout) < 0) syscallerror("write usage to stderr");
700 static void of_builtin(const struct optioninfo *oip, const char *value, char *key) {
701 overridetype= ot_builtin;
704 static void of_override(const struct optioninfo *oip, const char *value, char *key) {
705 overridetype= ot_string;
706 overridevalue= value;
709 static void of_overridefile(const struct optioninfo *oip,
710 const char *value, char *key) {
711 overridetype= ot_file;
712 overridevalue= value;
715 static void of_spoofuser(const struct optioninfo *oip,
716 const char *value, char *key) {
720 const struct optioninfo optioninfos[]= {
721 { 'f', "file", 2, of_file },
722 { 'w', "fdwait", 2, of_fdwait },
723 { 'D', "defvar", 2, of_defvar },
724 { 't', "timeout", 1, of_timeout },
725 { 'S', "signals", 1, of_signals },
726 { 'P', "sigpipe", 0, of_sigpipe },
727 { 'H', "hidecwd", 0, of_hidecwd },
728 { 'B', "builtin", 0, of_builtin },
729 { 'h', "help", 0, of_help },
730 { 0, "copyright", 0, of_copyright },
731 { 0, "override", 1, of_override },
732 { 0, "override-file", 1, of_overridefile },
733 { 0, "spoof-user", 1, of_spoofuser },
737 static void callvalueoption(const struct optioninfo *oip, char *arg) {
739 if (oip->values == 2) {
740 equals= strchr(arg,'=');
743 usageerror("option --%s (-%c) passed argument `%s' with no `='",
744 oip->full,oip->abbrev,arg);
746 usageerror("option --%s passed argument `%s' with no `='",
749 (oip->fn)(oip,equals,arg);
751 (oip->fn)(oip,arg,0);
756 * Main thread main processing functions - in order of execution.
759 static void security_init(void) {
760 /* May not open any file descriptors. */
762 mypid= getpid(); if (mypid == (pid_t)-1) syscallerror("getpid");
763 myuid= getuid(); if (myuid == (uid_t)-1) syscallerror("getuid");
764 mygid= getgid(); if (mygid == (gid_t)-1) syscallerror("getgid");
765 ngids= getgroups(0,0); if (ngids == (gid_t)-1) syscallerror("getgroups(0,0)");
766 gidarray= xmalloc(sizeof(gid_t)*ngids);
767 if (getgroups(ngids,gidarray) != ngids) syscallerror("getgroups(ngids,)");
771 if (ngids > MAX_GIDS) miscerror("caller is in far too many gids");
774 static void parse_arguments(int *argcp, char *const **argvp) {
775 static char fd0key[]= "stdin,fd,read";
776 static char fd1key[]= "stdout,fd,write";
777 static char fd2key[]= "stderr,fd,write";
781 const struct optioninfo *oip;
785 of_file(0,"stdin",fd0key);
786 of_file(0,"stdout",fd1key);
787 of_file(0,"stderr",fd2key);
789 for (argpp= *argvp+1;
790 (argp= *argpp) && *argp == '-' && argp[1];
792 if (!*++argp) usageerror("unknown option/argument `%s'",*argpp);
793 if (*argp == '-') { /* Two hyphens */
794 if (!*++argp) { argpp++; break; /* End of options. */ }
795 for (oip= optioninfos; oip->full && strcmp(oip->full,argp); oip++);
796 if (!oip->full) usageerror("unknown long option `%s'",*argpp);
798 if (!argpp[1]) usageerror("long option `%s' needs a value",*argpp);
799 callvalueoption(oip,*++argpp);
804 for (; *argp; argp++) {
805 for (oip= optioninfos; oip->full && oip->abbrev != *argp; oip++);
806 if (!oip->full) usageerror("unknown short option `-%c' in argument `%s'",
812 if (!argpp[1]) usageerror("short option `-%c' in argument `%s' needs"
813 " a value",*argp,*argpp);
816 callvalueoption(oip,argp);
817 break; /* No more options in this argument, go on to the next one. */
824 if (overridetype == ot_builtin) {
827 if (!*argpp) usageerror("no service user given after options");
828 serviceuser= *argpp++;
830 if (!*argpp) usageerror(overridetype == ot_builtin ?
831 "no service name given after options and service user" :
832 "no builtin service given after options");
834 *argcp-= (argpp-*argvp);
837 if (*argcp > MAX_ARGSDEFVAR) usageerror("far too many arguments");
839 for (fd=0; fd<fdsetupsize; fd++) {
840 if (!fdsetup[fd].filename) continue;
841 if (fdsetup[fd].mods & (fdm_wait|fdm_nowait|fdm_close)) continue;
842 assert(fdsetup[fd].mods & (fdm_read|fdm_write));
843 fdsetup[fd].mods |= (fdsetup[fd].mods & fdm_read) ? fdm_close : fdm_wait;
847 static void determine_users(void) {
855 logname= getenv("LOGNAME");
856 if (!logname) logname= getenv("USER");
858 pw= getpwnam(logname);
859 if (!pw || pw->pw_uid != myuid) logname= 0;
862 pw= getpwuid(myuid); if (!pw) miscerror("cannot determine your login name");
863 logname= pw->pw_name;
866 if (!strcmp(serviceuser,"-")) serviceuser= logname;
867 pw= getpwnam(serviceuser);
868 if (!pw) miscerror("requested service user `%s' is not a user",serviceuser);
869 serviceuid= pw->pw_uid;
871 if ((overridetype != ot_none || spoofuser) && myuid != 0 && myuid != serviceuid)
872 miscerror("--override and --spoof options only available to root or to"
873 " the user who will be providing the service");
877 pw= getpwnam(logname);
878 if (!pw) miscerror("spoofed login name `%s' is not valid",logname);
879 spoofuid= pw->pw_uid;
880 spoofgid= pw->pw_gid;
881 ngidssize= ngids; ngids= 0;
884 gidarray= xrealloc(gidarray,sizeof(gid_t)*ngidssize);
886 gidarray[ngids++]= spoofgid;
887 while ((gr= getgrent())) { /* ouch! getgrent has no error behaviour! */
888 for (mem= gr->gr_mem; *mem && strcmp(*mem,logname); mem++);
890 if (ngids>=ngidssize) {
891 if (ngids>=MAX_GIDS) miscerror("spoofed user is member of too many groups");
892 ngidssize= (ngids+5)<<1;
893 gidarray= xrealloc(gidarray,sizeof(gid_t)*ngidssize);
895 gidarray[ngids++]= gr->gr_gid;
900 static void determine_cwd(void) {
901 cwdbufsize= 0; cwdbuf= 0;
906 if (cwdbufsize > MAX_GENERAL_STRING) { cwdbufsize= 0; free(cwdbuf); break; }
907 cwdbufsize <<= 1; cwdbufsize+= 100;
908 cwdbuf= xrealloc(cwdbuf,cwdbufsize);
909 cwdbuf[cwdbufsize-1]= 0;
910 if (getcwd(cwdbuf,cwdbufsize-1)) { cwdbufsize= strlen(cwdbuf); break; }
911 if (errno != ERANGE) { cwdbufsize= 0; free(cwdbuf); break; }
915 static void process_override(const char *servicename) {
919 switch (overridetype) {
925 l= strlen(servicename);
926 if (l >= MAX_OVERRIDE_LEN-20)
927 miscerror("builtin service string is too long (%d, max is %d)",
928 l,MAX_OVERRIDE_LEN-21);
931 snprintf(ovbuf,l,"execute-builtin %s\n",servicename);
932 ovused= strlen(ovbuf);
935 l= strlen(overridevalue);
936 if (l >= MAX_OVERRIDE_LEN)
937 miscerror("override string is too long (%d, max is %d)",l,MAX_OVERRIDE_LEN-1);
939 snprintf(ovbuf,l+2,"%s\n",overridevalue);
943 ovfile= fopen(overridevalue,"r");
944 if (!ovfile) syscallerror("open overriding configuration file `%s'",overridevalue);
945 ovbuf= 0; ovavail= ovused= 0;
946 while ((c= getc(ovfile)) != EOF) {
947 if (!c) miscerror("overriding config file `%s' contains null(s)",overridevalue);
948 if (ovused >= MAX_OVERRIDE_LEN)
949 miscerror("override file is too long (max is %d)",MAX_OVERRIDE_LEN);
950 if (ovused >= ovavail) {
951 ovavail+=80; ovavail<<=2; ovbuf= xrealloc(ovbuf,ovavail);
955 if (ferror(ovfile) || fclose(ovfile))
956 syscallerror("read overriding configuration file `%s'",overridevalue);
957 ovbuf= xrealloc(ovbuf,ovused+1);
965 static int server_connect(void) {
966 struct sockaddr_un ssockname;
968 struct sigaction sig;
972 sigaddset(&sset,SIGCHLD);
973 sigaddset(&sset,SIGALRM);
974 sigaddset(&sset,SIGPIPE);
975 if (sigprocmask(SIG_UNBLOCK,&sset,0)) syscallerror("preliminarily unblock signals");
977 sig.sa_handler= SIG_IGN;
978 sigemptyset(&sig.sa_mask);
980 if (sigaction(SIGPIPE,&sig,0)) syscallerror("ignore sigpipe");
982 sfd= socket(AF_UNIX,SOCK_STREAM,0);
983 if (!sfd) syscallerror("create client socket");
985 assert(sizeof(ssockname.sun_path) > sizeof(RENDEZVOUSPATH));
986 ssockname.sun_family= AF_UNIX;
987 strcpy(ssockname.sun_path,RENDEZVOUSPATH);
989 while (connect(sfd,(struct sockaddr*)&ssockname,sizeof(ssockname))) {
990 if (errno == ECONNREFUSED || errno == ENOENT)
991 syscallerror("uservd daemon is not running - service not available");
993 syscallerror("unable to connect to uservd daemon: %m");
999 static void server_handshake(int sfd) {
1000 srfile= fdopen(sfd,"r");
1001 if (!srfile) syscallerror("turn socket fd into FILE* for read");
1002 if (setvbuf(srfile,0,_IOFBF,BUFSIZ)) syscallerror("set buffering on socket reads");
1004 swfile= fdopen(sfd,"w");
1005 if (!swfile) syscallerror("turn socket fd into FILE* for write");
1006 if (setvbuf(swfile,0,_IOFBF,BUFSIZ)) syscallerror("set buffering on socket writes");
1008 xfread(&opening_mbuf,sizeof(opening_mbuf),srfile);
1009 checkmagic(opening_mbuf.magic,OPENING_MAGIC,"in opening message");
1010 if (memcmp(protocolchecksumversion,opening_mbuf.protocolchecksumversion,PCSUMSIZE))
1011 protoerror("protocol version checksum mismatch - server not same as client");
1014 static void server_preparepipes(void) {
1015 char pipepathbuf[PIPEPATHMAXLEN+2];
1018 for (fd=0; fd<fdsetupsize; fd++) {
1019 if (!fdsetup[fd].filename) continue;
1020 pipepathbuf[PIPEPATHMAXLEN]= 0;
1021 sprintf(pipepathbuf, PIPEPATHFORMAT,
1022 (unsigned long)mypid, (unsigned long)opening_mbuf.serverpid, fd);
1023 assert(!pipepathbuf[PIPEPATHMAXLEN]);
1025 if (unlink(pipepathbuf) && errno != ENOENT)
1026 syscallerror("remove any old pipe `%s'",pipepathbuf);
1027 if (mkfifo(pipepathbuf,0600)) /* permissions are irrelevant */
1028 syscallerror("create pipe `%s'",pipepathbuf);
1029 tempfd= open(pipepathbuf,O_RDWR);
1030 if (tempfd<0) syscallerror("prelim open pipe `%s' for read+write",pipepathbuf);
1031 assert(fdsetup[fd].mods & (fdm_read|fdm_write));
1033 open(pipepathbuf, (fdsetup[fd].mods & fdm_read) ? O_WRONLY : O_RDONLY);
1034 if (fdsetup[fd].pipefd<0) syscallerror("real open pipe `%s'",pipepathbuf);
1035 if (close(tempfd)) syscallerror("close prelim fd onto pipe `%s'",pipepathbuf);
1040 static void server_sendrequest(int argc, char *const *argv) {
1041 struct request_msg request_mbuf;
1045 memset(&request_mbuf,0,sizeof(request_mbuf));
1046 request_mbuf.magic= REQUEST_MAGIC;
1047 request_mbuf.clientpid= getpid();
1048 request_mbuf.serviceuserlen= strlen(serviceuser);
1049 request_mbuf.servicelen= strlen(argv[0]);
1050 request_mbuf.lognamelen= strlen(logname);
1051 request_mbuf.spoofed= spoofuser ? 1 : 0;
1052 request_mbuf.cwdlen= cwdbufsize;
1053 request_mbuf.callinguid= spoofuid;
1054 request_mbuf.ngids= ngids+1;
1055 request_mbuf.nreadfds= 0;
1056 request_mbuf.nwritefds= 0;
1057 for (fd=0; fd<fdsetupsize; fd++) {
1058 if (!fdsetup[fd].filename) continue;
1059 assert(fdsetup[fd].mods & (fdm_write|fdm_read));
1060 if (fdsetup[fd].mods & fdm_write) request_mbuf.nwritefds++;
1061 else request_mbuf.nreadfds++;
1063 request_mbuf.nargs= argc-1;
1064 request_mbuf.nvars= defvarused;
1065 request_mbuf.overridelen= ovused;
1066 xfwrite(&request_mbuf,sizeof(request_mbuf),swfile);
1067 xfwrite(serviceuser,sizeof(*serviceuser)*request_mbuf.serviceuserlen,swfile);
1068 xfwrite(argv[0],sizeof(*argv[0])*request_mbuf.servicelen,swfile);
1069 xfwrite(logname,sizeof(*logname)*request_mbuf.lognamelen,swfile);
1070 xfwrite(cwdbuf,sizeof(*cwdbuf)*request_mbuf.cwdlen,swfile);
1071 if (ovused>=0) xfwrite(ovbuf,sizeof(*ovbuf)*ovused,swfile);
1072 xfwrite(&spoofgid,sizeof(gid_t),swfile);
1073 xfwrite(gidarray,sizeof(gid_t)*ngids,swfile);
1074 xfwritefds(fdm_read,request_mbuf.nreadfds,swfile);
1075 xfwritefds(fdm_write,request_mbuf.nwritefds,swfile);
1076 for (i=1; i<argc; i++)
1077 xfwritestring(argv[i],swfile);
1078 for (i=0; i<defvarused; i++) {
1079 xfwritestring(defvararray[i].key,swfile);
1080 xfwritestring(defvararray[i].value,swfile);
1082 ul= REQUEST_END_MAGIC; xfwrite(&ul,sizeof(ul),swfile);
1086 static void server_awaitconfirm(void) {
1087 struct progress_msg progress_mbuf;
1089 getprogress(&progress_mbuf,srfile);
1090 if (progress_mbuf.type != pt_ok)
1091 protoerror("progress message during configuration phase"
1092 " unexpected type %d",progress_mbuf.type);
1095 static void prepare_asynchsignals(void) {
1096 static char stderrbuf[BUFSIZ], stdoutbuf[BUFSIZ];
1098 struct sigaction sig;
1100 if (setvbuf(stderr,stderrbuf,_IOLBF,sizeof(stderrbuf)))
1101 syscallerror("set buffering on stderr");
1102 if (setvbuf(stdout,stdoutbuf,_IOFBF,sizeof(stdoutbuf)))
1103 syscallerror("set buffering on stdout");
1105 sig.sa_handler= sighandler_chld;
1106 sigemptyset(&sig.sa_mask);
1107 sigaddset(&sig.sa_mask,SIGCHLD);
1108 sigaddset(&sig.sa_mask,SIGALRM);
1110 if (sigaction(SIGCHLD,&sig,0)) syscallerror("set up sigchld handler");
1112 sig.sa_handler= sighandler_alrm;
1113 if (sigaction(SIGALRM,&sig,0)) syscallerror("set up sigalrm handler");
1115 if (!timeout) return;
1116 if (alarm(timeout)<0) syscallerror("set up timeout alarm");
1119 static void catdup(const char *which, int from, int to) {
1120 if (dup2(from,to)<0) {
1121 blocksignals(SIG_BLOCK);
1122 fprintf(stderr,"userv: %s: cannot dup for %s: %s\n",which,
1123 to?"stdout":"stdin", strerror(errno));
1128 static void connect_pipes(void) {
1129 struct sigaction sig;
1130 char catnamebuf[sizeof(int)*3+30];
1133 for (fd=0; fd<fdsetupsize; fd++) {
1134 if (!fdsetup[fd].filename) continue;
1135 if (!(fdsetup[fd].mods & fdm_fd)) {
1137 open(fdsetup[fd].filename,fdsetup[fd].oflags|O_NOCTTY,0777);
1138 if (fdsetup[fd].copyfd<0)
1139 syscallerror("open file `%s' for fd %d",fdsetup[fd].filename,fd);
1141 fdsetup[fd].catpid= fork();
1142 if (fdsetup[fd].catpid==-1) syscallerror("fork for cat for fd %d",fd);
1143 if (!fdsetup[fd].catpid) {
1144 snprintf(catnamebuf,sizeof(catnamebuf),"cat fd%d",fd);
1145 catnamebuf[sizeof(catnamebuf)-1]= 0;
1146 sig.sa_handler= SIG_DFL;
1147 sigemptyset(&sig.sa_mask);
1149 if (sigaction(SIGPIPE,&sig,0)) {
1150 fprintf(stderr,"userv: %s: reset sigpipe handler for cat: %s",
1151 catnamebuf,strerror(errno));
1154 reading= fdsetup[fd].mods & fdm_read;
1155 catdup(catnamebuf, fdsetup[fd].copyfd, reading ? 0 : 1);
1156 catdup(catnamebuf, fdsetup[fd].pipefd, reading ? 1 : 0);
1157 execl("/bin/cat",catnamebuf,(char*)0);
1158 fprintf(stderr,"userv: %s: cannot exec `cat': %s\n",catnamebuf,strerror(errno));
1161 if (fdsetup[fd].copyfd>2)
1162 if (close(fdsetup[fd].copyfd)) syscallerror("close real fd for %d",fd);
1163 if (close(fdsetup[fd].pipefd)) syscallerror("close pipe fd for %d",fd);
1167 static void server_sendconfirm(void) {
1168 struct event_msg event_mbuf;
1170 blocksignals(SIG_BLOCK);
1171 memset(&event_mbuf,0,sizeof(event_mbuf));
1172 event_mbuf.magic= EVENT_MAGIC;
1173 event_mbuf.type= et_confirm;
1174 xfwrite(&event_mbuf,sizeof(event_mbuf),swfile);
1176 blocksignals(SIG_UNBLOCK);
1179 static int server_awaitcompletion(void) {
1180 struct progress_msg progress_mbuf;
1182 getprogress(&progress_mbuf,srfile);
1183 if (progress_mbuf.type != pt_terminated)
1184 protoerror("progress message during execution phase"
1185 " unexpected type %d",progress_mbuf.type);
1188 return progress_mbuf.data.terminated.status;
1191 static void dispose_remaining_pipes(void) {
1195 blocksignals(SIG_BLOCK);
1196 for (fd=0; fd<fdsetupsize; fd++) {
1197 if (!(fdsetup[fd].catpid!=-1 && (fdsetup[fd].mods & fdm_close))) continue;
1198 if (kill(fdsetup[fd].catpid,SIGKILL)) syscallerror("kill cat for %d",fd);
1199 fdsetup[fd].killed= 1;
1201 blocksignals(SIG_UNBLOCK);
1204 blocksignals(SIG_BLOCK);
1206 fd<fdsetupsize && !(fdsetup[fd].catpid!=-1 && (fdsetup[fd].mods & fdm_wait));
1208 if (fd>=fdsetupsize) break;
1210 r= sigsuspend(&sset);
1211 if (r && errno != EINTR) syscallerror("sigsuspend failed in unexpected way");
1212 blocksignals(SIG_UNBLOCK);
1216 static void NONRETURNING process_exitstatus(int status) {
1217 blocksignals(SIG_BLOCK);
1219 if (systemerror) _exit(255);
1221 if (sigpipeok && signalsexit != se_stdout && WIFSIGNALED(status) &&
1222 WTERMSIG(status)==SIGPIPE && !WCOREDUMP(status)) status= 0;
1224 switch (signalsexit) {
1226 case se_numbernocore:
1227 if (WIFEXITED(status))
1228 _exit(WEXITSTATUS(status));
1229 else if (WIFSIGNALED(status))
1230 _exit(WTERMSIG(status) + (signalsexit==se_number && WCOREDUMP(status) ? 128 : 0));
1233 if (WIFEXITED(status))
1234 _exit(WEXITSTATUS(status)<=127 ? WEXITSTATUS(status) : 127);
1235 else if (WIFSIGNALED(status) && WTERMSIG(status)<=126)
1236 _exit(WTERMSIG(status)+128);
1239 printf("\n%d %d ",(status>>8)&0x0ff,status&0x0ff);
1240 if (WIFEXITED(status))
1241 printf("exited with code %d",WEXITSTATUS(status));
1242 else if (WIFSIGNALED(status))
1243 printf("killed by %s (signal %d)%s",
1244 strsignal(WTERMSIG(status)),WTERMSIG(status),
1245 WCOREDUMP(status) ? ", core dumped " : "");
1247 printf("unknown wait status");
1249 if (ferror(stdout) || fflush(stdout)) syscallerror("write exit status to stdout");
1252 if (WIFEXITED(status))
1253 _exit(WEXITSTATUS(status));
1254 else if (WIFSIGNALED(status))
1259 fprintf(stderr,"userv: unknown wait status %d\n",status);
1263 int main(int argc, char *const *argv) {
1264 int status, socketfd;
1267 # error Do not disable assertions in this security-critical code !
1271 parse_arguments(&argc,&argv);
1274 process_override(argv[0]);
1276 socketfd= server_connect();
1278 server_handshake(socketfd);
1279 server_preparepipes();
1280 server_sendrequest(argc,argv);
1282 priv_permanentlyrevokesuspended();
1284 server_awaitconfirm();
1285 prepare_asynchsignals();
1287 server_sendconfirm();
1288 status= server_awaitcompletion();
1290 dispose_remaining_pipes();
1291 process_exitstatus(status);