chiark / gitweb /
Fixed assertion failure if user's home directory not accessible
[userv.git] / overlord.c
1 /*
2  * userv - overlord.c
3  * daemon main program, collects request and forks handlers
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 #include <unistd.h>
23 #include <signal.h>
24 #include <syslog.h>
25 #include <errno.h>
26 #include <string.h>
27 #include <stdio.h>
28 #include <assert.h>
29 #include <fnmatch.h>
30 #include <sys/wait.h>
31 #include <sys/types.h>
32 #include <sys/time.h>
33 #include <sys/stat.h>
34 #include <sys/socket.h>
35 #include <sys/fcntl.h>
36 #include <dirent.h>
37 #include <sys/un.h>
38
39 #include "config.h"
40 #include "common.h"
41 #include "daemon.h"
42
43 pid_t overlordpid;
44
45 static pid_t checkpid= -1, detachpid= -1;
46 static sig_atomic_t needcheck= 1;
47
48 static void checkstalepipes(void) {
49   /* There is an unimportant race here.  If there is a stale pipe but
50    * another pair of processes with the same pids is about to create a
51    * new one we can check that the pipe is stale before they recreate
52    * it but then only remove it afterwards; then we remove the pipe
53    * they're actually using causing that invocation to fail with
54    * ENOENT on the pipe.  However, this can only happen if things are
55    * already shafted, because we check for stale pipes at startup
56    * before any children have been started, and then only when a child
57    * dies unhelpfully - and we actually have to have some stale pipes
58    * for the race to exist.
59    */
60   DIR *dir;
61   struct dirent *de;
62   struct stat stab;
63   time_t now;
64   unsigned long timediff;
65   int r;
66   
67   if (time(&now) == -1) { syslog(LOG_ERR,"get current time: %m"); return; }
68   dir= opendir(".");
69   if (!dir) { syslog(LOG_ERR,"open directory " VARDIR ": %m"); return; }
70   while ((de= readdir(dir))) {
71     if (fnmatch(PIPEPATTERN,de->d_name,FNM_PATHNAME|FNM_PERIOD)) continue;
72     r= lstat(de->d_name,&stab); if (r && errno==ENOENT) continue;
73     if (r) { syslog(LOG_ERR,"could not stat `" VARDIR "/%s': %m",de->d_name); continue; }
74     timediff= (unsigned long)now - (unsigned long)stab.st_ctime;
75     if (timediff >= (~0UL>>1) || timediff < 3600) continue;
76     if (unlink(de->d_name) && errno!=ENOENT)
77       syslog(LOG_ERR,"could not remove stale pipe `%s': %m",de->d_name);
78   }
79   if (closedir(dir)) syslog(LOG_ERR,"close directory " VARDIR ": %m");
80 }
81
82 static void sighandler_chld(int x) {
83   pid_t r;
84   int status, es, ar;
85
86   es= errno;
87   for (;;) {
88     r= waitpid((pid_t)-1,&status,WNOHANG);
89     if (!r || (r==-1 && errno==ECHILD)) break;
90     if (r==-1) { syslog(LOG_ERR,"wait in sigchild handler gave error: %m"); break; }
91     if (r==detachpid) {
92       if (WIFEXITED(status) && WEXITSTATUS(status)==4) _exit(4);
93       fprintf(stderr,"uservd: detaching child failed with unexpected code %d\n",status);
94       exit(6);
95     }
96     if (r==checkpid) {
97       if (WIFEXITED(status)) {
98         if (!WEXITSTATUS(status)) {
99           syslog(LOG_WARNING,"no longer the uservd - exiting");
100           _exit(2);
101         } else if (WEXITSTATUS(status)!=1) {
102           syslog(LOG_ERR,"check pid %ld exited with status %d",
103                  (long)checkpid,WEXITSTATUS(status));
104         }
105       } else if (WIFSIGNALED(status)) {
106         if (WTERMSIG(status) == SIGALRM && !WCOREDUMP(status)) {
107           syslog(LOG_WARNING,"check timed out; no longer the uservd - exiting");
108           _exit(2);
109         } else {
110           syslog(LOG_ERR,"check pid %ld %s due to signal %s",
111                  (long)checkpid,
112                  WCOREDUMP(status) ? "dumped core" : "died",
113                  strsignal(WTERMSIG(status)));
114         }
115       } else {
116         syslog(LOG_ERR,"check pid %ld died due to unknown reason, code %d",
117                (long)checkpid,status);
118       }
119       checkpid= -1;
120       ar= alarm(USERVD_MYSELF_CHECK);
121       if (ar<0) { syslog(LOG_CRIT,"set alarm for next check: %m"); exit(5); }
122     } else {
123       if (WIFSIGNALED(status)) {
124         syslog(LOG_ERR,"call pid %ld %s due to signal %s",
125                (long)r,
126                WCOREDUMP(status) ? "dumped core" : "died",
127                strsignal(WTERMSIG(status)));
128       } else if (!WIFEXITED(status)) {
129         syslog(LOG_ERR,"call pid %ld died due to unknown reason, code %d",
130                (long)r,status);
131       } else if (WEXITSTATUS(status)>12) {
132         if (WEXITSTATUS(status)>24)
133           syslog(LOG_ERR,"call pid %ld exited with status %d >24",
134                  (long)r,WEXITSTATUS(status));
135         checkstalepipes();
136       }
137     }
138   }
139   errno= es;
140   return;
141 }
142
143 static void sighandler_usr1(int x) {
144   _exit(0);
145 }
146
147 static void sighandler_alrm(int x) {
148   needcheck= 1;
149 }
150
151 static void sighandler_termint(int sig) {
152   syslog(LOG_NOTICE,"terminating due to signal %s",strsignal(sig));
153   _exit(1);
154 }
155
156 static void blocksignals(int how) {
157   int r;
158   sigset_t set;
159
160   sigemptyset(&set);
161   sigaddset(&set,SIGCHLD);
162   sigaddset(&set,SIGALRM);
163   sigaddset(&set,SIGTERM);
164   sigaddset(&set,SIGINT);
165   r= sigprocmask(how,&set,0); assert(!r);
166 }
167
168 static void NONRETURNING docheck(void) {
169 #ifndef DEBUG
170   /* This subprocess exits with status 0 if the parent should die,
171    * 1 if it should not, and something else if it fails horribly.
172    */
173   int sfd, r, remain;
174   unsigned char *p;
175   struct opening_msg opening_mbuf;
176   struct request_msg request_mbuf;
177   unsigned long endmagic;
178   struct sigaction sig;
179   struct sockaddr_un ssockname;
180
181   openlog(USERVDCHECK_LOGIDENT,LOG_NDELAY|LOG_PID,USERVD_LOGFACILITY);
182
183   sigemptyset(&sig.sa_mask);
184   sig.sa_flags= 0;
185   sig.sa_handler= SIG_IGN;
186   if (sigaction(SIGPIPE,&sig,0)) { syslog(LOG_ERR,"ignore sigpipe"); exit(1); }
187
188   sig.sa_handler= SIG_DFL;
189   if (sigaction(SIGALRM,&sig,0)) { syslog(LOG_ERR,"default sigalarm"); exit(1); }
190
191   sfd= socket(AF_UNIX,SOCK_STREAM,0);
192   if (!sfd) { syslog(LOG_ERR,"ignore sigpipe"); exit(1); }
193
194   assert(sizeof(ssockname.sun_path) > sizeof(RENDEZVOUS));
195   ssockname.sun_family= AF_UNIX;
196   strcpy(ssockname.sun_path,RENDEZVOUS);
197
198   r= connect(sfd,(struct sockaddr*)&ssockname,sizeof(ssockname));
199   if (r) {
200     if (errno == ECONNREFUSED || errno == ENOENT)
201       { syslog(LOG_WARNING,"real uservd daemon is not running: %m"); exit(0); }
202     syslog(LOG_ERR,"unable to connect to uservd daemon: %m"); exit(1);
203   }
204
205   r= alarm(USERVD_MYSELF_TIMEOUT);
206   if (r<0) { syslog(LOG_ERR,"set alarm for read: %m"); exit(1); }
207   remain= sizeof(opening_mbuf); p= (unsigned char*)&opening_mbuf;
208   while (remain) {
209     r= read(sfd,p,remain);
210     if (r<0) { syslog(LOG_ERR,"read from server: %m"); exit(1); }
211     if (r==0) { syslog(LOG_ERR,"unexpected EOF from server"); exit(1); }
212     remain-= r; p+= r;
213   }
214   if (opening_mbuf.magic != OPENING_MAGIC) {
215     syslog(LOG_WARNING,"magic number mismatch");
216     exit(0);
217   }
218   if (memcmp(opening_mbuf.protocolchecksumversion,protocolchecksumversion,PCSUMSIZE)) {
219     syslog(LOG_WARNING,"protocol checksum mismatch");
220     exit(0);
221   }
222   if (opening_mbuf.overlordpid != overlordpid) {
223     syslog(LOG_WARNING,"overlord pid mismatch");
224     exit(0);
225   }
226   memset(&request_mbuf,0,sizeof(request_mbuf));
227   request_mbuf.magic= REQUEST_MAGIC;
228   request_mbuf.clientpid= -1;
229   request_mbuf.serviceuserlen= 0;
230   request_mbuf.servicelen= 0;
231   request_mbuf.lognamelen= 0;
232   request_mbuf.spoofed= 0;
233   request_mbuf.cwdlen= 0;
234   request_mbuf.overridelen= -1;
235   request_mbuf.callinguid= -1;
236   request_mbuf.ngids= 0;
237   request_mbuf.nreadfds= 0;
238   request_mbuf.nwritefds= 0;
239   request_mbuf.nargs= 0;
240   request_mbuf.nvars= 0;
241   r= write(sfd,&request_mbuf,sizeof(request_mbuf));
242   if (r==sizeof(request_mbuf)) {
243     endmagic= REQUEST_END_MAGIC;
244     write(sfd,&endmagic,sizeof(endmagic));
245   }
246   syslog(LOG_NOTICE,"uservd[%ld] is running",(long)overlordpid);
247 #endif
248   exit(1);
249 }
250
251 static void NONRETURNING startupsyscallerr(const char *what) {
252   fprintf(stderr,
253           "uservd: system call failed during startup:\n"
254           "uservd: %s: %s\n",
255           what,strerror(errno));
256   exit(4);
257 }
258
259 int main(int argc, char *const *argv) {
260   int mfd, sfd, nfd, csocklen, e, r, becomedaemon;
261   struct sigaction sigact;
262   struct sockaddr_un ssockname, csockname;
263   pid_t child, parentpid, sid;
264
265 #ifdef NDEBUG
266   abort(); /* Do not disable assertions in this security-critical code ! */
267 #endif
268
269   becomedaemon= 0;
270   
271   if (argv[1] && !strcmp(argv[1],"-daemon")) {
272     becomedaemon= 1;
273     argv++; argc--;
274   }
275   if (argc>1) { fputs("usage: uservd [-daemon]\n",stderr); exit(3); }
276
277   openlog(USERVD_LOGIDENT,LOG_NDELAY|LOG_PID,USERVD_LOGFACILITY);
278
279   if (chdir(VARDIR)) startupsyscallerr("cannot change to " VARDIR);
280   checkstalepipes();
281
282   overlordpid= parentpid= getpid();
283   if (parentpid==-1) startupsyscallerr("cannot getpid");
284
285   mfd= socket(AF_UNIX,SOCK_STREAM,0);
286   if (mfd<0) startupsyscallerr("cannot create master socket");
287
288   assert(sizeof(ssockname.sun_path) > sizeof(RENDEZVOUS));
289   ssockname.sun_family= AF_UNIX;
290   strcpy(ssockname.sun_path,RENDEZVOUS);
291   unlink(RENDEZVOUS);
292   r= bind(mfd,(struct sockaddr*)&ssockname,sizeof(ssockname));
293   if (r) startupsyscallerr("cannot bind master socket");
294   if (listen(mfd,5)) startupsyscallerr("cannot listen on master socket");
295
296   sigemptyset(&sigact.sa_mask);
297   sigaddset(&sigact.sa_mask,SIGCHLD);
298   sigaddset(&sigact.sa_mask,SIGALRM);
299   sigact.sa_flags= SA_NOCLDSTOP;
300
301   sigact.sa_handler= sighandler_chld;
302   if (sigaction(SIGCHLD,&sigact,0)) startupsyscallerr("cannot setup sigchld handler");
303
304   sigact.sa_handler= sighandler_alrm;
305   if (sigaction(SIGALRM,&sigact,0)) startupsyscallerr("cannot setup sigalrm handler");
306
307   if (becomedaemon) {
308     sigact.sa_handler= sighandler_usr1;
309     if (sigaction(SIGUSR1,&sigact,0)) startupsyscallerr("cannot setup sigusr1 handler");
310     
311     detachpid= fork(); if (detachpid==-1) startupsyscallerr("cannot fork to detach");
312     if (detachpid) {
313       pause();
314       fputs("uservd: pause unexpectedly returned during detach\n",stderr);
315       exit(4);
316     }
317     sigact.sa_handler= SIG_DFL;
318     if (sigaction(SIGUSR1,&sigact,0)) startupsyscallerr("cannot restore sigusr1");
319   }
320
321   sigact.sa_handler= sighandler_termint;
322   if (sigaction(SIGTERM,&sigact,0)) startupsyscallerr("cannot setup sigterm handler");
323   if (sigaction(SIGINT,&sigact,0)) startupsyscallerr("cannot setup sigint handler");
324
325   if (becomedaemon) {
326     nfd= open("/dev/null",O_RDWR);
327     if (nfd<0) startupsyscallerr("cannot open /dev/null");
328     sid= setsid(); if (sid == -1) startupsyscallerr("cannot create new session");
329     overlordpid= getpid();
330     if (overlordpid == -1) startupsyscallerr("getpid after detach");
331     if (dup2(nfd,0)<0 || dup2(nfd,1)<0)
332       startupsyscallerr("cannot dup /dev/null for stdin/out");
333     r= kill(parentpid,SIGUSR1); if (r) startupsyscallerr("send SIGUSR1 to detach");
334     r= dup2(nfd,2);
335     if (r<0) { syslog(LOG_CRIT,"cannot dup /dev/null for stderr: %m"); exit(5); }
336     close(nfd);
337   }
338
339   syslog(LOG_NOTICE,"started");
340
341   for (;;) {
342     if (needcheck) {
343       assert(checkpid==-1);
344       for (;;) {
345         checkpid= fork();
346         if (checkpid!=-1) {
347           if (!checkpid) docheck();
348           break;
349         } else if (errno==EAGAIN) {
350           syslog(LOG_ERR,"fork for check - will wait and retry: %m");
351           r= alarm(USERVD_CHECKFORK_RETRY);
352           if (r<0) { syslog(LOG_CRIT,"set alarm for retry check: %m"); exit(5); }
353           break;
354         } else if (errno!=EINTR) {
355           syslog(LOG_CRIT,"fork for check: %m"); exit(5);
356         }
357       }
358       needcheck= 0;
359     }
360     csocklen= sizeof(csockname);
361     blocksignals(SIG_UNBLOCK);
362     sfd= accept(mfd,(struct sockaddr*)&csockname,&csocklen);
363     e= errno;
364     blocksignals(SIG_BLOCK);
365     if (sfd<0) {
366       errno= e;
367       if (errno == EINTR) continue;
368       if (errno == ENOMEM || errno == EPROTO || errno == EAGAIN) {
369         syslog(LOG_ERR,"unable to accept connection: %m");
370         continue;
371       } else {
372         syslog(LOG_CRIT,"unable to accept new connections: %m");
373         exit(5);
374       }
375     }
376     child= nondebug_fork();
377     if (child == (pid_t)-1) {
378       syslog(LOG_ERR,"unable to fork server: %m");
379       close(sfd);
380       continue;
381     }
382     if (!child) {
383       close(mfd);
384       closelog();
385       blocksignals(SIG_UNBLOCK);
386       servicerequest(sfd);
387     }
388     close(sfd);
389   }
390 }