3 * daemon code to process one request (is parent of service process)
5 * Copyright (C)1996-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 * 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
28 * the syslog() family of calls, and the associated
29 * syslogopenfacility variable
30 * swfile (stdio stream)
32 * The following objects are used in the main program unprotected
33 * and so must not be used in signal handlers:
36 * child and childtokill are used for communication between the
37 * main thread and the signal handlers; none of the signal handlers
38 * return so errno is OK too.
56 #include <sys/resource.h>
57 #include <sys/fcntl.h>
59 #include <sys/socket.h>
69 /* NB: defaults for the execution state are not set here, but in
70 * the RESET_CONFIGURATION #define in daemon.h. */
71 struct request_msg request_mbuf;
72 struct keyvaluepair *defvararray;
73 struct fdstate *fdarray;
74 int fdarraysize, fdarrayused;
75 int restfdwantstate= tokv_word_rejectfd, restfdwantrw;
78 char *serviceuser, *service, *loginname, *cwd;
79 char *overridedata, *userrcfile;
80 char *serviceuser_dir, *serviceuser_shell, *callinguser_shell;
81 gid_t *calling_gids, *service_gids;
82 uid_t serviceuser_uid=-1;
83 const char **calling_groups, **service_groups;
84 char *execpath, **execargs;
86 int setenvironment, suppressargs, disconnecthup;
87 builtinserviceexec_fnt *execbuiltin;
88 int syslogopenfacility=-1;
90 static FILE *swfile, *srfile;
91 static pid_t child=-1, childtokill=-1;
94 /* Function shared with servexec.c: */
96 int synchread(int fd, int ch) {
101 r= read(fd,&synchmsg,1);
103 if (r==0) { errno= ECONNRESET; return -1; }
105 if (errno!=EINTR) return -1;
107 assert(synchmsg==ch);
111 const char *defaultpath(void) {
112 return serviceuser_uid ? DEFAULTPATH_USER : DEFAULTPATH_ROOT;
115 /* General-purpose functions; these do nothing special about signals */
117 static void blocksignals(void) {
122 sigaddset(&set,SIGCHLD);
123 sigaddset(&set,SIGPIPE);
124 r= sigprocmask(SIG_BLOCK,&set,0); assert(!r);
127 static void xfwriteerror(void) {
128 if (errno != EPIPE) syscallerror("writing to client");
130 ensurelogopen(USERVD_LOGFACILITY);
131 syslog(LOG_INFO,"client went away (broken pipe)");
135 static void xfwrite(const void *p, size_t sz, FILE *file) {
137 nr= fwrite(p,1,sz,file);
138 if (nr != sz) xfwriteerror();
141 static void xfflush(FILE *file) {
142 if (fflush(file)) xfwriteerror();
145 /* Functions which may be called only from the main thread. These may
146 * use main-thread objects and must block signals before using signal
150 static void xfread(void *p, size_t sz) {
152 nr= working_fread(p,sz,srfile); if (nr == sz) return;
153 if (ferror(srfile)) syscallerror("reading from client");
155 assert(feof(srfile));
156 syslog(LOG_INFO,"client went away (unexpected EOF)");
161 static char *xfreadsetstring(int l) {
163 assert(l<=MAX_GENERAL_STRING);
165 xfread(s,sizeof(*s)*l);
170 static char *xfreadstring(void) {
172 xfread(&l,sizeof(l));
173 return xfreadsetstring(l);
176 static void getevent(struct event_msg *event_r) {
180 xfread(event_r,sizeof(struct event_msg));
181 switch (event_r->type) {
183 fd= event_r->data.closereadfd.fd;
184 if (fd >= fdarrayused) {
186 syslog(LOG_ERR,"client sent bad file descriptor %d to close (max %d)",
190 if (fdarray[fd].holdfd!=-1) {
191 if (close(fdarray[fd].holdfd)) syscallerror("cannot close holding fd");
192 fdarray[fd].holdfd= -1;
197 syslog(LOG_INFO,"client disconnected");
205 /* Functions which may be called either from signal handlers or from
206 * the main thread. They block signals in case they are on the main
207 * thread, and may only use signal handler objects. None of them
208 * return. If they did they'd have to restore the signal mask.
211 void miscerror(const char *what) {
213 syslog(LOG_ERR,"failure: %s",what);
217 void syscallerror(const char *what) {
222 syslog(LOG_ERR,"system call failure: %s: %s",what,strerror(e));
226 /* Functions which may be called from signal handlers. These
227 * may use signal-handler objects. The main program may only
228 * call them with signals blocked, and they may not use any
229 * main-thread objects.
232 void ensurelogopen(int wantfacility) {
233 if (syslogopenfacility==wantfacility) return;
234 if (syslogopenfacility!=-1) closelog();
235 openlog(USERVD_LOGIDENT,LOG_NDELAY|LOG_PID,wantfacility);
236 syslogopenfacility= wantfacility;
239 void NONRETURNING disconnect(int exitstatus) {
240 /* This function can sometimes indirectly call itself (eg,
241 * xfwrite, syscallerror can cause it to be called). So, all
242 * the global variables indicating need for action are reset
243 * before the action is taken so that if it fails it isn't
246 struct progress_msg progress_mbuf;
251 if (childtokill!=-1 && disconnecthup) {
252 orgtokill= childtokill;
255 r= kill(-orgtokill,SIGHUP);
256 if (r && errno!=EPERM && errno!=ESRCH)
257 syscallerror("sending SIGHUP to service process group");
264 memset(&progress_mbuf,0,sizeof(progress_mbuf));
265 progress_mbuf.magic= PROGRESS_MAGIC;
266 progress_mbuf.type= pt_failed;
267 xfwrite(&progress_mbuf,sizeof(progress_mbuf),swfilereal);
274 static void reporttermination(int status) {
275 struct progress_msg progress_mbuf;
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);
285 static void NONRETURNING sighandler_chld(int ignored) {
289 returned= wait3(&status,WNOHANG,0);
290 if (returned==-1) syscallerror("wait for child failed");
291 if (!returned) syscallerror("spurious sigchld");
292 if (returned!=child) syscallerror("spurious child process");
293 child= childtokill= -1;
295 reporttermination(status);
296 syslog(LOG_INFO,"service completed (status %d %d)",(status>>8)&0x0ff,status&0x0ff);
300 /* Functions which are called only during setup, before
301 * the signal asynchronicity starts. They can do anything they like.
304 void ensurefdarray(int fd) {
305 if (fd < fdarrayused) return;
306 if (fd >= fdarraysize) {
307 fdarraysize= ((fd+2)<<1);
308 fdarray= xrealloc(fdarray,sizeof(struct fdstate)*fdarraysize);
310 while (fd >= fdarrayused) {
311 fdarray[fdarrayused].iswrite= -1;
312 fdarray[fdarrayused].realfd= -1;
313 fdarray[fdarrayused].holdfd= -1;
314 fdarray[fdarrayused].wantstate= restfdwantstate;
315 fdarray[fdarrayused].wantrw= restfdwantrw;
320 static void NONRETURNING generalfailure(const char *prefix, int reserveerrno,
321 int errnoval, const char *fmt, va_list al) {
322 char errmsg[MAX_ERRMSG_LEN];
325 strnycpy(errmsg,prefix,sizeof(errmsg));
326 strnytcat(errmsg,": ",sizeof(errmsg));
330 vsnytprintfcat(errmsg,sizeof(errmsg)-reserveerrno,fmt,al);
332 strnytcat(errmsg,": ",sizeof(errmsg));
333 strnytcat(errmsg,strerror(errnoval),sizeof(errmsg));
335 senderrmsgstderr(errmsg);
336 syslog(LOG_INFO,"service failed (%s)",errmsg);
340 static void NONRETURNPRINTFFORMAT(1,2) failure(const char *fmt, ...) {
344 generalfailure(0,0,0,fmt,al);
347 static void NONRETURNPRINTFFORMAT(1,2) syscallfailure(const char *fmt, ...) {
353 generalfailure("system call failed",ERRMSG_RESERVE_ERRNO,e,fmt,al);
356 void senderrmsgstderr(const char *errmsg) {
357 struct progress_msg progress_mbuf;
362 memset(&progress_mbuf,0,sizeof(progress_mbuf));
363 progress_mbuf.magic= PROGRESS_MAGIC;
364 progress_mbuf.type= pt_errmsg;
365 progress_mbuf.data.errmsg.messagelen= l;
366 xfwrite(&progress_mbuf,sizeof(progress_mbuf),swfile);
367 xfwrite(errmsg,l,swfile);
368 ul= PROGRESS_ERRMSG_END_MAGIC;
369 xfwrite(&ul,sizeof(ul),swfile);
373 /* The per-request main program and its subfunctions. */
375 static void setup_comms(int sfd) {
376 static char swbuf[BUFSIZ];
377 static char srbuf[BUFSIZ];
379 struct sigaction sig;
381 ensurelogopen(USERVD_LOGFACILITY);
382 syslog(LOG_DEBUG,"call connected");
384 mypid= getpid(); if (mypid == -1) syscallerror("getpid");
386 sig.sa_handler= SIG_IGN;
387 sigemptyset(&sig.sa_mask);
389 if (sigaction(SIGPIPE,&sig,0)) syscallerror("cannot ignore sigpipe");
391 srfile= fdopen(sfd,"r");
392 if (!srfile) syscallerror("turn socket fd into reading FILE*");
393 if (setvbuf(srfile,srbuf,_IOFBF,sizeof(srbuf)))
394 syscallerror("set buffering on socket reads");
396 swfile= fdopen(sfd,"w");
397 if (!swfile) syscallerror("turn socket fd into writing FILE*");
398 if (setvbuf(swfile,swbuf,_IOFBF,sizeof(swbuf)))
399 syscallerror("set buffering on socket writes");
402 static void send_opening(void) {
403 struct opening_msg opening_mbuf;
405 memset(&opening_mbuf,0,sizeof(opening_mbuf));
406 opening_mbuf.magic= OPENING_MAGIC;
407 memcpy(opening_mbuf.protocolchecksumversion,protocolchecksumversion,PCSUMSIZE);
408 opening_mbuf.overlordpid= overlordpid;
409 opening_mbuf.serverpid= mypid;
410 xfwrite(&opening_mbuf,sizeof(opening_mbuf),swfile);
414 static void receive_request(void) {
418 xfread(&request_mbuf,sizeof(request_mbuf));
419 serviceuser= xfreadsetstring(request_mbuf.serviceuserlen);
420 service= xfreadsetstring(request_mbuf.servicelen);
421 assert(request_mbuf.spoofed==0 || request_mbuf.spoofed==1);
422 loginname= xfreadsetstring(request_mbuf.loginnamelen);
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 groupnames(int ngids, gid_t *gids, const char ***names_r) {
492 names= xmalloc(sizeof(char*)*ngids);
493 for (i=0; i<ngids; i++) {
494 gr= getgrgid(gids[i]);
495 if (!gr) miscerror("get group entry");
496 names[i]= xstrsave(gr->gr_name);
501 static void lookup_uidsgids(void) {
504 pw= getpwnam(loginname);
505 if (!pw) miscerror("look up calling user");
506 assert(!strcmp(pw->pw_name,loginname));
507 callinguser_shell= xstrsave(pw->pw_shell);
509 pw= getpwnam(serviceuser);
510 if (!pw) miscerror("look up service user");
511 assert(!strcmp(pw->pw_name,serviceuser));
512 serviceuser_dir= xstrsave(nondebug_serviceuserdir(pw->pw_dir));
513 serviceuser_shell= xstrsave(pw->pw_shell);
514 serviceuser_uid= pw->pw_uid;
516 if (setregid(pw->pw_gid,pw->pw_gid)) syscallerror("setregid 1");
517 if (initgroups(pw->pw_name,pw->pw_gid)) syscallerror("initgroups");
518 if (setreuid(pw->pw_uid,pw->pw_uid)) syscallerror("setreuid 1");
519 if (setreuid(pw->pw_uid,pw->pw_uid)) syscallerror("setreuid 2");
521 if (!setreuid(pw->pw_uid,0)) miscerror("setreuid 3 unexpectedly succeeded");
522 if (errno != EPERM) syscallerror("setreuid 3 failed in unexpected way");
524 if (setregid(pw->pw_gid,pw->pw_gid)) syscallerror("setregid 2");
526 service_ngids= getgroups(0,0); if (service_ngids == -1) syscallerror("getgroups(0,0)");
527 if (service_ngids > MAX_GIDS) miscerror("service user is in far too many groups");
528 service_gids= xmalloc(sizeof(gid_t)*(service_ngids+1));
529 service_gids[0]= pw->pw_gid;
530 if (getgroups(service_ngids,service_gids+1) != service_ngids)
531 syscallerror("getgroups(size,list)");
533 groupnames(request_mbuf.ngids,calling_gids,&calling_groups);
534 groupnames(service_ngids,service_gids,&service_groups);
537 static void findinpath(char *program) {
538 char *part, *exectry;
539 const char *string, *delim, *nextstring;
543 if (strchr(program,'/')) {
544 r= stat(program,&stab);
545 if (r) syscallfailure("failed check for program (containing slash) `%s'",program);
548 string= getenv("PATH");
549 if (!string) string= defaultpath();
551 delim= strchr(string,':');
553 if (delim-string > MAX_GENERAL_STRING)
554 failure("execute-from-path, but PATH component too long");
555 partsize= delim-string;
558 partsize= strlen(string);
561 part= xstrsubsave(string,partsize);
562 exectry= part[0] ? xstrcat3save(part,"/",program) : xstrsave(program);
564 r= stat(exectry,&stab);
565 if (!r) { execpath= exectry; break; }
569 if (!execpath) failure("program `%s' not found on default PATH",program);
573 static void check_find_executable(void) {
578 case tokv_word_reject:
579 failure("request rejected");
580 case tokv_word_execute:
581 findinpath(execpath);
583 case tokv_word_executefromdirectory:
584 r= stat(execpath,&stab);
585 if (r) syscallfailure("checking for executable in directory, `%s'",execpath);
587 case tokv_word_executebuiltin:
589 case tokv_word_executefrompath:
597 static void makenonexistentfd(int fd) {
598 if (fdarray[fd].realfd == -1) {
599 assert(fdarray[fd].holdfd == -1);
601 if (close(fdarray[fd].realfd))
602 syscallfailure("close unwanted file descriptor %d",fd);
603 fdarray[fd].realfd= -1;
605 if (fdarray[fd].holdfd != -1) {
606 if (close(fdarray[fd].holdfd))
607 syscallfailure("close unwanted hold descriptor for %d",fd);
608 fdarray[fd].holdfd= -1;
613 static void makenullfd(int fd) {
614 fdarray[fd].realfd= open("/dev/null",
615 fdarray[fd].wantrw == tokv_word_read ? O_RDONLY :
616 fdarray[fd].wantrw == tokv_word_write ? O_WRONLY :
618 if (fdarray[fd].realfd<0)
619 syscallfailure("cannot open /dev/null for null or allowed, unprovided fd");
622 static void check_fds(void) {
625 assert(fdarrayused>=2);
626 if (!(fdarray[2].wantstate == tokv_word_requirefd ||
627 fdarray[2].wantstate == tokv_word_allowfd) ||
628 fdarray[2].wantrw != tokv_word_write)
629 failure("must have stderr (fd 2), but file descriptor setup in "
630 "configuration does not have it or not for writing");
632 for (fd=0; fd<fdarrayused; fd++) {
633 switch (fdarray[fd].wantstate) {
634 case tokv_word_rejectfd:
635 if (fdarray[fd].realfd != -1)
636 failure("file descriptor %d provided but rejected",fd);
638 case tokv_word_ignorefd:
639 makenonexistentfd(fd);
641 case tokv_word_nullfd:
642 makenonexistentfd(fd);
645 case tokv_word_requirefd:
646 if (fdarray[fd].realfd == -1)
647 failure("file descriptor %d required but not provided",fd);
648 assert(fdarray[fd].holdfd == -1);
650 case tokv_word_allowfd:
651 if (fdarray[fd].realfd == -1) {
652 assert(fdarray[fd].holdfd == -1);
655 if (fdarray[fd].iswrite) {
656 if (fdarray[fd].wantrw == tokv_word_read)
657 failure("file descriptor %d provided write, wanted read",fd);
659 if (fdarray[fd].wantrw == tokv_word_write)
660 failure("file descriptor %d provided read, wanted write",fd);
667 static void send_progress_ok(void) {
668 struct progress_msg progress_mbuf;
670 memset(&progress_mbuf,0,sizeof(progress_mbuf));
671 progress_mbuf.magic= PROGRESS_MAGIC;
672 progress_mbuf.type= pt_ok;
673 xfwrite(&progress_mbuf,sizeof(progress_mbuf),swfile);
677 static void fork_service_synch(void) {
679 struct sigaction sig;
680 int r, synchsocket[2];
683 r= socketpair(AF_UNIX,SOCK_STREAM,0,synchsocket);
684 if (r) syscallerror("cannot create socket for synch");
686 /* Danger here. Firstly, we start handling signals asynchronously.
687 * Secondly after we fork the service we want it to put
688 * itself in a separate process group so that we can kill it and all
689 * its children - but, we mustn't kill the whole pgrp before it has
690 * done that (or we kill ourselves) and it mustn't fork until it
691 * knows that we are going to kill it the right way ...
693 sig.sa_handler= sighandler_chld;
694 sigemptyset(&sig.sa_mask);
695 sigaddset(&sig.sa_mask,SIGCHLD);
697 if (sigaction(SIGCHLD,&sig,0)) syscallerror("cannot set sigchld handler");
700 if (newchild == -1) syscallerror("cannot fork to invoke service");
701 if (!newchild) execservice(synchsocket,fileno(swfile));
702 childtokill= child= newchild;
704 if (close(synchsocket[1])) syscallerror("cannot close other end of synch socket");
706 r= synchread(synchsocket[0],'y');
707 if (r) syscallerror("read synch byte from child");
712 r= write(synchsocket[0],&synchmsg,1);
713 if (r!=1) syscallerror("write synch byte to child");
715 if (close(synchsocket[0])) syscallerror("cannot close my end of synch socket");
718 void servicerequest(int sfd) {
719 struct event_msg event_mbuf;
725 if (request_mbuf.clientpid == (pid_t)-1) _exit(2);
728 debug_dumprequest(mypid);
729 syslog(LOG_INFO,"%s %s -> %s %c %s",
730 request_mbuf.spoofed ? "spoof" : "user",
731 loginname, serviceuser, overridedata?'!':':', service);
734 r= parse_string(TOPLEVEL_OVERRIDDEN_CONFIGURATION,
735 "<builtin toplevel override configuration>",1);
737 r= parse_string(TOPLEVEL_CONFIGURATION,
738 "<builtin toplevel configuration>",1);
740 ensurelogopen(USERVD_LOGFACILITY);
741 if (r == tokv_error) failure("error encountered while parsing configuration");
742 assert(r == tokv_quit);
744 debug_dumpexecsettings();
746 check_find_executable();
750 getevent(&event_mbuf);
751 assert(event_mbuf.type == et_confirm);
753 if (execbuiltin == bisexec_shutdown && !serviceuser_uid) {
754 /* The check for the uid is just so we can give a nice
755 * error message (in the actual code for bisexec_shutdown).
756 * If this is spoofed somehow then the unlink() will simply fail.
758 r= unlink(RENDEZVOUSPATH);
759 if (r) syscallfailure("remove rendezvous socket %s",RENDEZVOUSPATH);
760 syslog(LOG_NOTICE,"arranging for termination, due to client request");
761 reporttermination(0);
765 fork_service_synch();
767 getevent(&event_mbuf);