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>
78 enum fdmodifiervalues {
92 struct fdmodifierinfo {
100 const char *filename; /* non-null iff this fd has been specified */
101 int copyfd; /* fd to copy, -1 unless mods & fdm_fd */
102 int mods, oflags, pipefd, killed; /* 0,0,-1,0 unless otherwise set */
103 pid_t catpid; /* -1 indicates no cat process */
106 enum signalsexitspecials { se_number=-100, se_numbernocore, se_highbit, se_stdout };
107 enum overridetypes { ot_none, ot_string, ot_file, ot_builtin };
109 struct constkeyvaluepair { const char *key, *value; };
111 /* Variables from command-line arguments */
112 static const char *serviceuser;
113 static uid_t serviceuid;
114 static struct fdsetupstate *fdsetup;
115 static int fdsetupsize;
116 static struct constkeyvaluepair *defvararray;
117 static int defvaravail, defvarused;
118 static unsigned long timeout;
119 static int signalsexit=254;
120 static int sigpipeok, hidecwd;
121 static int overridetype= ot_none;
122 static const char *overridevalue, *spoofuser=0;
124 /* Other state variables */
125 static FILE *srfile, *swfile;
127 static uid_t myuid, spoofuid;
128 static gid_t mygid, spoofgid, *gidarray;
130 static struct opening_msg opening_mbuf;
131 static const char *logname;
133 static size_t cwdbufsize;
135 static int ovused, systemerror;
137 static void blocksignals(int how) {
139 static const char blockerrmsg[]= "userv: failed to [un]block signals: ";
143 sigaddset(&set,SIGCHLD);
144 sigaddset(&set,SIGALRM);
145 if (sigprocmask(how,&set,0)) {
146 str= strerror(errno);
147 write(2,blockerrmsg,sizeof(blockerrmsg)-1);
148 write(2,str,strlen(str));
154 /* Functions which may be called either from signal handlers or from
155 * the main thread. They block signals in case they are on the main
156 * thread, and may only use signal handler objects. None of them
157 * return. If they did they'd have to restore the signal mask.
160 static void NONRETURNPRINTFFORMAT(1,2) miscerror(const char *fmt, ...) {
163 blocksignals(SIG_BLOCK);
165 fprintf(stderr,"userv: failure: ");
166 vfprintf(stderr,fmt,al);
167 fprintf(stderr,"\n");
171 static void NONRETURNPRINTFFORMAT(1,2) syscallerror(const char *fmt, ...) {
176 blocksignals(SIG_BLOCK);
178 fprintf(stderr,"userv: system call failure: ");
179 vfprintf(stderr,fmt,al);
180 fprintf(stderr,": %s\n",strerror(e));
184 static void NONRETURNING protoreaderror(FILE *file, const char *where) {
188 blocksignals(SIG_BLOCK);
190 fprintf(stderr,"userv: failure: read error %s: %s\n",where,strerror(e));
193 fprintf(stderr,"userv: internal failure: EOF from server %s\n",where);
198 static void NONRETURNPRINTFFORMAT(1,2) protoerror(const char *fmt, ...) {
201 blocksignals(SIG_BLOCK);
203 fprintf(stderr,"userv: internal failure: protocol error: ");
204 vfprintf(stderr,fmt,al);
205 fprintf(stderr,"\n");
210 * General-purpose functions; these do nothing special about signals,
211 * except that they can call error-handlers which may block them
212 * to print error messages.
215 static void xfread(void *p, size_t sz, FILE *file) {
217 nr= working_fread(p,sz,file);
218 if (nr != sz) protoreaderror(file,"in data");
221 static void xfwrite(const void *p, size_t sz, FILE *file) {
223 nr= fwrite(p,1,sz,file); if (nr == sz) return;
224 syscallerror("writing to server");
227 static void xfflush(FILE *file) {
228 if (fflush(file)) syscallerror("flush server socket");
231 /* Functions which may be called only from the main thread. These may
232 * use main-thread objects and must block signals before using signal
237 static void priv_suspend(void) { }
238 static void priv_resume(void) { }
239 static void priv_permanentlyrevokesuspended(void) { }
241 static void priv_suspend(void) {
242 if (setreuid(0,myuid) != 0) syscallerror("suspend root setreuid(0,myuid)");
244 static void priv_resume(void) {
245 if (setreuid(myuid,0) != 0) syscallerror("resume root setreuid(myuid,0)");
247 static void priv_permanentlyrevokesuspended(void) {
248 if (setreuid(myuid,myuid) != 0) syscallerror("revoke root setreuid(myuid,myuid)");
249 if (setreuid(myuid,myuid) != 0) syscallerror("rerevoke root setreuid(myuid,myuid)");
251 if (!setreuid(myuid,0)) miscerror("revoked root but setreuid(0,0) succeeded !");
252 if (errno != EPERM) syscallerror("revoked and setreuid(myuid,0) unexpected error");
257 static void checkmagic(unsigned long was, unsigned long should, const char *when) {
259 protoerror("magic number %s was %08lx, expected %08lx",when,was,should);
262 static void getprogress(struct progress_msg *progress_r, FILE *file) {
267 xfread(progress_r,sizeof(struct progress_msg),file);
268 checkmagic(progress_r->magic,PROGRESS_MAGIC,"in progress message");
269 switch (progress_r->type) {
271 blocksignals(SIG_BLOCK);
272 fputs("userv: uservd reports that service failed\n",stderr);
275 blocksignals(SIG_BLOCK);
276 fputs("uservd: ",stderr);
277 if (progress_r->data.errmsg.messagelen>MAX_ERRMSG_STRING)
278 protoerror("stderr message length %d is far too long",
279 progress_r->data.errmsg.messagelen);
280 for (i=0; i<progress_r->data.errmsg.messagelen; i++) {
281 c= working_getc(file);
282 if (c==EOF) protoreaderror(file,"in error message");
283 if (isprint(c)) putc(c,stderr);
284 else fprintf(stderr,"\\x%02x",(unsigned char)c);
287 if (ferror(stderr)) syscallerror("printing error message");
288 xfread(&ul,sizeof(ul),file);
289 checkmagic(ul,PROGRESS_ERRMSG_END_MAGIC,"after error message");
290 blocksignals(SIG_UNBLOCK);
299 * Functions which are called only during setup, before
300 * the signal asynchronicity starts. They can do anything they like.
303 static void *xmalloc(size_t s) {
306 if (!p) syscallerror("malloc (%lu bytes)",(unsigned long)s);
310 static void *xrealloc(void *p, size_t s) {
312 if (!p) syscallerror("realloc (%lu bytes)",(unsigned long)s);
316 static void xfwritestring(const char *s, FILE *file) {
319 assert(l<=MAX_GENERAL_STRING);
320 xfwrite(&l,sizeof(l),file);
321 xfwrite(s,sizeof(*s)*l,file);
324 static void xfwritefds(int modifier, int expected, FILE *file) {
327 for (i=0, fdcount=0; i<fdsetupsize; i++) {
328 if (!(fdsetup[i].filename && (fdsetup[i].mods & modifier)))
330 xfwrite(&i,sizeof(int),file); fdcount++;
332 assert(fdcount == expected);
335 /* Functions which may be called from signal handlers. These
336 * may use signal-handler objects. The main program may only
337 * call them with signals blocked, and they may not use any
338 * main-thread objects.
341 static void disconnect(void) /* DOES return, unlike in daemon */ {
342 struct event_msg event_mbuf;
346 memset(&event_mbuf,0,sizeof(event_mbuf));
347 event_mbuf.magic= EVENT_MAGIC;
348 event_mbuf.type= et_disconnect;
349 r= fwrite(&event_mbuf,1,sizeof(event_mbuf),swfile);
350 if ((r != sizeof(event_mbuf) || fflush(swfile)) && errno != EPIPE)
351 syscallerror("write to server when disconnecting\n");
356 static void sighandler_alrm(int ignored) /* DOES return, unlike in daemon */ {
359 fputs("userv: timeout\n",stderr);
364 static void sighandler_chld(int ignored) /* DOES return, unlike in daemon */ {
365 struct event_msg event_mbuf;
367 int status, fd, r, es;
371 child= wait3(&status,WNOHANG,0);
372 if (child == 0 || (child == -1 && errno == ECHILD)) break;
373 if (child == -1) syscallerror("wait for child process (in sigchld handler)");
374 for (fd=0; fd<fdsetupsize && fdsetup[fd].catpid != child; fd++);
375 if (fd>=fdsetupsize) continue; /* perhaps the caller gave us children */
376 if ((WIFEXITED(status) && WEXITSTATUS(status)==0) ||
377 (WIFSIGNALED(status) && WTERMSIG(status)==SIGPIPE) ||
378 (fdsetup[fd].killed && WIFSIGNALED(status) && WTERMSIG(status)==SIGKILL)) {
379 if (swfile && fdsetup[fd].mods & fdm_read) {
380 memset(&event_mbuf,0,sizeof(event_mbuf));
381 event_mbuf.magic= EVENT_MAGIC;
382 event_mbuf.type= et_closereadfd;
383 event_mbuf.data.closereadfd.fd= fd;
384 r= fwrite(&event_mbuf,1,sizeof(event_mbuf),swfile);
385 if (r != sizeof(event_mbuf) || fflush(swfile))
386 if (errno != EPIPE) syscallerror("inform service of closed read fd");
389 if (WIFEXITED(status))
390 fprintf(stderr,"userv: cat for fd %d exited with error exit status %d\n",
391 fd,WEXITSTATUS(status));
392 else if (WIFSIGNALED(status))
393 if (WCOREDUMP(status))
394 fprintf(stderr,"userv: cat for fd %d dumped core due to signal %s (%d)\n",
395 fd,strsignal(WTERMSIG(status)),WTERMSIG(status));
397 fprintf(stderr,"userv: cat for fd %d terminated by signal %s (%d)\n",
398 fd,strsignal(WTERMSIG(status)),WTERMSIG(status));
400 fprintf(stderr,"userv: cat for fd %d gave unknown wait status %d\n",
404 fdsetup[fd].catpid= -1;
410 * Argument parsing. These functions which are called only during
411 * setup, before the signal asynchronicity starts.
416 typedef void optionfunction(const struct optioninfo*, const char *value, char *key);
421 int values; /* 0: no value; 1: single value; 2: key and value */
425 static void usage(void) {
427 "usage: userv <options> [--] <service-user> <service-name> [<argument> ...]\n"
428 "usage: userv <options> -B|--builtin [--] <builtin-service> [<info-argument> ...]\n"
429 "options: -f|--file <fd>[<fdmodifiers>]=<filename>\n"
430 " -D|--defvar <name>=<value>\n"
431 " -t|--timeout <seconds>\n"
432 " -S|--signals <status>|number|number-nocore|highbit|stdout\n"
433 " -w|--fdwait <fd>=wait|nowait|close\n"
434 " -P|--sigpipe -H|--hidecwd -h|--help --copyright\n"
435 " --override <configuration-data> } available only\n"
436 " --override-file <filename> } to root\n"
437 " --spoof-user <username> } or same user\n"
438 "fdmodifiers: read write overwrite trunc[ate]\n"
439 "(separate with commas) append sync excl[usive] creat[e] fd\n\n"
440 "userv and uservd version " VERSION VEREXT "; copyright (C)1996-1997 Ian Jackson.\n"
441 "there is NO WARRANTY; type `userv --copyright' for details.\n",
443 syscallerror("write usage to stderr");
446 static void NONRETURNPRINTFFORMAT(1,2) usageerror(const char *fmt, ...) {
449 fputs("userv: ",stderr);
450 vfprintf(stderr,fmt,al);
451 fputs("\n\n",stderr);
456 static const struct fdmodifierinfo fdmodifierinfos[]= {
460 { "write", fdm_write,
463 { "overwrite", fdm_write|fdm_create|fdm_truncate,
464 fdm_read|fdm_fd|fdm_exclusive,
465 O_WRONLY|O_CREAT|O_TRUNC },
466 { "create", fdm_write|fdm_create,
469 { "creat", fdm_write|fdm_create,
472 { "exclusive", fdm_write|fdm_create|fdm_exclusive,
473 fdm_read|fdm_fd|fdm_truncate,
474 O_WRONLY|O_CREAT|O_EXCL },
475 { "excl", fdm_write|fdm_create|fdm_exclusive,
476 fdm_read|fdm_fd|fdm_truncate,
477 O_WRONLY|O_CREAT|O_EXCL },
478 { "truncate", fdm_write|fdm_truncate,
479 fdm_read|fdm_fd|fdm_exclusive,
480 O_WRONLY|O_CREAT|O_EXCL },
481 { "trunc", fdm_write|fdm_truncate,
482 fdm_read|fdm_fd|fdm_exclusive,
483 O_WRONLY|O_CREAT|O_EXCL },
484 { "append", fdm_write|fdm_append,
486 O_WRONLY|O_CREAT|O_APPEND },
487 { "sync", fdm_write|fdm_sync,
489 O_WRONLY|O_CREAT|O_SYNC },
491 fdm_nowait|fdm_close,
493 { "nowait", fdm_nowait,
496 { "close", fdm_close,
500 fdm_create|fdm_exclusive|fdm_truncate|fdm_append|fdm_sync,
505 static void addfdmodifier(int fd, const char *key) {
506 const struct fdmodifierinfo *fdmip;
509 for (fdmip= fdmodifierinfos; fdmip->string && strcmp(fdmip->string,key); fdmip++);
510 if (!fdmip->string) usageerror("unknown fdmodifer `%s' for fd %d",key,fd);
511 if (fdmip->conflicts & fdsetup[fd].mods)
512 usageerror("fdmodifier `%s' conflicts with another for fd %d",key,fd);
513 fdsetup[fd].mods |= fdmip->implies;
514 fdsetup[fd].oflags |= fdmip->oflags;
517 static int fdstdnumber(const char *string) {
518 if (!strcmp(string,"stdin")) return 0;
519 else if (!strcmp(string,"stdout")) return 1;
520 else if (!strcmp(string,"stderr")) return 2;
524 static void of_file(const struct optioninfo *oip, const char *value, char *key) {
525 unsigned long fd, copyfd;
530 fd= strtoul(key,&delim,10);
532 delim= strchr(key,',');
533 if (delim) *delim++= 0;
534 fd= fdstdnumber(key);
535 if (fd<0) usageerror("first part of argument to -f or --file must be numeric "
536 "file descriptor or `stdin', `stdout' or `stderr' - `%s' "
537 "is not recognized",key);
539 if (fd > MAX_ALLOW_FD)
540 usageerror("file descriptor specified (%lu) is larger than maximum allowed (%d)",
542 if (fd >= fdsetupsize) {
543 oldarraysize= fdsetupsize;
544 fdsetupsize+=2; fdsetupsize<<=1;
545 fdsetup= xrealloc(fdsetup,sizeof(struct fdsetupstate)*fdsetupsize);
546 while (oldarraysize < fdsetupsize) {
547 fdsetup[oldarraysize].filename= 0;
548 fdsetup[oldarraysize].pipefd= -1;
549 fdsetup[oldarraysize].copyfd= -1;
550 fdsetup[oldarraysize].mods= 0;
551 fdsetup[oldarraysize].oflags= 0;
552 fdsetup[oldarraysize].catpid= -1;
553 fdsetup[oldarraysize].killed= 0;
554 fdsetup[oldarraysize].filename= 0;
558 fdsetup[fd].filename= value;
559 fdsetup[fd].oflags= 0;
561 fdsetup[fd].copyfd= -1;
562 while (delim && *delim) {
564 delim= strchr(key,',');
565 if (delim) *delim++= 0;
566 addfdmodifier(fd,key);
568 if (!(fdsetup[fd].mods & (fdm_read|fdm_write))) {
570 addfdmodifier(fd,"read");
571 } else if (fdsetup[fd].mods & fdm_fd) {
572 addfdmodifier(fd,"write");
574 addfdmodifier(fd,"overwrite");
577 if (fdsetup[fd].mods & fdm_fd) {
578 copyfd= fdstdnumber(value);
580 copyfd= strtoul(value,&delim,0);
582 usageerror("value part of argument to --file with fd modifier must be "
583 "numeric or fd name - `%s' is not recognised",value);
584 else if (copyfd > MAX_ALLOW_FD)
585 usageerror("file descriptor %lu named as target of file descriptor redirection"
586 " (for file descriptor %lu) is larger than maximum allowed (%d)",
587 copyfd,fd,MAX_ALLOW_FD);
589 r= fstat(copyfd,&stab);
591 if (oip) syscallerror("check filedescriptor %lu (named as target of file "
592 "descriptor redirection for %lu)",copyfd,fd);
593 else syscallerror("check basic filedescriptor %lu at program start",copyfd);
595 fdsetup[fd].copyfd= copyfd;
599 static void of_fdwait(const struct optioninfo *oip, const char *value, char *key) {
600 const struct fdmodifierinfo *fdmip;
605 fd= fdstdnumber(key);
607 ul= strtoul(key,&delim,0);
608 if (*delim) usageerror("first part of argument to --fdwait must be "
609 "numeric or fd name - `%s' is not recognised",key);
610 if (ul>MAX_ALLOW_FD) usageerror("first part of argument to --fdwait is too large");
613 if (fd >= fdsetupsize || !fdsetup[fd].filename)
614 usageerror("file descriptor %d specified in --fdwait option is not open",fd);
615 for (fdmip= fdmodifierinfos; fdmip->string && strcmp(fdmip->string,value); fdmip++);
616 if (!fdmip->string || !(fdmip->implies & (fdm_wait|fdm_nowait|fdm_close)))
617 usageerror("value for --fdwait must be `wait', `nowait' or `close', not `%s'",value);
618 fdsetup[fd].mods &= ~(fdm_wait|fdm_nowait|fdm_close);
619 fdsetup[fd].mods |= fdmip->implies;
622 static void of_defvar(const struct optioninfo *oip, const char *value, char *key) {
626 usageerror("empty string not allowed as variable name");
627 if (strlen(key)>MAX_GENERAL_STRING)
628 usageerror("variable name `%s' is far too long",key);
629 if (strlen(value)>MAX_GENERAL_STRING)
630 usageerror("variable `%s' has value `%s' which is far too long",key,value);
631 for (i=0; i<defvarused && strcmp(defvararray[i].key,key); i++);
632 if (defvarused >= MAX_ARGSDEFVAR) usageerror("far too many --defvar or -D options");
633 if (i>=defvaravail) {
634 defvaravail+=10; defvaravail<<=1;
635 defvararray= xrealloc(defvararray,sizeof(struct constkeyvaluepair)*defvaravail);
637 if (i==defvarused) defvarused++;
638 defvararray[i].key= key;
639 defvararray[i].value= value;
642 static void of_timeout(const struct optioninfo *oip, const char *value, char *key) {
646 ul= strtoul(value,&endp,0);
647 if (*endp) usageerror("timeout value `%s' must be a plain decimal string",value);
648 if (ul>INT_MAX) usageerror("timeout value %lu too large",ul);
652 static void of_signals(const struct optioninfo *oip, const char *value, char *key) {
653 unsigned long numvalue;
656 numvalue= strtoul(value,&endp,0);
658 if (!strcmp(value,"number")) signalsexit= se_number;
659 else if (!strcmp(value,"number-nocore")) signalsexit= se_numbernocore;
660 else if (!strcmp(value,"highbit")) signalsexit= se_highbit;
661 else if (!strcmp(value,"stdout")) signalsexit= se_stdout;
662 else usageerror("value `%s' for --signals not understood",value);
664 if (numvalue<0 || numvalue>255)
665 usageerror("value %lu for --signals not 0...255",numvalue);
666 signalsexit= numvalue;
670 static void of_sigpipe(const struct optioninfo *oip, const char *value, char *key) {
674 static void of_hidecwd(const struct optioninfo *oip, const char *value, char *key) {
678 static void of_help(const struct optioninfo *oip, const char *value, char *key) {
683 static void of_copyright(const struct optioninfo *oip, const char *value, char *key) {
685 " userv - user service daemon and client; copyright (C)1996-1997 Ian Jackson\n\n"
686 " This is free software; you can redistribute it and/or modify it under the\n"
687 " terms of the GNU General Public License as published by the Free Software\n"
688 " Foundation; either version 2 of the License, or (at your option) any\n"
689 " later version.\n\n"
690 " This program is distributed in the hope that it will be useful, but\n"
691 " WITHOUT ANY WARRANTY; without even the implied warranty of\n"
692 " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\n"
693 " Public License for more details.\n\n"
694 " You should have received a copy of the GNU General Public License along\n"
695 " with userv; if not, write to Ian Jackson <ian@chiark.greenend.org.uk> or\n"
696 " to the Free Software Foundation, 59 Temple Place - Suite 330, Boston,\n"
697 " MA 02111-1307, USA.\n",
698 stdout) < 0) syscallerror("write usage to stderr");
702 static void of_builtin(const struct optioninfo *oip, const char *value, char *key) {
703 overridetype= ot_builtin;
706 static void of_override(const struct optioninfo *oip, const char *value, char *key) {
707 overridetype= ot_string;
708 overridevalue= value;
711 static void of_overridefile(const struct optioninfo *oip,
712 const char *value, char *key) {
713 overridetype= ot_file;
714 overridevalue= value;
717 static void of_spoofuser(const struct optioninfo *oip,
718 const char *value, char *key) {
722 const struct optioninfo optioninfos[]= {
723 { 'f', "file", 2, of_file },
724 { 'w', "fdwait", 2, of_fdwait },
725 { 'D', "defvar", 2, of_defvar },
726 { 't', "timeout", 1, of_timeout },
727 { 'S', "signals", 1, of_signals },
728 { 'P', "sigpipe", 0, of_sigpipe },
729 { 'H', "hidecwd", 0, of_hidecwd },
730 { 'B', "builtin", 0, of_builtin },
731 { 'h', "help", 0, of_help },
732 { 0, "copyright", 0, of_copyright },
733 { 0, "override", 1, of_override },
734 { 0, "override-file", 1, of_overridefile },
735 { 0, "spoof-user", 1, of_spoofuser },
739 static void callvalueoption(const struct optioninfo *oip, char *arg) {
741 if (oip->values == 2) {
742 equals= strchr(arg,'=');
745 usageerror("option --%s (-%c) passed argument `%s' with no `='",
746 oip->full,oip->abbrev,arg);
748 usageerror("option --%s passed argument `%s' with no `='",
752 (oip->fn)(oip,equals,arg);
754 (oip->fn)(oip,arg,0);
759 * Main thread main processing functions - in order of execution.
762 static void security_init(void) {
763 /* May not open any file descriptors. */
765 mypid= getpid(); if (mypid == (pid_t)-1) syscallerror("getpid");
766 myuid= getuid(); if (myuid == (uid_t)-1) syscallerror("getuid");
767 mygid= getgid(); if (mygid == (gid_t)-1) syscallerror("getgid");
768 ngids= getgroups(0,0); if (ngids == (gid_t)-1) syscallerror("getgroups(0,0)");
769 gidarray= xmalloc(sizeof(gid_t)*ngids);
770 if (getgroups(ngids,gidarray) != ngids) syscallerror("getgroups(ngids,)");
774 if (ngids > MAX_GIDS) miscerror("caller is in far too many gids");
777 static void parse_arguments(int *argcp, char *const **argvp) {
778 static char fd0key[]= "stdin,fd,read";
779 static char fd1key[]= "stdout,fd,write";
780 static char fd2key[]= "stderr,fd,write";
784 const struct optioninfo *oip;
788 of_file(0,"stdin",fd0key);
789 of_file(0,"stdout",fd1key);
790 of_file(0,"stderr",fd2key);
792 for (argpp= *argvp+1;
793 (argp= *argpp) && *argp == '-' && argp[1];
795 if (!*++argp) usageerror("unknown option/argument `%s'",*argpp);
796 if (*argp == '-') { /* Two hyphens */
797 if (!*++argp) { argpp++; break; /* End of options. */ }
798 for (oip= optioninfos; oip->full && strcmp(oip->full,argp); oip++);
799 if (!oip->full) usageerror("unknown long option `%s'",*argpp);
801 if (!argpp[1]) usageerror("long option `%s' needs a value",*argpp);
802 callvalueoption(oip,*++argpp);
807 for (; *argp; argp++) {
808 for (oip= optioninfos; oip->full && oip->abbrev != *argp; oip++);
809 if (!oip->full) usageerror("unknown short option `-%c' in argument `%s'",
815 if (!argpp[1]) usageerror("short option `-%c' in argument `%s' needs"
816 " a value",*argp,*argpp);
819 callvalueoption(oip,argp);
820 break; /* No more options in this argument, go on to the next one. */
827 if (overridetype == ot_builtin) {
830 if (!*argpp) usageerror("no service user given after options");
831 serviceuser= *argpp++;
833 if (!*argpp) usageerror(overridetype == ot_builtin ?
834 "no service name given after options and service user" :
835 "no builtin service given after options");
837 *argcp-= (argpp-*argvp);
840 if (*argcp > MAX_ARGSDEFVAR) usageerror("far too many arguments");
842 for (fd=0; fd<fdsetupsize; fd++) {
843 if (!fdsetup[fd].filename) continue;
844 if (fdsetup[fd].mods & (fdm_wait|fdm_nowait|fdm_close)) continue;
845 assert(fdsetup[fd].mods & (fdm_read|fdm_write));
846 fdsetup[fd].mods |= (fdsetup[fd].mods & fdm_read) ? fdm_close : fdm_wait;
850 static void determine_users(void) {
858 logname= getenv("LOGNAME");
859 if (!logname) logname= getenv("USER");
861 pw= getpwnam(logname);
862 if (!pw || pw->pw_uid != myuid) logname= 0;
865 pw= getpwuid(myuid); if (!pw) miscerror("cannot determine your login name");
866 logname= pw->pw_name;
869 if (!strcmp(serviceuser,"-")) serviceuser= logname;
870 pw= getpwnam(serviceuser);
871 if (!pw) miscerror("requested service user `%s' is not a user",serviceuser);
872 serviceuid= pw->pw_uid;
874 if ((overridetype != ot_none || spoofuser) && myuid != 0 && myuid != serviceuid)
875 miscerror("--override and --spoof options only available to root or to"
876 " the user who will be providing the service");
880 pw= getpwnam(logname);
881 if (!pw) miscerror("spoofed login name `%s' is not valid",logname);
882 spoofuid= pw->pw_uid;
883 spoofgid= pw->pw_gid;
884 ngidssize= ngids; ngids= 0;
887 gidarray= xrealloc(gidarray,sizeof(gid_t)*ngidssize);
889 gidarray[ngids++]= spoofgid;
890 while ((gr= getgrent())) { /* ouch! getgrent has no error behaviour! */
891 for (mem= gr->gr_mem; *mem && strcmp(*mem,logname); mem++);
893 if (ngids>=ngidssize) {
894 if (ngids>=MAX_GIDS) miscerror("spoofed user is member of too many groups");
895 ngidssize= (ngids+5)<<1;
896 gidarray= xrealloc(gidarray,sizeof(gid_t)*ngidssize);
898 gidarray[ngids++]= gr->gr_gid;
903 static void determine_cwd(void) {
904 cwdbufsize= 0; cwdbuf= 0;
909 if (cwdbufsize > MAX_GENERAL_STRING) { cwdbufsize= 0; free(cwdbuf); break; }
910 cwdbufsize <<= 1; cwdbufsize+= 100;
911 cwdbuf= xrealloc(cwdbuf,cwdbufsize);
912 cwdbuf[cwdbufsize-1]= 0;
913 if (getcwd(cwdbuf,cwdbufsize-1)) { cwdbufsize= strlen(cwdbuf); break; }
914 if (errno != ERANGE) { cwdbufsize= 0; free(cwdbuf); break; }
918 static void process_override(const char *servicename) {
922 switch (overridetype) {
928 l= strlen(servicename);
929 if (l >= MAX_OVERRIDE_LEN-20)
930 miscerror("builtin service string is too long (%d, max is %d)",
931 l,MAX_OVERRIDE_LEN-21);
934 snprintf(ovbuf,l,"execute-builtin %s\n",servicename);
935 ovused= strlen(ovbuf);
938 l= strlen(overridevalue);
939 if (l >= MAX_OVERRIDE_LEN)
940 miscerror("override string is too long (%d, max is %d)",l,MAX_OVERRIDE_LEN-1);
942 snprintf(ovbuf,l+2,"%s\n",overridevalue);
946 ovfile= fopen(overridevalue,"r");
947 if (!ovfile) syscallerror("open overriding configuration file `%s'",overridevalue);
948 ovbuf= 0; ovavail= ovused= 0;
949 while ((c= getc(ovfile)) != EOF) {
950 if (!c) miscerror("overriding config file `%s' contains null(s)",overridevalue);
951 if (ovused >= MAX_OVERRIDE_LEN)
952 miscerror("override file is too long (max is %d)",MAX_OVERRIDE_LEN);
953 if (ovused >= ovavail) {
954 ovavail+=80; ovavail<<=2; ovbuf= xrealloc(ovbuf,ovavail);
958 if (ferror(ovfile) || fclose(ovfile))
959 syscallerror("read overriding configuration file `%s'",overridevalue);
960 ovbuf= xrealloc(ovbuf,ovused+1);
968 static int server_connect(void) {
969 struct sockaddr_un ssockname;
971 struct sigaction sig;
975 sigaddset(&sset,SIGCHLD);
976 sigaddset(&sset,SIGALRM);
977 sigaddset(&sset,SIGPIPE);
978 if (sigprocmask(SIG_UNBLOCK,&sset,0)) syscallerror("preliminarily unblock signals");
980 sig.sa_handler= SIG_IGN;
981 sigemptyset(&sig.sa_mask);
983 if (sigaction(SIGPIPE,&sig,0)) syscallerror("ignore sigpipe");
985 sfd= socket(AF_UNIX,SOCK_STREAM,0);
986 if (!sfd) syscallerror("create client socket");
988 assert(sizeof(ssockname.sun_path) > sizeof(RENDEZVOUSPATH));
989 ssockname.sun_family= AF_UNIX;
990 strcpy(ssockname.sun_path,RENDEZVOUSPATH);
992 while (connect(sfd,(struct sockaddr*)&ssockname,sizeof(ssockname))) {
993 if (errno == ECONNREFUSED || errno == ENOENT)
994 syscallerror("uservd daemon is not running - service not available");
996 syscallerror("unable to connect to uservd daemon: %m");
1002 static void server_handshake(int sfd) {
1003 srfile= fdopen(sfd,"r");
1004 if (!srfile) syscallerror("turn socket fd into FILE* for read");
1005 if (setvbuf(srfile,0,_IOFBF,BUFSIZ)) syscallerror("set buffering on socket reads");
1007 swfile= fdopen(sfd,"w");
1008 if (!swfile) syscallerror("turn socket fd into FILE* for write");
1009 if (setvbuf(swfile,0,_IOFBF,BUFSIZ)) syscallerror("set buffering on socket writes");
1011 xfread(&opening_mbuf,sizeof(opening_mbuf),srfile);
1012 checkmagic(opening_mbuf.magic,OPENING_MAGIC,"in opening message");
1013 if (memcmp(protocolchecksumversion,opening_mbuf.protocolchecksumversion,PCSUMSIZE))
1014 protoerror("protocol version checksum mismatch - server not same as client");
1017 static void server_preparepipes(void) {
1018 char pipepathbuf[PIPEPATHMAXLEN+2];
1021 for (fd=0; fd<fdsetupsize; fd++) {
1022 if (!fdsetup[fd].filename) continue;
1023 pipepathbuf[PIPEPATHMAXLEN]= 0;
1024 sprintf(pipepathbuf, PIPEPATHFORMAT,
1025 (unsigned long)mypid, (unsigned long)opening_mbuf.serverpid, fd);
1026 assert(!pipepathbuf[PIPEPATHMAXLEN]);
1028 if (unlink(pipepathbuf) && errno != ENOENT)
1029 syscallerror("remove any old pipe `%s'",pipepathbuf);
1030 if (mkfifo(pipepathbuf,0600)) /* permissions are irrelevant */
1031 syscallerror("create pipe `%s'",pipepathbuf);
1032 tempfd= open(pipepathbuf,O_RDWR);
1033 if (tempfd<0) syscallerror("prelim open pipe `%s' for read+write",pipepathbuf);
1034 assert(fdsetup[fd].mods & (fdm_read|fdm_write));
1036 open(pipepathbuf, (fdsetup[fd].mods & fdm_read) ? O_WRONLY : O_RDONLY);
1037 if (fdsetup[fd].pipefd<0) syscallerror("real open pipe `%s'",pipepathbuf);
1038 if (close(tempfd)) syscallerror("close prelim fd onto pipe `%s'",pipepathbuf);
1043 static void server_sendrequest(int argc, char *const *argv) {
1044 struct request_msg request_mbuf;
1048 memset(&request_mbuf,0,sizeof(request_mbuf));
1049 request_mbuf.magic= REQUEST_MAGIC;
1050 request_mbuf.clientpid= getpid();
1051 request_mbuf.serviceuserlen= strlen(serviceuser);
1052 request_mbuf.servicelen= strlen(argv[0]);
1053 request_mbuf.lognamelen= strlen(logname);
1054 request_mbuf.spoofed= spoofuser ? 1 : 0;
1055 request_mbuf.cwdlen= cwdbufsize;
1056 request_mbuf.callinguid= spoofuid;
1057 request_mbuf.ngids= ngids+1;
1058 request_mbuf.nreadfds= 0;
1059 request_mbuf.nwritefds= 0;
1060 for (fd=0; fd<fdsetupsize; fd++) {
1061 if (!fdsetup[fd].filename) continue;
1062 assert(fdsetup[fd].mods & (fdm_write|fdm_read));
1063 if (fdsetup[fd].mods & fdm_write) request_mbuf.nwritefds++;
1064 else request_mbuf.nreadfds++;
1066 request_mbuf.nargs= argc-1;
1067 request_mbuf.nvars= defvarused;
1068 request_mbuf.overridelen= ovused;
1069 xfwrite(&request_mbuf,sizeof(request_mbuf),swfile);
1070 xfwrite(serviceuser,sizeof(*serviceuser)*request_mbuf.serviceuserlen,swfile);
1071 xfwrite(argv[0],sizeof(*argv[0])*request_mbuf.servicelen,swfile);
1072 xfwrite(logname,sizeof(*logname)*request_mbuf.lognamelen,swfile);
1073 xfwrite(cwdbuf,sizeof(*cwdbuf)*request_mbuf.cwdlen,swfile);
1074 if (ovused>=0) xfwrite(ovbuf,sizeof(*ovbuf)*ovused,swfile);
1075 xfwrite(&spoofgid,sizeof(gid_t),swfile);
1076 xfwrite(gidarray,sizeof(gid_t)*ngids,swfile);
1077 xfwritefds(fdm_read,request_mbuf.nreadfds,swfile);
1078 xfwritefds(fdm_write,request_mbuf.nwritefds,swfile);
1079 for (i=1; i<argc; i++)
1080 xfwritestring(argv[i],swfile);
1081 for (i=0; i<defvarused; i++) {
1082 xfwritestring(defvararray[i].key,swfile);
1083 xfwritestring(defvararray[i].value,swfile);
1085 ul= REQUEST_END_MAGIC; xfwrite(&ul,sizeof(ul),swfile);
1089 static void server_awaitconfirm(void) {
1090 struct progress_msg progress_mbuf;
1092 getprogress(&progress_mbuf,srfile);
1093 if (progress_mbuf.type != pt_ok)
1094 protoerror("progress message during configuration phase"
1095 " unexpected type %d",progress_mbuf.type);
1098 static void prepare_asynchsignals(void) {
1099 static char stderrbuf[BUFSIZ], stdoutbuf[BUFSIZ];
1101 struct sigaction sig;
1103 if (setvbuf(stderr,stderrbuf,_IOLBF,sizeof(stderrbuf)))
1104 syscallerror("set buffering on stderr");
1105 if (setvbuf(stdout,stdoutbuf,_IOFBF,sizeof(stdoutbuf)))
1106 syscallerror("set buffering on stdout");
1108 sig.sa_handler= sighandler_chld;
1109 sigemptyset(&sig.sa_mask);
1110 sigaddset(&sig.sa_mask,SIGCHLD);
1111 sigaddset(&sig.sa_mask,SIGALRM);
1113 if (sigaction(SIGCHLD,&sig,0)) syscallerror("set up sigchld handler");
1115 sig.sa_handler= sighandler_alrm;
1116 if (sigaction(SIGALRM,&sig,0)) syscallerror("set up sigalrm handler");
1118 if (!timeout) return;
1119 if (alarm(timeout)<0) syscallerror("set up timeout alarm");
1122 static void catdup(const char *which, int from, int to) {
1123 if (dup2(from,to)<0) {
1124 blocksignals(SIG_BLOCK);
1125 fprintf(stderr,"userv: %s: cannot dup for %s: %s\n",which,
1126 to?"stdout":"stdin", strerror(errno));
1131 static void connect_pipes(void) {
1132 struct sigaction sig;
1133 char catnamebuf[sizeof(int)*3+30];
1137 for (fd=0; fd<fdsetupsize; fd++) {
1138 if (!fdsetup[fd].filename) continue;
1139 if (!(fdsetup[fd].mods & fdm_fd)) {
1141 open(fdsetup[fd].filename,fdsetup[fd].oflags|O_NOCTTY,0777);
1142 if (fdsetup[fd].copyfd<0)
1143 syscallerror("open file `%s' for fd %d",fdsetup[fd].filename,fd);
1145 blocksignals(SIG_BLOCK);
1147 fdsetup[fd].catpid= child;
1148 blocksignals(SIG_UNBLOCK);
1149 if (child==-1) syscallerror("fork for cat for fd %d",fd);
1151 snprintf(catnamebuf,sizeof(catnamebuf),"cat fd%d",fd);
1152 catnamebuf[sizeof(catnamebuf)-1]= 0;
1153 sig.sa_handler= SIG_DFL;
1154 sigemptyset(&sig.sa_mask);
1156 if (sigaction(SIGPIPE,&sig,0)) {
1157 fprintf(stderr,"userv: %s: reset sigpipe handler for cat: %s",
1158 catnamebuf,strerror(errno));
1161 reading= fdsetup[fd].mods & fdm_read;
1162 catdup(catnamebuf, fdsetup[fd].copyfd, reading ? 0 : 1);
1163 catdup(catnamebuf, fdsetup[fd].pipefd, reading ? 1 : 0);
1164 execl("/bin/cat",catnamebuf,(char*)0);
1165 fprintf(stderr,"userv: %s: cannot exec `cat': %s\n",catnamebuf,strerror(errno));
1168 if (fdsetup[fd].copyfd>2)
1169 if (close(fdsetup[fd].copyfd)) syscallerror("close real fd for %d",fd);
1170 if (close(fdsetup[fd].pipefd)) syscallerror("close pipe fd for %d",fd);
1174 static void server_sendconfirm(void) {
1175 struct event_msg event_mbuf;
1177 blocksignals(SIG_BLOCK);
1178 memset(&event_mbuf,0,sizeof(event_mbuf));
1179 event_mbuf.magic= EVENT_MAGIC;
1180 event_mbuf.type= et_confirm;
1181 xfwrite(&event_mbuf,sizeof(event_mbuf),swfile);
1183 blocksignals(SIG_UNBLOCK);
1186 static int server_awaitcompletion(void) {
1187 struct progress_msg progress_mbuf;
1189 getprogress(&progress_mbuf,srfile);
1190 if (progress_mbuf.type != pt_terminated)
1191 protoerror("progress message during execution phase"
1192 " unexpected type %d",progress_mbuf.type);
1195 return progress_mbuf.data.terminated.status;
1198 static void dispose_remaining_pipes(void) {
1202 blocksignals(SIG_BLOCK);
1203 for (fd=0; fd<fdsetupsize; fd++) {
1204 if (!(fdsetup[fd].catpid!=-1 && (fdsetup[fd].mods & fdm_close))) continue;
1205 if (kill(fdsetup[fd].catpid,SIGKILL)) syscallerror("kill cat for %d",fd);
1206 fdsetup[fd].killed= 1;
1208 blocksignals(SIG_UNBLOCK);
1211 blocksignals(SIG_BLOCK);
1213 fd<fdsetupsize && !(fdsetup[fd].catpid!=-1 && (fdsetup[fd].mods & fdm_wait));
1215 if (fd>=fdsetupsize) break;
1217 r= sigsuspend(&sset);
1218 if (r && errno != EINTR) syscallerror("sigsuspend failed in unexpected way");
1219 blocksignals(SIG_UNBLOCK);
1223 static void NONRETURNING process_exitstatus(int status) {
1224 blocksignals(SIG_BLOCK);
1226 if (systemerror) _exit(255);
1228 if (sigpipeok && signalsexit != se_stdout && WIFSIGNALED(status) &&
1229 WTERMSIG(status)==SIGPIPE && !WCOREDUMP(status)) status= 0;
1231 switch (signalsexit) {
1233 case se_numbernocore:
1234 if (WIFEXITED(status))
1235 _exit(WEXITSTATUS(status));
1236 else if (WIFSIGNALED(status))
1237 _exit(WTERMSIG(status) + (signalsexit==se_number && WCOREDUMP(status) ? 128 : 0));
1240 if (WIFEXITED(status))
1241 _exit(WEXITSTATUS(status)<=127 ? WEXITSTATUS(status) : 127);
1242 else if (WIFSIGNALED(status) && WTERMSIG(status)<=126)
1243 _exit(WTERMSIG(status)+128);
1246 printf("\n%d %d ",(status>>8)&0x0ff,status&0x0ff);
1247 if (WIFEXITED(status))
1248 printf("exited with code %d",WEXITSTATUS(status));
1249 else if (WIFSIGNALED(status))
1250 printf("killed by %s (signal %d)%s",
1251 strsignal(WTERMSIG(status)),WTERMSIG(status),
1252 WCOREDUMP(status) ? ", core dumped " : "");
1254 printf("unknown wait status");
1256 if (ferror(stdout) || fflush(stdout)) syscallerror("write exit status to stdout");
1259 if (WIFEXITED(status))
1260 _exit(WEXITSTATUS(status));
1261 else if (WIFSIGNALED(status))
1266 fprintf(stderr,"userv: unknown wait status %d\n",status);
1270 int main(int argc, char *const *argv) {
1271 int status, socketfd;
1274 # error Do not disable assertions in this security-critical code !
1278 parse_arguments(&argc,&argv);
1281 process_override(argv[0]);
1283 socketfd= server_connect();
1285 server_handshake(socketfd);
1286 server_preparepipes();
1287 server_sendrequest(argc,argv);
1289 priv_permanentlyrevokesuspended();
1291 server_awaitconfirm();
1292 prepare_asynchsignals();
1294 server_sendconfirm();
1295 status= server_awaitcompletion();
1297 dispose_remaining_pipes();
1298 process_exitstatus(status);