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");
992 syscallerror("unable to connect to uservd daemon: %m");
998 static void server_handshake(int sfd) {
999 srfile= fdopen(sfd,"r");
1000 if (!srfile) syscallerror("turn socket fd into FILE* for read");
1001 if (setvbuf(srfile,0,_IOFBF,BUFSIZ)) syscallerror("set buffering on socket reads");
1003 swfile= fdopen(sfd,"w");
1004 if (!swfile) syscallerror("turn socket fd into FILE* for write");
1005 if (setvbuf(swfile,0,_IOFBF,BUFSIZ)) syscallerror("set buffering on socket writes");
1007 xfread(&opening_mbuf,sizeof(opening_mbuf),srfile);
1008 checkmagic(opening_mbuf.magic,OPENING_MAGIC,"in opening message");
1009 if (memcmp(protocolchecksumversion,opening_mbuf.protocolchecksumversion,PCSUMSIZE))
1010 protoerror("protocol version checksum mismatch - server not same as client");
1013 static void server_preparepipes(void) {
1014 char pipepathbuf[PIPEPATHMAXLEN+2];
1017 for (fd=0; fd<fdsetupsize; fd++) {
1018 if (!fdsetup[fd].filename) continue;
1019 pipepathbuf[PIPEPATHMAXLEN]= 0;
1020 sprintf(pipepathbuf, PIPEPATHFORMAT,
1021 (unsigned long)mypid, (unsigned long)opening_mbuf.serverpid, fd);
1022 assert(!pipepathbuf[PIPEPATHMAXLEN]);
1024 if (unlink(pipepathbuf) && errno != ENOENT)
1025 syscallerror("remove any old pipe `%s'",pipepathbuf);
1026 if (mkfifo(pipepathbuf,0600)) /* permissions are irrelevant */
1027 syscallerror("create pipe `%s'",pipepathbuf);
1028 tempfd= open(pipepathbuf,O_RDWR);
1029 if (tempfd<0) syscallerror("prelim open pipe `%s' for read+write",pipepathbuf);
1030 assert(fdsetup[fd].mods & (fdm_read|fdm_write));
1032 open(pipepathbuf, (fdsetup[fd].mods & fdm_read) ? O_WRONLY : O_RDONLY);
1033 if (fdsetup[fd].pipefd<0) syscallerror("real open pipe `%s'",pipepathbuf);
1034 if (close(tempfd)) syscallerror("close prelim fd onto pipe `%s'",pipepathbuf);
1039 static void server_sendrequest(int argc, char *const *argv) {
1040 struct request_msg request_mbuf;
1044 memset(&request_mbuf,0,sizeof(request_mbuf));
1045 request_mbuf.magic= REQUEST_MAGIC;
1046 request_mbuf.clientpid= getpid();
1047 request_mbuf.serviceuserlen= strlen(serviceuser);
1048 request_mbuf.servicelen= strlen(argv[0]);
1049 request_mbuf.lognamelen= strlen(logname);
1050 request_mbuf.cwdlen= cwdbufsize;
1051 request_mbuf.callinguid= spoofuid;
1052 request_mbuf.ngids= ngids+1;
1053 request_mbuf.nreadfds= 0;
1054 request_mbuf.nwritefds= 0;
1055 for (fd=0; fd<fdsetupsize; fd++) {
1056 if (!fdsetup[fd].filename) continue;
1057 assert(fdsetup[fd].mods & (fdm_write|fdm_read));
1058 if (fdsetup[fd].mods & fdm_write) request_mbuf.nwritefds++;
1059 else request_mbuf.nreadfds++;
1061 request_mbuf.nargs= argc-1;
1062 request_mbuf.nvars= defvarused;
1063 request_mbuf.overridelen= ovused;
1064 xfwrite(&request_mbuf,sizeof(request_mbuf),swfile);
1065 xfwrite(serviceuser,sizeof(*serviceuser)*request_mbuf.serviceuserlen,swfile);
1066 xfwrite(argv[0],sizeof(*argv[0])*request_mbuf.servicelen,swfile);
1067 xfwrite(logname,sizeof(*logname)*request_mbuf.lognamelen,swfile);
1068 xfwrite(cwdbuf,sizeof(*cwdbuf)*request_mbuf.cwdlen,swfile);
1069 if (ovused>=0) xfwrite(ovbuf,sizeof(*ovbuf)*ovused,swfile);
1070 xfwrite(&spoofgid,sizeof(gid_t),swfile);
1071 xfwrite(gidarray,sizeof(gid_t)*ngids,swfile);
1072 xfwritefds(fdm_read,request_mbuf.nreadfds,swfile);
1073 xfwritefds(fdm_write,request_mbuf.nwritefds,swfile);
1074 for (i=1; i<argc; i++)
1075 xfwritestring(argv[i],swfile);
1076 for (i=0; i<defvarused; i++) {
1077 xfwritestring(defvararray[i].key,swfile);
1078 xfwritestring(defvararray[i].value,swfile);
1080 ul= REQUEST_END_MAGIC; xfwrite(&ul,sizeof(ul),swfile);
1084 static void server_awaitconfirm(void) {
1085 struct progress_msg progress_mbuf;
1087 getprogress(&progress_mbuf,srfile);
1088 if (progress_mbuf.type != pt_ok)
1089 protoerror("progress message during configuration phase"
1090 " unexpected type %d",progress_mbuf.type);
1093 static void prepare_asynchsignals(void) {
1094 static char stderrbuf[BUFSIZ], stdoutbuf[BUFSIZ];
1096 struct sigaction sig;
1098 if (setvbuf(stderr,stderrbuf,_IOLBF,sizeof(stderrbuf)))
1099 syscallerror("set buffering on stderr");
1100 if (setvbuf(stdout,stdoutbuf,_IOFBF,sizeof(stdoutbuf)))
1101 syscallerror("set buffering on stdout");
1103 sig.sa_handler= sighandler_chld;
1104 sigemptyset(&sig.sa_mask);
1105 sigaddset(&sig.sa_mask,SIGCHLD);
1106 sigaddset(&sig.sa_mask,SIGALRM);
1108 if (sigaction(SIGCHLD,&sig,0)) syscallerror("set up sigchld handler");
1110 sig.sa_handler= sighandler_alrm;
1111 if (sigaction(SIGALRM,&sig,0)) syscallerror("set up sigalrm handler");
1113 if (!timeout) return;
1114 if (alarm(timeout)<0) syscallerror("set up timeout alarm");
1117 static void catdup(const char *which, int from, int to) {
1118 if (dup2(from,to)<0) {
1119 blocksignals(SIG_BLOCK);
1120 fprintf(stderr,"userv: %s: cannot dup for %s: %s\n",which,
1121 to?"stdout":"stdin", strerror(errno));
1126 static void connect_pipes(void) {
1127 struct sigaction sig;
1128 char catnamebuf[sizeof(int)*3+30];
1131 for (fd=0; fd<fdsetupsize; fd++) {
1132 if (!fdsetup[fd].filename) continue;
1133 if (!(fdsetup[fd].mods & fdm_fd)) {
1135 open(fdsetup[fd].filename,fdsetup[fd].oflags|O_NOCTTY,0777);
1136 if (fdsetup[fd].copyfd<0)
1137 syscallerror("open file `%s' for fd %d",fdsetup[fd].filename,fd);
1139 fdsetup[fd].catpid= fork();
1140 if (fdsetup[fd].catpid==-1) syscallerror("fork for cat for fd %d",fd);
1141 if (!fdsetup[fd].catpid) {
1142 snprintf(catnamebuf,sizeof(catnamebuf),"cat fd%d",fd);
1143 catnamebuf[sizeof(catnamebuf)-1]= 0;
1144 sig.sa_handler= SIG_DFL;
1145 sigemptyset(&sig.sa_mask);
1147 if (sigaction(SIGPIPE,&sig,0)) {
1148 fprintf(stderr,"userv: %s: reset sigpipe handler for cat: %s",
1149 catnamebuf,strerror(errno));
1152 reading= fdsetup[fd].mods & fdm_read;
1153 catdup(catnamebuf, fdsetup[fd].copyfd, reading ? 0 : 1);
1154 catdup(catnamebuf, fdsetup[fd].pipefd, reading ? 1 : 0);
1155 execl("/bin/cat",catnamebuf,(char*)0);
1156 fprintf(stderr,"userv: %s: cannot exec `cat': %s\n",catnamebuf,strerror(errno));
1159 if (fdsetup[fd].copyfd>2)
1160 if (close(fdsetup[fd].copyfd)) syscallerror("close real fd for %d",fd);
1161 if (close(fdsetup[fd].pipefd)) syscallerror("close pipe fd for %d",fd);
1165 static void server_sendconfirm(void) {
1166 struct event_msg event_mbuf;
1168 blocksignals(SIG_BLOCK);
1169 memset(&event_mbuf,0,sizeof(event_mbuf));
1170 event_mbuf.magic= EVENT_MAGIC;
1171 event_mbuf.type= et_confirm;
1172 xfwrite(&event_mbuf,sizeof(event_mbuf),swfile);
1174 blocksignals(SIG_UNBLOCK);
1177 static int server_awaitcompletion(void) {
1178 struct progress_msg progress_mbuf;
1180 getprogress(&progress_mbuf,srfile);
1181 if (progress_mbuf.type != pt_terminated)
1182 protoerror("progress message during execution phase"
1183 " unexpected type %d",progress_mbuf.type);
1186 return progress_mbuf.data.terminated.status;
1189 static void dispose_remaining_pipes(void) {
1193 blocksignals(SIG_BLOCK);
1194 for (fd=0; fd<fdsetupsize; fd++) {
1195 if (!(fdsetup[fd].catpid!=-1 && (fdsetup[fd].mods & fdm_close))) continue;
1196 if (kill(fdsetup[fd].catpid,SIGKILL)) syscallerror("kill cat for %d",fd);
1197 fdsetup[fd].killed= 1;
1199 blocksignals(SIG_UNBLOCK);
1202 blocksignals(SIG_BLOCK);
1204 fd<fdsetupsize && !(fdsetup[fd].catpid!=-1 && (fdsetup[fd].mods & fdm_wait));
1206 if (fd>=fdsetupsize) break;
1208 r= sigsuspend(&sset);
1209 if (r && errno != EINTR) syscallerror("sigsuspend failed in unexpected way");
1210 blocksignals(SIG_UNBLOCK);
1214 static void NONRETURNING process_exitstatus(int status) {
1215 blocksignals(SIG_BLOCK);
1217 if (systemerror) _exit(255);
1219 if (sigpipeok && signalsexit != se_stdout && WIFSIGNALED(status) &&
1220 WTERMSIG(status)==SIGPIPE && !WCOREDUMP(status)) status= 0;
1222 switch (signalsexit) {
1224 case se_numbernocore:
1225 if (WIFEXITED(status))
1226 _exit(WEXITSTATUS(status));
1227 else if (WIFSIGNALED(status))
1228 _exit(WTERMSIG(status) + (signalsexit==se_number && WCOREDUMP(status) ? 128 : 0));
1231 if (WIFEXITED(status))
1232 _exit(WEXITSTATUS(status)<=127 ? WEXITSTATUS(status) : 127);
1233 else if (WIFSIGNALED(status) && WTERMSIG(status)<=126)
1234 _exit(WTERMSIG(status)+128);
1237 printf("\n%d %d ",(status>>8)&0x0ff,status&0x0ff);
1238 if (WIFEXITED(status))
1239 printf("exited with code %d",WEXITSTATUS(status));
1240 else if (WIFSIGNALED(status))
1241 printf("killed by %s (signal %d)%s",
1242 strsignal(WTERMSIG(status)),WTERMSIG(status),
1243 WCOREDUMP(status) ? ", core dumped " : "");
1245 printf("unknown wait status");
1247 if (ferror(stdout) || fflush(stdout)) syscallerror("write exit status to stdout");
1250 if (WIFEXITED(status))
1251 _exit(WEXITSTATUS(status));
1252 else if (WIFSIGNALED(status))
1257 fprintf(stderr,"userv: unknown wait status %d\n",status);
1261 int main(int argc, char *const *argv) {
1262 int status, socketfd;
1265 # error Do not disable assertions in this security-critical code !
1269 parse_arguments(&argc,&argv);
1272 process_override(argv[0]);
1274 socketfd= server_connect();
1276 server_handshake(socketfd);
1277 server_preparepipes();
1278 server_sendrequest(argc,argv);
1280 priv_permanentlyrevokesuspended();
1282 server_awaitconfirm();
1283 prepare_asynchsignals();
1285 server_sendconfirm();
1286 status= server_awaitcompletion();
1288 dispose_remaining_pipes();
1289 process_exitstatus(status);