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_DEBUG,"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_DEBUG,"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_DEBUG,"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_DEBUG,"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_DEBUG,"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.serverpid= mypid;
403 xfwrite(&opening_mbuf,sizeof(opening_mbuf),swfile);
407 static void receive_request(void) {
411 xfread(&request_mbuf,sizeof(request_mbuf));
412 serviceuser= xfreadsetstring(request_mbuf.serviceuserlen);
413 service= xfreadsetstring(request_mbuf.servicelen);
414 logname= xfreadsetstring(request_mbuf.lognamelen);
415 cwd= xfreadsetstring(request_mbuf.cwdlen);
416 if (request_mbuf.overridelen >= 0) {
417 assert(request_mbuf.overridelen <= MAX_OVERRIDE_LEN);
418 overridedata= xfreadsetstring(request_mbuf.overridelen);
420 assert(request_mbuf.overridelen == -1);
423 assert(request_mbuf.ngids <= MAX_GIDS);
424 calling_gids= xmalloc(sizeof(gid_t)*request_mbuf.ngids);
425 xfread(calling_gids,sizeof(gid_t)*request_mbuf.ngids);
427 fdarraysize= 4; fdarray= xmalloc(sizeof(struct fdstate)*fdarraysize);
428 fdarrayused= 1; fdarray[0].iswrite= -1;
429 fdarray[0].wantstate= tokv_word_rejectfd;
430 assert(request_mbuf.nreadfds+request_mbuf.nwritefds <= MAX_ALLOW_FD+1);
431 for (i=0; i<request_mbuf.nreadfds+request_mbuf.nwritefds; i++) {
432 xfread(&fd,sizeof(int));
433 assert(fd <= MAX_ALLOW_FD);
435 assert(fdarray[fd].iswrite == -1);
436 fdarray[fd].iswrite= (i>=request_mbuf.nreadfds);
439 assert(request_mbuf.nargs <= MAX_ARGSDEFVAR);
440 argarray= xmalloc(sizeof(char*)*(request_mbuf.nargs));
441 for (i=0; i<request_mbuf.nargs; i++) argarray[i]= xfreadstring();
442 assert(request_mbuf.nvars <= MAX_ARGSDEFVAR);
443 defvararray= xmalloc(sizeof(struct keyvaluepair)*request_mbuf.nvars);
444 for (i=0; i<request_mbuf.nvars; i++) {
445 defvararray[i].key= xfreadstring();
446 assert(defvararray[i].key[0]);
447 defvararray[i].value= xfreadstring();
449 xfread(&ul,sizeof(ul));
450 assert(ul == REQUEST_END_MAGIC);
453 static void establish_pipes(void) {
455 char pipepathbuf[PIPEMAXLEN+2];
457 for (fd=0; fd<fdarrayused; fd++) {
458 if (fdarray[fd].iswrite == -1) continue;
459 pipepathbuf[sizeof(pipepathbuf)-2]= 0;
460 snyprintf(pipepathbuf,sizeof(pipepathbuf),PIPEFORMAT,
461 (unsigned long)request_mbuf.clientpid,(unsigned long)mypid,fd);
462 assert(!pipepathbuf[sizeof(pipepathbuf)-2]);
463 tempfd= open(pipepathbuf,O_RDWR);
464 if (tempfd<0) syscallerror("prelim open pipe");
465 if (fdarray[fd].iswrite) {
466 fdarray[fd].holdfd= -1;
467 fdarray[fd].realfd= open(pipepathbuf, O_WRONLY);
469 fdarray[fd].holdfd= open(pipepathbuf, O_WRONLY);
470 if (fdarray[fd].holdfd<0) syscallerror("hold open pipe");
471 fdarray[fd].realfd= open(pipepathbuf, O_RDONLY);
473 if (fdarray[fd].realfd<0) syscallerror("real open pipe");
474 if (unlink(pipepathbuf)) syscallerror("unlink pipe");
475 if (close(tempfd)) syscallerror("close prelim fd onto pipe");
479 static void groupnames(int ngids, gid_t *gids, const char ***names_r) {
484 names= xmalloc(sizeof(char*)*ngids);
485 for (i=0; i<ngids; i++) {
486 gr= getgrgid(gids[i]);
487 if (!gr) miscerror("get group entry");
488 names[i]= xstrsave(gr->gr_name);
493 static void lookup_uidsgids(void) {
496 pw= getpwnam(logname);
497 if (!pw) miscerror("look up calling user");
498 assert(!strcmp(pw->pw_name,logname));
499 callinguser_shell= xstrsave(pw->pw_shell);
501 pw= getpwnam(serviceuser);
502 if (!pw) miscerror("look up service user");
503 assert(!strcmp(pw->pw_name,serviceuser));
504 serviceuser_dir= xstrsave(nondebug_serviceuserdir(pw->pw_dir));
505 serviceuser_shell= xstrsave(pw->pw_shell);
506 serviceuser_uid= pw->pw_uid;
508 if (initgroups(pw->pw_name,pw->pw_gid)) syscallerror("initgroups");
509 if (setreuid(pw->pw_uid,pw->pw_uid)) syscallerror("setreuid 1");
510 if (setreuid(pw->pw_uid,pw->pw_uid)) syscallerror("setreuid 2");
512 if (!setreuid(pw->pw_uid,0)) miscerror("setreuid 3 unexpectedly succeeded");
513 if (errno != EPERM) syscallerror("setreuid 3 failed in unexpected way");
515 service_ngids= getgroups(0,0); if (service_ngids == -1) syscallerror("getgroups(0,0)");
516 if (service_ngids > MAX_GIDS) miscerror("service user is in far too many groups");
517 service_gids= xmalloc(sizeof(gid_t)*(service_ngids+1));
518 service_gids[0]= pw->pw_gid;
519 if (getgroups(service_ngids,service_gids+1) != service_ngids)
520 syscallerror("getgroups(size,list)");
522 groupnames(request_mbuf.ngids,calling_gids,&calling_groups);
523 groupnames(service_ngids,service_gids,&service_groups);
526 static void findinpath(char *program) {
527 char *part, *exectry;
528 const char *string, *delim, *nextstring;
532 if (strchr(program,'/')) {
533 r= stat(program,&stab);
534 if (r) syscallfailure("failed check for program (containing slash) `%s'",program);
537 string= getenv("PATH");
538 if (!string) string= defaultpath();
540 delim= strchr(string,':');
542 if (delim-string > MAX_GENERAL_STRING)
543 failure("execute-from-path, but PATH component too long");
544 partsize= delim-string;
547 partsize= strlen(string);
550 part= xstrsubsave(string,partsize);
551 exectry= part[0] ? xstrcat3save(part,"/",program) : xstrsave(program);
553 r= stat(exectry,&stab);
554 if (!r) { execpath= exectry; break; }
558 if (!execpath) failure("program `%s' not found on default PATH",program);
562 static void check_find_executable(void) {
567 case tokv_word_reject:
568 failure("request rejected");
569 case tokv_word_execute:
570 findinpath(execpath);
572 case tokv_word_executefromdirectory:
573 r= stat(execpath,&stab);
574 if (r) syscallfailure("checking for executable in directory, `%s'",execpath);
576 case tokv_word_executebuiltin:
578 case tokv_word_executefrompath:
586 static void makenonexistentfd(int fd) {
587 if (fdarray[fd].realfd == -1) {
588 assert(fdarray[fd].holdfd == -1);
590 if (close(fdarray[fd].realfd))
591 syscallfailure("close unwanted file descriptor %d",fd);
592 fdarray[fd].realfd= -1;
594 if (fdarray[fd].holdfd != -1) {
595 if (close(fdarray[fd].holdfd))
596 syscallfailure("close unwanted hold descriptor for %d",fd);
601 static void makenullfd(int fd) {
602 fdarray[fd].realfd= open("/dev/null",
603 fdarray[fd].wantrw == tokv_word_read ? O_RDONLY :
604 fdarray[fd].wantrw == tokv_word_write ? O_WRONLY :
606 if (fdarray[fd].realfd<0)
607 syscallfailure("cannot open /dev/null for null or allowed, unprovided fd");
610 static void check_fds(void) {
613 assert(fdarrayused>=2);
614 if (!(fdarray[2].wantstate == tokv_word_requirefd ||
615 fdarray[2].wantstate == tokv_word_allowfd) ||
616 fdarray[2].wantrw != tokv_word_write)
617 failure("must have stderr (fd 2), but file descriptor setup in "
618 "configuration does not have it or not for writing");
620 for (fd=0; fd<fdarrayused; fd++) {
621 switch (fdarray[fd].wantstate) {
622 case tokv_word_rejectfd:
623 if (fdarray[fd].realfd != -1)
624 failure("file descriptor %d provided but rejected",fd);
626 case tokv_word_ignorefd:
627 makenonexistentfd(fd);
629 case tokv_word_nullfd:
630 makenonexistentfd(fd);
633 case tokv_word_requirefd:
634 if (fdarray[fd].realfd == -1)
635 failure("file descriptor %d required but not provided",fd);
636 assert(fdarray[fd].holdfd == -1);
638 case tokv_word_allowfd:
639 if (fdarray[fd].realfd == -1) {
640 assert(fdarray[fd].holdfd == -1);
643 if (fdarray[fd].iswrite) {
644 if (fdarray[fd].wantrw == tokv_word_read)
645 failure("file descriptor %d provided write, wanted read",fd);
647 if (fdarray[fd].wantrw == tokv_word_write)
648 failure("file descriptor %d provided read, wanted write",fd);
655 static void send_progress_ok(void) {
656 struct progress_msg progress_mbuf;
658 memset(&progress_mbuf,0,sizeof(progress_mbuf));
659 progress_mbuf.magic= PROGRESS_MAGIC;
660 progress_mbuf.type= pt_ok;
661 xfwrite(&progress_mbuf,sizeof(progress_mbuf),swfile);
665 static void fork_service_synch(void) {
667 struct sigaction sig;
668 int r, synchsocket[2];
671 r= socketpair(AF_UNIX,SOCK_STREAM,0,synchsocket);
672 if (r) syscallerror("cannot create socket for synch");
674 /* Danger here. Firstly, we start handling signals asynchronously.
675 * Secondly after we fork the service we want it to put
676 * itself in a separate process group so that we can kill it and all
677 * its children - but, we mustn't kill the whole pgrp before it has
678 * done that (or we kill ourselves) and it mustn't fork until it
679 * knows that we are going to kill it the right way ...
681 sig.sa_handler= sighandler_chld;
682 sigemptyset(&sig.sa_mask);
683 sigaddset(&sig.sa_mask,SIGCHLD);
685 if (sigaction(SIGCHLD,&sig,0)) syscallerror("cannot set sigchld handler");
688 if (newchild == -1) syscallerror("cannot fork to invoke service");
689 if (!newchild) execservice(synchsocket,fileno(swfile));
690 childtokill= child= newchild;
692 if (close(synchsocket[1])) syscallerror("cannot close other end of synch socket");
694 r= synchread(synchsocket[0],'y');
695 if (r) syscallerror("read synch byte from child");
700 r= write(synchsocket[0],&synchmsg,1);
701 if (r!=1) syscallerror("write synch byte to child");
703 if (close(synchsocket[0])) syscallerror("cannot close my end of synch socket");
706 void servicerequest(int sfd) {
707 struct event_msg event_mbuf;
715 debug_dumprequest(mypid);
718 r= parse_string(TOPLEVEL_OVERRIDDEN_CONFIGURATION,
719 "<builtin toplevel override configuration>",1);
721 r= parse_string(TOPLEVEL_CONFIGURATION,
722 "<builtin toplevel configuration>",1);
724 ensurelogopen(USERVD_LOGFACILITY);
725 if (r == tokv_error) failure("error encountered while parsing configuration");
726 assert(r == tokv_quit);
728 debug_dumpexecsettings();
730 check_find_executable();
734 getevent(&event_mbuf);
735 assert(event_mbuf.type == et_confirm);
737 fork_service_synch();
739 getevent(&event_mbuf);