chiark / gitweb /
poll: Make handling of fds array actually dynamic
[secnet.git] / secnet.c
1 #include "secnet.h"
2 #include <stdio.h>
3 #include <assert.h>
4 #include <limits.h>
5 #include <string.h>
6 #include <getopt.h>
7 #include <errno.h>
8 #include <unistd.h>
9 #include <sys/socket.h>
10 #include <arpa/inet.h>
11 #include <pwd.h>
12 #include <grp.h>
13
14 #include "util.h"
15 #include "conffile.h"
16 #include "process.h"
17
18 #if __APPLE__
19 /* apple's poll() does not work on char devs */
20 # define USE_SELECT 1
21 #endif
22
23 /* XXX should be from autoconf */
24 static const char *configfile="/etc/secnet/secnet.conf";
25 static const char *sites_key="sites";
26 bool_t just_check_config=False;
27 static char *userid=NULL;
28 static uid_t uid=0;
29 static gid_t gid;
30 bool_t background=True;
31 static char *pidfile=NULL;
32 bool_t require_root_privileges=False;
33 cstring_t require_root_privileges_explanation=NULL;
34
35 static pid_t secnet_pid;
36
37 /* Structures dealing with poll() call */
38 struct poll_interest {
39     beforepoll_fn *before;
40     afterpoll_fn *after;
41     void *state;
42     int32_t max_nfds;
43     int32_t nfds;
44     cstring_t desc;
45     LIST_ENTRY(poll_interest) entry;
46 };
47 static LIST_HEAD(, poll_interest) reg = LIST_HEAD_INITIALIZER(&reg);
48
49 static bool_t finished=False;
50
51 /* Parse the command line options */
52 static void parse_options(int argc, char **argv)
53 {
54     int c;
55
56     while (True) {
57         int option_index = 0;
58         static struct option long_options[] = {
59             {"verbose", 0, 0, 'v'},
60             {"nowarnings", 0, 0, 'w'},
61             {"help", 0, 0, 2},
62             {"version", 0, 0, 1},
63             {"nodetach", 0, 0, 'n'},
64             {"managed", 0, 0, 'm'},
65             {"silent", 0, 0, 'f'},
66             {"quiet", 0, 0, 'f'},
67             {"debug", 0, 0, 'd'},
68             {"config", 1, 0, 'c'},
69             {"just-check-config", 0, 0, 'j'},
70             {"sites-key", 1, 0, 's'},
71             {0,0,0,0}
72         };
73
74         c=getopt_long(argc, argv, "vwdnjc:ft:s:m",
75                       long_options, &option_index);
76         if (c==-1)
77             break;
78
79         switch(c) {
80         case 2:
81             /* Help */
82             printf("Usage: secnet [OPTION]...\n\n"
83                    "  -f, --silent, --quiet   suppress error messages\n"
84                    "  -w, --nowarnings        suppress warnings\n"
85                    "  -v, --verbose           output extra diagnostics\n"
86                    "  -c, --config=filename   specify a configuration file\n"
87                    "  -j, --just-check-config stop after reading "
88                    "configuration file\n"
89                    "  -s, --sites-key=name    configuration key that "
90                    "specifies active sites\n"
91                    "  -n, --nodetach          do not run in background\n"
92                    "  -m, --managed           running under a supervisor\n"
93                    "  -d, --debug             output debug messages\n"
94                    "      --help              display this help and exit\n"
95                    "      --version           output version information "
96                    "and exit\n"
97                 );
98             exit(0);
99             break;
100       
101         case 1:
102             /* Version */
103             printf("%s\n",version);
104             exit(0);
105             break;
106
107         case 'v':
108             message_level|=M_INFO|M_NOTICE|M_WARNING|M_ERR|M_SECURITY|
109                 M_FATAL;
110             break;
111
112         case 'w':
113             message_level&=(~M_WARNING);
114             break;
115
116         case 'd':
117             message_level|=M_DEBUG_CONFIG|M_DEBUG_PHASE|M_DEBUG;
118             break;
119
120         case 'f':
121             message_level=M_FATAL;
122             break;
123
124         case 'n':
125             background=False;
126             break;
127
128         case 'm':
129             secnet_is_daemon=True;
130             break;
131
132         case 'c':
133             if (optarg)
134                 configfile=safe_strdup(optarg,"config_filename");
135             else
136                 fatal("secnet: no config filename specified");
137             break;
138
139         case 'j':
140             just_check_config=True;
141             break;
142
143         case 's':
144             if (optarg)
145                 sites_key=safe_strdup(optarg,"sites-key");
146             else
147                 fatal("secnet: no sites key specified");
148             break;
149
150         case '?':
151             exit(1);
152             break;
153
154         default:
155             Message(M_ERR,"secnet: Unknown getopt code %c\n",c);
156         }
157     }
158
159     if (argc-optind != 0) {
160         Message(M_ERR,"secnet: You gave extra command line parameters, "
161                 "which were ignored.\n");
162     }
163 }
164
165 static void setup(dict_t *config)
166 {
167     list_t *l;
168     item_t *site;
169     dict_t *system;
170     struct passwd *pw;
171     struct cloc loc;
172     int i;
173
174     l=dict_lookup(config,"system");
175
176     if (!l || list_elem(l,0)->type!=t_dict) {
177         fatal("configuration does not include a \"system\" dictionary");
178     }
179     system=list_elem(l,0)->data.dict;
180     loc=list_elem(l,0)->loc;
181
182     /* Arrange systemwide log facility */
183     l=dict_lookup(system,"log");
184     if (!l) {
185         fatal("configuration does not include a system/log facility");
186     }
187     system_log=init_log(l);
188
189     /* Who are we supposed to run as? */
190     userid=dict_read_string(system,"userid",False,"system",loc);
191     if (userid) {
192         if (!(pw=getpwnam(userid)))
193             fatal("userid \"%s\" not found",userid);
194         uid=pw->pw_uid;
195         gid=pw->pw_gid;
196     }
197
198     /* Pidfile name */
199     pidfile=dict_read_string(system,"pidfile",False,"system",loc);
200
201     /* Check whether we need root privileges */
202     if (require_root_privileges && uid!=0) {
203         fatal("the configured feature \"%s\" requires "
204               "that secnet retain root privileges while running.",
205               require_root_privileges_explanation);
206     }
207
208     /* Go along site list, starting sites */
209     l=dict_lookup(config,sites_key);
210     if (!l) {
211         Message(M_WARNING,"secnet: configuration key \"%s\" is missing; no "
212                 "remote sites are defined\n",sites_key);
213     } else {
214         i=0;
215         while ((site=list_elem(l, i++))) {
216             struct site_if *s;
217             if (site->type!=t_closure) {
218                 cfgfatal(site->loc,"system","non-closure in site list");
219             }
220             if (site->data.closure->type!=CL_SITE) {
221                 cfgfatal(site->loc,"system","non-site closure in site list");
222             }
223             s=site->data.closure->interface;
224             s->control(s->st,True);
225         }
226     }
227 }
228
229 void register_for_poll(void *st, beforepoll_fn *before,
230                        afterpoll_fn *after, int32_t max_nfds, cstring_t desc)
231 {
232     struct poll_interest *i;
233
234     i=safe_malloc(sizeof(*i),"register_for_poll");
235     i->before=before;
236     i->after=after;
237     i->state=st;
238     i->max_nfds=max_nfds;
239     i->nfds=0;
240     i->desc=desc;
241     LIST_INSERT_HEAD(&reg, i, entry);
242     return;
243 }
244
245 static void system_phase_hook(void *sst, uint32_t newphase)
246 {
247     if (newphase==PHASE_SHUTDOWN && pidfile) {
248         /* Try to unlink the pidfile; don't care if it fails */
249         unlink(pidfile);
250     }
251 }
252
253 #if USE_SELECT
254 static int fakepoll(struct pollfd *fds, int nfds, int timeout) {
255     fd_set infds[1], outfds[1];
256     int maxfd = -1, i, rc;
257     struct timeval tvtimeout;
258     FD_ZERO(infds);
259     FD_ZERO(outfds);
260     for(i = 0; i < nfds; ++i) {
261         if(fds[i].events & POLLIN)
262             FD_SET(fds[i].fd, infds);
263         if(fds[i].events & POLLOUT)
264             FD_SET(fds[i].fd, outfds);
265         if(fds[i].fd > maxfd)
266             maxfd = fds[i].fd;
267     }
268     if(timeout != -1) {
269         tvtimeout.tv_sec = timeout / 1000;
270         tvtimeout.tv_usec = 1000 * (timeout % 1000);
271     }
272     rc = select(maxfd + 1, infds, outfds, NULL, 
273                 timeout == -1 ? NULL : &tvtimeout);
274     if(rc >= 0) {
275         for(i = 0; i < nfds; ++i) {
276             int revents = 0;
277             if(FD_ISSET(fds[i].fd, infds))
278                 revents |= POLLIN;
279             if(FD_ISSET(fds[i].fd, outfds))
280                 revents |= POLLOUT;
281             fds[i].revents = revents;
282         }
283     }
284     return rc;
285 }
286 #endif
287
288 struct timeval tv_now_global;
289 uint64_t now_global;
290
291 static void run(void)
292 {
293     struct poll_interest *i;
294     int rv, nfds, remain, idx;
295     int timeout;
296     struct pollfd *fds=0;
297     int allocdfds=0, shortfall=0;
298
299     Message(M_NOTICE,"%s [%d]: starting\n",version,secnet_pid);
300
301     do {
302         if (gettimeofday(&tv_now_global, NULL)!=0) {
303             fatal_perror("main loop: gettimeofday");
304         }
305         now_global=((uint64_t)tv_now_global.tv_sec*(uint64_t)1000)+
306                    ((uint64_t)tv_now_global.tv_usec/(uint64_t)1000);
307         idx=0;
308         LIST_FOREACH(i, &reg, entry) {
309             int check;
310             for (check=0; check<i->nfds; check++) {
311                 if(fds[idx+check].revents & POLLNVAL) {
312                     fatal("run: poll (%s#%d) set POLLNVAL", i->desc, check);
313                 }
314             }
315             i->after(i->state, fds+idx, i->nfds);
316             idx+=i->nfds;
317         }
318         if (shortfall) {
319             allocdfds *= 2;
320             allocdfds += shortfall;
321             fds=safe_realloc_ary(fds,sizeof(*fds),allocdfds, "run");
322         }
323         remain=allocdfds;
324         shortfall=0;
325         idx=0;
326         timeout=-1;
327         LIST_FOREACH(i, &reg, entry) {
328             nfds=remain;
329             rv=i->before(i->state, fds+idx, &nfds, &timeout);
330             if (rv!=0) {
331                 if (rv!=ERANGE)
332                     fatal("run: beforepoll_fn (%s) returns %d",i->desc,rv);
333                 assert(nfds < INT_MAX/4 - shortfall);
334                 shortfall += nfds-remain;
335                 nfds=0;
336                 timeout=0;
337             }
338             if (timeout<-1) {
339                 fatal("run: beforepoll_fn (%s) set timeout to %d",
340                       i->desc,timeout);
341             }
342             idx+=nfds;
343             remain-=nfds;
344             i->nfds=nfds;
345         }
346         do {
347             if (finished) break;
348 #if USE_SELECT
349             rv=fakepoll(fds, idx, timeout);
350 #else
351             rv=poll(fds, idx, timeout);
352 #endif
353             if (rv<0) {
354                 if (errno!=EINTR) {
355                     fatal_perror("run: poll");
356                 }
357             }
358         } while (rv<0);
359     } while (!finished);
360     free(fds);
361 }
362
363 /* Surrender privileges, if necessary */
364 static void droppriv(void)
365 {
366     if (userid) {
367         if (setgid(gid)!=0)
368             fatal_perror("can't set gid to %ld",(long)gid);
369         if (initgroups(userid, gid) < 0)
370             fatal_perror("initgroups"); 
371         if (setuid(uid)!=0) {
372             fatal_perror("can't set uid to \"%s\"",userid);
373         }
374         assert(getuid() == uid);
375         assert(geteuid() == uid);
376         assert(getgid() == gid);
377         assert(getegid() == gid);
378     }
379 }
380
381 /* Become a daemon, if necessary */
382 static void become_daemon(void)
383 {
384     FILE *pf=NULL;
385     pid_t p;
386     int errfds[2];
387
388     add_hook(PHASE_SHUTDOWN,system_phase_hook,NULL);
389
390     /* We only want to become a daemon if we are not one
391      already */
392     if (background && !secnet_is_daemon) {
393         p=fork();
394         if (p>0) {
395             /* Parent process - just exit */
396             _exit(0);
397         } else if (p==0) {
398             /* Child process - all done, just carry on */
399             secnet_is_daemon=True;
400             if (setsid() < 0)
401                 fatal_perror("setsid");
402         } else {
403             /* Error */
404             fatal_perror("cannot fork");
405             exit(1);
406         }
407     }
408     if (secnet_is_daemon) {
409         /* stderr etc are redirected to the system/log facility */
410         pipe_cloexec(errfds);
411         if (dup2(errfds[1],0) < 0
412             || dup2(errfds[1],1) < 0
413             || dup2(errfds[1],2) < 0)
414             fatal_perror("can't dup2 pipe");
415         if (close(errfds[1]) < 0)
416             fatal_perror("can't close redundant pipe endpoint");
417         log_from_fd(errfds[0],"stderr",system_log);
418     }
419     secnet_pid=getpid();
420     
421     /* Now we can write the pidfile */
422     if (pidfile) {
423         pf=fopen(pidfile,"w");
424         if (!pf) {
425             fatal_perror("cannot open pidfile \"%s\"",pidfile);
426         }
427         if (fprintf(pf,"%ld\n",(long)secnet_pid) < 0
428             || fclose(pf) < 0)
429             fatal_perror("cannot write to pidfile \"%s\"",pidfile);
430     }
431 }
432
433 static signal_notify_fn finish,ignore_hup;
434 static void finish(void *st, int signum)
435 {
436     finished=True;
437     Message(M_NOTICE,"%s [%d]: received %s\n",version,secnet_pid,(string_t)st);
438 }
439 static void ignore_hup(void *st, int signum)
440 {
441     Message(M_INFO,"%s [%d]: received SIGHUP\n",version,secnet_pid);
442     return;
443 }
444
445 int main(int argc, char **argv)
446 {
447     dict_t *config;
448
449     enter_phase(PHASE_GETOPTS);
450     parse_options(argc,argv);
451
452     enter_phase(PHASE_READCONFIG);
453     config=read_conffile(configfile);
454
455     enter_phase(PHASE_SETUP);
456     setup(config);
457
458     if (just_check_config) {
459         Message(M_INFO,"configuration file check complete\n");
460         exit(0);
461     }
462
463     enter_phase(PHASE_DAEMONIZE);
464     become_daemon();
465     
466     enter_phase(PHASE_GETRESOURCES);
467     /* Appropriate phase hooks will have been run */
468     
469     enter_phase(PHASE_DROPPRIV);
470     droppriv();
471
472     start_signal_handling();
473     request_signal_notification(SIGTERM,finish,safe_strdup("SIGTERM","run"));
474     if (!background) request_signal_notification(SIGINT,finish,
475                                                  safe_strdup("SIGINT","run"));
476     request_signal_notification(SIGHUP,ignore_hup,NULL);
477     enter_phase(PHASE_RUN);
478     run();
479
480     enter_phase(PHASE_SHUTDOWN);
481     Message(M_NOTICE,"%s [%d]: finished\n",version,secnet_pid);
482
483     return 0;
484 }