chiark / gitweb /
Fixed spurious failure with Interrupted system call; Fixed race when fd closed at...
[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 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 <ctype.h>
53 #include <limits.h>
54 #include <sys/wait.h>
55 #include <sys/types.h>
56 #include <sys/fcntl.h>
57 #include <sys/stat.h>
58 #include <sys/socket.h>
59 #include <sys/un.h>
60
61 #include "config.h"
62 #include "common.h"
63 #include "both.h"
64 #include "daemon.h"
65 #include "lib.h"
66 #include "tokens.h"
67
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;
75 int service_ngids;
76 char **argarray;
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;
84 int execute;
85 int setenvironment, suppressargs, disconnecthup;
86 builtinserviceexec_fnt *execbuiltin;
87 int syslogopenfacility=-1;
88
89 static FILE *swfile, *srfile;
90 static pid_t child=-1, childtokill=-1;
91 static pid_t mypid;
92
93 /* Function shared with servexec.c: */
94
95 int synchread(int fd, int ch) {
96   char synchmsg;
97   int r;
98   
99   for (;;) {
100     r= read(fd,&synchmsg,1);
101     if (r==1) break;
102     if (r==0) { errno= ECONNRESET; return -1; }
103     assert(r<0);
104     if (errno!=EINTR) return -1;
105   };
106   assert(synchmsg==ch);
107   return 0;
108 }
109
110 const char *defaultpath(void) {
111   return serviceuser_uid ? DEFAULTPATH_USER : DEFAULTPATH_ROOT;
112 }
113
114 /* General-purpose functions; these do nothing special about signals */
115
116 static void blocksignals(void) {
117   int r;
118   sigset_t set;
119
120   sigemptyset(&set);
121   sigaddset(&set,SIGCHLD);
122   sigaddset(&set,SIGPIPE);
123   r= sigprocmask(SIG_BLOCK,&set,0); assert(!r);
124 }
125
126 static void xfwriteerror(void) {
127   if (errno != EPIPE) syscallerror("writing to client");
128   blocksignals();
129   ensurelogopen(USERVD_LOGFACILITY);
130   syslog(LOG_INFO,"client went away (broken pipe)");
131   disconnect(8);
132 }
133
134 static void xfwrite(const void *p, size_t sz, FILE *file) {
135   size_t nr;
136   nr= fwrite(p,1,sz,file);
137   if (nr != sz) xfwriteerror();
138 }
139
140 static void xfflush(FILE *file) {
141   if (fflush(file)) xfwriteerror();
142 }
143
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
146  * handler objects.
147  */
148
149 static void xfread(void *p, size_t sz) {
150   size_t nr;
151   nr= working_fread(p,sz,srfile); if (nr == sz) return;
152   if (ferror(srfile)) syscallerror("reading from client");
153   blocksignals();
154   assert(feof(srfile));
155   syslog(LOG_INFO,"client went away (unexpected EOF)");
156   swfile= 0;
157   disconnect(8);
158 }
159
160 static char *xfreadsetstring(int l) {
161   char *s;
162   assert(l<=MAX_GENERAL_STRING);
163   s= xmalloc(l+1);
164   xfread(s,sizeof(*s)*l);
165   s[l]= 0;
166   return s;
167 }
168
169 static char *xfreadstring(void) {
170   int l;
171   xfread(&l,sizeof(l));
172   return xfreadsetstring(l);
173 }
174
175 static void getevent(struct event_msg *event_r) {
176   int fd;
177   
178   for (;;) {
179     xfread(event_r,sizeof(struct event_msg));
180     switch (event_r->type) {
181     case et_closereadfd:
182       fd= event_r->data.closereadfd.fd;
183       if (fd >= fdarrayused) {
184         blocksignals();
185         syslog(LOG_ERR,"client sent bad file descriptor %d to close (max %d)",
186                fd,fdarrayused-1);
187         disconnect(20);
188       }
189       if (fdarray[fd].holdfd!=-1) {
190         if (close(fdarray[fd].holdfd)) syscallerror("cannot close holding fd");
191         fdarray[fd].holdfd= -1;
192       }
193       break;
194     case et_disconnect:
195       blocksignals();
196       syslog(LOG_INFO,"client disconnected");
197       disconnect(4);
198     default:
199       return;
200     }
201   }
202 }
203
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.
208  */
209
210 void miscerror(const char *what) {
211   blocksignals();
212   syslog(LOG_ERR,"failure: %s",what);
213   disconnect(16);
214 }
215
216 void syscallerror(const char *what) {
217   int e;
218
219   e= errno;
220   blocksignals();
221   syslog(LOG_ERR,"system call failure: %s: %s",what,strerror(e));
222   disconnect(16);
223 }
224
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.
229  */
230
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;
236 }
237
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
243    * attempted again.
244    */
245   struct progress_msg progress_mbuf;
246   FILE *swfilereal;
247   pid_t orgtokill;
248   int r;
249   
250   if (childtokill!=-1 && disconnecthup) {
251     orgtokill= childtokill;
252     childtokill= -1;
253     if (disconnecthup) {
254       r= kill(-orgtokill,SIGHUP);
255       if (r && errno!=EPERM && errno!=ESRCH)
256         syscallerror("sending SIGHUP to service process group");
257     }
258     child= -1;
259   }
260   if (swfile) {
261     swfilereal= swfile;
262     swfile= 0;
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);
267     xfflush(swfilereal);
268   }
269
270   _exit(exitstatus);
271 }
272
273 static void NONRETURNING sighandler_chld(int ignored) {
274   struct progress_msg progress_mbuf;
275   int status;
276   pid_t returned;
277
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;
283
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);
289   xfflush(swfile);
290
291   syslog(LOG_INFO,"service completed (status %d %d)",(status>>8)&0x0ff,status&0x0ff);
292   _exit(0);
293 }
294
295 /* Functions which are called only during setup, before
296  * the signal asynchronicity starts.  They can do anything they like.
297  */
298
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);
304   }
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;
311     fdarrayused++;
312   }
313 }
314
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];
318
319   if (prefix) {
320     strnycpy(errmsg,prefix,sizeof(errmsg));
321     strnytcat(errmsg,": ",sizeof(errmsg));
322   } else {
323     errmsg[0]= 0;
324   }
325   vsnytprintfcat(errmsg,sizeof(errmsg)-reserveerrno,fmt,al);
326   if (reserveerrno) {
327     strnytcat(errmsg,": ",sizeof(errmsg));
328     strnytcat(errmsg,strerror(errnoval),sizeof(errmsg));
329   }
330   senderrmsgstderr(errmsg);
331   syslog(LOG_INFO,"service failed (%s)",errmsg);
332   disconnect(12);
333 }
334
335 static void NONRETURNPRINTFFORMAT(1,2) failure(const char *fmt, ...) {
336   va_list al;
337
338   va_start(al,fmt);
339   generalfailure(0,0,0,fmt,al);
340 }  
341
342 static void NONRETURNPRINTFFORMAT(1,2) syscallfailure(const char *fmt, ...) {
343   va_list al;
344   int e;
345
346   e= errno;
347   va_start(al,fmt);
348   generalfailure("system call failed",ERRMSG_RESERVE_ERRNO,e,fmt,al);
349 }
350
351 void senderrmsgstderr(const char *errmsg) {
352   struct progress_msg progress_mbuf;
353   unsigned long ul;
354   int l;
355
356   l= strlen(errmsg);
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);
365   xfflush(swfile);
366 }
367
368 /* The per-request main program and its subfunctions. */
369
370 static void setup_comms(int sfd) {
371   static char swbuf[BUFSIZ];
372   static char srbuf[BUFSIZ];
373
374   struct sigaction sig;
375   
376   ensurelogopen(USERVD_LOGFACILITY);
377   syslog(LOG_DEBUG,"call connected");
378
379   mypid= getpid(); if (mypid == -1) syscallerror("getpid");
380
381   sig.sa_handler= SIG_IGN;
382   sigemptyset(&sig.sa_mask);
383   sig.sa_flags= 0;
384   if (sigaction(SIGPIPE,&sig,0)) syscallerror("cannot ignore sigpipe");
385
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");
390
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");
395 }
396
397 static void send_opening(void) {
398   struct opening_msg opening_mbuf;
399
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);
406   xfflush(swfile);
407 }
408
409 static void receive_request(void) {
410   int i, fd;
411   unsigned long ul;
412
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);
422   } else {
423     assert(request_mbuf.overridelen == -1);
424     overridedata= 0;
425   }
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);
429
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);
437     ensurefdarray(fd);
438     assert(fdarray[fd].iswrite == -1);
439     fdarray[fd].iswrite= (i>=request_mbuf.nreadfds);
440   }
441
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();
451   }
452   xfread(&ul,sizeof(ul));
453   assert(ul == REQUEST_END_MAGIC);
454 }
455
456 static void establish_pipes(void) {
457   int fd, tempfd;
458   char pipepathbuf[PIPEMAXLEN+2];
459   
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);
471     } else {
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);
475     }
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");
479   }
480 }
481
482 static void groupnames(int ngids, gid_t *gids, const char ***names_r) {
483   const char **names;
484   struct group *gr;
485   int i;
486   
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);
492   }
493   *names_r= names;
494 }
495   
496 static void lookup_uidsgids(void) {
497   struct passwd *pw;
498
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);
503
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;
510   
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");
515   if (pw->pw_uid) {
516     if (!setreuid(pw->pw_uid,0)) miscerror("setreuid 3 unexpectedly succeeded");
517     if (errno != EPERM) syscallerror("setreuid 3 failed in unexpected way");
518   }
519   if (setregid(pw->pw_gid,pw->pw_gid)) syscallerror("setregid 2");
520
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)");
527
528   groupnames(request_mbuf.ngids,calling_gids,&calling_groups);
529   groupnames(service_ngids,service_gids,&service_groups);
530 }
531
532 static void findinpath(char *program) {
533   char *part, *exectry;
534   const char *string, *delim, *nextstring;
535   struct stat stab;
536   int r, partsize;
537   
538   if (strchr(program,'/')) {
539     r= stat(program,&stab);
540     if (r) syscallfailure("failed check for program (containing slash) `%s'",program);
541     execpath= program;
542   } else {
543     string= getenv("PATH");
544     if (!string) string= defaultpath();
545     while (string) {
546       delim= strchr(string,':');
547       if (delim) {
548         if (delim-string > MAX_GENERAL_STRING)
549           failure("execute-from-path, but PATH component too long");
550         partsize= delim-string;
551         nextstring= delim+1;
552       } else {
553         partsize= strlen(string);
554         nextstring= 0;
555       }
556       part= xstrsubsave(string,partsize);
557       exectry= part[0] ? xstrcat3save(part,"/",program) : xstrsave(program);
558       free(part);
559       r= stat(exectry,&stab);
560       if (!r) { execpath= exectry; break; }
561       free(exectry);
562       string= nextstring;
563     }
564     if (!execpath) failure("program `%s' not found on default PATH",program);
565   }
566 }
567   
568 static void check_find_executable(void) {
569   struct stat stab;
570   int r;
571
572   switch (execute) {
573   case tokv_word_reject:
574     failure("request rejected");
575   case tokv_word_execute:
576     findinpath(execpath);
577     break;
578   case tokv_word_executefromdirectory:
579     r= stat(execpath,&stab);
580     if (r) syscallfailure("checking for executable in directory, `%s'",execpath);
581     break;
582   case tokv_word_executebuiltin:
583     break;
584   case tokv_word_executefrompath:
585     findinpath(service);
586     break;
587   default:
588     abort();
589   }
590 }
591
592 static void makenonexistentfd(int fd) {
593   if (fdarray[fd].realfd == -1) {
594     assert(fdarray[fd].holdfd == -1);
595   } else {
596     if (close(fdarray[fd].realfd))
597       syscallfailure("close unwanted file descriptor %d",fd);
598     fdarray[fd].realfd= -1;
599   
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;
604     }
605   }
606 }
607
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 :
612                            0);
613   if (fdarray[fd].realfd<0)
614     syscallfailure("cannot open /dev/null for null or allowed, unprovided fd");
615 }
616
617 static void check_fds(void) {
618   int fd;
619   
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");
626
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);
632       break;
633     case tokv_word_ignorefd:
634       makenonexistentfd(fd);
635       break;
636     case tokv_word_nullfd:
637       makenonexistentfd(fd);
638       makenullfd(fd);
639       break;
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);
644       /* fall through */
645     case tokv_word_allowfd:
646       if (fdarray[fd].realfd == -1) {
647         assert(fdarray[fd].holdfd == -1);
648         makenullfd(fd);
649       } else {
650         if (fdarray[fd].iswrite) {
651           if (fdarray[fd].wantrw == tokv_word_read)
652             failure("file descriptor %d provided write, wanted read",fd);
653         } else {
654           if (fdarray[fd].wantrw == tokv_word_write)
655             failure("file descriptor %d provided read, wanted write",fd);
656         }
657       }
658     }
659   }
660 }
661
662 static void send_progress_ok(void) {
663   struct progress_msg progress_mbuf;
664
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);
669   xfflush(swfile);
670 }
671
672 static void fork_service_synch(void) {
673   pid_t newchild;
674   struct sigaction sig;
675   int r, synchsocket[2];
676   char synchmsg;
677
678   r= socketpair(AF_UNIX,SOCK_STREAM,0,synchsocket);
679   if (r) syscallerror("cannot create socket for synch");
680
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 ...
687    */
688   sig.sa_handler= sighandler_chld;
689   sigemptyset(&sig.sa_mask);
690   sigaddset(&sig.sa_mask,SIGCHLD);
691   sig.sa_flags= 0;
692   if (sigaction(SIGCHLD,&sig,0)) syscallerror("cannot set sigchld handler");
693
694   newchild= fork();
695   if (newchild == -1) syscallerror("cannot fork to invoke service");
696   if (!newchild) execservice(synchsocket,fileno(swfile));
697   childtokill= child= newchild;
698
699   if (close(synchsocket[1])) syscallerror("cannot close other end of synch socket");
700
701   r= synchread(synchsocket[0],'y');
702   if (r) syscallerror("read synch byte from child");
703
704   childtokill= -child;
705
706   synchmsg= 'g';
707   r= write(synchsocket[0],&synchmsg,1);
708   if (r!=1) syscallerror("write synch byte to child");
709
710   if (close(synchsocket[0])) syscallerror("cannot close my end of synch socket");
711 }
712
713 void servicerequest(int sfd) {
714   struct event_msg event_mbuf;
715   int r;
716
717   setup_comms(sfd);
718   send_opening();
719   receive_request();
720   if (request_mbuf.clientpid == (pid_t)-1) _exit(2);
721   establish_pipes();
722   lookup_uidsgids();
723   debug_dumprequest(mypid);
724   syslog(LOG_INFO,"%s %s -> %s %c %s",
725          request_mbuf.spoofed ? "spoof" : "user",
726          logname, serviceuser, overridedata?'!':':', service);
727
728   if (overridedata)
729     r= parse_string(TOPLEVEL_OVERRIDDEN_CONFIGURATION,
730                     "<builtin toplevel override configuration>",1);
731   else
732     r= parse_string(TOPLEVEL_CONFIGURATION,
733                     "<builtin toplevel configuration>",1);
734   
735   ensurelogopen(USERVD_LOGFACILITY);
736   if (r == tokv_error) failure("error encountered while parsing configuration");
737   assert(r == tokv_quit);
738
739   debug_dumpexecsettings();
740
741   check_find_executable();
742   check_fds();
743   send_progress_ok();
744
745   getevent(&event_mbuf);
746   assert(event_mbuf.type == et_confirm);
747
748   fork_service_synch();
749   
750   getevent(&event_mbuf);
751   abort();
752 }