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