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 r= fwrite(&event_mbuf,1,sizeof(event_mbuf),swfile);
382 if (r != sizeof(event_mbuf) || fflush(swfile))
383 if (errno != EPIPE) syscallerror("inform service of closed read fd");
386 if (WIFEXITED(status))
387 fprintf(stderr,"userv: cat for fd %d exited with error exit status %d\n",
388 fd,WEXITSTATUS(status));
389 else if (WIFSIGNALED(status))
390 if (WCOREDUMP(status))
391 fprintf(stderr,"userv: cat for fd %d dumped core due to signal %s (%d)\n",
392 fd,strsignal(WTERMSIG(status)),WTERMSIG(status));
394 fprintf(stderr,"userv: cat for fd %d terminated by signal %s (%d)\n",
395 fd,strsignal(WTERMSIG(status)),WTERMSIG(status));
397 fprintf(stderr,"userv: cat for fd %d gave unknown wait status %d\n",
401 fdsetup[fd].catpid= -1;
407 * Argument parsing. These functions which are called only during
408 * setup, before the signal asynchronicity starts.
413 typedef void optionfunction(const struct optioninfo*, const char *value, char *key);
418 int values; /* 0: no value; 1: single value; 2: key and value */
422 static void usage(void) {
424 "usage: userv <options> [--] <service-user> <service-name> [<argument> ...]\n"
425 "usage: userv <options> -B|--builtin [--] <builtin-service> [<info-argument> ...]\n"
426 "options: -f|--file <fd>[<fdmodifiers>]=<filename>\n"
427 " -D|--defvar <name>=<value>\n"
428 " -t|--timeout <seconds>\n"
429 " -S|--signals <status>|number|number-nocore|highbit|stdout\n"
430 " -w|--fdwait <fd>=wait|nowait|close\n"
431 " -P|--sigpipe -H|--hidecwd -h|--help --copyright\n"
432 " --override <configuration-data> } available only\n"
433 " --override-file <filename> } to root\n"
434 " --spoof-user <username> } or same user\n"
435 "fdmodifiers: read write overwrite trunc[ate]\n"
436 "(separate with commas) append sync excl[usive] creat[e] fd\n\n"
437 "userv and uservd version " VERSION "; copyright (C)1996-1997 Ian Jackson.\n"
438 "there is NO WARRANTY; type `userv --copyright' for details.\n",
440 syscallerror("write usage to stderr");
443 static void NONRETURNPRINTFFORMAT(1,2) usageerror(const char *fmt, ...) {
446 fputs("userv: ",stderr);
447 vfprintf(stderr,fmt,al);
448 fputs("\n\n",stderr);
453 static const struct fdmodifierinfo fdmodifierinfos[]= {
457 { "write", fdm_write,
460 { "overwrite", fdm_write|fdm_create|fdm_truncate,
461 fdm_read|fdm_fd|fdm_exclusive,
462 O_WRONLY|O_CREAT|O_TRUNC },
463 { "create", fdm_write|fdm_create,
466 { "creat", fdm_write|fdm_create,
469 { "exclusive", fdm_write|fdm_create|fdm_exclusive,
470 fdm_read|fdm_fd|fdm_truncate,
471 O_WRONLY|O_CREAT|O_EXCL },
472 { "excl", fdm_write|fdm_create|fdm_exclusive,
473 fdm_read|fdm_fd|fdm_truncate,
474 O_WRONLY|O_CREAT|O_EXCL },
475 { "truncate", fdm_write|fdm_truncate,
476 fdm_read|fdm_fd|fdm_exclusive,
477 O_WRONLY|O_CREAT|O_EXCL },
478 { "trunc", fdm_write|fdm_truncate,
479 fdm_read|fdm_fd|fdm_exclusive,
480 O_WRONLY|O_CREAT|O_EXCL },
481 { "append", fdm_write|fdm_append,
483 O_WRONLY|O_CREAT|O_APPEND },
484 { "sync", fdm_write|fdm_sync,
486 O_WRONLY|O_CREAT|O_SYNC },
488 fdm_nowait|fdm_close,
490 { "nowait", fdm_nowait,
493 { "close", fdm_close,
497 fdm_create|fdm_exclusive|fdm_truncate|fdm_append|fdm_sync,
502 static void addfdmodifier(int fd, const char *key) {
503 const struct fdmodifierinfo *fdmip;
506 for (fdmip= fdmodifierinfos; fdmip->string && strcmp(fdmip->string,key); fdmip++);
507 if (!fdmip->string) usageerror("unknown fdmodifer `%s' for fd %d",key,fd);
508 if (fdmip->conflicts & fdsetup[fd].mods)
509 usageerror("fdmodifier `%s' conflicts with another for fd %d",key,fd);
510 fdsetup[fd].mods |= fdmip->implies;
511 fdsetup[fd].oflags |= fdmip->oflags;
514 static int fdstdnumber(const char *string) {
515 if (!strcmp(string,"stdin")) return 0;
516 else if (!strcmp(string,"stdout")) return 1;
517 else if (!strcmp(string,"stderr")) return 2;
521 static void of_file(const struct optioninfo *oip, const char *value, char *key) {
522 unsigned long fd, copyfd;
527 fd= strtoul(key,&delim,10);
529 delim= strchr(key,',');
530 if (delim) *delim++= 0;
531 fd= fdstdnumber(key);
532 if (fd<0) usageerror("first part of argument to -f or --file must be numeric "
533 "file descriptor or `stdin', `stdout' or `stderr' - `%s' "
534 "is not recognized",key);
536 if (fd > MAX_ALLOW_FD)
537 usageerror("file descriptor specified (%lu) is larger than maximum allowed (%d)",
539 if (fd >= fdsetupsize) {
540 oldarraysize= fdsetupsize;
541 fdsetupsize+=2; fdsetupsize<<=1;
542 fdsetup= xrealloc(fdsetup,sizeof(struct fdsetupstate)*fdsetupsize);
543 while (oldarraysize < fdsetupsize) {
544 fdsetup[oldarraysize].filename= 0;
545 fdsetup[oldarraysize].pipefd= -1;
546 fdsetup[oldarraysize].copyfd= -1;
547 fdsetup[oldarraysize].mods= 0;
548 fdsetup[oldarraysize].oflags= 0;
549 fdsetup[oldarraysize].catpid= -1;
550 fdsetup[oldarraysize].killed= 0;
551 fdsetup[oldarraysize].filename= 0;
555 fdsetup[fd].filename= value;
556 fdsetup[fd].oflags= 0;
558 fdsetup[fd].copyfd= -1;
559 while (delim && *delim) {
561 delim= strchr(key,',');
562 if (delim) *delim++= 0;
563 addfdmodifier(fd,key);
565 if (!(fdsetup[fd].mods & (fdm_read|fdm_write))) {
567 addfdmodifier(fd,"read");
568 } else if (fdsetup[fd].mods & fdm_fd) {
569 addfdmodifier(fd,"write");
571 addfdmodifier(fd,"overwrite");
574 if (fdsetup[fd].mods & fdm_fd) {
575 copyfd= fdstdnumber(value);
577 copyfd= strtoul(value,&delim,0);
579 usageerror("value part of argument to --file with fd modifier must be "
580 "numeric or fd name - `%s' is not recognised",value);
581 else if (copyfd > MAX_ALLOW_FD)
582 usageerror("file descriptor %lu named as target of file descriptor redirection"
583 " (for file descriptor %lu) is larger than maximum allowed (%d)",
584 copyfd,fd,MAX_ALLOW_FD);
586 r= fstat(copyfd,&stab);
588 if (oip) syscallerror("check filedescriptor %lu (named as target of file "
589 "descriptor redirection for %lu)",copyfd,fd);
590 else syscallerror("check basic filedescriptor %lu at program start",copyfd);
592 fdsetup[fd].copyfd= copyfd;
596 static void of_fdwait(const struct optioninfo *oip, const char *value, char *key) {
597 const struct fdmodifierinfo *fdmip;
602 fd= fdstdnumber(key);
604 ul= strtoul(key,&delim,0);
605 if (*delim) usageerror("first part of argument to --fdwait must be "
606 "numeric or fd name - `%s' is not recognised",key);
607 if (ul>MAX_ALLOW_FD) usageerror("first part of argument to --fdwait is too large");
610 if (fd >= fdsetupsize || !fdsetup[fd].filename)
611 usageerror("file descriptor %d specified in --fdwait option is not open",fd);
612 for (fdmip= fdmodifierinfos; fdmip->string && strcmp(fdmip->string,value); fdmip++);
613 if (!fdmip->string || !(fdmip->implies & (fdm_wait|fdm_nowait|fdm_close)))
614 usageerror("value for --fdwait must be `wait', `nowait' or `close', not `%s'",value);
615 fdsetup[fd].mods &= ~(fdm_wait|fdm_nowait|fdm_close);
616 fdsetup[fd].mods |= fdmip->implies;
619 static void of_defvar(const struct optioninfo *oip, const char *value, char *key) {
623 usageerror("empty string not allowed as variable name");
624 if (strlen(key)>MAX_GENERAL_STRING)
625 usageerror("variable name `%s' is far too long",key);
626 if (strlen(value)>MAX_GENERAL_STRING)
627 usageerror("variable `%s' has value `%s' which is far too long",key,value);
628 for (i=0; i<defvarused && strcmp(defvararray[i].key,key); i++);
629 if (defvarused >= MAX_ARGSDEFVAR) usageerror("far too many --defvar or -D options");
630 if (i>=defvaravail) {
631 defvaravail+=10; defvaravail<<=1;
632 defvararray= xrealloc(defvararray,sizeof(struct constkeyvaluepair)*defvaravail);
634 if (i==defvarused) defvarused++;
635 defvararray[i].key= key;
636 defvararray[i].value= value;
639 static void of_timeout(const struct optioninfo *oip, const char *value, char *key) {
643 ul= strtoul(value,&endp,0);
644 if (*endp) usageerror("timeout value `%s' must be a plain decimal string",value);
645 if (ul>INT_MAX) usageerror("timeout value %lu too large",ul);
649 static void of_signals(const struct optioninfo *oip, const char *value, char *key) {
650 unsigned long numvalue;
653 numvalue= strtoul(value,&endp,0);
655 if (!strcmp(value,"number")) signalsexit= se_number;
656 else if (!strcmp(value,"number-nocore")) signalsexit= se_numbernocore;
657 else if (!strcmp(value,"highbit")) signalsexit= se_highbit;
658 else if (!strcmp(value,"stdout")) signalsexit= se_stdout;
659 else usageerror("value `%s' for --signals not understood",value);
661 if (numvalue<0 || numvalue>255)
662 usageerror("value %lu for --signals not 0...255",numvalue);
663 signalsexit= numvalue;
667 static void of_sigpipe(const struct optioninfo *oip, const char *value, char *key) {
671 static void of_hidecwd(const struct optioninfo *oip, const char *value, char *key) {
675 static void of_help(const struct optioninfo *oip, const char *value, char *key) {
680 static void of_copyright(const struct optioninfo *oip, const char *value, char *key) {
682 " userv - user service daemon and client; copyright (C)1996-1997 Ian Jackson\n\n"
683 " This is free software; you can redistribute it and/or modify it under the\n"
684 " terms of the GNU General Public License as published by the Free Software\n"
685 " Foundation; either version 2 of the License, or (at your option) any\n"
686 " later version.\n\n"
687 " This program is distributed in the hope that it will be useful, but\n"
688 " WITHOUT ANY WARRANTY; without even the implied warranty of\n"
689 " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\n"
690 " Public License for more details.\n\n"
691 " You should have received a copy of the GNU General Public License along\n"
692 " with userv; if not, write to Ian Jackson <ian@chiark.greenend.org.uk> or\n"
693 " to the Free Software Foundation, 59 Temple Place - Suite 330, Boston,\n"
694 " MA 02111-1307, USA.\n",
695 stdout) < 0) syscallerror("write usage to stderr");
699 static void of_builtin(const struct optioninfo *oip, const char *value, char *key) {
700 overridetype= ot_builtin;
703 static void of_override(const struct optioninfo *oip, const char *value, char *key) {
704 overridetype= ot_string;
705 overridevalue= value;
708 static void of_overridefile(const struct optioninfo *oip,
709 const char *value, char *key) {
710 overridetype= ot_file;
711 overridevalue= value;
714 static void of_spoofuser(const struct optioninfo *oip,
715 const char *value, char *key) {
719 const struct optioninfo optioninfos[]= {
720 { 'f', "file", 2, of_file },
721 { 'w', "fdwait", 2, of_fdwait },
722 { 'D', "defvar", 2, of_defvar },
723 { 't', "timeout", 1, of_timeout },
724 { 'S', "signals", 1, of_signals },
725 { 'P', "sigpipe", 0, of_sigpipe },
726 { 'H', "hidecwd", 0, of_hidecwd },
727 { 'B', "builtin", 0, of_builtin },
728 { 'h', "help", 0, of_help },
729 { 0, "copyright", 0, of_copyright },
730 { 0, "override", 1, of_override },
731 { 0, "override-file", 1, of_overridefile },
732 { 0, "spoof-user", 1, of_spoofuser },
736 static void callvalueoption(const struct optioninfo *oip, char *arg) {
738 if (oip->values == 2) {
739 equals= strchr(arg,'=');
742 usageerror("option --%s (-%c) passed argument `%s' with no `='",
743 oip->full,oip->abbrev,arg);
745 usageerror("option --%s passed argument `%s' with no `='",
748 (oip->fn)(oip,equals,arg);
750 (oip->fn)(oip,arg,0);
755 * Main thread main processing functions - in order of execution.
758 static void security_init(void) {
759 /* May not open any file descriptors. */
761 mypid= getpid(); if (mypid == (pid_t)-1) syscallerror("getpid");
762 myuid= getuid(); if (myuid == (uid_t)-1) syscallerror("getuid");
763 mygid= getgid(); if (mygid == (gid_t)-1) syscallerror("getgid");
764 ngids= getgroups(0,0); if (ngids == (gid_t)-1) syscallerror("getgroups(0,0)");
765 gidarray= xmalloc(sizeof(gid_t)*ngids);
766 if (getgroups(ngids,gidarray) != ngids) syscallerror("getgroups(ngids,)");
770 if (ngids > MAX_GIDS) miscerror("caller is in far too many gids");
773 static void parse_arguments(int *argcp, char *const **argvp) {
774 static char fd0key[]= "stdin,fd,read";
775 static char fd1key[]= "stdout,fd,write";
776 static char fd2key[]= "stderr,fd,write";
780 const struct optioninfo *oip;
784 of_file(0,"stdin",fd0key);
785 of_file(0,"stdout",fd1key);
786 of_file(0,"stderr",fd2key);
788 for (argpp= *argvp+1;
789 (argp= *argpp) && *argp == '-' && argp[1];
791 if (!*++argp) usageerror("unknown option/argument `%s'",*argpp);
792 if (*argp == '-') { /* Two hyphens */
793 if (!*++argp) { argpp++; break; /* End of options. */ }
794 for (oip= optioninfos; oip->full && strcmp(oip->full,argp); oip++);
795 if (!oip->full) usageerror("unknown long option `%s'",*argpp);
797 if (!argpp[1]) usageerror("long option `%s' needs a value",*argpp);
798 callvalueoption(oip,*++argpp);
803 for (; *argp; argp++) {
804 for (oip= optioninfos; oip->full && oip->abbrev != *argp; oip++);
805 if (!oip->full) usageerror("unknown short option `-%c' in argument `%s'",
811 if (!argpp[1]) usageerror("short option `-%c' in argument `%s' needs"
812 " a value",*argp,*argpp);
815 callvalueoption(oip,argp);
816 break; /* No more options in this argument, go on to the next one. */
823 if (overridetype == ot_builtin) {
826 if (!*argpp) usageerror("no service user given after options");
827 serviceuser= *argpp++;
829 if (!*argpp) usageerror(overridetype == ot_builtin ?
830 "no service name given after options and service user" :
831 "no builtin service given after options");
833 *argcp-= (argpp-*argvp);
836 if (*argcp > MAX_ARGSDEFVAR) usageerror("far too many arguments");
838 for (fd=0; fd<fdsetupsize; fd++) {
839 if (!fdsetup[fd].filename) continue;
840 if (fdsetup[fd].mods & (fdm_wait|fdm_nowait|fdm_close)) continue;
841 assert(fdsetup[fd].mods & (fdm_read|fdm_write));
842 fdsetup[fd].mods |= (fdsetup[fd].mods & fdm_read) ? fdm_close : fdm_wait;
846 static void determine_users(void) {
854 logname= getenv("LOGNAME");
855 if (!logname) logname= getenv("USER");
857 pw= getpwnam(logname);
858 if (!pw || pw->pw_uid != myuid) logname= 0;
861 pw= getpwuid(myuid); if (!pw) miscerror("cannot determine your login name");
862 logname= pw->pw_name;
865 if (!strcmp(serviceuser,"-")) serviceuser= logname;
866 pw= getpwnam(serviceuser);
867 if (!pw) miscerror("requested service user `%s' is not a user",serviceuser);
868 serviceuid= pw->pw_uid;
870 if ((overridetype != ot_none || spoofuser) && myuid != 0 && myuid != serviceuid)
871 miscerror("--override and --spoof options only available to root or to"
872 " the user who will be providing the service");
876 pw= getpwnam(logname);
877 if (!pw) miscerror("spoofed login name `%s' is not valid",logname);
878 spoofuid= pw->pw_uid;
879 spoofgid= pw->pw_gid;
880 ngidssize= ngids; ngids= 0;
883 gidarray= xrealloc(gidarray,sizeof(gid_t)*ngidssize);
885 gidarray[ngids++]= spoofgid;
886 while ((gr= getgrent())) { /* ouch! getgrent has no error behaviour! */
887 for (mem= gr->gr_mem; *mem && strcmp(*mem,logname); mem++);
889 if (ngids>=ngidssize) {
890 if (ngids>=MAX_GIDS) miscerror("spoofed user is member of too many groups");
891 ngidssize= (ngids+5)<<1;
892 gidarray= xrealloc(gidarray,sizeof(gid_t)*ngidssize);
894 gidarray[ngids++]= gr->gr_gid;
899 static void determine_cwd(void) {
900 cwdbufsize= 0; cwdbuf= 0;
905 if (cwdbufsize > MAX_GENERAL_STRING) { cwdbufsize= 0; free(cwdbuf); break; }
906 cwdbufsize <<= 1; cwdbufsize+= 100;
907 cwdbuf= xrealloc(cwdbuf,cwdbufsize);
908 cwdbuf[cwdbufsize-1]= 0;
909 if (getcwd(cwdbuf,cwdbufsize-1)) { cwdbufsize= strlen(cwdbuf); break; }
910 if (errno != ERANGE) { cwdbufsize= 0; free(cwdbuf); break; }
914 static void process_override(const char *servicename) {
918 switch (overridetype) {
924 l= strlen(servicename);
925 if (l >= MAX_OVERRIDE_LEN-20)
926 miscerror("builtin service string is too long (%d, max is %d)",
927 l,MAX_OVERRIDE_LEN-21);
930 snprintf(ovbuf,l,"execute-builtin %s\n",servicename);
931 ovused= strlen(ovbuf);
934 l= strlen(overridevalue);
935 if (l >= MAX_OVERRIDE_LEN)
936 miscerror("override string is too long (%d, max is %d)",l,MAX_OVERRIDE_LEN-1);
938 snprintf(ovbuf,l+2,"%s\n",overridevalue);
942 ovfile= fopen(overridevalue,"r");
943 if (!ovfile) syscallerror("open overriding configuration file `%s'",overridevalue);
944 ovbuf= 0; ovavail= ovused= 0;
945 while ((c= getc(ovfile)) != EOF) {
946 if (!c) miscerror("overriding config file `%s' contains null(s)",overridevalue);
947 if (ovused >= MAX_OVERRIDE_LEN)
948 miscerror("override file is too long (max is %d)",MAX_OVERRIDE_LEN);
949 if (ovused >= ovavail) {
950 ovavail+=80; ovavail<<=2; ovbuf= xrealloc(ovbuf,ovavail);
954 if (ferror(ovfile) || fclose(ovfile))
955 syscallerror("read overriding configuration file `%s'",overridevalue);
956 ovbuf= xrealloc(ovbuf,ovused+1);
964 static int server_connect(void) {
965 struct sockaddr_un ssockname;
967 struct sigaction sig;
971 sigaddset(&sset,SIGCHLD);
972 sigaddset(&sset,SIGALRM);
973 sigaddset(&sset,SIGPIPE);
974 if (sigprocmask(SIG_UNBLOCK,&sset,0)) syscallerror("preliminarily unblock signals");
976 sig.sa_handler= SIG_IGN;
977 sigemptyset(&sig.sa_mask);
979 if (sigaction(SIGPIPE,&sig,0)) syscallerror("ignore sigpipe");
981 sfd= socket(AF_UNIX,SOCK_STREAM,0);
982 if (!sfd) syscallerror("create client socket");
984 assert(sizeof(ssockname.sun_path) > sizeof(RENDEZVOUSPATH));
985 ssockname.sun_family= AF_UNIX;
986 strcpy(ssockname.sun_path,RENDEZVOUSPATH);
988 while (connect(sfd,(struct sockaddr*)&ssockname,sizeof(ssockname))) {
989 if (errno == ECONNREFUSED || errno == ENOENT)
990 syscallerror("uservd daemon is not running - service not available");
991 syscallerror("unable to connect to uservd daemon");
997 static void server_handshake(int sfd) {
998 srfile= fdopen(sfd,"r");
999 if (!srfile) syscallerror("turn socket fd into FILE* for read");
1000 if (setvbuf(srfile,0,_IOFBF,BUFSIZ)) syscallerror("set buffering on socket reads");
1002 swfile= fdopen(sfd,"w");
1003 if (!swfile) syscallerror("turn socket fd into FILE* for write");
1004 if (setvbuf(swfile,0,_IOFBF,BUFSIZ)) syscallerror("set buffering on socket writes");
1006 xfread(&opening_mbuf,sizeof(opening_mbuf),srfile);
1007 checkmagic(opening_mbuf.magic,OPENING_MAGIC,"in opening message");
1008 if (memcmp(protocolchecksumversion,opening_mbuf.protocolchecksumversion,PCSUMSIZE))
1009 protoerror("protocol version checksum mismatch - server not same as client");
1012 static void server_preparepipes(void) {
1013 char pipepathbuf[PIPEPATHMAXLEN+2];
1016 for (fd=0; fd<fdsetupsize; fd++) {
1017 if (!fdsetup[fd].filename) continue;
1018 pipepathbuf[PIPEPATHMAXLEN]= 0;
1019 sprintf(pipepathbuf, PIPEPATHFORMAT,
1020 (unsigned long)mypid, (unsigned long)opening_mbuf.serverpid, fd);
1021 assert(!pipepathbuf[PIPEPATHMAXLEN]);
1023 if (unlink(pipepathbuf) && errno != ENOENT)
1024 syscallerror("remove any old pipe `%s'",pipepathbuf);
1025 if (mkfifo(pipepathbuf,0600)) /* permissions are irrelevant */
1026 syscallerror("create pipe `%s'",pipepathbuf);
1027 tempfd= open(pipepathbuf,O_RDWR);
1028 if (tempfd<0) syscallerror("prelim open pipe `%s' for read+write",pipepathbuf);
1029 assert(fdsetup[fd].mods & (fdm_read|fdm_write));
1031 open(pipepathbuf, (fdsetup[fd].mods & fdm_read) ? O_WRONLY : O_RDONLY);
1032 if (fdsetup[fd].pipefd<0) syscallerror("real open pipe `%s'",pipepathbuf);
1033 if (close(tempfd)) syscallerror("close prelim fd onto pipe `%s'",pipepathbuf);
1038 static void server_sendrequest(int argc, char *const *argv) {
1039 struct request_msg request_mbuf;
1043 memset(&request_mbuf,0,sizeof(request_mbuf));
1044 request_mbuf.magic= REQUEST_MAGIC;
1045 request_mbuf.clientpid= getpid();
1046 request_mbuf.serviceuserlen= strlen(serviceuser);
1047 request_mbuf.servicelen= strlen(argv[0]);
1048 request_mbuf.lognamelen= strlen(logname);
1049 request_mbuf.cwdlen= cwdbufsize;
1050 request_mbuf.callinguid= spoofuid;
1051 request_mbuf.ngids= ngids+1;
1052 request_mbuf.nreadfds= 0;
1053 request_mbuf.nwritefds= 0;
1054 for (fd=0; fd<fdsetupsize; fd++) {
1055 if (!fdsetup[fd].filename) continue;
1056 assert(fdsetup[fd].mods & (fdm_write|fdm_read));
1057 if (fdsetup[fd].mods & fdm_write) request_mbuf.nwritefds++;
1058 else request_mbuf.nreadfds++;
1060 request_mbuf.nargs= argc-1;
1061 request_mbuf.nvars= defvarused;
1062 request_mbuf.overridelen= ovused;
1063 xfwrite(&request_mbuf,sizeof(request_mbuf),swfile);
1064 xfwrite(serviceuser,sizeof(*serviceuser)*request_mbuf.serviceuserlen,swfile);
1065 xfwrite(argv[0],sizeof(*argv[0])*request_mbuf.servicelen,swfile);
1066 xfwrite(logname,sizeof(*logname)*request_mbuf.lognamelen,swfile);
1067 xfwrite(cwdbuf,sizeof(*cwdbuf)*request_mbuf.cwdlen,swfile);
1068 if (ovused>=0) xfwrite(ovbuf,sizeof(*ovbuf)*ovused,swfile);
1069 xfwrite(&spoofgid,sizeof(gid_t),swfile);
1070 xfwrite(gidarray,sizeof(gid_t)*ngids,swfile);
1071 xfwritefds(fdm_read,request_mbuf.nreadfds,swfile);
1072 xfwritefds(fdm_write,request_mbuf.nwritefds,swfile);
1073 for (i=1; i<argc; i++)
1074 xfwritestring(argv[i],swfile);
1075 for (i=0; i<defvarused; i++) {
1076 xfwritestring(defvararray[i].key,swfile);
1077 xfwritestring(defvararray[i].value,swfile);
1079 ul= REQUEST_END_MAGIC; xfwrite(&ul,sizeof(ul),swfile);
1083 static void server_awaitconfirm(void) {
1084 struct progress_msg progress_mbuf;
1086 getprogress(&progress_mbuf,srfile);
1087 if (progress_mbuf.type != pt_ok)
1088 protoerror("progress message during configuration phase"
1089 " unexpected type %d",progress_mbuf.type);
1092 static void prepare_asynchsignals(void) {
1093 static char stderrbuf[BUFSIZ], stdoutbuf[BUFSIZ];
1095 struct sigaction sig;
1097 if (setvbuf(stderr,stderrbuf,_IOLBF,sizeof(stderrbuf)))
1098 syscallerror("set buffering on stderr");
1099 if (setvbuf(stdout,stdoutbuf,_IOFBF,sizeof(stdoutbuf)))
1100 syscallerror("set buffering on stdout");
1102 sig.sa_handler= sighandler_chld;
1103 sigemptyset(&sig.sa_mask);
1104 sigaddset(&sig.sa_mask,SIGCHLD);
1105 sigaddset(&sig.sa_mask,SIGALRM);
1107 if (sigaction(SIGCHLD,&sig,0)) syscallerror("set up sigchld handler");
1109 sig.sa_handler= sighandler_alrm;
1110 if (sigaction(SIGALRM,&sig,0)) syscallerror("set up sigalrm handler");
1112 if (!timeout) return;
1113 if (alarm(timeout)<0) syscallerror("set up timeout alarm");
1116 static void catdup(const char *which, int from, int to) {
1117 if (dup2(from,to)<0) {
1118 blocksignals(SIG_BLOCK);
1119 fprintf(stderr,"userv: %s: cannot dup for %s: %s\n",which,
1120 to?"stdout":"stdin", strerror(errno));
1125 static void connect_pipes(void) {
1126 struct sigaction sig;
1127 char catnamebuf[sizeof(int)*3+30];
1130 for (fd=0; fd<fdsetupsize; fd++) {
1131 if (!fdsetup[fd].filename) continue;
1132 if (!(fdsetup[fd].mods & fdm_fd)) {
1134 open(fdsetup[fd].filename,fdsetup[fd].oflags|O_NOCTTY,0777);
1135 if (fdsetup[fd].copyfd<0)
1136 syscallerror("open file `%s' for fd %d",fdsetup[fd].filename,fd);
1138 fdsetup[fd].catpid= fork();
1139 if (fdsetup[fd].catpid==-1) syscallerror("fork for cat for fd %d",fd);
1140 if (!fdsetup[fd].catpid) {
1141 snprintf(catnamebuf,sizeof(catnamebuf),"cat fd%d",fd);
1142 catnamebuf[sizeof(catnamebuf)-1]= 0;
1143 sig.sa_handler= SIG_DFL;
1144 sigemptyset(&sig.sa_mask);
1146 if (sigaction(SIGPIPE,&sig,0)) {
1147 fprintf(stderr,"userv: %s: reset sigpipe handler for cat: %s",
1148 catnamebuf,strerror(errno));
1151 reading= fdsetup[fd].mods & fdm_read;
1152 catdup(catnamebuf, fdsetup[fd].copyfd, reading ? 0 : 1);
1153 catdup(catnamebuf, fdsetup[fd].pipefd, reading ? 1 : 0);
1154 execl("/bin/cat",catnamebuf,(char*)0);
1155 fprintf(stderr,"userv: %s: cannot exec `cat': %s\n",catnamebuf,strerror(errno));
1158 if (fdsetup[fd].copyfd>2)
1159 if (close(fdsetup[fd].copyfd)) syscallerror("close real fd for %d",fd);
1160 if (close(fdsetup[fd].pipefd)) syscallerror("close pipe fd for %d",fd);
1164 static void server_sendconfirm(void) {
1165 struct event_msg event_mbuf;
1167 blocksignals(SIG_BLOCK);
1168 memset(&event_mbuf,0,sizeof(event_mbuf));
1169 event_mbuf.magic= EVENT_MAGIC;
1170 event_mbuf.type= et_confirm;
1171 xfwrite(&event_mbuf,sizeof(event_mbuf),swfile);
1173 blocksignals(SIG_UNBLOCK);
1176 static int server_awaitcompletion(void) {
1177 struct progress_msg progress_mbuf;
1179 getprogress(&progress_mbuf,srfile);
1180 if (progress_mbuf.type != pt_terminated)
1181 protoerror("progress message during execution phase"
1182 " unexpected type %d",progress_mbuf.type);
1185 return progress_mbuf.data.terminated.status;
1188 static void dispose_remaining_pipes(void) {
1192 blocksignals(SIG_BLOCK);
1193 for (fd=0; fd<fdsetupsize; fd++) {
1194 if (!(fdsetup[fd].catpid!=-1 && (fdsetup[fd].mods & fdm_close))) continue;
1195 if (kill(fdsetup[fd].catpid,SIGKILL)) syscallerror("kill cat for %d",fd);
1196 fdsetup[fd].killed= 1;
1198 blocksignals(SIG_UNBLOCK);
1201 blocksignals(SIG_BLOCK);
1203 fd<fdsetupsize && !(fdsetup[fd].catpid!=-1 && (fdsetup[fd].mods & fdm_wait));
1205 if (fd>=fdsetupsize) break;
1207 r= sigsuspend(&sset);
1208 if (r && errno != EINTR) syscallerror("sigsuspend failed in unexpected way");
1209 blocksignals(SIG_UNBLOCK);
1213 static void NONRETURNING process_exitstatus(int status) {
1214 blocksignals(SIG_BLOCK);
1216 if (systemerror) _exit(255);
1218 if (sigpipeok && signalsexit != se_stdout && WIFSIGNALED(status) &&
1219 WTERMSIG(status)==SIGPIPE && !WCOREDUMP(status)) status= 0;
1221 switch (signalsexit) {
1223 case se_numbernocore:
1224 if (WIFEXITED(status))
1225 _exit(WEXITSTATUS(status));
1226 else if (WIFSIGNALED(status))
1227 _exit(WTERMSIG(status) + (signalsexit==se_number && WCOREDUMP(status) ? 128 : 0));
1230 if (WIFEXITED(status))
1231 _exit(WEXITSTATUS(status)<=127 ? WEXITSTATUS(status) : 127);
1232 else if (WIFSIGNALED(status) && WTERMSIG(status)<=126)
1233 _exit(WTERMSIG(status)+128);
1236 printf("\n%d %d ",(status>>8)&0x0ff,status&0x0ff);
1237 if (WIFEXITED(status))
1238 printf("exited with code %d",WEXITSTATUS(status));
1239 else if (WIFSIGNALED(status))
1240 printf("killed by %s (signal %d)%s",
1241 strsignal(WTERMSIG(status)),WTERMSIG(status),
1242 WCOREDUMP(status) ? ", core dumped " : "");
1244 printf("unknown wait status");
1246 if (ferror(stdout) || fflush(stdout)) syscallerror("write exit status to stdout");
1249 if (WIFEXITED(status))
1250 _exit(WEXITSTATUS(status));
1251 else if (WIFSIGNALED(status))
1256 fprintf(stderr,"userv: unknown wait status %d\n",status);
1260 int main(int argc, char *const *argv) {
1261 int status, socketfd;
1264 # error Do not disable assertions in this security-critical code !
1268 parse_arguments(&argc,&argv);
1271 process_override(argv[0]);
1273 socketfd= server_connect();
1275 server_handshake(socketfd);
1276 server_preparepipes();
1277 server_sendrequest(argc,argv);
1279 priv_permanentlyrevokesuspended();
1281 server_awaitconfirm();
1282 prepare_asynchsignals();
1284 server_sendconfirm();
1285 status= server_awaitcompletion();
1287 dispose_remaining_pipes();
1288 process_exitstatus(status);