chiark / gitweb /
packaging fixes
[userv.git] / process.c
1 /*
2  * userv - process.c
3  * daemon code to process one request (is parent of service process)
4  *
5  * Copyright (C)1996-1999,2001,2003 Ian Jackson
6  *
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.
11  *
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.
16  *
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.
20  */
21
22 /*
23  * We do some horrible asynchronous stuff with signals.
24  *
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
27  * the main program:
28  *  the syslog() family of calls, and the associated
29  *    syslogopenfacility variable
30  *  swfile (stdio stream)
31  *
32  * The following objects are used in the main program unprotected
33  * and so must not be used in signal handlers:
34  *  srfile
35  *
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.
39  */
40
41 #include <stdio.h>
42 #include <stdarg.h>
43 #include <unistd.h>
44 #include <assert.h>
45 #include <signal.h>
46 #include <string.h>
47 #include <stdlib.h>
48 #include <errno.h>
49 #include <syslog.h>
50 #include <pwd.h>
51 #include <grp.h>
52 #include <limits.h>
53 #include <fcntl.h>
54 #include <sys/wait.h>
55 #include <sys/time.h>
56 #include <sys/resource.h>
57 #include <sys/types.h>
58 #include <sys/stat.h>
59 #include <sys/socket.h>
60 #include <sys/un.h>
61
62 #include "config.h"
63 #include "common.h"
64 #include "both.h"
65 #include "daemon.h"
66 #include "lib.h"
67 #include "tokens.h"
68
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;
76 int service_ngids;
77 char **argarray;
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;
85 int execute;
86 int setenvironment, suppressargs, disconnecthup;
87 builtinserviceexec_fnt *execbuiltin;
88 int syslogopenfacility=-1;
89
90 static FILE *swfile, *srfile;
91 static pid_t child=-1, childtokill=-1;
92 static pid_t mypid;
93
94 /* Function shared with servexec.c: */
95
96 int synchread(int fd, int ch) {
97   char synchmsg;
98   int r;
99   
100   for (;;) {
101     r= read(fd,&synchmsg,1);
102     if (r==1) break;
103     if (r==0) { errno= ECONNRESET; return -1; }
104     assert(r<0);
105     if (errno!=EINTR) return -1;
106   };
107   assert(synchmsg==ch);
108   return 0;
109 }
110
111 const char *defaultpath(void) {
112   return serviceuser_uid ? DEFAULTPATH_USER : DEFAULTPATH_ROOT;
113 }
114
115 /* General-purpose functions; these do nothing special about signals */
116
117 static void blocksignals(void) {
118   int r;
119   sigset_t set;
120
121   sigemptyset(&set);
122   sigaddset(&set,SIGCHLD);
123   sigaddset(&set,SIGPIPE);
124   r= sigprocmask(SIG_BLOCK,&set,0); assert(!r);
125 }
126
127 static void xfwriteerror(void) {
128   if (errno != EPIPE) syscallerror("writing to client");
129   blocksignals();
130   ensurelogopen(USERVD_LOGFACILITY);
131   syslog(LOG_INFO,"client went away (broken pipe)");
132   disconnect(8);
133 }
134
135 static void xfwrite(const void *p, size_t sz, FILE *file) {
136   size_t nr;
137   nr= fwrite(p,1,sz,file);
138   if (nr != sz) xfwriteerror();
139 }
140
141 static void xfflush(FILE *file) {
142   if (fflush(file)) xfwriteerror();
143 }
144
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
147  * handler objects.
148  */
149
150 static void xfread(void *p, size_t sz) {
151   size_t nr;
152   nr= working_fread(p,sz,srfile); if (nr == sz) return;
153   if (ferror(srfile)) syscallerror("reading from client");
154   blocksignals();
155   assert(feof(srfile));
156   syslog(LOG_INFO,"client went away (unexpected EOF)");
157   swfile= 0;
158   disconnect(8);
159 }
160
161 static char *xfreadsetstring(int l) {
162   char *s;
163   assert(l<=MAX_GENERAL_STRING);
164   s= xmalloc(l+1);
165   xfread(s,sizeof(*s)*l);
166   s[l]= 0;
167   return s;
168 }
169
170 static char *xfreadstring(void) {
171   int l;
172   xfread(&l,sizeof(l));
173   return xfreadsetstring(l);
174 }
175
176 static void getevent(struct event_msg *event_r) {
177   int fd;
178   
179   for (;;) {
180     xfread(event_r,sizeof(struct event_msg));
181     switch (event_r->type) {
182     case et_closereadfd:
183       fd= event_r->data.closereadfd.fd;
184       if (fd >= fdarrayused) {
185         blocksignals();
186         syslog(LOG_ERR,"client sent bad file descriptor %d to close (max %d)",
187                fd,fdarrayused-1);
188         disconnect(20);
189       }
190       if (fdarray[fd].holdfd!=-1) {
191         if (close(fdarray[fd].holdfd)) syscallerror("cannot close holding fd");
192         fdarray[fd].holdfd= -1;
193       }
194       break;
195     case et_disconnect:
196       blocksignals();
197       syslog(LOG_INFO,"client disconnected");
198       disconnect(4);
199     default:
200       return;
201     }
202   }
203 }
204
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.
209  */
210
211 void miscerror(const char *what) {
212   blocksignals();
213   syslog(LOG_ERR,"failure: %s",what);
214   disconnect(16);
215 }
216
217 void syscallerror(const char *what) {
218   int e;
219
220   e= errno;
221   blocksignals();
222   syslog(LOG_ERR,"system call failure: %s: %s",what,strerror(e));
223   disconnect(16);
224 }
225
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.
230  */
231
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;
237 }
238
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
244    * attempted again.
245    */
246   struct progress_msg progress_mbuf;
247   FILE *swfilereal;
248   pid_t orgtokill;
249   int r;
250   
251   if (childtokill!=-1 && disconnecthup) {
252     orgtokill= childtokill;
253     childtokill= -1;
254     if (disconnecthup) {
255       r= kill(-orgtokill,SIGHUP);
256       if (r && errno!=EPERM && errno!=ESRCH)
257         syscallerror("sending SIGHUP to service process group");
258     }
259     child= -1;
260   }
261   if (swfile) {
262     swfilereal= swfile;
263     swfile= 0;
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);
268     xfflush(swfilereal);
269   }
270
271   _exit(exitstatus);
272 }
273
274 static void reporttermination(int status) {
275   struct progress_msg progress_mbuf;
276   
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);
282   xfflush(swfile);
283 }
284
285 static void NONRETURNING sighandler_chld(int ignored) {
286   int status;
287   pid_t returned;
288
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;
294
295   reporttermination(status);
296   syslog(LOG_INFO,"service completed (status %d %d)",(status>>8)&0x0ff,status&0x0ff);
297   _exit(0);
298 }
299
300 /* Functions which are called only during setup, before
301  * the signal asynchronicity starts.  They can do anything they like.
302  */
303
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);
309   }
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;
316     fdarrayused++;
317   }
318 }
319
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];
323
324   if (prefix) {
325     strnycpy(errmsg,prefix,sizeof(errmsg));
326     strnytcat(errmsg,": ",sizeof(errmsg));
327   } else {
328     errmsg[0]= 0;
329   }
330   vsnytprintfcat(errmsg,sizeof(errmsg)-reserveerrno,fmt,al);
331   if (reserveerrno) {
332     strnytcat(errmsg,": ",sizeof(errmsg));
333     strnytcat(errmsg,strerror(errnoval),sizeof(errmsg));
334   }
335   senderrmsgstderr(errmsg);
336   syslog(LOG_INFO,"service failed (%s)",errmsg);
337   disconnect(12);
338 }
339
340 static void NONRETURNPRINTFFORMAT(1,2) failure(const char *fmt, ...) {
341   va_list al;
342
343   va_start(al,fmt);
344   generalfailure(0,0,0,fmt,al);
345 }  
346
347 static void NONRETURNPRINTFFORMAT(1,2) syscallfailure(const char *fmt, ...) {
348   va_list al;
349   int e;
350
351   e= errno;
352   va_start(al,fmt);
353   generalfailure("system call failed",ERRMSG_RESERVE_ERRNO,e,fmt,al);
354 }
355
356 void senderrmsgstderr(const char *errmsg) {
357   struct progress_msg progress_mbuf;
358   unsigned long ul;
359   int l;
360
361   l= strlen(errmsg);
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);
370   xfflush(swfile);
371 }
372
373 /* The per-request main program and its subfunctions. */
374
375 static void setup_comms(int sfd) {
376   static char swbuf[BUFSIZ];
377   static char srbuf[BUFSIZ];
378
379   struct sigaction sig;
380   
381   ensurelogopen(USERVD_LOGFACILITY);
382   syslog(LOG_DEBUG,"call connected");
383
384   mypid= getpid(); if (mypid == -1) syscallerror("getpid");
385
386   sig.sa_handler= SIG_IGN;
387   sigemptyset(&sig.sa_mask);
388   sig.sa_flags= 0;
389   if (sigaction(SIGPIPE,&sig,0)) syscallerror("cannot ignore sigpipe");
390
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");
395
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");
400 }
401
402 static void send_opening(void) {
403   struct opening_msg opening_mbuf;
404
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);
411   xfflush(swfile);
412 }
413
414 static void receive_request(void) {
415   int i, fd;
416   unsigned long ul;
417
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);
427   } else {
428     assert(request_mbuf.overridelen == -1);
429     overridedata= 0;
430   }
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);
434
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);
442     ensurefdarray(fd);
443     assert(fdarray[fd].iswrite == -1);
444     fdarray[fd].iswrite= (i>=request_mbuf.nreadfds);
445   }
446   /* fdarray[].iswrite now set; rest is still blank
447    * (ie want reject read, no realfd holdfd). */
448
449   assert(request_mbuf.nargs <= MAX_ARGSDEFVAR);
450   argarray= xmalloc(sizeof(char*)*(request_mbuf.nargs));
451   for (i=0; i<request_mbuf.nargs; i++) argarray[i]= xfreadstring();
452   assert(request_mbuf.nvars <= MAX_ARGSDEFVAR);
453   defvararray= xmalloc(sizeof(struct keyvaluepair)*request_mbuf.nvars);
454   for (i=0; i<request_mbuf.nvars; i++) {
455     defvararray[i].key= xfreadstring();
456     assert(defvararray[i].key[0]);
457     defvararray[i].value= xfreadstring();
458   }
459   xfread(&ul,sizeof(ul));
460   assert(ul == REQUEST_END_MAGIC);
461 }
462
463 static void establish_pipes(void) {
464   int fd, tempfd;
465   char pipepathbuf[PIPEMAXLEN+2];
466   
467   for (fd=0; fd<fdarrayused; fd++) {
468     if (fdarray[fd].iswrite == -1) continue;
469     pipepathbuf[sizeof(pipepathbuf)-2]= 0;
470     snyprintf(pipepathbuf,sizeof(pipepathbuf),PIPEFORMAT,
471               (unsigned long)request_mbuf.clientpid,(unsigned long)mypid,fd);
472     assert(!pipepathbuf[sizeof(pipepathbuf)-2]);
473     tempfd= open(pipepathbuf,O_RDWR);
474     if (tempfd<0) syscallerror("prelim open pipe");
475     if (fdarray[fd].iswrite) {
476       fdarray[fd].holdfd= -1;
477       fdarray[fd].realfd= open(pipepathbuf, O_WRONLY);
478     } else {
479       fdarray[fd].holdfd= open(pipepathbuf, O_WRONLY);
480       if (fdarray[fd].holdfd<0) syscallerror("hold open pipe");
481       fdarray[fd].realfd= open(pipepathbuf, O_RDONLY);
482     }
483     if (fdarray[fd].realfd<0) syscallerror("real open pipe");
484     if (unlink(pipepathbuf)) syscallerror("unlink pipe");
485     if (close(tempfd)) syscallerror("close prelim fd onto pipe");
486   }
487   /* Now fdarray[].realfd is pipe end for service in case service
488    * wants it.  If it's an input pipe, then .holdfd is the other
489    * (writing) end of the pipe - we keep it around so that the service
490    * doesn't get an apparently clean EOF if the caller disappears (eg
491    * due to a file read error) or the like (ie so that on disconnect
492    * we can guarantee to send the service SIGHUP before it gets EOF on
493    * the input fd).  Otherwise, .holdfd=-1.
494    */
495 }
496
497 static void groupnames(int ngids, gid_t *gids, const char ***names_r) {
498   const char **names;
499   struct group *gr;
500   int i;
501   
502   names= xmalloc(sizeof(char*)*ngids);
503   for (i=0; i<ngids; i++) {
504     gr= getgrgid(gids[i]);
505     if (!gr) miscerror("get group entry");
506     names[i]= xstrsave(gr->gr_name);
507   }
508   *names_r= names;
509 }
510   
511 static void lookup_uidsgids(void) {
512   struct passwd *pw;
513
514   pw= getpwnam(loginname);
515   if (!pw) miscerror("look up calling user");
516   assert(!strcmp(pw->pw_name,loginname));
517   callinguser_shell= xstrsave(pw->pw_shell);
518
519   pw= getpwnam(serviceuser);
520   if (!pw) miscerror("look up service user");
521   assert(!strcmp(pw->pw_name,serviceuser));
522   serviceuser_dir= xstrsave(nondebug_serviceuserdir(pw->pw_dir));
523   serviceuser_shell= xstrsave(pw->pw_shell);
524   serviceuser_uid= pw->pw_uid;
525   
526   if (setregid(pw->pw_gid,pw->pw_gid)) syscallerror("setregid 1");
527   if (initgroups(pw->pw_name,pw->pw_gid)) syscallerror("initgroups");
528   if (setreuid(pw->pw_uid,pw->pw_uid)) syscallerror("setreuid 1");
529   if (setreuid(pw->pw_uid,pw->pw_uid)) syscallerror("setreuid 2");
530   if (pw->pw_uid) {
531     if (!setreuid(pw->pw_uid,0)) miscerror("setreuid 3 unexpectedly succeeded");
532     if (errno != EPERM) syscallerror("setreuid 3 failed in unexpected way");
533   }
534   if (setregid(pw->pw_gid,pw->pw_gid)) syscallerror("setregid 2");
535
536   service_ngids= getgroups(0,0); if (service_ngids == -1) syscallerror("getgroups(0,0)");
537   if (service_ngids > MAX_GIDS) miscerror("service user is in far too many groups");
538   service_gids= xmalloc(sizeof(gid_t)*(service_ngids+1));
539   service_gids[0]= pw->pw_gid;
540   if (getgroups(service_ngids,service_gids+1) != service_ngids)
541     syscallerror("getgroups(size,list)");
542
543   groupnames(request_mbuf.ngids,calling_gids,&calling_groups);
544   groupnames(service_ngids,service_gids,&service_groups);
545 }
546
547 static void findinpath(char *program) {
548   char *part, *exectry;
549   const char *string, *delim, *nextstring;
550   struct stat stab;
551   int r, partsize;
552   
553   if (strchr(program,'/')) {
554     r= stat(program,&stab);
555     if (r) syscallfailure("failed check for program (containing slash) `%s'",program);
556     execpath= program;
557   } else {
558     string= getenv("PATH");
559     if (!string) string= defaultpath();
560     while (string) {
561       delim= strchr(string,':');
562       if (delim) {
563         if (delim-string > MAX_GENERAL_STRING)
564           failure("execute-from-path, but PATH component too long");
565         partsize= delim-string;
566         nextstring= delim+1;
567       } else {
568         partsize= strlen(string);
569         nextstring= 0;
570       }
571       part= xstrsubsave(string,partsize);
572       exectry= part[0] ? xstrcat3save(part,"/",program) : xstrsave(program);
573       free(part);
574       r= stat(exectry,&stab);
575       if (!r) { execpath= exectry; break; }
576       free(exectry);
577       string= nextstring;
578     }
579     if (!execpath) failure("program `%s' not found on default PATH",program);
580   }
581 }
582   
583 static void check_find_executable(void) {
584   struct stat stab;
585   int r;
586
587   switch (execute) {
588   case tokv_word_reject:
589     failure("request rejected");
590   case tokv_word_execute:
591     findinpath(execpath);
592     break;
593   case tokv_word_executefromdirectory:
594     r= stat(execpath,&stab);
595     if (r) syscallfailure("checking for executable in directory, `%s'",execpath);
596     break;
597   case tokv_word_executebuiltin:
598     break;
599   case tokv_word_executefrompath:
600     findinpath(service);
601     break;
602   default:
603     abort();
604   }
605 }
606
607 static void makenonexistentfd(int fd) {
608   if (fdarray[fd].realfd == -1) {
609     assert(fdarray[fd].holdfd == -1);
610   } else {
611     if (close(fdarray[fd].realfd))
612       syscallfailure("close unwanted file descriptor %d",fd);
613     fdarray[fd].realfd= -1;
614   
615     if (fdarray[fd].holdfd != -1) {
616       if (close(fdarray[fd].holdfd))
617         syscallfailure("close unwanted hold descriptor for %d",fd);
618       fdarray[fd].holdfd= -1;
619     }
620   }
621 }
622
623 static void makenullfd(int fd) {
624   fdarray[fd].realfd= open("/dev/null",
625                            fdarray[fd].wantrw == tokv_word_read ? O_RDONLY :
626                            fdarray[fd].wantrw == tokv_word_write ? O_WRONLY :
627                            0);
628   if (fdarray[fd].realfd<0)
629     syscallfailure("cannot open /dev/null for null or allowed, unprovided fd");
630 }
631
632 static void check_fds(void) {
633   int fd;
634   
635   assert(fdarrayused>=2);
636   if (!(fdarray[2].wantstate == tokv_word_requirefd ||
637         fdarray[2].wantstate == tokv_word_allowfd) ||
638       fdarray[2].wantrw != tokv_word_write)
639     failure("must have stderr (fd 2), but file descriptor setup in "
640             "configuration does not have it or not for writing");
641
642   for (fd=0; fd<fdarrayused; fd++) {
643     switch (fdarray[fd].wantstate) {
644     case tokv_word_rejectfd:
645       if (fdarray[fd].realfd != -1)
646         failure("file descriptor %d provided but rejected",fd);
647       break;
648     case tokv_word_ignorefd:
649       makenonexistentfd(fd);
650       break;
651     case tokv_word_nullfd:
652       makenonexistentfd(fd);
653       makenullfd(fd);
654       break;
655     case tokv_word_requirefd:
656       if (fdarray[fd].realfd == -1)
657         failure("file descriptor %d required but not provided",fd);
658       /* fall through */
659     case tokv_word_allowfd:
660       if (fdarray[fd].realfd == -1) {
661         assert(fdarray[fd].holdfd == -1);
662         makenullfd(fd);
663       } else {
664         if (fdarray[fd].iswrite) {
665           if (fdarray[fd].wantrw == tokv_word_read)
666             failure("file descriptor %d provided write, wanted read",fd);
667         } else {
668           if (fdarray[fd].wantrw == tokv_word_write)
669             failure("file descriptor %d provided read, wanted write",fd);
670         }
671       }
672     }
673   }
674   /* Now fdarray[].realfd is exactly what service wants: pipe end or
675    * /dev/null or -1.  If .realfd is not -1 then .holdfd may be the fd
676    * for the writing end of the corresponding pipe.
677    */
678 }
679
680 static void send_progress_ok(void) {
681   struct progress_msg progress_mbuf;
682
683   memset(&progress_mbuf,0,sizeof(progress_mbuf));
684   progress_mbuf.magic= PROGRESS_MAGIC;
685   progress_mbuf.type= pt_ok;
686   xfwrite(&progress_mbuf,sizeof(progress_mbuf),swfile);
687   xfflush(swfile);
688 }
689
690 static void fork_service_synch(void) {
691   pid_t newchild;
692   struct sigaction sig;
693   int r, synchsocket[2];
694   char synchmsg;
695
696   r= socketpair(AF_UNIX,SOCK_STREAM,0,synchsocket);
697   if (r) syscallerror("cannot create socket for synch");
698
699   /* Danger here.  Firstly, we start handling signals asynchronously.
700    * Secondly after we fork the service we want it to put
701    * itself in a separate process group so that we can kill it and all
702    * its children - but, we mustn't kill the whole pgrp before it has
703    * done that (or we kill ourselves) and it mustn't fork until it
704    * knows that we are going to kill it the right way ...
705    */
706   sig.sa_handler= sighandler_chld;
707   sigemptyset(&sig.sa_mask);
708   sigaddset(&sig.sa_mask,SIGCHLD);
709   sig.sa_flags= 0;
710   if (sigaction(SIGCHLD,&sig,0)) syscallerror("cannot set sigchld handler");
711
712   newchild= fork();
713   if (newchild == -1) syscallerror("cannot fork to invoke service");
714   if (!newchild) execservice(synchsocket,fileno(swfile));
715   childtokill= child= newchild;
716
717   if (close(synchsocket[1])) syscallerror("cannot close other end of synch socket");
718
719   r= synchread(synchsocket[0],'y');
720   if (r) syscallerror("read synch byte from child");
721
722   childtokill= -child;
723
724   synchmsg= 'g';
725   r= write(synchsocket[0],&synchmsg,1);
726   if (r!=1) syscallerror("write synch byte to child");
727
728   if (close(synchsocket[0])) syscallerror("cannot close my end of synch socket");
729 }
730
731 void servicerequest(int sfd) {
732   struct event_msg event_mbuf;
733   int r;
734
735   setup_comms(sfd);
736   send_opening();
737   receive_request();
738   if (request_mbuf.clientpid == (pid_t)-1) _exit(2);
739   establish_pipes();
740   lookup_uidsgids();
741   debug_dumprequest(mypid);
742   syslog(LOG_INFO,"%s %s -> %s %c %s",
743          request_mbuf.spoofed ? "spoof" : "user",
744          loginname, serviceuser, overridedata?'!':':', service);
745
746   if (overridedata)
747     r= parse_string(TOPLEVEL_OVERRIDDEN_CONFIGURATION,
748                     "<builtin toplevel override configuration>",1);
749   else
750     r= parse_string(TOPLEVEL_CONFIGURATION,
751                     "<builtin toplevel configuration>",1);
752   
753   ensurelogopen(USERVD_LOGFACILITY);
754   if (r == tokv_error) failure("error encountered while parsing configuration");
755   assert(r == tokv_quit);
756
757   debug_dumpexecsettings();
758
759   check_find_executable();
760   check_fds();
761   send_progress_ok();
762
763   getevent(&event_mbuf);
764   assert(event_mbuf.type == et_confirm);
765
766   if (execbuiltin == bisexec_shutdown && !serviceuser_uid) {
767     /* The check for the uid is just so we can give a nice
768      * error message (in the actual code for bisexec_shutdown).
769      * If this is spoofed somehow then the unlink() will simply fail.
770      */
771     r= unlink(RENDEZVOUSPATH);
772     if (r) syscallfailure("remove rendezvous socket %s",RENDEZVOUSPATH);
773     syslog(LOG_NOTICE,"arranging for termination, due to client request");
774     reporttermination(0);
775     _exit(10);
776   }
777
778   fork_service_synch();
779   
780   getevent(&event_mbuf);
781   abort();
782 }