5 * Copyright (C)1996-1997,1999 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 *loginname;
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) fsyscallerror(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 void syscallerror(const char *what) {
185 fsyscallerror("%s",what);
188 static void NONRETURNING protoreaderror(FILE *file, const char *where) {
192 blocksignals(SIG_BLOCK);
194 fprintf(stderr,"userv: failure: read error %s: %s\n",where,strerror(e));
197 fprintf(stderr,"userv: internal failure: EOF from server %s\n",where);
202 static void NONRETURNPRINTFFORMAT(1,2) protoerror(const char *fmt, ...) {
205 blocksignals(SIG_BLOCK);
207 fprintf(stderr,"userv: internal failure: protocol error: ");
208 vfprintf(stderr,fmt,al);
209 fprintf(stderr,"\n");
214 * General-purpose functions; these do nothing special about signals,
215 * except that they can call error-handlers which may block them
216 * to print error messages.
219 static void xfread(void *p, size_t sz, FILE *file) {
221 nr= working_fread(p,sz,file);
222 if (nr != sz) protoreaderror(file,"in data");
225 static void xfwrite(const void *p, size_t sz, FILE *file) {
227 nr= fwrite(p,1,sz,file); if (nr == sz) return;
228 syscallerror("writing to server");
231 static void xfflush(FILE *file) {
232 if (fflush(file)) syscallerror("flush server socket");
235 /* Functions which may be called only from the main thread. These may
236 * use main-thread objects and must block signals before using signal
241 static void priv_suspend(void) { }
242 static void priv_resume(void) { }
243 static void priv_permanentlyrevokesuspended(void) { }
245 static void priv_suspend(void) {
246 if (setreuid(0,myuid) != 0) syscallerror("suspend root setreuid(0,myuid)");
248 static void priv_resume(void) {
249 if (setreuid(myuid,0) != 0) syscallerror("resume root setreuid(myuid,0)");
251 static void priv_permanentlyrevokesuspended(void) {
252 if (setreuid(myuid,myuid) != 0) syscallerror("revoke root setreuid(myuid,myuid)");
253 if (setreuid(myuid,myuid) != 0) syscallerror("rerevoke root setreuid(myuid,myuid)");
255 if (!setreuid(myuid,0)) miscerror("revoked root but setreuid(0,0) succeeded !");
256 if (errno != EPERM) syscallerror("revoked and setreuid(myuid,0) unexpected error");
261 static void checkmagic(unsigned long was, unsigned long should, const char *when) {
263 protoerror("magic number %s was %08lx, expected %08lx",when,was,should);
266 static void getprogress(struct progress_msg *progress_r, FILE *file) {
271 xfread(progress_r,sizeof(struct progress_msg),file);
272 checkmagic(progress_r->magic,PROGRESS_MAGIC,"in progress message");
273 switch (progress_r->type) {
275 blocksignals(SIG_BLOCK);
276 fputs("userv: uservd reports that service failed\n",stderr);
279 blocksignals(SIG_BLOCK);
280 fputs("uservd: ",stderr);
281 if (progress_r->data.errmsg.messagelen>MAX_ERRMSG_STRING)
282 protoerror("stderr message length %d is far too long",
283 progress_r->data.errmsg.messagelen);
284 for (i=0; i<progress_r->data.errmsg.messagelen; i++) {
285 c= working_getc(file);
286 if (c==EOF) protoreaderror(file,"in error message");
287 if (isprint(c)) putc(c,stderr);
288 else fprintf(stderr,"\\x%02x",(unsigned char)c);
291 if (ferror(stderr)) syscallerror("printing error message");
292 xfread(&ul,sizeof(ul),file);
293 checkmagic(ul,PROGRESS_ERRMSG_END_MAGIC,"after error message");
294 blocksignals(SIG_UNBLOCK);
303 * Functions which are called only during setup, before
304 * the signal asynchronicity starts. They can do anything they like.
307 /* This includes xmalloc and xrealloc from both.c */
309 static void xfwritestring(const char *s, FILE *file) {
312 assert(l<=MAX_GENERAL_STRING);
313 xfwrite(&l,sizeof(l),file);
314 xfwrite(s,sizeof(*s)*l,file);
317 static void xfwritefds(int modifier, int expected, FILE *file) {
320 for (i=0, fdcount=0; i<fdsetupsize; i++) {
321 if (!(fdsetup[i].filename && (fdsetup[i].mods & modifier)))
323 xfwrite(&i,sizeof(int),file); fdcount++;
325 assert(fdcount == expected);
328 /* Functions which may be called from signal handlers. These
329 * may use signal-handler objects. The main program may only
330 * call them with signals blocked, and they may not use any
331 * main-thread objects.
334 static void disconnect(void) /* DOES return, unlike in daemon */ {
335 struct event_msg event_mbuf;
339 memset(&event_mbuf,0,sizeof(event_mbuf));
340 event_mbuf.magic= EVENT_MAGIC;
341 event_mbuf.type= et_disconnect;
342 r= fwrite(&event_mbuf,1,sizeof(event_mbuf),swfile);
343 if ((r != sizeof(event_mbuf) || fflush(swfile)) && errno != EPIPE)
344 syscallerror("write to server when disconnecting");
349 static void sighandler_alrm(int ignored) /* DOES return, unlike in daemon */ {
352 fputs("userv: timeout\n",stderr);
357 static void sighandler_chld(int ignored) /* DOES return, unlike in daemon */ {
358 struct event_msg event_mbuf;
360 int status, fd, r, es;
364 child= wait3(&status,WNOHANG,0);
365 if (child == 0 || (child == -1 && errno == ECHILD)) break;
366 if (child == -1) syscallerror("wait for child process (in sigchld handler)");
367 for (fd=0; fd<fdsetupsize && fdsetup[fd].catpid != child; fd++);
368 if (fd>=fdsetupsize) continue; /* perhaps the caller gave us children */
369 if ((WIFEXITED(status) && WEXITSTATUS(status)==0) ||
370 (WIFSIGNALED(status) && WTERMSIG(status)==SIGPIPE) ||
371 (fdsetup[fd].killed && WIFSIGNALED(status) && WTERMSIG(status)==SIGKILL)) {
372 if (swfile && fdsetup[fd].mods & fdm_read) {
373 memset(&event_mbuf,0,sizeof(event_mbuf));
374 event_mbuf.magic= EVENT_MAGIC;
375 event_mbuf.type= et_closereadfd;
376 event_mbuf.data.closereadfd.fd= fd;
377 r= fwrite(&event_mbuf,1,sizeof(event_mbuf),swfile);
378 if (r != sizeof(event_mbuf) || fflush(swfile))
379 if (errno != EPIPE) syscallerror("inform service of closed read fd");
382 if (WIFEXITED(status))
383 fprintf(stderr,"userv: cat for fd %d exited with error exit status %d\n",
384 fd,WEXITSTATUS(status));
385 else if (WIFSIGNALED(status))
386 if (WCOREDUMP(status))
387 fprintf(stderr,"userv: cat for fd %d dumped core due to signal %s (%d)\n",
388 fd,strsignal(WTERMSIG(status)),WTERMSIG(status));
390 fprintf(stderr,"userv: cat for fd %d terminated by signal %s (%d)\n",
391 fd,strsignal(WTERMSIG(status)),WTERMSIG(status));
393 fprintf(stderr,"userv: cat for fd %d gave unknown wait status %d\n",
397 fdsetup[fd].catpid= -1;
403 * Argument parsing. These functions which are called only during
404 * setup, before the signal asynchronicity starts.
409 typedef void optionfunction(const struct optioninfo*, const char *value, char *key);
414 int values; /* 0: no value; 1: single value; 2: key and value */
418 static void usage(void) {
420 "usage: userv <options> [--] <service-user> <service-name> [<argument> ...]\n"
421 "usage: userv <options> -B|--builtin [--] <builtin-service> [<info-argument> ...]\n"
422 "options: -f|--file <fd>[<fdmodifiers>]=<filename>\n"
423 " -D|--defvar <name>=<value>\n"
424 " -t|--timeout <seconds>\n"
425 " -S|--signals <status>|number|number-nocore|highbit|stdout\n"
426 " -w|--fdwait <fd>=wait|nowait|close\n"
427 " -P|--sigpipe -H|--hidecwd -h|--help --copyright\n"
428 " --override <configuration-data> } available only\n"
429 " --override-file <filename> } to root\n"
430 " --spoof-user <username> } or same user\n"
431 "fdmodifiers: read write overwrite trunc[ate]\n"
432 "(separate with commas) append sync excl[usive] creat[e] fd\n"
433 "userv -B 'X' ... is same as userv --override 'execute-builtin X' - 'X' ...\n"
434 " for help, type `userv -B help'; remember to quote multi-word X\n"
435 "userv and uservd version " VERSION VEREXT "; copyright (C)1996-1999 Ian Jackson.\n"
436 "there is NO WARRANTY; type `userv --copyright' for details.\n",
438 syscallerror("write usage to stderr");
441 static void NONRETURNPRINTFFORMAT(1,2) usageerror(const char *fmt, ...) {
444 fputs("userv: ",stderr);
445 vfprintf(stderr,fmt,al);
446 fputs("\n\n",stderr);
451 static const struct fdmodifierinfo fdmodifierinfos[]= {
455 { "write", fdm_write,
458 { "overwrite", fdm_write|fdm_create|fdm_truncate,
459 fdm_read|fdm_fd|fdm_exclusive,
460 O_WRONLY|O_CREAT|O_TRUNC },
461 { "create", fdm_write|fdm_create,
464 { "creat", fdm_write|fdm_create,
467 { "exclusive", fdm_write|fdm_create|fdm_exclusive,
468 fdm_read|fdm_fd|fdm_truncate,
469 O_WRONLY|O_CREAT|O_EXCL },
470 { "excl", fdm_write|fdm_create|fdm_exclusive,
471 fdm_read|fdm_fd|fdm_truncate,
472 O_WRONLY|O_CREAT|O_EXCL },
473 { "truncate", fdm_write|fdm_truncate,
474 fdm_read|fdm_fd|fdm_exclusive,
475 O_WRONLY|O_CREAT|O_EXCL },
476 { "trunc", fdm_write|fdm_truncate,
477 fdm_read|fdm_fd|fdm_exclusive,
478 O_WRONLY|O_CREAT|O_EXCL },
479 { "append", fdm_write|fdm_append,
481 O_WRONLY|O_CREAT|O_APPEND },
482 { "sync", fdm_write|fdm_sync,
484 O_WRONLY|O_CREAT|O_SYNC },
486 fdm_nowait|fdm_close,
488 { "nowait", fdm_nowait,
491 { "close", fdm_close,
495 fdm_create|fdm_exclusive|fdm_truncate|fdm_append|fdm_sync,
500 static void addfdmodifier(int fd, const char *key) {
501 const struct fdmodifierinfo *fdmip;
504 for (fdmip= fdmodifierinfos; fdmip->string && strcmp(fdmip->string,key); fdmip++);
505 if (!fdmip->string) usageerror("unknown fdmodifer `%s' for fd %d",key,fd);
506 if (fdmip->conflicts & fdsetup[fd].mods)
507 usageerror("fdmodifier `%s' conflicts with another for fd %d",key,fd);
508 fdsetup[fd].mods |= fdmip->implies;
509 fdsetup[fd].oflags |= fdmip->oflags;
512 static int fdstdnumber(const char *string) {
513 if (!strcmp(string,"stdin")) return 0;
514 else if (!strcmp(string,"stdout")) return 1;
515 else if (!strcmp(string,"stderr")) return 2;
519 static void of_file(const struct optioninfo *oip, const char *value, char *key) {
520 unsigned long fd, copyfd;
525 fd= strtoul(key,&delim,10);
527 delim= strchr(key,',');
528 if (delim) *delim++= 0;
529 fd= fdstdnumber(key);
530 if (fd<0) usageerror("first part of argument to -f or --file must be numeric "
531 "file descriptor or `stdin', `stdout' or `stderr' - `%s' "
532 "is not recognized",key);
534 if (fd > MAX_ALLOW_FD)
535 usageerror("file descriptor specified (%lu) is larger than maximum allowed (%d)",
537 if (fd >= fdsetupsize) {
538 oldarraysize= fdsetupsize;
539 fdsetupsize+=2; fdsetupsize<<=1;
540 fdsetup= xrealloc(fdsetup,sizeof(struct fdsetupstate)*fdsetupsize);
541 while (oldarraysize < fdsetupsize) {
542 fdsetup[oldarraysize].filename= 0;
543 fdsetup[oldarraysize].pipefd= -1;
544 fdsetup[oldarraysize].copyfd= -1;
545 fdsetup[oldarraysize].mods= 0;
546 fdsetup[oldarraysize].oflags= 0;
547 fdsetup[oldarraysize].catpid= -1;
548 fdsetup[oldarraysize].killed= 0;
549 fdsetup[oldarraysize].filename= 0;
553 fdsetup[fd].filename= value;
554 fdsetup[fd].oflags= 0;
556 fdsetup[fd].copyfd= -1;
557 while (delim && *delim) {
559 delim= strchr(key,',');
560 if (delim) *delim++= 0;
561 addfdmodifier(fd,key);
563 if (!(fdsetup[fd].mods & (fdm_read|fdm_write))) {
565 addfdmodifier(fd,"read");
566 } else if (fdsetup[fd].mods & fdm_fd) {
567 addfdmodifier(fd,"write");
569 addfdmodifier(fd,"overwrite");
572 if (fdsetup[fd].mods & fdm_fd) {
573 copyfd= fdstdnumber(value);
575 copyfd= strtoul(value,&delim,0);
577 usageerror("value part of argument to --file with fd modifier must be "
578 "numeric or fd name - `%s' is not recognised",value);
579 else if (copyfd > MAX_ALLOW_FD)
580 usageerror("file descriptor %lu named as target of file descriptor redirection"
581 " (for file descriptor %lu) is larger than maximum allowed (%d)",
582 copyfd,fd,MAX_ALLOW_FD);
584 r= fstat(copyfd,&stab);
586 if (oip) fsyscallerror("check filedescriptor %lu (named as target of file "
587 "descriptor redirection for %lu)",copyfd,fd);
588 else fsyscallerror("check basic filedescriptor %lu at program start",copyfd);
590 fdsetup[fd].copyfd= copyfd;
594 static void of_fdwait(const struct optioninfo *oip, const char *value, char *key) {
595 const struct fdmodifierinfo *fdmip;
600 fd= fdstdnumber(key);
602 ul= strtoul(key,&delim,0);
603 if (*delim) usageerror("first part of argument to --fdwait must be "
604 "numeric or fd name - `%s' is not recognised",key);
605 if (ul>MAX_ALLOW_FD) usageerror("first part of argument to --fdwait is too large");
608 if (fd >= fdsetupsize || !fdsetup[fd].filename)
609 usageerror("file descriptor %d specified in --fdwait option is not open",fd);
610 for (fdmip= fdmodifierinfos; fdmip->string && strcmp(fdmip->string,value); fdmip++);
611 if (!fdmip->string || !(fdmip->implies & (fdm_wait|fdm_nowait|fdm_close)))
612 usageerror("value for --fdwait must be `wait', `nowait' or `close', not `%s'",value);
613 fdsetup[fd].mods &= ~(fdm_wait|fdm_nowait|fdm_close);
614 fdsetup[fd].mods |= fdmip->implies;
617 static void of_defvar(const struct optioninfo *oip, const char *value, char *key) {
621 usageerror("empty string not allowed as variable name");
622 if (strlen(key)>MAX_GENERAL_STRING)
623 usageerror("variable name `%s' is far too long",key);
624 if (strlen(value)>MAX_GENERAL_STRING)
625 usageerror("variable `%s' has value `%s' which is far too long",key,value);
626 for (i=0; i<defvarused && strcmp(defvararray[i].key,key); i++);
627 if (defvarused >= MAX_ARGSDEFVAR) usageerror("far too many --defvar or -D options");
628 if (i>=defvaravail) {
629 defvaravail+=10; defvaravail<<=1;
630 defvararray= xrealloc(defvararray,sizeof(struct constkeyvaluepair)*defvaravail);
632 if (i==defvarused) defvarused++;
633 defvararray[i].key= key;
634 defvararray[i].value= value;
637 static void of_timeout(const struct optioninfo *oip, const char *value, char *key) {
641 ul= strtoul(value,&endp,0);
642 if (*endp) usageerror("timeout value `%s' must be a plain decimal string",value);
643 if (ul>INT_MAX) usageerror("timeout value %lu too large",ul);
647 static void of_signals(const struct optioninfo *oip, const char *value, char *key) {
648 unsigned long numvalue;
651 numvalue= strtoul(value,&endp,0);
653 if (!strcmp(value,"number")) signalsexit= se_number;
654 else if (!strcmp(value,"number-nocore")) signalsexit= se_numbernocore;
655 else if (!strcmp(value,"highbit")) signalsexit= se_highbit;
656 else if (!strcmp(value,"stdout")) signalsexit= se_stdout;
657 else usageerror("value `%s' for --signals not understood",value);
659 if (numvalue<0 || numvalue>255)
660 usageerror("value %lu for --signals not 0...255",numvalue);
661 signalsexit= numvalue;
665 static void of_sigpipe(const struct optioninfo *oip, const char *value, char *key) {
669 static void of_hidecwd(const struct optioninfo *oip, const char *value, char *key) {
673 static void of_help(const struct optioninfo *oip, const char *value, char *key) {
678 static void of_copyright(const struct optioninfo *oip, const char *value, char *key) {
680 " userv - user service daemon and client; copyright (C)1996-1999 Ian Jackson\n\n"
681 " This is free software; you can redistribute it and/or modify it under the\n"
682 " terms of the GNU General Public License as published by the Free Software\n"
683 " Foundation; either version 2 of the License, or (at your option) any\n"
684 " later version.\n\n"
685 " This program is distributed in the hope that it will be useful, but\n"
686 " WITHOUT ANY WARRANTY; without even the implied warranty of\n"
687 " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\n"
688 " Public License for more details.\n\n"
689 " You should have received a copy of the GNU General Public License along\n"
690 " with userv; if not, write to Ian Jackson <ian@davenant.greenend.org.uk> or\n"
691 " to the Free Software Foundation, 59 Temple Place - Suite 330, Boston,\n"
692 " MA 02111-1307, USA.\n",
693 stdout) < 0) syscallerror("write usage to stderr");
697 static void of_builtin(const struct optioninfo *oip, const char *value, char *key) {
698 overridetype= ot_builtin;
701 static void of_override(const struct optioninfo *oip, const char *value, char *key) {
702 overridetype= ot_string;
703 overridevalue= value;
706 static void of_overridefile(const struct optioninfo *oip,
707 const char *value, char *key) {
708 overridetype= ot_file;
709 overridevalue= value;
712 static void of_spoofuser(const struct optioninfo *oip,
713 const char *value, char *key) {
717 const struct optioninfo optioninfos[]= {
718 { 'f', "file", 2, of_file },
719 { 'w', "fdwait", 2, of_fdwait },
720 { 'D', "defvar", 2, of_defvar },
721 { 't', "timeout", 1, of_timeout },
722 { 'S', "signals", 1, of_signals },
723 { 'P', "sigpipe", 0, of_sigpipe },
724 { 'H', "hidecwd", 0, of_hidecwd },
725 { 'B', "builtin", 0, of_builtin },
726 { 'h', "help", 0, of_help },
727 { 0, "copyright", 0, of_copyright },
728 { 0, "override", 1, of_override },
729 { 0, "override-file", 1, of_overridefile },
730 { 0, "spoof-user", 1, of_spoofuser },
734 static void callvalueoption(const struct optioninfo *oip, char *arg) {
736 if (oip->values == 2) {
737 equals= strchr(arg,'=');
740 usageerror("option --%s (-%c) passed argument `%s' with no `='",
741 oip->full,oip->abbrev,arg);
743 usageerror("option --%s passed argument `%s' with no `='",
747 (oip->fn)(oip,equals,arg);
749 (oip->fn)(oip,arg,0);
754 * Main thread main processing functions - in order of execution.
757 static void security_init(void) {
758 /* May not open any file descriptors. */
760 mypid= getpid(); if (mypid == (pid_t)-1) syscallerror("getpid");
761 myuid= getuid(); if (myuid == (uid_t)-1) syscallerror("getuid");
762 mygid= getgid(); if (mygid == (gid_t)-1) syscallerror("getgid");
763 ngids= getgroups(0,0); if (ngids == (gid_t)-1) syscallerror("getgroups(0,0)");
764 gidarray= xmalloc(sizeof(gid_t)*ngids);
765 if (getgroups(ngids,gidarray) != ngids) syscallerror("getgroups(ngids,)");
769 if (ngids > MAX_GIDS) miscerror("caller is in far too many gids");
772 static void parse_arguments(int *argcp, char *const **argvp) {
773 static char fd0key[]= "stdin,fd,read";
774 static char fd1key[]= "stdout,fd,write";
775 static char fd2key[]= "stderr,fd,write";
779 const struct optioninfo *oip;
783 of_file(0,"stdin",fd0key);
784 of_file(0,"stdout",fd1key);
785 of_file(0,"stderr",fd2key);
787 for (argpp= *argvp+1;
788 (argp= *argpp) && *argp == '-' && argp[1];
790 if (!*++argp) usageerror("unknown option/argument `%s'",*argpp);
791 if (*argp == '-') { /* Two hyphens */
792 if (!*++argp) { argpp++; break; /* End of options. */ }
793 for (oip= optioninfos; oip->full && strcmp(oip->full,argp); oip++);
794 if (!oip->full) usageerror("unknown long option `%s'",*argpp);
796 if (!argpp[1]) usageerror("long option `%s' needs a value",*argpp);
797 callvalueoption(oip,*++argpp);
802 for (; *argp; argp++) {
803 for (oip= optioninfos; oip->full && oip->abbrev != *argp; oip++);
804 if (!oip->full) usageerror("unknown short option `-%c' in argument `%s'",
810 if (!argpp[1]) usageerror("short option `-%c' in argument `%s' needs"
811 " a value",*argp,*argpp);
814 callvalueoption(oip,argp);
815 break; /* No more options in this argument, go on to the next one. */
822 if (overridetype == ot_builtin) {
825 if (!*argpp) usageerror("no service user given after options");
826 serviceuser= *argpp++;
828 if (!*argpp) usageerror(overridetype == ot_builtin ?
829 "no service name given after options and service user" :
830 "no builtin service given after options");
832 *argcp-= (argpp-*argvp);
835 if (*argcp > MAX_ARGSDEFVAR) usageerror("far too many arguments");
837 for (fd=0; fd<fdsetupsize; fd++) {
838 if (!fdsetup[fd].filename) continue;
839 if (fdsetup[fd].mods & (fdm_wait|fdm_nowait|fdm_close)) continue;
840 assert(fdsetup[fd].mods & (fdm_read|fdm_write));
841 fdsetup[fd].mods |= (fdsetup[fd].mods & fdm_read) ? fdm_close : fdm_wait;
845 static void determine_users(void) {
853 loginname= getenv("LOGNAME");
854 if (!loginname) loginname= getenv("USER");
856 pw= getpwnam(loginname);
857 if (!pw || pw->pw_uid != myuid) loginname= 0;
860 pw= getpwuid(myuid); if (!pw) miscerror("cannot determine your login name");
861 loginname= xstrsave(pw->pw_name);
864 if (!strcmp(serviceuser,"-")) serviceuser= loginname;
865 pw= getpwnam(serviceuser);
866 if (!pw) miscerror("requested service user `%s' is not a user",serviceuser);
867 serviceuid= pw->pw_uid;
869 if ((overridetype != ot_none || spoofuser) && myuid != 0 && myuid != serviceuid)
870 miscerror("--override and --spoof options only available to root or to"
871 " the user who will be providing the service");
874 loginname= spoofuser;
875 pw= getpwnam(loginname);
876 if (!pw) miscerror("spoofed login name `%s' is not valid",loginname);
877 spoofuid= pw->pw_uid;
878 spoofgid= pw->pw_gid;
879 ngidssize= ngids; ngids= 0;
882 gidarray= xrealloc(gidarray,sizeof(gid_t)*ngidssize);
884 gidarray[ngids++]= spoofgid;
885 while ((gr= getgrent())) { /* ouch! getgrent has no error behaviour! */
886 for (mem= gr->gr_mem; *mem && strcmp(*mem,loginname); mem++);
888 if (ngids>=ngidssize) {
889 if (ngids>=MAX_GIDS) miscerror("spoofed user is member of too many groups");
890 ngidssize= (ngids+5)<<1;
891 gidarray= xrealloc(gidarray,sizeof(gid_t)*ngidssize);
893 gidarray[ngids++]= gr->gr_gid;
898 static void determine_cwd(void) {
899 cwdbufsize= 0; cwdbuf= 0;
904 if (cwdbufsize > MAX_GENERAL_STRING) { cwdbufsize= 0; free(cwdbuf); break; }
905 cwdbufsize <<= 1; cwdbufsize+= 100;
906 cwdbuf= xrealloc(cwdbuf,cwdbufsize);
907 cwdbuf[cwdbufsize-1]= 0;
908 if (getcwd(cwdbuf,cwdbufsize-1)) { cwdbufsize= strlen(cwdbuf); break; }
909 if (errno != ERANGE) { cwdbufsize= 0; free(cwdbuf); break; }
913 static void process_override(const char *servicename) {
917 switch (overridetype) {
923 l= strlen(servicename);
924 if (l >= MAX_OVERRIDE_LEN-20)
925 miscerror("builtin service string is too long (%d, max is %d)",
926 l,MAX_OVERRIDE_LEN-21);
929 snprintf(ovbuf,l,"execute-builtin %s\n",servicename);
930 ovused= strlen(ovbuf);
933 l= strlen(overridevalue);
934 if (l >= MAX_OVERRIDE_LEN)
935 miscerror("override string is too long (%d, max is %d)",l,MAX_OVERRIDE_LEN-1);
937 snprintf(ovbuf,l+2,"%s\n",overridevalue);
941 ovfile= fopen(overridevalue,"r");
942 if (!ovfile) fsyscallerror("open overriding configuration file `%s'",overridevalue);
943 ovbuf= 0; ovavail= ovused= 0;
944 while ((c= getc(ovfile)) != EOF) {
945 if (!c) miscerror("overriding config file `%s' contains null(s)",overridevalue);
946 if (ovused >= MAX_OVERRIDE_LEN)
947 miscerror("override file is too long (max is %d)",MAX_OVERRIDE_LEN);
948 if (ovused >= ovavail) {
949 ovavail+=80; ovavail<<=2; ovbuf= xrealloc(ovbuf,ovavail);
953 if (ferror(ovfile) || fclose(ovfile))
954 fsyscallerror("read overriding configuration file `%s'",overridevalue);
955 ovbuf= xrealloc(ovbuf,ovused+1);
963 static int server_connect(void) {
964 struct sockaddr_un ssockname;
966 struct sigaction sig;
970 sigaddset(&sset,SIGCHLD);
971 sigaddset(&sset,SIGALRM);
972 sigaddset(&sset,SIGPIPE);
973 if (sigprocmask(SIG_UNBLOCK,&sset,0)) syscallerror("preliminarily unblock signals");
975 sig.sa_handler= SIG_IGN;
976 sigemptyset(&sig.sa_mask);
978 if (sigaction(SIGPIPE,&sig,0)) syscallerror("ignore sigpipe");
980 sfd= socket(AF_UNIX,SOCK_STREAM,0);
981 if (!sfd) syscallerror("create client socket");
983 assert(sizeof(ssockname.sun_path) > sizeof(RENDEZVOUSPATH));
984 ssockname.sun_family= AF_UNIX;
985 strcpy(ssockname.sun_path,RENDEZVOUSPATH);
987 while (connect(sfd,(struct sockaddr*)&ssockname,sizeof(ssockname))) {
988 if (errno == ECONNREFUSED || errno == ENOENT)
989 syscallerror("uservd daemon is not running - service not available");
991 fsyscallerror("unable to connect to uservd daemon: %m");
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 fsyscallerror("remove any old pipe `%s'",pipepathbuf);
1025 if (mkfifo(pipepathbuf,0600)) /* permissions are irrelevant */
1026 fsyscallerror("create pipe `%s'",pipepathbuf);
1027 tempfd= open(pipepathbuf,O_RDWR);
1028 if (tempfd<0) fsyscallerror("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) fsyscallerror("real open pipe `%s'",pipepathbuf);
1033 if (close(tempfd)) fsyscallerror("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.loginnamelen= strlen(loginname);
1049 request_mbuf.spoofed= spoofuser ? 1 : 0;
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(loginname,sizeof(*loginname)*request_mbuf.loginnamelen,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];
1132 for (fd=0; fd<fdsetupsize; fd++) {
1133 if (!fdsetup[fd].filename) continue;
1134 if (!(fdsetup[fd].mods & fdm_fd)) {
1136 open(fdsetup[fd].filename,fdsetup[fd].oflags|O_NOCTTY,0777);
1137 if (fdsetup[fd].copyfd<0)
1138 fsyscallerror("open file `%s' for fd %d",fdsetup[fd].filename,fd);
1140 blocksignals(SIG_BLOCK);
1142 fdsetup[fd].catpid= child;
1143 blocksignals(SIG_UNBLOCK);
1144 if (child==-1) fsyscallerror("fork for cat for fd %d",fd);
1146 snprintf(catnamebuf,sizeof(catnamebuf),"cat fd%d",fd);
1147 catnamebuf[sizeof(catnamebuf)-1]= 0;
1148 sig.sa_handler= SIG_DFL;
1149 sigemptyset(&sig.sa_mask);
1151 if (sigaction(SIGPIPE,&sig,0)) {
1152 fprintf(stderr,"userv: %s: reset sigpipe handler for cat: %s",
1153 catnamebuf,strerror(errno));
1156 reading= fdsetup[fd].mods & fdm_read;
1157 catdup(catnamebuf, fdsetup[fd].copyfd, reading ? 0 : 1);
1158 catdup(catnamebuf, fdsetup[fd].pipefd, reading ? 1 : 0);
1159 execl("/bin/cat",catnamebuf,(char*)0);
1160 fprintf(stderr,"userv: %s: cannot exec `cat': %s\n",catnamebuf,strerror(errno));
1163 if (fdsetup[fd].copyfd>2)
1164 if (close(fdsetup[fd].copyfd)) fsyscallerror("close real fd for %d",fd);
1165 if (close(fdsetup[fd].pipefd)) fsyscallerror("close pipe fd for %d",fd);
1169 static void server_sendconfirm(void) {
1170 struct event_msg event_mbuf;
1172 blocksignals(SIG_BLOCK);
1173 memset(&event_mbuf,0,sizeof(event_mbuf));
1174 event_mbuf.magic= EVENT_MAGIC;
1175 event_mbuf.type= et_confirm;
1176 xfwrite(&event_mbuf,sizeof(event_mbuf),swfile);
1178 blocksignals(SIG_UNBLOCK);
1181 static int server_awaitcompletion(void) {
1182 struct progress_msg progress_mbuf;
1184 getprogress(&progress_mbuf,srfile);
1185 if (progress_mbuf.type != pt_terminated)
1186 protoerror("progress message during execution phase"
1187 " unexpected type %d",progress_mbuf.type);
1190 return progress_mbuf.data.terminated.status;
1193 static void dispose_remaining_pipes(void) {
1197 blocksignals(SIG_BLOCK);
1198 for (fd=0; fd<fdsetupsize; fd++) {
1199 if (!(fdsetup[fd].catpid!=-1 && (fdsetup[fd].mods & fdm_close))) continue;
1200 if (kill(fdsetup[fd].catpid,SIGKILL)) fsyscallerror("kill cat for %d",fd);
1201 fdsetup[fd].killed= 1;
1203 blocksignals(SIG_UNBLOCK);
1206 blocksignals(SIG_BLOCK);
1208 fd<fdsetupsize && !(fdsetup[fd].catpid!=-1 && (fdsetup[fd].mods & fdm_wait));
1210 if (fd>=fdsetupsize) break;
1212 r= sigsuspend(&sset);
1213 if (r && errno != EINTR) syscallerror("sigsuspend failed in unexpected way");
1214 blocksignals(SIG_UNBLOCK);
1218 static void NONRETURNING process_exitstatus(int status) {
1219 blocksignals(SIG_BLOCK);
1221 if (systemerror) _exit(255);
1223 if (sigpipeok && signalsexit != se_stdout && WIFSIGNALED(status) &&
1224 WTERMSIG(status)==SIGPIPE && !WCOREDUMP(status)) status= 0;
1226 switch (signalsexit) {
1228 case se_numbernocore:
1229 if (WIFEXITED(status))
1230 _exit(WEXITSTATUS(status));
1231 else if (WIFSIGNALED(status))
1232 _exit(WTERMSIG(status) + (signalsexit==se_number && WCOREDUMP(status) ? 128 : 0));
1235 if (WIFEXITED(status))
1236 _exit(WEXITSTATUS(status)<=127 ? WEXITSTATUS(status) : 127);
1237 else if (WIFSIGNALED(status) && WTERMSIG(status)<=126)
1238 _exit(WTERMSIG(status)+128);
1241 printf("\n%d %d ",(status>>8)&0x0ff,status&0x0ff);
1242 if (WIFEXITED(status))
1243 printf("exited with code %d",WEXITSTATUS(status));
1244 else if (WIFSIGNALED(status))
1245 printf("killed by %s (signal %d)%s",
1246 strsignal(WTERMSIG(status)),WTERMSIG(status),
1247 WCOREDUMP(status) ? ", core dumped " : "");
1249 printf("unknown wait status");
1251 if (ferror(stdout) || fflush(stdout)) syscallerror("write exit status to stdout");
1254 if (WIFEXITED(status))
1255 _exit(WEXITSTATUS(status));
1256 else if (WIFSIGNALED(status))
1261 fprintf(stderr,"userv: unknown wait status %d\n",status);
1265 int main(int argc, char *const *argv) {
1266 int status, socketfd;
1269 # error Do not disable assertions in this security-critical code !
1273 parse_arguments(&argc,&argv);
1276 process_override(argv[0]);
1278 socketfd= server_connect();
1280 server_handshake(socketfd);
1281 server_preparepipes();
1282 server_sendrequest(argc,argv);
1284 priv_permanentlyrevokesuspended();
1286 server_awaitconfirm();
1287 prepare_asynchsignals();
1289 server_sendconfirm();
1290 status= server_awaitcompletion();
1292 dispose_remaining_pipes();
1293 process_exitstatus(status);