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