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.
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.
55 #include <sys/types.h>
56 #include <sys/fcntl.h>
58 #include <sys/socket.h>
67 /* NB: defaults for the execution state are not set here, but in
68 * the RESET_CONFIGURATION #define in daemon.h. */
69 struct request_msg request_mbuf;
70 struct keyvaluepair *defvararray;
71 struct fdstate *fdarray;
72 int fdarraysize, fdarrayused;
73 int restfdwantstate= tokv_word_rejectfd, restfdwantrw;
76 char *serviceuser, *service, *logname, *cwd;
77 char *overridedata, *userrcfile;
78 char *serviceuser_dir, *serviceuser_shell, *callinguser_shell;
79 gid_t *calling_gids, *service_gids;
80 uid_t serviceuser_uid=-1;
81 const char **calling_groups, **service_groups;
82 char *execpath, **execargs;
84 int setenvironment, suppressargs, disconnecthup;
85 builtinserviceexec_fnt *execbuiltin;
86 int syslogopenfacility=-1;
88 static FILE *swfile, *srfile;
89 static pid_t child=-1, childtokill=-1;
92 /* Function shared with servexec.c: */
94 int synchread(int fd, int ch) {
99 r= read(fd,&synchmsg,1);
101 if (r==0) { errno= ECONNRESET; return -1; }
103 if (errno!=EINTR) return -1;
105 assert(synchmsg==ch);
109 const char *defaultpath(void) {
110 return serviceuser_uid ? DEFAULTPATH_USER : DEFAULTPATH_ROOT;
113 /* General-purpose functions; these do nothing special about signals */
115 static void blocksignals(void) {
120 sigaddset(&set,SIGCHLD);
121 sigaddset(&set,SIGPIPE);
122 r= sigprocmask(SIG_BLOCK,&set,0); assert(!r);
125 static void xfwriteerror(void) {
126 if (errno != EPIPE) syscallerror("writing to client");
128 ensurelogopen(USERVD_LOGFACILITY);
129 syslog(LOG_INFO,"client went away (broken pipe)");
133 static void xfwrite(const void *p, size_t sz, FILE *file) {
135 nr= fwrite(p,1,sz,file);
136 if (nr != sz) xfwriteerror();
139 static void xfflush(FILE *file) {
140 if (fflush(file)) xfwriteerror();
143 /* Functions which may be called only from the main thread. These may
144 * use main-thread objects and must block signals before using signal
148 static void xfread(void *p, size_t sz) {
150 nr= fread(p,1,sz,srfile); if (nr == sz) return;
151 if (ferror(srfile)) syscallerror("reading from client");
153 assert(feof(srfile));
154 syslog(LOG_INFO,"client went away (unexpected EOF)");
159 static char *xfreadsetstring(int l) {
161 assert(l<=MAX_GENERAL_STRING);
163 xfread(s,sizeof(*s)*l);
168 static char *xfreadstring(void) {
170 xfread(&l,sizeof(l));
171 return xfreadsetstring(l);
174 static void getevent(struct event_msg *event_r) {
178 xfread(event_r,sizeof(struct event_msg));
179 switch (event_r->type) {
181 fd= event_r->data.closereadfd.fd;
182 if (fd >= fdarrayused) {
184 syslog(LOG_ERR,"client sent bad file descriptor %d to close (max %d)",
188 if (fdarray[fd].holdfd!=-1) {
189 if (close(fdarray[fd].holdfd)) syscallerror("cannot close holding fd");
190 fdarray[fd].holdfd= -1;
195 syslog(LOG_INFO,"client disconnected");
203 /* Functions which may be called either from signal handlers or from
204 * the main thread. They block signals in case they are on the main
205 * thread, and may only use signal handler objects. None of them
206 * return. If they did they'd have to restore the signal mask.
209 void miscerror(const char *what) {
211 syslog(LOG_ERR,"failure: %s",what);
215 void syscallerror(const char *what) {
220 syslog(LOG_ERR,"system call failure: %s: %s",what,strerror(e));
224 /* Functions which may be called from signal handlers. These
225 * may use signal-handler objects. The main program may only
226 * call them with signals blocked, and they may not use any
227 * main-thread objects.
230 void ensurelogopen(int wantfacility) {
231 if (syslogopenfacility==wantfacility) return;
232 if (syslogopenfacility!=-1) closelog();
233 openlog(USERVD_LOGIDENT,LOG_NDELAY|LOG_PID,wantfacility);
234 syslogopenfacility= wantfacility;
237 void NONRETURNING disconnect(int exitstatus) {
238 /* This function can sometimes indirectly call itself (eg,
239 * xfwrite, syscallerror can cause it to be called). So, all
240 * the global variables indicating need for action are reset
241 * before the action is taken so that if it fails it isn't
244 struct progress_msg progress_mbuf;
249 if (childtokill!=-1 && disconnecthup) {
250 orgtokill= childtokill;
253 r= kill(-orgtokill,SIGHUP);
254 if (r && errno!=EPERM && errno!=ESRCH)
255 syscallerror("sending SIGHUP to service process group");
262 memset(&progress_mbuf,0,sizeof(progress_mbuf));
263 progress_mbuf.magic= PROGRESS_MAGIC;
264 progress_mbuf.type= pt_failed;
265 xfwrite(&progress_mbuf,sizeof(progress_mbuf),swfilereal);
272 static void NONRETURNING sighandler_chld(int ignored) {
273 struct progress_msg progress_mbuf;
277 returned= wait3(&status,WNOHANG,0);
278 if (returned==-1) syscallerror("wait for child failed");
279 if (!returned) syscallerror("spurious sigchld");
280 if (returned!=child) syscallerror("spurious child process");
281 child= childtokill= -1;
283 memset(&progress_mbuf,0,sizeof(progress_mbuf));
284 progress_mbuf.magic= PROGRESS_MAGIC;
285 progress_mbuf.type= pt_terminated;
286 progress_mbuf.data.terminated.status= status;
287 xfwrite(&progress_mbuf,sizeof(progress_mbuf),swfile);
290 syslog(LOG_INFO,"service completed (status %d %d)",(status>>8)&0x0ff,status&0x0ff);
294 /* Functions which are called only during setup, before
295 * the signal asynchronicity starts. They can do anything they like.
298 void ensurefdarray(int fd) {
299 if (fd < fdarrayused) return;
300 if (fd >= fdarraysize) {
301 fdarraysize= ((fd+2)<<1);
302 fdarray= xrealloc(fdarray,sizeof(struct fdstate)*fdarraysize);
304 while (fd >= fdarrayused) {
305 fdarray[fdarrayused].iswrite= -1;
306 fdarray[fdarrayused].realfd= -1;
307 fdarray[fdarrayused].holdfd= -1;
308 fdarray[fdarrayused].wantstate= restfdwantstate;
309 fdarray[fdarrayused].wantrw= restfdwantrw;
314 static void NONRETURNING generalfailure(const char *prefix, int reserveerrno,
315 int errnoval, const char *fmt, va_list al) {
316 char errmsg[MAX_ERRMSG_LEN];
319 strnycpy(errmsg,prefix,sizeof(errmsg));
320 strnytcat(errmsg,": ",sizeof(errmsg));
324 vsnytprintfcat(errmsg,sizeof(errmsg)-reserveerrno,fmt,al);
326 strnytcat(errmsg,": ",sizeof(errmsg));
327 strnytcat(errmsg,strerror(errnoval),sizeof(errmsg));
329 senderrmsgstderr(errmsg);
330 syslog(LOG_INFO,"service failed (%s)",errmsg);
334 static void NONRETURNPRINTFFORMAT(1,2) failure(const char *fmt, ...) {
338 generalfailure(0,0,0,fmt,al);
341 static void NONRETURNPRINTFFORMAT(1,2) syscallfailure(const char *fmt, ...) {
347 generalfailure("system call failed",ERRMSG_RESERVE_ERRNO,e,fmt,al);
350 void senderrmsgstderr(const char *errmsg) {
351 struct progress_msg progress_mbuf;
356 memset(&progress_mbuf,0,sizeof(progress_mbuf));
357 progress_mbuf.magic= PROGRESS_MAGIC;
358 progress_mbuf.type= pt_errmsg;
359 progress_mbuf.data.errmsg.messagelen= l;
360 xfwrite(&progress_mbuf,sizeof(progress_mbuf),swfile);
361 xfwrite(errmsg,l,swfile);
362 ul= PROGRESS_ERRMSG_END_MAGIC;
363 xfwrite(&ul,sizeof(ul),swfile);
367 /* The per-request main program and its subfunctions. */
369 static void setup_comms(int sfd) {
370 static char swbuf[BUFSIZ];
371 static char srbuf[BUFSIZ];
373 struct sigaction sig;
375 ensurelogopen(USERVD_LOGFACILITY);
376 syslog(LOG_DEBUG,"call connected");
378 mypid= getpid(); if (mypid == -1) syscallerror("getpid");
380 sig.sa_handler= SIG_IGN;
381 sigemptyset(&sig.sa_mask);
383 if (sigaction(SIGPIPE,&sig,0)) syscallerror("cannot ignore sigpipe");
385 srfile= fdopen(sfd,"r");
386 if (!srfile) syscallerror("turn socket fd into reading FILE*");
387 if (setvbuf(srfile,srbuf,_IOFBF,sizeof(srbuf)))
388 syscallerror("set buffering on socket reads");
390 swfile= fdopen(sfd,"w");
391 if (!swfile) syscallerror("turn socket fd into writing FILE*");
392 if (setvbuf(swfile,swbuf,_IOFBF,sizeof(swbuf)))
393 syscallerror("set buffering on socket writes");
396 static void send_opening(void) {
397 struct opening_msg opening_mbuf;
399 memset(&opening_mbuf,0,sizeof(opening_mbuf));
400 opening_mbuf.magic= OPENING_MAGIC;
401 memcpy(opening_mbuf.protocolchecksumversion,protocolchecksumversion,PCSUMSIZE);
402 opening_mbuf.overlordpid= overlordpid;
403 opening_mbuf.serverpid= mypid;
404 xfwrite(&opening_mbuf,sizeof(opening_mbuf),swfile);
408 static void receive_request(void) {
412 xfread(&request_mbuf,sizeof(request_mbuf));
413 serviceuser= xfreadsetstring(request_mbuf.serviceuserlen);
414 service= xfreadsetstring(request_mbuf.servicelen);
415 assert(request_mbuf.spoofed==0 || request_mbuf.spoofed==1);
416 logname= xfreadsetstring(request_mbuf.lognamelen);
417 cwd= xfreadsetstring(request_mbuf.cwdlen);
418 if (request_mbuf.overridelen >= 0) {
419 assert(request_mbuf.overridelen <= MAX_OVERRIDE_LEN);
420 overridedata= xfreadsetstring(request_mbuf.overridelen);
422 assert(request_mbuf.overridelen == -1);
425 assert(request_mbuf.ngids <= MAX_GIDS);
426 calling_gids= xmalloc(sizeof(gid_t)*request_mbuf.ngids);
427 xfread(calling_gids,sizeof(gid_t)*request_mbuf.ngids);
429 fdarraysize= 4; fdarray= xmalloc(sizeof(struct fdstate)*fdarraysize);
430 fdarrayused= 1; fdarray[0].iswrite= -1;
431 fdarray[0].wantstate= tokv_word_rejectfd;
432 assert(request_mbuf.nreadfds+request_mbuf.nwritefds <= MAX_ALLOW_FD+1);
433 for (i=0; i<request_mbuf.nreadfds+request_mbuf.nwritefds; i++) {
434 xfread(&fd,sizeof(int));
435 assert(fd <= MAX_ALLOW_FD);
437 assert(fdarray[fd].iswrite == -1);
438 fdarray[fd].iswrite= (i>=request_mbuf.nreadfds);
441 assert(request_mbuf.nargs <= MAX_ARGSDEFVAR);
442 argarray= xmalloc(sizeof(char*)*(request_mbuf.nargs));
443 for (i=0; i<request_mbuf.nargs; i++) argarray[i]= xfreadstring();
444 assert(request_mbuf.nvars <= MAX_ARGSDEFVAR);
445 defvararray= xmalloc(sizeof(struct keyvaluepair)*request_mbuf.nvars);
446 for (i=0; i<request_mbuf.nvars; i++) {
447 defvararray[i].key= xfreadstring();
448 assert(defvararray[i].key[0]);
449 defvararray[i].value= xfreadstring();
451 xfread(&ul,sizeof(ul));
452 assert(ul == REQUEST_END_MAGIC);
455 static void establish_pipes(void) {
457 char pipepathbuf[PIPEMAXLEN+2];
459 for (fd=0; fd<fdarrayused; fd++) {
460 if (fdarray[fd].iswrite == -1) continue;
461 pipepathbuf[sizeof(pipepathbuf)-2]= 0;
462 snyprintf(pipepathbuf,sizeof(pipepathbuf),PIPEFORMAT,
463 (unsigned long)request_mbuf.clientpid,(unsigned long)mypid,fd);
464 assert(!pipepathbuf[sizeof(pipepathbuf)-2]);
465 tempfd= open(pipepathbuf,O_RDWR);
466 if (tempfd<0) syscallerror("prelim open pipe");
467 if (fdarray[fd].iswrite) {
468 fdarray[fd].holdfd= -1;
469 fdarray[fd].realfd= open(pipepathbuf, O_WRONLY);
471 fdarray[fd].holdfd= open(pipepathbuf, O_WRONLY);
472 if (fdarray[fd].holdfd<0) syscallerror("hold open pipe");
473 fdarray[fd].realfd= open(pipepathbuf, O_RDONLY);
475 if (fdarray[fd].realfd<0) syscallerror("real open pipe");
476 if (unlink(pipepathbuf)) syscallerror("unlink pipe");
477 if (close(tempfd)) syscallerror("close prelim fd onto pipe");
481 static void groupnames(int ngids, gid_t *gids, const char ***names_r) {
486 names= xmalloc(sizeof(char*)*ngids);
487 for (i=0; i<ngids; i++) {
488 gr= getgrgid(gids[i]);
489 if (!gr) miscerror("get group entry");
490 names[i]= xstrsave(gr->gr_name);
495 static void lookup_uidsgids(void) {
498 pw= getpwnam(logname);
499 if (!pw) miscerror("look up calling user");
500 assert(!strcmp(pw->pw_name,logname));
501 callinguser_shell= xstrsave(pw->pw_shell);
503 pw= getpwnam(serviceuser);
504 if (!pw) miscerror("look up service user");
505 assert(!strcmp(pw->pw_name,serviceuser));
506 serviceuser_dir= xstrsave(nondebug_serviceuserdir(pw->pw_dir));
507 serviceuser_shell= xstrsave(pw->pw_shell);
508 serviceuser_uid= pw->pw_uid;
510 if (setregid(pw->pw_gid,pw->pw_gid)) syscallerror("setregid 1");
511 if (initgroups(pw->pw_name,pw->pw_gid)) syscallerror("initgroups");
512 if (setreuid(pw->pw_uid,pw->pw_uid)) syscallerror("setreuid 1");
513 if (setreuid(pw->pw_uid,pw->pw_uid)) syscallerror("setreuid 2");
515 if (!setreuid(pw->pw_uid,0)) miscerror("setreuid 3 unexpectedly succeeded");
516 if (errno != EPERM) syscallerror("setreuid 3 failed in unexpected way");
518 if (setregid(pw->pw_gid,pw->pw_gid)) syscallerror("setregid 2");
520 service_ngids= getgroups(0,0); if (service_ngids == -1) syscallerror("getgroups(0,0)");
521 if (service_ngids > MAX_GIDS) miscerror("service user is in far too many groups");
522 service_gids= xmalloc(sizeof(gid_t)*(service_ngids+1));
523 service_gids[0]= pw->pw_gid;
524 if (getgroups(service_ngids,service_gids+1) != service_ngids)
525 syscallerror("getgroups(size,list)");
527 groupnames(request_mbuf.ngids,calling_gids,&calling_groups);
528 groupnames(service_ngids,service_gids,&service_groups);
531 static void findinpath(char *program) {
532 char *part, *exectry;
533 const char *string, *delim, *nextstring;
537 if (strchr(program,'/')) {
538 r= stat(program,&stab);
539 if (r) syscallfailure("failed check for program (containing slash) `%s'",program);
542 string= getenv("PATH");
543 if (!string) string= defaultpath();
545 delim= strchr(string,':');
547 if (delim-string > MAX_GENERAL_STRING)
548 failure("execute-from-path, but PATH component too long");
549 partsize= delim-string;
552 partsize= strlen(string);
555 part= xstrsubsave(string,partsize);
556 exectry= part[0] ? xstrcat3save(part,"/",program) : xstrsave(program);
558 r= stat(exectry,&stab);
559 if (!r) { execpath= exectry; break; }
563 if (!execpath) failure("program `%s' not found on default PATH",program);
567 static void check_find_executable(void) {
572 case tokv_word_reject:
573 failure("request rejected");
574 case tokv_word_execute:
575 findinpath(execpath);
577 case tokv_word_executefromdirectory:
578 r= stat(execpath,&stab);
579 if (r) syscallfailure("checking for executable in directory, `%s'",execpath);
581 case tokv_word_executebuiltin:
583 case tokv_word_executefrompath:
591 static void makenonexistentfd(int fd) {
592 if (fdarray[fd].realfd == -1) {
593 assert(fdarray[fd].holdfd == -1);
595 if (close(fdarray[fd].realfd))
596 syscallfailure("close unwanted file descriptor %d",fd);
597 fdarray[fd].realfd= -1;
599 if (fdarray[fd].holdfd != -1) {
600 if (close(fdarray[fd].holdfd))
601 syscallfailure("close unwanted hold descriptor for %d",fd);
602 fdarray[fd].holdfd= -1;
607 static void makenullfd(int fd) {
608 fdarray[fd].realfd= open("/dev/null",
609 fdarray[fd].wantrw == tokv_word_read ? O_RDONLY :
610 fdarray[fd].wantrw == tokv_word_write ? O_WRONLY :
612 if (fdarray[fd].realfd<0)
613 syscallfailure("cannot open /dev/null for null or allowed, unprovided fd");
616 static void check_fds(void) {
619 assert(fdarrayused>=2);
620 if (!(fdarray[2].wantstate == tokv_word_requirefd ||
621 fdarray[2].wantstate == tokv_word_allowfd) ||
622 fdarray[2].wantrw != tokv_word_write)
623 failure("must have stderr (fd 2), but file descriptor setup in "
624 "configuration does not have it or not for writing");
626 for (fd=0; fd<fdarrayused; fd++) {
627 switch (fdarray[fd].wantstate) {
628 case tokv_word_rejectfd:
629 if (fdarray[fd].realfd != -1)
630 failure("file descriptor %d provided but rejected",fd);
632 case tokv_word_ignorefd:
633 makenonexistentfd(fd);
635 case tokv_word_nullfd:
636 makenonexistentfd(fd);
639 case tokv_word_requirefd:
640 if (fdarray[fd].realfd == -1)
641 failure("file descriptor %d required but not provided",fd);
642 assert(fdarray[fd].holdfd == -1);
644 case tokv_word_allowfd:
645 if (fdarray[fd].realfd == -1) {
646 assert(fdarray[fd].holdfd == -1);
649 if (fdarray[fd].iswrite) {
650 if (fdarray[fd].wantrw == tokv_word_read)
651 failure("file descriptor %d provided write, wanted read",fd);
653 if (fdarray[fd].wantrw == tokv_word_write)
654 failure("file descriptor %d provided read, wanted write",fd);
661 static void send_progress_ok(void) {
662 struct progress_msg progress_mbuf;
664 memset(&progress_mbuf,0,sizeof(progress_mbuf));
665 progress_mbuf.magic= PROGRESS_MAGIC;
666 progress_mbuf.type= pt_ok;
667 xfwrite(&progress_mbuf,sizeof(progress_mbuf),swfile);
671 static void fork_service_synch(void) {
673 struct sigaction sig;
674 int r, synchsocket[2];
677 r= socketpair(AF_UNIX,SOCK_STREAM,0,synchsocket);
678 if (r) syscallerror("cannot create socket for synch");
680 /* Danger here. Firstly, we start handling signals asynchronously.
681 * Secondly after we fork the service we want it to put
682 * itself in a separate process group so that we can kill it and all
683 * its children - but, we mustn't kill the whole pgrp before it has
684 * done that (or we kill ourselves) and it mustn't fork until it
685 * knows that we are going to kill it the right way ...
687 sig.sa_handler= sighandler_chld;
688 sigemptyset(&sig.sa_mask);
689 sigaddset(&sig.sa_mask,SIGCHLD);
691 if (sigaction(SIGCHLD,&sig,0)) syscallerror("cannot set sigchld handler");
694 if (newchild == -1) syscallerror("cannot fork to invoke service");
695 if (!newchild) execservice(synchsocket,fileno(swfile));
696 childtokill= child= newchild;
698 if (close(synchsocket[1])) syscallerror("cannot close other end of synch socket");
700 r= synchread(synchsocket[0],'y');
701 if (r) syscallerror("read synch byte from child");
706 r= write(synchsocket[0],&synchmsg,1);
707 if (r!=1) syscallerror("write synch byte to child");
709 if (close(synchsocket[0])) syscallerror("cannot close my end of synch socket");
712 void servicerequest(int sfd) {
713 struct event_msg event_mbuf;
719 if (request_mbuf.clientpid == (pid_t)-1) _exit(2);
722 debug_dumprequest(mypid);
723 syslog(LOG_INFO,"%s %s -> %s %c %s",
724 request_mbuf.spoofed ? "spoof" : "user",
725 logname, serviceuser, overridedata?'!':':', service);
728 r= parse_string(TOPLEVEL_OVERRIDDEN_CONFIGURATION,
729 "<builtin toplevel override configuration>",1);
731 r= parse_string(TOPLEVEL_CONFIGURATION,
732 "<builtin toplevel configuration>",1);
734 ensurelogopen(USERVD_LOGFACILITY);
735 if (r == tokv_error) failure("error encountered while parsing configuration");
736 assert(r == tokv_quit);
738 debug_dumpexecsettings();
740 check_find_executable();
744 getevent(&event_mbuf);
745 assert(event_mbuf.type == et_confirm);
747 fork_service_synch();
749 getevent(&event_mbuf);