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