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.
35 #include <sys/types.h>
37 #include <sys/socket.h>
39 #include <sys/resource.h>
47 typedef void optionfunction(const struct optioninfo*, const char *value, char *key);
52 int values; /* 0: no value; 1: single value; 2: key and value */
56 enum fdmodifiervalues {
70 struct fdmodifierinfo {
77 const struct fdmodifierinfo fdmodifierinfos[]= {
84 { "overwrite", fdm_write|fdm_create|fdm_truncate,
85 fdm_read|fdm_fd|fdm_exclusive,
86 O_WRONLY|O_CREAT|O_TRUNC },
87 { "create", fdm_write|fdm_create,
90 { "creat", fdm_write|fdm_create,
93 { "exclusive", fdm_write|fdm_create|fdm_exclusive,
94 fdm_read|fdm_fd|fdm_truncate,
95 O_WRONLY|O_CREAT|O_EXCL },
96 { "excl", fdm_write|fdm_create|fdm_exclusive,
97 fdm_read|fdm_fd|fdm_truncate,
98 O_WRONLY|O_CREAT|O_EXCL },
99 { "truncate", fdm_write|fdm_truncate,
100 fdm_read|fdm_fd|fdm_exclusive,
101 O_WRONLY|O_CREAT|O_EXCL },
102 { "trunc", fdm_write|fdm_truncate,
103 fdm_read|fdm_fd|fdm_exclusive,
104 O_WRONLY|O_CREAT|O_EXCL },
105 { "append", fdm_write|fdm_append,
107 O_WRONLY|O_CREAT|O_APPEND },
108 { "sync", fdm_write|fdm_sync,
110 O_WRONLY|O_CREAT|O_SYNC },
112 fdm_nowait|fdm_close,
114 { "nowait", fdm_nowait,
117 { "close", fdm_close,
121 fdm_create|fdm_exclusive|fdm_truncate|fdm_append|fdm_sync,
126 struct fdsetupstate {
127 const char *filename;
129 int mods, oflags, pipefd, killed;
133 enum signalsexitspecials { se_number=-100, se_numbernocore, se_highbit, se_stdout };
134 enum overridetypes { ot_none, ot_string, ot_file };
136 static const char *serviceuser=0;
137 static uid_t serviceuid, myuid;
138 static struct fdsetupstate *fdsetup=0;
139 static int fdsetupsize=0;
140 static const char *(*defvarsarray)[2];
141 static int defvarsavail=0, defvarsused=0;
142 static unsigned long timeout=0;
143 static int signalsexit=254;
144 static int sigpipeok=0, hidecwd=0;
145 static int overridetype= ot_none;
146 static const char *overridevalue;
148 static FILE *srfile, *swfile;
150 static void blocksignals(int how) {
152 static const char blockerrmsg[]= "userv: failed to [un]block signals: ";
156 sigaddset(&set,SIGCHLD);
157 sigaddset(&set,SIGALRM);
158 if (sigprocmask(how,&set,0)) {
159 str= strerror(errno);
160 write(2,blockerrmsg,sizeof(blockerrmsg)-1);
161 write(2,str,strlen(str));
167 static void NONRETURNPRINTFFORMAT(1,2) miscerror(const char *fmt, ...) {
170 blocksignals(SIG_BLOCK);
172 fprintf(stderr,"userv: failure: ");
173 vfprintf(stderr,fmt,al);
174 fprintf(stderr,"\n");
178 static void NONRETURNPRINTFFORMAT(1,2) syscallerror(const char *fmt, ...) {
183 blocksignals(SIG_BLOCK);
185 fprintf(stderr,"userv: system call failure: ");
186 vfprintf(stderr,fmt,al);
187 fprintf(stderr,": %s\n",strerror(e));
191 static void NONRETURNING protoreaderror(FILE *file, const char *where) {
195 blocksignals(SIG_BLOCK);
197 fprintf(stderr,"userv: failure: read error %s: %s\n",where,strerror(e));
200 fprintf(stderr,"userv: internal failure: EOF from server %s\n",where);
205 static void NONRETURNPRINTFFORMAT(1,2) protoerror(const char *fmt, ...) {
208 blocksignals(SIG_BLOCK);
210 fprintf(stderr,"userv: internal failure: protocol error: ");
211 vfprintf(stderr,fmt,al);
212 fprintf(stderr,"\n");
217 static void priv_suspend(void) { }
218 static void priv_resume(void) { }
219 static void priv_permanentlyrevokesuspended(void) { }
221 static void priv_suspend(void) {
222 if (setreuid(0,myuid) != 0) syscallerror("suspend root setreuid(0,myuid)");
224 static void priv_resume(void) {
225 if (setreuid(myuid,0) != 0) syscallerror("resume root setreuid(myuid,0)");
227 static void priv_permanentlyrevokesuspended(void) {
228 if (setreuid(myuid,myuid) != 0) syscallerror("revoke root setreuid(myuid,myuid)");
229 if (setreuid(myuid,myuid) != 0) syscallerror("rerevoke root setreuid(myuid,myuid)");
231 if (!setreuid(myuid,0)) miscerror("revoked root but setreuid(0,0) succeeded !");
232 if (errno != EPERM) syscallerror("revoked and setreuid(myuid,0) unexpected error");
237 static void *xmalloc(size_t s) {
240 if (!p) syscallerror("malloc (%lu bytes)",(unsigned long)s);
244 static void *xrealloc(void *p, size_t s) {
246 if (!p) syscallerror("realloc (%lu bytes)",(unsigned long)s);
250 static void xfread(void *p, size_t sz, FILE *file) {
252 nr= fread(p,1,sz,file);
253 if (nr != sz) protoreaderror(file,"in data");
256 static void xfwrite(const void *p, size_t sz, FILE *file) {
258 nr= fwrite(p,1,sz,file); if (nr == sz) return;
259 syscallerror("writing to server");
262 static void xfwritestring(const char *s, FILE *file) {
265 xfwrite(&l,sizeof(l),file);
266 xfwrite(s,sizeof(*s)*l,file);
269 static void xfflush(FILE *file) {
270 if (fflush(file)) syscallerror("flush server socket");
273 static void usage(void) {
275 "usage: userv <options> [--] <service-user> <service-name> [<argument> ...]\n"
276 "options: -f|--file <fd>[<fdmodifiers>]=<filename>\n"
277 " -D|--defvar <name>=<value>\n"
278 " -t|--timeout <seconds>\n"
279 " -S|--signals <status>|number|number-nocore|highbit|stdout\n"
280 " -w|--fdwait <fd>=wait|nowait|close\n"
281 " -P|--sigpipe -H|--hidecwd -h|--help --copyright\n"
282 " --override <configuration-data> } available only to\n"
283 " --override-file <filename> } root or same user\n"
284 "fdmodifiers: read write overwrite trunc[ate]\n"
285 "(separate with commas) append sync excl[usive] creat[e] fd\n\n"
286 "userv and uservd are copyright (C)1996-1997 Ian Jackson.\n"
287 "They come with NO WARRANTY; type `userv --copyright' for details.\n")
288 == EOF) syscallerror("write usage to stderr");
291 static void NONRETURNPRINTFFORMAT(1,2) usageerror(const char *fmt, ...) {
294 fprintf(stderr,"userv: ");
295 vfprintf(stderr,fmt,al);
296 fprintf(stderr,"\n\n");
301 static void addfdmodifier(struct fdsetupstate *fdsus, int fd, const char *key) {
302 const struct fdmodifierinfo *fdmip;
305 for (fdmip= fdmodifierinfos; fdmip->string && strcmp(fdmip->string,key); fdmip++);
306 if (!fdmip->string) usageerror("unknown fdmodifer `%s' for fd %d",key,fd);
307 if (fdmip->conflicts & fdsetup[fd].mods)
308 usageerror("fdmodifier `%s' conflicts with another for fd %d",key,fd);
309 fdsetup[fd].mods |= fdmip->implies;
310 fdsetup[fd].oflags |= fdmip->oflags;
313 static int fdstdnumber(const char *string) {
314 if (!strcmp(string,"stdin")) return 0;
315 else if (!strcmp(string,"stdout")) return 1;
316 else if (!strcmp(string,"stderr")) return 2;
320 static void of_file(const struct optioninfo *oip, const char *value, char *key) {
321 unsigned long fd, copyfd;
326 fd= strtoul(key,&delim,10);
328 delim= strchr(key,',');
329 if (delim) *delim++= 0;
330 fd= fdstdnumber(key);
331 if (fd<0) usageerror("first part of argument to -f or --file must be numeric "
332 "file descriptor or `stdin', `stdout' or `stderr' - `%s' "
333 "is not recognized",key);
335 if (fd > MAX_ALLOW_FD)
336 usageerror("file descriptor specified (%lu) is larger than maximum allowed (%d)",
338 if (fd >= fdsetupsize) {
339 oldarraysize= fdsetupsize;
340 fdsetupsize+=2; fdsetupsize<<=1;
341 fdsetup= xrealloc(fdsetup,sizeof(struct fdsetupstate)*fdsetupsize);
342 while (oldarraysize < fdsetupsize) {
343 fdsetup[oldarraysize].filename= 0;
344 fdsetup[oldarraysize].copyfd= -1;
345 fdsetup[oldarraysize].mods= 0;
346 fdsetup[oldarraysize].catpid= -1;
347 fdsetup[oldarraysize].killed= 0;
348 fdsetup[oldarraysize++].filename= 0;
352 fdsetup[fd].filename= value;
353 fdsetup[fd].oflags= 0;
355 fdsetup[fd].copyfd= -1;
356 while (delim && *delim) {
358 delim= strchr(key,',');
359 if (delim) *delim++= 0;
360 addfdmodifier(&fdsetup[fd],fd,key);
362 if (!(fdsetup[fd].mods & (fdm_read|fdm_write))) {
363 if (fd != 1 && fd != 2) {
364 addfdmodifier(&fdsetup[fd],fd,"read");
365 } else if (fdsetup[fd].mods & fdm_fd) {
366 addfdmodifier(&fdsetup[fd],fd,"write");
368 addfdmodifier(&fdsetup[fd],fd,"overwrite");
371 if (fdsetup[fd].mods & fdm_fd) {
372 copyfd= fdstdnumber(value);
374 copyfd= strtoul(value,&delim,0);
376 usageerror("value part of argument to --file with fd modifier must be "
377 "numeric or fd name- `%s' is not recognised",value);
378 else if (copyfd > MAX_ALLOW_FD)
379 usageerror("file descriptor %lu named as target of file descriptor redirection"
380 " (for file descriptor %lu) is larger than maximum allowed (%d)",
381 copyfd,fd,MAX_ALLOW_FD);
383 do { r= fstat(copyfd,&stab); } while (r && errno==EINTR);
385 if (oip) syscallerror("check filedescriptor %lu (named as target of file "
386 "descriptor redirection for %lu)",copyfd,fd);
387 else syscallerror("check basic filedescriptor %lu at program start",copyfd);
389 fdsetup[fd].copyfd= copyfd;
393 static void of_fdwait(const struct optioninfo *oip, const char *value, char *key) {
394 const struct fdmodifierinfo *fdmip;
399 fd= fdstdnumber(key);
401 ul= strtoul(key,&delim,0);
402 if (*delim) usageerror("first part of argument to --fdwait must be "
403 "numeric or fd name - `%s' is not recognised",key);
404 if (ul>INT_MAX) usageerror("first part of argument to --fdwait is far too large");
407 if (fd >= fdsetupsize || !fdsetup[fd].filename)
408 usageerror("file descriptor %d specified in --fdwait option is not open",fd);
409 for (fdmip= fdmodifierinfos; fdmip->string && strcmp(fdmip->string,value); fdmip++);
410 if (!fdmip->string || !(fdmip->implies & (fdm_wait|fdm_nowait|fdm_close)))
411 usageerror("value for --fdwait must be `wait', `nowait' or `close', not `%s'",value);
412 fdsetup[fd].mods &= ~(fdm_wait|fdm_nowait|fdm_close);
413 fdsetup[fd].mods |= fdmip->implies;
416 static void of_defvar(const struct optioninfo *oip, const char *value, char *key) {
419 for (i=0; i<defvarsused && strcmp(defvarsarray[i][0],key); i++);
420 if (i>=defvarsavail) {
421 defvarsavail+=10; defvarsavail<<=1;
422 defvarsarray= xrealloc(defvarsarray,sizeof(const char*)*2*defvarsavail);
424 if (i==defvarsused) defvarsused++;
425 defvarsarray[i][0]= key;
426 defvarsarray[i][1]= value;
429 static void of_timeout(const struct optioninfo *oip, const char *value, char *key) {
431 timeout= strtoul(value,&endp,0);
432 if (*endp) usageerror("timeout value `%s' must be a plain decimal string",value);
433 if (timeout>INT_MAX) usageerror("timeout value %lu too large",timeout);
436 static void of_signals(const struct optioninfo *oip, const char *value, char *key) {
437 unsigned long numvalue;
439 numvalue= strtoul(value,&endp,0);
441 if (!strcmp(value,"number")) signalsexit= se_number;
442 else if (!strcmp(value,"number-nocore")) signalsexit= se_numbernocore;
443 else if (!strcmp(value,"highbit")) signalsexit= se_highbit;
444 else if (!strcmp(value,"stdout")) signalsexit= se_stdout;
445 else usageerror("value `%s' for --signals not understood",value);
447 if (numvalue<0 || numvalue>255)
448 usageerror("value %lu for --signals not 0...255",numvalue);
449 signalsexit= numvalue;
453 static void of_sigpipe(const struct optioninfo *oip, const char *value, char *key) {
457 static void of_hidecwd(const struct optioninfo *oip, const char *value, char *key) {
461 static void of_help(const struct optioninfo *oip, const char *value, char *key) {
466 static void of_copyright(const struct optioninfo *oip, const char *value, char *key) {
468 " userv - user service daemon and client; copyright (C)1996-1997 Ian Jackson\n\n"
469 " This is free software; you can redistribute it and/or modify it under the\n"
470 " terms of the GNU General Public License as published by the Free Software\n"
471 " Foundation; either version 2 of the License, or (at your option) any\n"
472 " later version.\n\n"
473 " This program is distributed in the hope that it will be useful, but\n"
474 " WITHOUT ANY WARRANTY; without even the implied warranty of\n"
475 " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\n"
476 " Public License for more details.\n\n"
477 " You should have received a copy of the GNU General Public License along\n"
478 " with userv; if not, write to Ian Jackson <ian@chiark.greenend.org.uk> or\n"
479 " to the Free Software Foundation, 59 Temple Place - Suite 330, Boston,\n"
480 " MA 02111-1307, USA.\n"
481 ) == EOF) syscallerror("write usage to stderr");
485 static void of_override(const struct optioninfo *oip, const char *value, char *key) {
486 overridetype= ot_string;
487 overridevalue= value;
490 static void of_overridefile(const struct optioninfo *oip,
491 const char *value, char *key) {
492 overridetype= ot_file;
493 overridevalue= value;
496 const struct optioninfo optioninfos[]= {
497 { 'f', "file", 2, of_file },
498 { 'w', "fdwait", 2, of_fdwait },
499 { 'D', "defvar", 2, of_defvar },
500 { 't', "timeout", 1, of_timeout },
501 { 'S', "signals", 1, of_signals },
502 { 'P', "sigpipe", 0, of_sigpipe },
503 { 'H', "hidecwd", 0, of_hidecwd },
504 { 'h', "help", 0, of_help },
505 { 0, "copyright", 0, of_copyright },
506 { 0, "override", 1, of_override },
507 { 0, "override-file", 1, of_overridefile },
511 static void callvalueoption(const struct optioninfo *oip, char *arg) {
513 if (oip->values == 2) {
514 equals= strchr(arg,'=');
517 usageerror("option --%s (-%c) passed argument `%s' with no `='",
518 oip->full,oip->abbrev,arg);
520 usageerror("option --%s passed argument `%s' with no `='",
523 (oip->fn)(oip,equals,arg);
525 (oip->fn)(oip,arg,0);
529 static void checkmagic(unsigned long was, unsigned long should, const char *when) {
531 protoerror("magic number %s was %08lx, expected %08lx",when,was,should);
534 static void getprogress(struct progress_msg *progress_r, FILE *file) {
539 xfread(progress_r,sizeof(struct progress_msg),file);
540 switch (progress_r->type) {
542 blocksignals(SIG_BLOCK);
543 fputs("userv: uservd reports that service failed\n",stderr);
546 blocksignals(SIG_BLOCK);
547 fputs("uservd: ",stderr);
548 if (progress_r->data.errmsg.messagelen>4096)
549 protoerror("stderr message length %d is far too long",
550 progress_r->data.errmsg.messagelen);
551 for (i=0; i<progress_r->data.errmsg.messagelen; i++) {
552 c= getc(file); if (c==EOF) protoreaderror(file,"in error message");
553 if (isprint(c)) putc(c,stderr);
554 else fprintf(stderr,"\\x%02x",(unsigned char)c);
557 if (ferror(stderr)) syscallerror("printing error message");
558 xfread(&ul,sizeof(ul),file);
559 checkmagic(ul,PROGRESS_ERRMSG_END_MAGIC,"after error message");
560 blocksignals(SIG_UNBLOCK);
568 static void xfwritefds(int modifier, int expected, FILE *file) {
571 for (i=0, fdcount=0; i<fdsetupsize; i++) {
572 if (!(fdsetup[i].filename && (fdsetup[i].mods & modifier)))
574 xfwrite(&i,sizeof(int),file); fdcount++;
576 assert(fdcount == expected);
579 static void disconnect(void) /* DOES return, unlike in daemon */ {
580 struct event_msg event_mbuf;
583 fputs("userv: failed, after service program terminated\n",stderr);
586 memset(&event_mbuf,0,sizeof(event_mbuf));
587 event_mbuf.magic= EVENT_MAGIC;
588 event_mbuf.type= et_disconnect;
589 xfwrite(&event_mbuf,sizeof(event_mbuf),swfile);
593 static void sighandler_alrm(int ignored) /* DOES return, unlike in daemon */ {
596 fputs("userv: timeout\n",stderr);
601 static void sighandler_chld(int ignored) /* DOES return, unlike in daemon */ {
602 struct event_msg event_mbuf;
604 int status, fd, r, es;
608 child= wait3(&status,WNOHANG,0);
609 if (child == 0 || (child == -1 && errno == ECHILD)) break;
610 if (child == -1) syscallerror("wait for child process (in sigchld handler)");
611 for (fd=0; fd<fdsetupsize && fdsetup[fd].catpid != child; fd++);
612 if (fd>=fdsetupsize) continue; /* perhaps the invoker gave us children */
613 if ((WIFEXITED(status) && WEXITSTATUS(status)==0) ||
614 (WIFSIGNALED(status) && WTERMSIG(status)==SIGPIPE) ||
615 (fdsetup[fd].killed && WIFSIGNALED(status) && WTERMSIG(status)==SIGKILL)) {
616 if (swfile && fdsetup[fd].mods & fdm_read) {
617 memset(&event_mbuf,0,sizeof(event_mbuf));
618 event_mbuf.magic= EVENT_MAGIC;
619 event_mbuf.type= et_closereadfd;
620 r= fwrite(&event_mbuf,1,sizeof(event_mbuf),swfile);
621 if (r != sizeof(event_mbuf) || fflush(swfile))
622 if (errno != EPIPE) syscallerror("inform service of closed read fd");
625 if (WIFEXITED(status))
626 fprintf(stderr,"userv: cat for fd %d exited with error exit status %d\n",
627 fd,WEXITSTATUS(status));
628 else if (WIFSIGNALED(status))
629 if (WCOREDUMP(status))
630 fprintf(stderr,"userv: cat for fd %d dumped core due to signal %s (%d)\n",
631 fd,strsignal(WTERMSIG(status)),WTERMSIG(status));
633 fprintf(stderr,"userv: cat for fd %d terminated by signal %s (%d)\n",
634 fd,strsignal(WTERMSIG(status)),WTERMSIG(status));
636 fprintf(stderr,"userv: cat for fd %d gave unknown wait status %d\n",
640 fdsetup[fd].catpid= -1;
645 static void catdup(const char *which, int from, int to) {
646 if (dup2(from,to)<0) {
647 blocksignals(SIG_BLOCK);
648 fprintf(stderr,"userv: %s: cannot dup for %s: %s\n",which,
649 to?"stdout":"stdin", strerror(errno));
654 int main(int argc, char *const *argv) {
655 static char fd0key[]= "stdin,fd,read";
656 static char fd1key[]= "stdout,fd,write";
657 static char fd2key[]= "stderr,fd,write";
658 static char stderrbuf[BUFSIZ], stdoutbuf[1024];
662 const struct optioninfo *oip;
663 struct sockaddr_un ssockname;
664 int sfd, ngids, i, j, tempfd, l, c, reading, fd, r, status;
669 struct opening_msg opening_mbuf;
670 struct request_msg request_mbuf;
671 struct progress_msg progress_mbuf;
672 struct event_msg event_mbuf;
674 gid_t mygid, *gidarray;
680 char pipepathbuf[PIPEPATHMAXLEN], catnamebuf[sizeof(int)*3+30];
681 struct sigaction sig;
684 # error Do not disable assertions in this security-critical code !
687 mypid= getpid(); if (mypid == (pid_t)-1) syscallerror("getpid");
688 myuid= getuid(); if (myuid == (uid_t)-1) syscallerror("getuid");
689 mygid= getgid(); if (mygid == (gid_t)-1) syscallerror("getgid");
690 ngids= getgroups(0,0); if (ngids == (gid_t)-1) syscallerror("getgroups(0,0)");
691 gidarray= xmalloc(sizeof(gid_t)*ngids);
692 if (getgroups(ngids,gidarray) != ngids) syscallerror("getgroups(ngids,)");
696 of_file(0,"stdin",fd0key);
697 of_file(0,"stdout",fd1key);
698 of_file(0,"stderr",fd2key);
701 (argp= *argpp) && *argp == '-';
703 if (!*++argp) usageerror("unknown option/argument `%s'",*argpp);
704 if (*argp == '-') { /* Two hyphens */
705 if (!*++argp) { argpp++; break; /* End of options. */ }
706 for (oip= optioninfos; oip->full && strcmp(oip->full,argp); oip++);
707 if (!oip->full) usageerror("unknown long option `%s'",*argpp);
709 if (!argpp[1]) usageerror("long option `%s' needs a value",*argpp);
710 callvalueoption(oip,*++argpp);
715 for (; *argp; argp++) {
716 for (oip= optioninfos; oip->full && oip->abbrev != *argp; oip++);
717 if (!oip->full) usageerror("unknown short option `-%c' in argument `%s'",
723 if (!argpp[1]) usageerror("short option `-%c' in argument `%s' needs"
724 " a value",*argp,*argpp);
727 callvalueoption(oip,argp);
728 break; /* No more options in this argument, go on to the next one. */
735 if (!*argpp) usageerror("no service user given after options");
736 serviceuser= *argpp++;
737 if (!*argpp) usageerror("no service name given after options and service user");
739 for (fd=0; fd<fdsetupsize; fd++) {
740 if (!fdsetup[fd].filename) continue;
741 if (fdsetup[fd].mods & (fdm_wait|fdm_nowait|fdm_close)) continue;
742 assert(fdsetup[fd].mods & (fdm_read|fdm_write));
743 fdsetup[fd].mods |= (fdsetup[fd].mods & fdm_read) ? fdm_close : fdm_wait;
746 if (setvbuf(stderr,stderrbuf,_IOLBF,sizeof(stderrbuf)))
747 syscallerror("set buffering on stderr");
748 if (setvbuf(stdout,stdoutbuf,_IOFBF,sizeof(stdoutbuf)))
749 syscallerror("set buffering on stdout");
754 pw= getpwnam(serviceuser);
755 if (!pw) miscerror("requested service user `%s' is not a user",serviceuser);
756 serviceuid= pw->pw_uid;
758 if (overridetype != ot_none && myuid != 0 && myuid != serviceuid)
759 miscerror("--override options only available to root or to"
760 " the user who will be providing the service");
762 logname= getenv("LOGNAME");
763 if (!logname) logname= getenv("USER");
765 pw= getpwnam(logname);
766 if (!pw || pw->pw_uid != myuid) logname= 0;
769 pw= getpwuid(myuid); if (!pw) syscallerror("cannot determine your login name");
770 logname= pw->pw_name;
773 cwdbufsize= 0; cwdbuf= 0;
776 assert(cwdbufsize < INT_MAX/3);
777 cwdbufsize <<= 1; cwdbufsize+= 100;
778 cwdbuf= xrealloc(cwdbuf,cwdbufsize);
779 cwdbuf[cwdbufsize-1]= 0;
780 if (getcwd(cwdbuf,cwdbufsize-1)) { cwdbufsize= strlen(cwdbuf); break; }
781 if (errno != ERANGE) { cwdbufsize= 0; break; }
785 switch (overridetype) {
791 l= strlen(overridevalue);
792 if (l >= MAX_OVERRIDE_LEN)
793 miscerror("override string is too long (%d, max is %d)",l,MAX_OVERRIDE_LEN-1);
795 strcpy(ovbuf,overridevalue);
800 ovfile= fopen(overridevalue,"r");
801 if (!ovfile) syscallerror("open overriding configuration file `%s'",overridevalue);
802 ovbuf= 0; ovavail= ovused= 0;
803 while ((c= getc(ovfile)) != EOF) {
804 if (!c) miscerror("overriding config file `%s' contains null(s)",overridevalue);
805 if (ovused >= MAX_OVERRIDE_LEN)
806 miscerror("override file is too long (max is %d)",MAX_OVERRIDE_LEN);
807 if (ovused >= ovavail) {
808 ovavail+=80; ovavail<<=2; ovbuf= xrealloc(ovbuf,ovavail);
812 if (ferror(ovfile) || fclose(ovfile))
813 syscallerror("read overriding configuration file `%s'",overridevalue);
814 ovbuf= xrealloc(ovbuf,ovused+1);
821 sig.sa_handler= SIG_IGN;
822 sigemptyset(&sig.sa_mask);
824 if (sigaction(SIGPIPE,&sig,0)) syscallerror("ignore sigpipe");
826 sfd= socket(AF_UNIX,SOCK_STREAM,0);
827 if (!sfd) syscallerror("create client socket");
829 assert(sizeof(ssockname.sun_path) > sizeof(RENDEZVOUSPATH));
830 ssockname.sun_family= AF_UNIX;
831 strcpy(ssockname.sun_path,RENDEZVOUSPATH);
833 while (connect(sfd,(struct sockaddr*)&ssockname,sizeof(ssockname))) {
834 if (errno == ECONNREFUSED || errno == ENOENT)
835 syscallerror("uservd daemon is not running - service not available");
836 syscallerror("unable to connect to uservd daemon");
840 srfile= fdopen(sfd,"r");
841 if (!srfile) syscallerror("turn socket fd into FILE* for read");
842 if (setvbuf(srfile,0,_IOFBF,BUFSIZ)) syscallerror("set buffering on socket reads");
844 swfile= fdopen(sfd,"w");
845 if (!swfile) syscallerror("turn socket fd into FILE* for write");
846 if (setvbuf(swfile,0,_IOFBF,BUFSIZ)) syscallerror("set buffering on socket writes");
848 xfread(&opening_mbuf,sizeof(opening_mbuf),srfile);
849 checkmagic(opening_mbuf.magic,OPENING_MAGIC,"in opening message");
850 if (memcmp(protocolchecksumversion,opening_mbuf.protocolchecksumversion,PCSUMSIZE))
851 protoerror("protocol version checksum mismatch - server not same as client");
853 for (fd=0; fd<fdsetupsize; fd++) {
854 if (!fdsetup[fd].filename) continue;
855 sprintf(pipepathbuf, PIPEPATHFORMAT,
856 (unsigned long)mypid, (unsigned long)opening_mbuf.serverpid, fd);
858 if (unlink(pipepathbuf) && errno != ENOENT)
859 syscallerror("remove any old pipe `%s'",pipepathbuf);
860 if (mkfifo(pipepathbuf,0600)) /* permissions are irrelevant */
861 syscallerror("create pipe `%s'",pipepathbuf);
862 tempfd= open(pipepathbuf,O_RDWR);
863 if (tempfd == -1) syscallerror("prelim open pipe `%s' for read+write",pipepathbuf);
864 assert(fdsetup[fd].mods & (fdm_read|fdm_write));
866 open(pipepathbuf, (fdsetup[fd].mods & fdm_read) ? O_WRONLY : O_RDONLY);
867 if (fdsetup[fd].pipefd == -1) syscallerror("real open pipe `%s'",pipepathbuf);
868 if (close(tempfd)) syscallerror("close prelim fd onto pipe `%s'",pipepathbuf);
872 memset(&request_mbuf,0,sizeof(request_mbuf));
873 request_mbuf.magic= REQUEST_MAGIC;
874 request_mbuf.clientpid= getpid();
875 request_mbuf.serviceuserlen= strlen(serviceuser);
876 request_mbuf.servicelen= strlen(argv[0]);
877 request_mbuf.lognamelen= strlen(logname);
878 request_mbuf.cwdlen= cwdbufsize;
879 request_mbuf.callinguid= myuid;
880 request_mbuf.ngids= ngids+1;
881 request_mbuf.nreadfds= 0;
882 request_mbuf.nwritefds= 0;
883 for (fd=0; fd<fdsetupsize; fd++) {
884 if (!fdsetup[fd].filename) continue;
885 assert(fdsetup[fd].mods & (fdm_write|fdm_read));
886 if (fdsetup[fd].mods & fdm_write) request_mbuf.nwritefds++;
887 else request_mbuf.nreadfds++;
889 request_mbuf.nargs= argc-1;
890 request_mbuf.nvars= defvarsused;
891 request_mbuf.overridelen= ovused;
892 xfwrite(&request_mbuf,sizeof(request_mbuf),swfile);
893 xfwrite(serviceuser,sizeof(*serviceuser)*request_mbuf.serviceuserlen,swfile);
894 xfwrite(argv[0],sizeof(*argv[0])*request_mbuf.servicelen,swfile);
895 xfwrite(logname,sizeof(*logname)*request_mbuf.lognamelen,swfile);
896 xfwrite(cwdbuf,sizeof(*cwdbuf)*request_mbuf.cwdlen,swfile);
897 if (ovused>=0) xfwrite(ovbuf,sizeof(*ovbuf)*ovused,swfile);
898 xfwrite(&mygid,sizeof(gid_t),swfile);
899 xfwrite(gidarray,sizeof(gid_t)*ngids,swfile);
900 xfwritefds(fdm_read,request_mbuf.nreadfds,swfile);
901 xfwritefds(fdm_write,request_mbuf.nwritefds,swfile);
902 for (i=1; i<argc; i++)
903 xfwritestring(argv[i],swfile);
904 for (i=0; i<defvarsused; i++)
906 xfwritestring(defvarsarray[i][j],swfile);
907 ul= REQUEST_END_MAGIC; xfwrite(&ul,sizeof(ul),swfile);
910 priv_permanentlyrevokesuspended(); /* Must not do this before we give our real id */
912 getprogress(&progress_mbuf,srfile);
913 if (progress_mbuf.type != pt_ok)
914 protoerror("progress message during configuration phase"
915 " unexpected type %d",progress_mbuf.type);
917 sig.sa_handler= sighandler_chld;
918 sigemptyset(&sig.sa_mask);
919 sigaddset(&sig.sa_mask,SIGCHLD);
920 sigaddset(&sig.sa_mask,SIGALRM);
922 if (sigaction(SIGCHLD,&sig,0)) syscallerror("set up sigchld handler");
924 sig.sa_handler= sighandler_alrm;
925 if (sigaction(SIGALRM,&sig,0)) syscallerror("set up sigalrm handler");
927 for (fd=0; fd<fdsetupsize; fd++) {
928 if (!fdsetup[fd].filename) continue;
929 if (!(fdsetup[fd].mods & fdm_fd)) {
931 open(fdsetup[fd].filename,fdsetup[fd].oflags,0777);
932 if (fdsetup[fd].copyfd<0)
933 syscallerror("open file `%s' for fd %d",fdsetup[fd].filename,fd);
935 fdsetup[fd].catpid= fork();
936 if (fdsetup[fd].catpid==-1) syscallerror("fork for cat for fd %d",fd);
937 if (!fdsetup[fd].catpid) {
938 snprintf(catnamebuf,sizeof(catnamebuf),"cat fd%d",fd);
939 sig.sa_handler= SIG_DFL;
940 sigemptyset(&sig.sa_mask);
942 if (sigaction(SIGPIPE,&sig,0)) {
943 fprintf(stderr,"userv: %s: reset sigpipe handler for cat: %s",
944 catnamebuf,strerror(errno));
947 catnamebuf[sizeof(catnamebuf)-1]= 0;
948 reading= fdsetup[fd].mods & fdm_read;
949 catdup(catnamebuf, fdsetup[fd].copyfd, reading ? 0 : 1);
950 catdup(catnamebuf, fdsetup[fd].pipefd, reading ? 1 : 0);
951 execlp("cat",catnamebuf,(char*)0);
952 fprintf(stderr,"userv: %s: cannot exec `cat': %s\n",catnamebuf,strerror(errno));
955 if (fdsetup[fd].copyfd>2)
956 if (close(fdsetup[fd].copyfd)) syscallerror("close real fd for %d",fd);
957 if (close(fdsetup[fd].pipefd)) syscallerror("close pipe fd for %d",fd);
961 if (alarm(timeout)<0) syscallerror("set up timeout alarm");
963 blocksignals(SIG_BLOCK);
964 memset(&event_mbuf,0,sizeof(event_mbuf));
965 event_mbuf.magic= EVENT_MAGIC;
966 event_mbuf.type= et_confirm;
967 xfwrite(&event_mbuf,sizeof(event_mbuf),swfile);
969 blocksignals(SIG_UNBLOCK);
971 getprogress(&progress_mbuf,srfile);
972 if (progress_mbuf.type != pt_terminated)
973 protoerror("progress message during execution phase"
974 " unexpected type %d",progress_mbuf.type);
978 blocksignals(SIG_BLOCK);
979 for (fd=0; fd<fdsetupsize; fd++) {
980 if (!(fdsetup[fd].catpid!=-1 && (fdsetup[fd].mods & fdm_close))) continue;
981 if (kill(fdsetup[fd].catpid,SIGKILL)) syscallerror("kill cat for %d",fd);
982 fdsetup[fd].killed= 1;
984 blocksignals(SIG_UNBLOCK);
987 blocksignals(SIG_BLOCK);
989 fd<fdsetupsize && !(fdsetup[fd].catpid!=-1 && (fdsetup[fd].mods & fdm_wait));
991 if (fd>=fdsetupsize) break;
993 r= sigsuspend(&sset);
994 if (r && errno != EINTR) syscallerror("sigsuspend failed in unexpected way");
995 blocksignals(SIG_UNBLOCK);
998 blocksignals(SIG_BLOCK);
1000 status= progress_mbuf.data.terminated.status;
1001 if (sigpipeok && signalsexit != se_stdout && WIFSIGNALED(status) &&
1002 WTERMSIG(status)==SIGPIPE && !WCOREDUMP(status)) status= 0;
1004 switch (signalsexit) {
1006 case se_numbernocore:
1007 if (WIFEXITED(status))
1008 _exit(WEXITSTATUS(status));
1009 else if (WIFSIGNALED(status))
1010 _exit(WTERMSIG(status) + (signalsexit==se_number && WCOREDUMP(status) ? 128 : 0));
1013 if (WIFEXITED(status))
1014 _exit(WEXITSTATUS(status)<=127 ? WEXITSTATUS(status) : 127);
1015 else if (WIFSIGNALED(status) && WTERMSIG(status)<=126)
1016 _exit(WTERMSIG(status)+128);
1019 printf("\n%d %d ",(status>>8)&0x0ff,status&0x0ff);
1020 if (WIFEXITED(status))
1021 printf("exited with code %d",WEXITSTATUS(status));
1022 else if (WIFSIGNALED(status))
1023 printf("killed by %s (signal %d)%s",
1024 strsignal(WTERMSIG(status)),WTERMSIG(status),
1025 WCOREDUMP(status) ? ", core dumped " : "");
1027 printf("unknown wait status");
1029 if (ferror(stdout) || fflush(stdout)) syscallerror("write exit status to stdout");
1032 if (WIFEXITED(status))
1033 _exit(WEXITSTATUS(status));
1034 else if (WIFSIGNALED(status))
1039 fprintf(stderr,"unknown wait status %d\n",status);