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.
55 #include <sys/types.h>
56 #include <sys/fcntl.h>
58 #include <sys/socket.h>
68 /* NB: defaults for the execution state are not set here, but in
69 * the RESET_CONFIGURATION #define in daemon.h. */
70 struct request_msg request_mbuf;
71 struct keyvaluepair *defvararray;
72 struct fdstate *fdarray;
73 int fdarraysize, fdarrayused;
74 int restfdwantstate= tokv_word_rejectfd, restfdwantrw;
77 char *serviceuser, *service, *logname, *cwd;
78 char *overridedata, *userrcfile;
79 char *serviceuser_dir, *serviceuser_shell, *callinguser_shell;
80 gid_t *calling_gids, *service_gids;
81 uid_t serviceuser_uid=-1;
82 const char **calling_groups, **service_groups;
83 char *execpath, **execargs;
85 int setenvironment, suppressargs, disconnecthup;
86 builtinserviceexec_fnt *execbuiltin;
87 int syslogopenfacility=-1;
89 static FILE *swfile, *srfile;
90 static pid_t child=-1, childtokill=-1;
93 /* Function shared with servexec.c: */
95 int synchread(int fd, int ch) {
100 r= read(fd,&synchmsg,1);
102 if (r==0) { errno= ECONNRESET; return -1; }
104 if (errno!=EINTR) return -1;
106 assert(synchmsg==ch);
110 const char *defaultpath(void) {
111 return serviceuser_uid ? DEFAULTPATH_USER : DEFAULTPATH_ROOT;
114 /* General-purpose functions; these do nothing special about signals */
116 static void blocksignals(void) {
121 sigaddset(&set,SIGCHLD);
122 sigaddset(&set,SIGPIPE);
123 r= sigprocmask(SIG_BLOCK,&set,0); assert(!r);
126 static void xfwriteerror(void) {
127 if (errno != EPIPE) syscallerror("writing to client");
129 ensurelogopen(USERVD_LOGFACILITY);
130 syslog(LOG_INFO,"client went away (broken pipe)");
134 static void xfwrite(const void *p, size_t sz, FILE *file) {
136 nr= fwrite(p,1,sz,file);
137 if (nr != sz) xfwriteerror();
140 static void xfflush(FILE *file) {
141 if (fflush(file)) xfwriteerror();
144 /* Functions which may be called only from the main thread. These may
145 * use main-thread objects and must block signals before using signal
149 static void xfread(void *p, size_t sz) {
151 nr= working_fread(p,sz,srfile); if (nr == sz) return;
152 if (ferror(srfile)) syscallerror("reading from client");
154 assert(feof(srfile));
155 syslog(LOG_INFO,"client went away (unexpected EOF)");
160 static char *xfreadsetstring(int l) {
162 assert(l<=MAX_GENERAL_STRING);
164 xfread(s,sizeof(*s)*l);
169 static char *xfreadstring(void) {
171 xfread(&l,sizeof(l));
172 return xfreadsetstring(l);
175 static void getevent(struct event_msg *event_r) {
179 xfread(event_r,sizeof(struct event_msg));
180 switch (event_r->type) {
182 fd= event_r->data.closereadfd.fd;
183 if (fd >= fdarrayused) {
185 syslog(LOG_ERR,"client sent bad file descriptor %d to close (max %d)",
189 if (fdarray[fd].holdfd!=-1) {
190 if (close(fdarray[fd].holdfd)) syscallerror("cannot close holding fd");
191 fdarray[fd].holdfd= -1;
196 syslog(LOG_INFO,"client disconnected");
204 /* Functions which may be called either from signal handlers or from
205 * the main thread. They block signals in case they are on the main
206 * thread, and may only use signal handler objects. None of them
207 * return. If they did they'd have to restore the signal mask.
210 void miscerror(const char *what) {
212 syslog(LOG_ERR,"failure: %s",what);
216 void syscallerror(const char *what) {
221 syslog(LOG_ERR,"system call failure: %s: %s",what,strerror(e));
225 /* Functions which may be called from signal handlers. These
226 * may use signal-handler objects. The main program may only
227 * call them with signals blocked, and they may not use any
228 * main-thread objects.
231 void ensurelogopen(int wantfacility) {
232 if (syslogopenfacility==wantfacility) return;
233 if (syslogopenfacility!=-1) closelog();
234 openlog(USERVD_LOGIDENT,LOG_NDELAY|LOG_PID,wantfacility);
235 syslogopenfacility= wantfacility;
238 void NONRETURNING disconnect(int exitstatus) {
239 /* This function can sometimes indirectly call itself (eg,
240 * xfwrite, syscallerror can cause it to be called). So, all
241 * the global variables indicating need for action are reset
242 * before the action is taken so that if it fails it isn't
245 struct progress_msg progress_mbuf;
250 if (childtokill!=-1 && disconnecthup) {
251 orgtokill= childtokill;
254 r= kill(-orgtokill,SIGHUP);
255 if (r && errno!=EPERM && errno!=ESRCH)
256 syscallerror("sending SIGHUP to service process group");
263 memset(&progress_mbuf,0,sizeof(progress_mbuf));
264 progress_mbuf.magic= PROGRESS_MAGIC;
265 progress_mbuf.type= pt_failed;
266 xfwrite(&progress_mbuf,sizeof(progress_mbuf),swfilereal);
273 static void NONRETURNING sighandler_chld(int ignored) {
274 struct progress_msg progress_mbuf;
278 returned= wait3(&status,WNOHANG,0);
279 if (returned==-1) syscallerror("wait for child failed");
280 if (!returned) syscallerror("spurious sigchld");
281 if (returned!=child) syscallerror("spurious child process");
282 child= childtokill= -1;
284 memset(&progress_mbuf,0,sizeof(progress_mbuf));
285 progress_mbuf.magic= PROGRESS_MAGIC;
286 progress_mbuf.type= pt_terminated;
287 progress_mbuf.data.terminated.status= status;
288 xfwrite(&progress_mbuf,sizeof(progress_mbuf),swfile);
291 syslog(LOG_INFO,"service completed (status %d %d)",(status>>8)&0x0ff,status&0x0ff);
295 /* Functions which are called only during setup, before
296 * the signal asynchronicity starts. They can do anything they like.
299 void ensurefdarray(int fd) {
300 if (fd < fdarrayused) return;
301 if (fd >= fdarraysize) {
302 fdarraysize= ((fd+2)<<1);
303 fdarray= xrealloc(fdarray,sizeof(struct fdstate)*fdarraysize);
305 while (fd >= fdarrayused) {
306 fdarray[fdarrayused].iswrite= -1;
307 fdarray[fdarrayused].realfd= -1;
308 fdarray[fdarrayused].holdfd= -1;
309 fdarray[fdarrayused].wantstate= restfdwantstate;
310 fdarray[fdarrayused].wantrw= restfdwantrw;
315 static void NONRETURNING generalfailure(const char *prefix, int reserveerrno,
316 int errnoval, const char *fmt, va_list al) {
317 char errmsg[MAX_ERRMSG_LEN];
320 strnycpy(errmsg,prefix,sizeof(errmsg));
321 strnytcat(errmsg,": ",sizeof(errmsg));
325 vsnytprintfcat(errmsg,sizeof(errmsg)-reserveerrno,fmt,al);
327 strnytcat(errmsg,": ",sizeof(errmsg));
328 strnytcat(errmsg,strerror(errnoval),sizeof(errmsg));
330 senderrmsgstderr(errmsg);
331 syslog(LOG_INFO,"service failed (%s)",errmsg);
335 static void NONRETURNPRINTFFORMAT(1,2) failure(const char *fmt, ...) {
339 generalfailure(0,0,0,fmt,al);
342 static void NONRETURNPRINTFFORMAT(1,2) syscallfailure(const char *fmt, ...) {
348 generalfailure("system call failed",ERRMSG_RESERVE_ERRNO,e,fmt,al);
351 void senderrmsgstderr(const char *errmsg) {
352 struct progress_msg progress_mbuf;
357 memset(&progress_mbuf,0,sizeof(progress_mbuf));
358 progress_mbuf.magic= PROGRESS_MAGIC;
359 progress_mbuf.type= pt_errmsg;
360 progress_mbuf.data.errmsg.messagelen= l;
361 xfwrite(&progress_mbuf,sizeof(progress_mbuf),swfile);
362 xfwrite(errmsg,l,swfile);
363 ul= PROGRESS_ERRMSG_END_MAGIC;
364 xfwrite(&ul,sizeof(ul),swfile);
368 /* The per-request main program and its subfunctions. */
370 static void setup_comms(int sfd) {
371 static char swbuf[BUFSIZ];
372 static char srbuf[BUFSIZ];
374 struct sigaction sig;
376 ensurelogopen(USERVD_LOGFACILITY);
377 syslog(LOG_DEBUG,"call connected");
379 mypid= getpid(); if (mypid == -1) syscallerror("getpid");
381 sig.sa_handler= SIG_IGN;
382 sigemptyset(&sig.sa_mask);
384 if (sigaction(SIGPIPE,&sig,0)) syscallerror("cannot ignore sigpipe");
386 srfile= fdopen(sfd,"r");
387 if (!srfile) syscallerror("turn socket fd into reading FILE*");
388 if (setvbuf(srfile,srbuf,_IOFBF,sizeof(srbuf)))
389 syscallerror("set buffering on socket reads");
391 swfile= fdopen(sfd,"w");
392 if (!swfile) syscallerror("turn socket fd into writing FILE*");
393 if (setvbuf(swfile,swbuf,_IOFBF,sizeof(swbuf)))
394 syscallerror("set buffering on socket writes");
397 static void send_opening(void) {
398 struct opening_msg opening_mbuf;
400 memset(&opening_mbuf,0,sizeof(opening_mbuf));
401 opening_mbuf.magic= OPENING_MAGIC;
402 memcpy(opening_mbuf.protocolchecksumversion,protocolchecksumversion,PCSUMSIZE);
403 opening_mbuf.overlordpid= overlordpid;
404 opening_mbuf.serverpid= mypid;
405 xfwrite(&opening_mbuf,sizeof(opening_mbuf),swfile);
409 static void receive_request(void) {
413 xfread(&request_mbuf,sizeof(request_mbuf));
414 serviceuser= xfreadsetstring(request_mbuf.serviceuserlen);
415 service= xfreadsetstring(request_mbuf.servicelen);
416 assert(request_mbuf.spoofed==0 || request_mbuf.spoofed==1);
417 logname= xfreadsetstring(request_mbuf.lognamelen);
418 cwd= xfreadsetstring(request_mbuf.cwdlen);
419 if (request_mbuf.overridelen >= 0) {
420 assert(request_mbuf.overridelen <= MAX_OVERRIDE_LEN);
421 overridedata= xfreadsetstring(request_mbuf.overridelen);
423 assert(request_mbuf.overridelen == -1);
426 assert(request_mbuf.ngids <= MAX_GIDS);
427 calling_gids= xmalloc(sizeof(gid_t)*request_mbuf.ngids);
428 xfread(calling_gids,sizeof(gid_t)*request_mbuf.ngids);
430 fdarraysize= 4; fdarray= xmalloc(sizeof(struct fdstate)*fdarraysize);
431 fdarrayused= 1; fdarray[0].iswrite= -1;
432 fdarray[0].wantstate= tokv_word_rejectfd;
433 assert(request_mbuf.nreadfds+request_mbuf.nwritefds <= MAX_ALLOW_FD+1);
434 for (i=0; i<request_mbuf.nreadfds+request_mbuf.nwritefds; i++) {
435 xfread(&fd,sizeof(int));
436 assert(fd <= MAX_ALLOW_FD);
438 assert(fdarray[fd].iswrite == -1);
439 fdarray[fd].iswrite= (i>=request_mbuf.nreadfds);
442 assert(request_mbuf.nargs <= MAX_ARGSDEFVAR);
443 argarray= xmalloc(sizeof(char*)*(request_mbuf.nargs));
444 for (i=0; i<request_mbuf.nargs; i++) argarray[i]= xfreadstring();
445 assert(request_mbuf.nvars <= MAX_ARGSDEFVAR);
446 defvararray= xmalloc(sizeof(struct keyvaluepair)*request_mbuf.nvars);
447 for (i=0; i<request_mbuf.nvars; i++) {
448 defvararray[i].key= xfreadstring();
449 assert(defvararray[i].key[0]);
450 defvararray[i].value= xfreadstring();
452 xfread(&ul,sizeof(ul));
453 assert(ul == REQUEST_END_MAGIC);
456 static void establish_pipes(void) {
458 char pipepathbuf[PIPEMAXLEN+2];
460 for (fd=0; fd<fdarrayused; fd++) {
461 if (fdarray[fd].iswrite == -1) continue;
462 pipepathbuf[sizeof(pipepathbuf)-2]= 0;
463 snyprintf(pipepathbuf,sizeof(pipepathbuf),PIPEFORMAT,
464 (unsigned long)request_mbuf.clientpid,(unsigned long)mypid,fd);
465 assert(!pipepathbuf[sizeof(pipepathbuf)-2]);
466 tempfd= open(pipepathbuf,O_RDWR);
467 if (tempfd<0) syscallerror("prelim open pipe");
468 if (fdarray[fd].iswrite) {
469 fdarray[fd].holdfd= -1;
470 fdarray[fd].realfd= open(pipepathbuf, O_WRONLY);
472 fdarray[fd].holdfd= open(pipepathbuf, O_WRONLY);
473 if (fdarray[fd].holdfd<0) syscallerror("hold open pipe");
474 fdarray[fd].realfd= open(pipepathbuf, O_RDONLY);
476 if (fdarray[fd].realfd<0) syscallerror("real open pipe");
477 if (unlink(pipepathbuf)) syscallerror("unlink pipe");
478 if (close(tempfd)) syscallerror("close prelim fd onto pipe");
482 static void groupnames(int ngids, gid_t *gids, const char ***names_r) {
487 names= xmalloc(sizeof(char*)*ngids);
488 for (i=0; i<ngids; i++) {
489 gr= getgrgid(gids[i]);
490 if (!gr) miscerror("get group entry");
491 names[i]= xstrsave(gr->gr_name);
496 static void lookup_uidsgids(void) {
499 pw= getpwnam(logname);
500 if (!pw) miscerror("look up calling user");
501 assert(!strcmp(pw->pw_name,logname));
502 callinguser_shell= xstrsave(pw->pw_shell);
504 pw= getpwnam(serviceuser);
505 if (!pw) miscerror("look up service user");
506 assert(!strcmp(pw->pw_name,serviceuser));
507 serviceuser_dir= xstrsave(nondebug_serviceuserdir(pw->pw_dir));
508 serviceuser_shell= xstrsave(pw->pw_shell);
509 serviceuser_uid= pw->pw_uid;
511 if (setregid(pw->pw_gid,pw->pw_gid)) syscallerror("setregid 1");
512 if (initgroups(pw->pw_name,pw->pw_gid)) syscallerror("initgroups");
513 if (setreuid(pw->pw_uid,pw->pw_uid)) syscallerror("setreuid 1");
514 if (setreuid(pw->pw_uid,pw->pw_uid)) syscallerror("setreuid 2");
516 if (!setreuid(pw->pw_uid,0)) miscerror("setreuid 3 unexpectedly succeeded");
517 if (errno != EPERM) syscallerror("setreuid 3 failed in unexpected way");
519 if (setregid(pw->pw_gid,pw->pw_gid)) syscallerror("setregid 2");
521 service_ngids= getgroups(0,0); if (service_ngids == -1) syscallerror("getgroups(0,0)");
522 if (service_ngids > MAX_GIDS) miscerror("service user is in far too many groups");
523 service_gids= xmalloc(sizeof(gid_t)*(service_ngids+1));
524 service_gids[0]= pw->pw_gid;
525 if (getgroups(service_ngids,service_gids+1) != service_ngids)
526 syscallerror("getgroups(size,list)");
528 groupnames(request_mbuf.ngids,calling_gids,&calling_groups);
529 groupnames(service_ngids,service_gids,&service_groups);
532 static void findinpath(char *program) {
533 char *part, *exectry;
534 const char *string, *delim, *nextstring;
538 if (strchr(program,'/')) {
539 r= stat(program,&stab);
540 if (r) syscallfailure("failed check for program (containing slash) `%s'",program);
543 string= getenv("PATH");
544 if (!string) string= defaultpath();
546 delim= strchr(string,':');
548 if (delim-string > MAX_GENERAL_STRING)
549 failure("execute-from-path, but PATH component too long");
550 partsize= delim-string;
553 partsize= strlen(string);
556 part= xstrsubsave(string,partsize);
557 exectry= part[0] ? xstrcat3save(part,"/",program) : xstrsave(program);
559 r= stat(exectry,&stab);
560 if (!r) { execpath= exectry; break; }
564 if (!execpath) failure("program `%s' not found on default PATH",program);
568 static void check_find_executable(void) {
573 case tokv_word_reject:
574 failure("request rejected");
575 case tokv_word_execute:
576 findinpath(execpath);
578 case tokv_word_executefromdirectory:
579 r= stat(execpath,&stab);
580 if (r) syscallfailure("checking for executable in directory, `%s'",execpath);
582 case tokv_word_executebuiltin:
584 case tokv_word_executefrompath:
592 static void makenonexistentfd(int fd) {
593 if (fdarray[fd].realfd == -1) {
594 assert(fdarray[fd].holdfd == -1);
596 if (close(fdarray[fd].realfd))
597 syscallfailure("close unwanted file descriptor %d",fd);
598 fdarray[fd].realfd= -1;
600 if (fdarray[fd].holdfd != -1) {
601 if (close(fdarray[fd].holdfd))
602 syscallfailure("close unwanted hold descriptor for %d",fd);
603 fdarray[fd].holdfd= -1;
608 static void makenullfd(int fd) {
609 fdarray[fd].realfd= open("/dev/null",
610 fdarray[fd].wantrw == tokv_word_read ? O_RDONLY :
611 fdarray[fd].wantrw == tokv_word_write ? O_WRONLY :
613 if (fdarray[fd].realfd<0)
614 syscallfailure("cannot open /dev/null for null or allowed, unprovided fd");
617 static void check_fds(void) {
620 assert(fdarrayused>=2);
621 if (!(fdarray[2].wantstate == tokv_word_requirefd ||
622 fdarray[2].wantstate == tokv_word_allowfd) ||
623 fdarray[2].wantrw != tokv_word_write)
624 failure("must have stderr (fd 2), but file descriptor setup in "
625 "configuration does not have it or not for writing");
627 for (fd=0; fd<fdarrayused; fd++) {
628 switch (fdarray[fd].wantstate) {
629 case tokv_word_rejectfd:
630 if (fdarray[fd].realfd != -1)
631 failure("file descriptor %d provided but rejected",fd);
633 case tokv_word_ignorefd:
634 makenonexistentfd(fd);
636 case tokv_word_nullfd:
637 makenonexistentfd(fd);
640 case tokv_word_requirefd:
641 if (fdarray[fd].realfd == -1)
642 failure("file descriptor %d required but not provided",fd);
643 assert(fdarray[fd].holdfd == -1);
645 case tokv_word_allowfd:
646 if (fdarray[fd].realfd == -1) {
647 assert(fdarray[fd].holdfd == -1);
650 if (fdarray[fd].iswrite) {
651 if (fdarray[fd].wantrw == tokv_word_read)
652 failure("file descriptor %d provided write, wanted read",fd);
654 if (fdarray[fd].wantrw == tokv_word_write)
655 failure("file descriptor %d provided read, wanted write",fd);
662 static void send_progress_ok(void) {
663 struct progress_msg progress_mbuf;
665 memset(&progress_mbuf,0,sizeof(progress_mbuf));
666 progress_mbuf.magic= PROGRESS_MAGIC;
667 progress_mbuf.type= pt_ok;
668 xfwrite(&progress_mbuf,sizeof(progress_mbuf),swfile);
672 static void fork_service_synch(void) {
674 struct sigaction sig;
675 int r, synchsocket[2];
678 r= socketpair(AF_UNIX,SOCK_STREAM,0,synchsocket);
679 if (r) syscallerror("cannot create socket for synch");
681 /* Danger here. Firstly, we start handling signals asynchronously.
682 * Secondly after we fork the service we want it to put
683 * itself in a separate process group so that we can kill it and all
684 * its children - but, we mustn't kill the whole pgrp before it has
685 * done that (or we kill ourselves) and it mustn't fork until it
686 * knows that we are going to kill it the right way ...
688 sig.sa_handler= sighandler_chld;
689 sigemptyset(&sig.sa_mask);
690 sigaddset(&sig.sa_mask,SIGCHLD);
692 if (sigaction(SIGCHLD,&sig,0)) syscallerror("cannot set sigchld handler");
695 if (newchild == -1) syscallerror("cannot fork to invoke service");
696 if (!newchild) execservice(synchsocket,fileno(swfile));
697 childtokill= child= newchild;
699 if (close(synchsocket[1])) syscallerror("cannot close other end of synch socket");
701 r= synchread(synchsocket[0],'y');
702 if (r) syscallerror("read synch byte from child");
707 r= write(synchsocket[0],&synchmsg,1);
708 if (r!=1) syscallerror("write synch byte to child");
710 if (close(synchsocket[0])) syscallerror("cannot close my end of synch socket");
713 void servicerequest(int sfd) {
714 struct event_msg event_mbuf;
720 if (request_mbuf.clientpid == (pid_t)-1) _exit(2);
723 debug_dumprequest(mypid);
724 syslog(LOG_INFO,"%s %s -> %s %c %s",
725 request_mbuf.spoofed ? "spoof" : "user",
726 logname, serviceuser, overridedata?'!':':', service);
729 r= parse_string(TOPLEVEL_OVERRIDDEN_CONFIGURATION,
730 "<builtin toplevel override configuration>",1);
732 r= parse_string(TOPLEVEL_CONFIGURATION,
733 "<builtin toplevel configuration>",1);
735 ensurelogopen(USERVD_LOGFACILITY);
736 if (r == tokv_error) failure("error encountered while parsing configuration");
737 assert(r == tokv_quit);
739 debug_dumpexecsettings();
741 check_find_executable();
745 getevent(&event_mbuf);
746 assert(event_mbuf.type == et_confirm);
748 fork_service_synch();
750 getevent(&event_mbuf);