3 * daemon code to process one request (is parent of service process)
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.
22 /* We do some horrible asynchronous stuff with signals.
24 * The following objects &c. are used in signal handlers and so
25 * must be protected by calls to blocksignals if they are used in
27 * the syslog() family of calls, and the associated
28 * syslogopenfacility variable
29 * swfile (stdio stream)
31 * The following objects are used in the main program unprotected
32 * and so must not be used in signal handlers:
35 * child and childtokill are used for communication between the
36 * main thread and the signal handlers; none of the signal handlers
37 * return so errno is OK too.
54 #include <sys/types.h>
55 #include <sys/fcntl.h>
57 #include <sys/socket.h>
66 /* NB: defaults for the execution state are not set here, but in
67 * the RESET_CONFIGURATION #define in daemon.h. */
68 struct request_msg request_mbuf;
69 struct keyvaluepair *defvararray;
70 struct fdstate *fdarray;
71 int fdarraysize, fdarrayused;
72 int restfdwantstate= tokv_word_rejectfd, restfdwantrw;
75 char *serviceuser, *service, *logname, *cwd;
76 char *overridedata, *userrcfile;
77 char *serviceuser_dir, *serviceuser_shell, *callinguser_shell;
78 gid_t *calling_gids, *service_gids;
79 uid_t serviceuser_uid=-1;
80 const char **calling_groups, **service_groups;
81 char *execpath, **execargs;
83 int setenvironment, suppressargs, disconnecthup;
84 builtinserviceexec_fnt *execbuiltin;
85 int syslogopenfacility=-1;
87 static FILE *swfile, *srfile;
88 static pid_t child=-1, childtokill=-1;
91 /* Function shared with servexec.c: */
93 int synchread(int fd, int ch) {
98 r= read(fd,&synchmsg,1);
100 if (r==0) { errno= ECONNRESET; return -1; }
102 if (errno!=EINTR) return -1;
104 assert(synchmsg==ch);
108 const char *defaultpath(void) {
109 return serviceuser_uid ? DEFAULTPATH_USER : DEFAULTPATH_ROOT;
112 /* General-purpose functions; these do nothing special about signals */
114 static void blocksignals(void) {
119 sigaddset(&set,SIGCHLD);
120 sigaddset(&set,SIGPIPE);
121 r= sigprocmask(SIG_BLOCK,&set,0); assert(!r);
124 static void xfwriteerror(void) {
125 if (errno != EPIPE) syscallerror("writing to client");
127 ensurelogopen(USERVD_LOGFACILITY);
128 syslog(LOG_DEBUG,"client went away (broken pipe)");
132 static void xfwrite(const void *p, size_t sz, FILE *file) {
134 nr= fwrite(p,1,sz,file);
135 if (nr != sz) xfwriteerror();
138 static void xfflush(FILE *file) {
139 if (fflush(file)) xfwriteerror();
142 /* Functions which may be called only from the main thread. These may
143 * use main-thread objects and must block signals before using signal
147 static void xfread(void *p, size_t sz) {
149 nr= fread(p,1,sz,srfile); if (nr == sz) return;
150 if (ferror(srfile)) syscallerror("reading from client");
152 assert(feof(srfile));
153 syslog(LOG_DEBUG,"client went away (unexpected EOF)");
158 static char *xfreadsetstring(int l) {
160 assert(l<=MAX_GENERAL_STRING);
162 xfread(s,sizeof(*s)*l);
167 static char *xfreadstring(void) {
169 xfread(&l,sizeof(l));
170 return xfreadsetstring(l);
173 static void getevent(struct event_msg *event_r) {
177 xfread(event_r,sizeof(struct event_msg));
178 switch (event_r->type) {
180 fd= event_r->data.closereadfd.fd;
181 assert(fd<fdarrayused);
182 if (fdarray[fd].holdfd!=-1) {
183 if (close(fdarray[fd].holdfd)) syscallerror("cannot close holding fd");
184 fdarray[fd].holdfd= -1;
189 syslog(LOG_DEBUG,"client disconnected");
197 /* Functions which may be called either from signal handlers or from
198 * the main thread. They block signals in case they are on the main
199 * thread, and may only use signal handler objects. None of them
200 * return. If they did they'd have to restore the signal mask.
203 void miscerror(const char *what) {
205 syslog(LOG_ERR,"failure: %s",what);
209 void syscallerror(const char *what) {
214 syslog(LOG_ERR,"system call failure: %s: %s",what,strerror(e));
218 /* Functions which may be called from signal handlers. These
219 * may use signal-handler objects. The main program may only
220 * call them with signals blocked, and they may not use any
221 * main-thread objects.
224 void ensurelogopen(int wantfacility) {
225 if (syslogopenfacility==wantfacility) return;
226 if (syslogopenfacility!=-1) closelog();
227 openlog(USERVD_LOGIDENT,LOG_NDELAY|LOG_PID,wantfacility);
228 syslogopenfacility= wantfacility;
231 void NONRETURNING disconnect(int exitstatus) {
232 /* This function can sometimes indirectly call itself (eg,
233 * xfwrite, syscallerror can cause it to be called). So, all
234 * the global variables indicating need for action are reset
235 * before the action is taken so that if it fails it isn't
238 struct progress_msg progress_mbuf;
243 if (childtokill!=-1 && disconnecthup) {
244 orgtokill= childtokill;
247 r= kill(-orgtokill,SIGHUP);
248 if (r && errno!=EPERM && errno!=ESRCH)
249 syscallerror("sending SIGHUP to service process group");
256 memset(&progress_mbuf,0,sizeof(progress_mbuf));
257 progress_mbuf.magic= PROGRESS_MAGIC;
258 progress_mbuf.type= pt_failed;
259 xfwrite(&progress_mbuf,sizeof(progress_mbuf),swfilereal);
266 static void NONRETURNING sighandler_chld(int ignored) {
267 struct progress_msg progress_mbuf;
271 returned= wait3(&status,WNOHANG,0);
272 if (returned==-1) syscallerror("wait for child failed");
273 if (!returned) syscallerror("spurious sigchld");
274 if (returned!=child) syscallerror("spurious child process");
275 child= childtokill= -1;
277 memset(&progress_mbuf,0,sizeof(progress_mbuf));
278 progress_mbuf.magic= PROGRESS_MAGIC;
279 progress_mbuf.type= pt_terminated;
280 progress_mbuf.data.terminated.status= status;
281 xfwrite(&progress_mbuf,sizeof(progress_mbuf),swfile);
284 syslog(LOG_DEBUG,"service completed (status %d %d)",(status>>8)&0x0ff,status&0x0ff);
288 /* Functions which are called only during setup, before
289 * the signal asynchronicity starts. They can do anything they like.
292 void ensurefdarray(int fd) {
293 if (fd < fdarrayused) return;
294 if (fd >= fdarraysize) {
295 fdarraysize= ((fd+2)<<1);
296 fdarray= xrealloc(fdarray,sizeof(struct fdstate)*fdarraysize);
298 while (fd >= fdarrayused) {
299 fdarray[fdarrayused].iswrite= -1;
300 fdarray[fdarrayused].realfd= -1;
301 fdarray[fdarrayused].holdfd= -1;
302 fdarray[fdarrayused].wantstate= restfdwantstate;
303 fdarray[fdarrayused].wantrw= restfdwantrw;
308 static void NONRETURNING generalfailure(const char *prefix, int reserveerrno,
309 int errnoval, const char *fmt, va_list al) {
310 char errmsg[MAX_ERRMSG_LEN];
313 strnycpy(errmsg,prefix,sizeof(errmsg));
314 strnytcat(errmsg,": ",sizeof(errmsg));
318 vsnytprintfcat(errmsg,sizeof(errmsg)-reserveerrno,fmt,al);
320 strnytcat(errmsg,": ",sizeof(errmsg));
321 strnytcat(errmsg,strerror(errnoval),sizeof(errmsg));
323 senderrmsgstderr(errmsg);
324 syslog(LOG_DEBUG,"service failed (%s)",errmsg);
328 static void NONRETURNPRINTFFORMAT(1,2) failure(const char *fmt, ...) {
332 generalfailure(0,0,0,fmt,al);
335 static void NONRETURNPRINTFFORMAT(1,2) syscallfailure(const char *fmt, ...) {
341 generalfailure("system call failed",ERRMSG_RESERVE_ERRNO,e,fmt,al);
344 void senderrmsgstderr(const char *errmsg) {
345 struct progress_msg progress_mbuf;
350 memset(&progress_mbuf,0,sizeof(progress_mbuf));
351 progress_mbuf.magic= PROGRESS_MAGIC;
352 progress_mbuf.type= pt_errmsg;
353 progress_mbuf.data.errmsg.messagelen= l;
354 xfwrite(&progress_mbuf,sizeof(progress_mbuf),swfile);
355 xfwrite(errmsg,l,swfile);
356 ul= PROGRESS_ERRMSG_END_MAGIC;
357 xfwrite(&ul,sizeof(ul),swfile);
361 static void getgroupnames(int ngids, gid_t *list, const char ***names_r) {
366 names= xmalloc(sizeof(char*)*ngids);
367 for (i=0; i<ngids; i++) {
368 cgrp= getgrgid(list[i]);
369 if (!cgrp) miscerror("get group entry");
370 names[i]= xstrsave(cgrp->gr_name);
375 /* The per-request main program and its subfunctions. */
377 static void setup_comms(int sfd) {
378 static char swbuf[BUFSIZ];
379 static char srbuf[BUFSIZ];
381 struct sigaction sig;
383 ensurelogopen(USERVD_LOGFACILITY);
384 syslog(LOG_DEBUG,"call connected");
386 mypid= getpid(); if (mypid == -1) syscallerror("getpid");
388 sig.sa_handler= SIG_IGN;
389 sigemptyset(&sig.sa_mask);
391 if (sigaction(SIGPIPE,&sig,0)) syscallerror("cannot ignore sigpipe");
393 srfile= fdopen(sfd,"r");
394 if (!srfile) syscallerror("turn socket fd into reading FILE*");
395 if (setvbuf(srfile,srbuf,_IOFBF,sizeof(srbuf)))
396 syscallerror("set buffering on socket reads");
398 swfile= fdopen(sfd,"w");
399 if (!swfile) syscallerror("turn socket fd into writing FILE*");
400 if (setvbuf(swfile,swbuf,_IOFBF,sizeof(swbuf)))
401 syscallerror("set buffering on socket writes");
404 static void send_opening(void) {
405 struct opening_msg opening_mbuf;
407 memset(&opening_mbuf,0,sizeof(opening_mbuf));
408 opening_mbuf.magic= OPENING_MAGIC;
409 memcpy(opening_mbuf.protocolchecksumversion,protocolchecksumversion,PCSUMSIZE);
410 opening_mbuf.serverpid= mypid;
411 xfwrite(&opening_mbuf,sizeof(opening_mbuf),swfile);
415 static void receive_request(void) {
419 xfread(&request_mbuf,sizeof(request_mbuf));
420 serviceuser= xfreadsetstring(request_mbuf.serviceuserlen);
421 service= xfreadsetstring(request_mbuf.servicelen);
422 logname= xfreadsetstring(request_mbuf.lognamelen);
423 cwd= xfreadsetstring(request_mbuf.cwdlen);
424 if (request_mbuf.overridelen >= 0) {
425 assert(request_mbuf.overridelen <= MAX_OVERRIDE_LEN);
426 overridedata= xfreadsetstring(request_mbuf.overridelen);
428 assert(request_mbuf.overridelen == -1);
431 assert(request_mbuf.ngids <= MAX_GIDS);
432 calling_gids= xmalloc(sizeof(gid_t)*request_mbuf.ngids);
433 xfread(calling_gids,sizeof(gid_t)*request_mbuf.ngids);
435 fdarraysize= 4; fdarray= xmalloc(sizeof(struct fdstate)*fdarraysize);
436 fdarrayused= 1; fdarray[0].iswrite= -1;
437 fdarray[0].wantstate= tokv_word_rejectfd;
438 assert(request_mbuf.nreadfds+request_mbuf.nwritefds <= MAX_ALLOW_FD+1);
439 for (i=0; i<request_mbuf.nreadfds+request_mbuf.nwritefds; i++) {
440 xfread(&fd,sizeof(int));
441 assert(fd <= MAX_ALLOW_FD);
443 assert(fdarray[fd].iswrite == -1);
444 fdarray[fd].iswrite= (i>=request_mbuf.nreadfds);
447 assert(request_mbuf.nargs <= MAX_ARGSDEFVAR);
448 argarray= xmalloc(sizeof(char*)*(request_mbuf.nargs));
449 for (i=0; i<request_mbuf.nargs; i++) argarray[i]= xfreadstring();
450 assert(request_mbuf.nvars <= MAX_ARGSDEFVAR);
451 defvararray= xmalloc(sizeof(struct keyvaluepair)*request_mbuf.nvars);
452 for (i=0; i<request_mbuf.nvars; i++) {
453 defvararray[i].key= xfreadstring();
454 assert(defvararray[i].key[0]);
455 defvararray[i].value= xfreadstring();
457 xfread(&ul,sizeof(ul));
458 assert(ul == REQUEST_END_MAGIC);
461 static void establish_pipes(void) {
463 char pipepathbuf[PIPEMAXLEN+2];
465 for (fd=0; fd<fdarrayused; fd++) {
466 if (fdarray[fd].iswrite == -1) continue;
467 pipepathbuf[sizeof(pipepathbuf)-2]= 0;
468 snyprintf(pipepathbuf,sizeof(pipepathbuf),PIPEFORMAT,
469 (unsigned long)request_mbuf.clientpid,(unsigned long)mypid,fd);
470 assert(!pipepathbuf[sizeof(pipepathbuf)-2]);
471 tempfd= open(pipepathbuf,O_RDWR);
472 if (tempfd<0) syscallerror("prelim open pipe");
473 if (fdarray[fd].iswrite) {
474 fdarray[fd].holdfd= -1;
475 fdarray[fd].realfd= open(pipepathbuf, O_WRONLY);
477 fdarray[fd].holdfd= open(pipepathbuf, O_WRONLY);
478 if (fdarray[fd].holdfd<0) syscallerror("hold open pipe");
479 fdarray[fd].realfd= open(pipepathbuf, O_RDONLY);
481 if (fdarray[fd].realfd<0) syscallerror("real open pipe");
482 if (unlink(pipepathbuf)) syscallerror("unlink pipe");
483 if (close(tempfd)) syscallerror("close prelim fd onto pipe");
487 static void lookup_uidsgids(void) {
490 pw= getpwnam(logname);
491 if (!pw) miscerror("look up calling user");
492 assert(!strcmp(pw->pw_name,logname));
493 callinguser_shell= xstrsave(pw->pw_shell);
495 pw= getpwnam(serviceuser);
496 if (!pw) miscerror("look up service user");
497 assert(!strcmp(pw->pw_name,serviceuser));
498 serviceuser_dir= xstrsave(nondebug_serviceuserdir(pw->pw_dir));
499 serviceuser_shell= xstrsave(pw->pw_shell);
500 serviceuser_uid= pw->pw_uid;
502 if (initgroups(pw->pw_name,pw->pw_gid)) syscallerror("initgroups");
503 if (setreuid(pw->pw_uid,pw->pw_uid)) syscallerror("setreuid 1");
504 if (setreuid(pw->pw_uid,pw->pw_uid)) syscallerror("setreuid 2");
506 if (!setreuid(pw->pw_uid,0)) miscerror("setreuid 3 unexpectedly succeeded");
507 if (errno != EPERM) syscallerror("setreuid 3 failed in unexpected way");
509 service_ngids= getgroups(0,0); if (service_ngids == -1) syscallerror("getgroups(0,0)");
510 if (service_ngids > MAX_GIDS) miscerror("service user is in far too many groups");
511 service_gids= xmalloc(sizeof(gid_t)*(service_ngids+1));
512 service_gids[0]= pw->pw_gid;
513 if (getgroups(service_ngids,service_gids+1) != service_ngids)
514 syscallerror("getgroups(size,list)");
516 getgroupnames(service_ngids,service_gids,&service_groups);
517 getgroupnames(request_mbuf.ngids,calling_gids,&calling_groups);
520 static void check_find_executable(void) {
522 char *part, *exectry;
523 const char *string, *delim, *nextstring;
527 case tokv_word_reject:
528 failure("request rejected");
529 case tokv_word_execute:
530 r= stat(execpath,&stab);
531 if (r) syscallfailure("checking for executable `%s'",execpath);
533 case tokv_word_executefromdirectory:
534 r= stat(execpath,&stab);
535 if (r) syscallfailure("checking for executable in directory, `%s'",execpath);
537 case tokv_word_executebuiltin:
539 case tokv_word_executefrompath:
540 if (strchr(service,'/')) {
541 r= stat(service,&stab);
542 if (r) syscallfailure("execute-from-path (contains slash)"
543 " cannot check for executable `%s'",service);
546 string= getenv("PATH");
547 if (!string) string= defaultpath();
549 delim= strchr(string,':');
551 if (delim-string > MAX_GENERAL_STRING)
552 failure("execute-from-path, but PATH component too long");
553 partsize= delim-string;
556 partsize= strlen(string);
559 part= xstrsubsave(string,partsize);
560 exectry= part[0] ? xstrcat3save(part,"/",service) : xstrsave(service);
562 r= stat(exectry,&stab);
563 if (!r) { execpath= exectry; break; }
567 if (!execpath) failure("execute-from-path, but program `%s' not found",service);
575 static void check_fds(void) {
578 assert(fdarrayused>=2);
579 if (!(fdarray[2].wantstate == tokv_word_requirefd ||
580 fdarray[2].wantstate == tokv_word_allowfd) ||
581 fdarray[2].wantrw != tokv_word_write)
582 failure("must have stderr (fd 2), but file descriptor setup in "
583 "configuration does not have it or not for writing");
585 for (fd=0; fd<fdarrayused; fd++) {
586 switch (fdarray[fd].wantstate) {
587 case tokv_word_rejectfd:
588 if (fdarray[fd].realfd != -1)
589 failure("file descriptor %d provided but rejected",fd);
591 case tokv_word_ignorefd:
592 if (fdarray[fd].realfd != -1)
593 if (close(fdarray[fd].realfd))
594 syscallfailure("close unwanted file descriptor %d",fd);
595 fdarray[fd].realfd= -1;
597 case tokv_word_nullfd:
598 if (fdarray[fd].realfd != -1) close(fdarray[fd].realfd);
599 fdarray[fd].realfd= open("/dev/null",
600 fdarray[fd].iswrite == -1 ? O_RDWR :
601 fdarray[fd].iswrite ? O_WRONLY : O_RDONLY);
602 if (fdarray[fd].realfd<0)
603 syscallfailure("cannot open /dev/null for null fd");
605 case tokv_word_requirefd:
606 if (fdarray[fd].realfd == -1)
607 failure("file descriptor %d not provided but required",fd);
609 case tokv_word_allowfd:
610 if (fdarray[fd].realfd == -1) {
611 fdarray[fd].iswrite= (fdarray[fd].wantrw == tokv_word_write);
612 fdarray[fd].realfd= open("/dev/null",fdarray[fd].iswrite ? O_WRONLY : O_RDONLY);
613 if (fdarray[fd].realfd<0)
614 syscallfailure("cannot open /dev/null for allowed but not provided fd");
616 if (fdarray[fd].iswrite) {
617 if (fdarray[fd].wantrw != tokv_word_write)
618 failure("file descriptor %d provided write, wanted read",fd);
620 if (fdarray[fd].wantrw != tokv_word_read)
621 failure("file descriptor %d provided read, wanted write",fd);
628 static void send_progress_ok(void) {
629 struct progress_msg progress_mbuf;
631 memset(&progress_mbuf,0,sizeof(progress_mbuf));
632 progress_mbuf.magic= PROGRESS_MAGIC;
633 progress_mbuf.type= pt_ok;
634 xfwrite(&progress_mbuf,sizeof(progress_mbuf),swfile);
638 static void fork_service_synch(void) {
640 struct sigaction sig;
641 int r, synchsocket[2];
644 r= socketpair(AF_UNIX,SOCK_STREAM,0,synchsocket);
645 if (r) syscallerror("cannot create socket for synch");
647 sig.sa_handler= sighandler_chld;
648 sigemptyset(&sig.sa_mask);
649 sigaddset(&sig.sa_mask,SIGCHLD);
651 if (sigaction(SIGCHLD,&sig,0)) syscallerror("cannot set sigchld handler");
654 if (newchild == -1) syscallerror("cannot fork to invoke service");
655 if (!newchild) execservice(synchsocket,fileno(swfile));
656 childtokill= child= newchild;
658 if (close(synchsocket[1])) syscallerror("cannot close other end of synch socket");
660 r= synchread(synchsocket[0],'y');
661 if (r) syscallerror("read synch byte from child");
666 r= write(synchsocket[0],&synchmsg,1);
667 if (r!=1) syscallerror("write synch byte to child");
669 if (close(synchsocket[0])) syscallerror("cannot close my end of synch socket");
672 void servicerequest(int sfd) {
673 struct event_msg event_mbuf;
681 debug_dumprequest(mypid);
684 r= parse_string(TOPLEVEL_OVERRIDDEN_CONFIGURATION,
685 "<builtin toplevel override configuration>",1);
687 r= parse_string(TOPLEVEL_CONFIGURATION,
688 "<builtin toplevel configuration>",1);
690 ensurelogopen(USERVD_LOGFACILITY);
691 if (r == tokv_error) failure("error encountered while parsing configuration");
692 assert(r == tokv_quit);
694 debug_dumpexecsettings();
696 check_find_executable();
700 getevent(&event_mbuf);
701 assert(event_mbuf.type == et_confirm);
703 fork_service_synch();
705 getevent(&event_mbuf);