chiark / gitweb /
Closures: Provide closure_type_name
[secnet.git] / secnet.c
1 /*
2  * This file is part of secnet.
3  * See README for full list of copyright holders.
4  *
5  * secnet is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  * 
10  * secnet is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  * 
15  * You should have received a copy of the GNU General Public License
16  * version 3 along with secnet; if not, see
17  * https://www.gnu.org/licenses/gpl.html.
18  */
19
20 #include "secnet.h"
21 #include <stdio.h>
22 #include <assert.h>
23 #include <limits.h>
24 #include <string.h>
25 #include <getopt.h>
26 #include <errno.h>
27 #include <unistd.h>
28 #include <sys/socket.h>
29 #include <arpa/inet.h>
30 #include <pwd.h>
31 #include <grp.h>
32
33 #include "util.h"
34 #include "conffile.h"
35 #include "process.h"
36
37 #if __APPLE__
38 /* apple's poll() does not work on char devs */
39 # define USE_SELECT 1
40 #endif
41
42 /* XXX should be from autoconf */
43 static const char *configfile="/etc/secnet/secnet.conf";
44 static const char *sites_key="sites";
45 bool_t just_check_config=False;
46 static char *userid=NULL;
47 static uid_t uid=0;
48 static gid_t gid;
49 bool_t background=True;
50 static char *pidfile=NULL;
51 bool_t require_root_privileges=False;
52 cstring_t require_root_privileges_explanation=NULL;
53
54 const char *const closure_type_names[] = {
55  [ CL_PURE       ] = "PURE"       ,
56  [ CL_RESOLVER   ] = "RESOLVER"   ,
57  [ CL_RANDOMSRC  ] = "RANDOMSRC"  ,
58  [ CL_SIGPUBKEY  ] = "SIGPUBKEY"  ,
59  [ CL_SIGPRIVKEY ] = "SIGPRIVKEY" ,
60  [ CL_COMM       ] = "COMM"       ,
61  [ CL_IPIF       ] = "IPIF"       ,
62  [ CL_LOG        ] = "LOG"        ,
63  [ CL_SITE       ] = "SITE"       ,
64  [ CL_TRANSFORM  ] = "TRANSFORM"  ,
65  [ CL_DH         ] = "DH"         ,
66  [ CL_HASH       ] = "HASH"       ,
67  [ CL_BUFFER     ] = "BUFFER"     ,
68  [ CL_NETLINK    ] = "NETLINK"    ,
69  [ CL_PRIVCACHE  ] = "PRIVCACHE"  ,
70 };
71
72 const char *closure_type_name(uint32_t ty, char buf[]) {
73     if (ty < ARRAY_SIZE(closure_type_names))
74         return closure_type_names[ty];
75     sprintf(buf, "CL#%.6u", (unsigned)ty);
76     buf[9] = 0;
77     return buf;
78 }
79
80 static pid_t secnet_pid;
81
82 /* Structures dealing with poll() call */
83 struct poll_interest {
84     beforepoll_fn *before; /* 0 if deregistered and waiting to be deleted */
85     afterpoll_fn *after;
86     void *state;
87     int32_t nfds;
88     cstring_t desc;
89     LIST_ENTRY(poll_interest) entry;
90 };
91 static LIST_HEAD(, poll_interest) reg = LIST_HEAD_INITIALIZER(&reg);
92
93 static bool_t interest_isregistered(const struct poll_interest *i)
94 {
95     return !!i->before;
96 }
97
98 static bool_t finished=False;
99
100 /* Parse the command line options */
101 static void parse_options(int argc, char **argv)
102 {
103     int c;
104
105     while (True) {
106         int option_index = 0;
107         static struct option long_options[] = {
108             {"verbose", 0, 0, 'v'},
109             {"nowarnings", 0, 0, 'w'},
110             {"help", 0, 0, 2},
111             {"version", 0, 0, 1},
112             {"nodetach", 0, 0, 'n'},
113             {"managed", 0, 0, 'm'},
114             {"silent", 0, 0, 'f'},
115             {"quiet", 0, 0, 'f'},
116             {"debug", 0, 0, 'd'},
117             {"config", 1, 0, 'c'},
118             {"just-check-config", 0, 0, 'j'},
119             {"sites-key", 1, 0, 's'},
120             {0,0,0,0}
121         };
122
123         c=getopt_long(argc, argv, "vwdnjc:ft:s:m",
124                       long_options, &option_index);
125         if (c==-1)
126             break;
127
128         switch(c) {
129         case 2:
130             /* Help */
131             printf("Usage: secnet [OPTION]...\n\n"
132                    "  -f, --silent, --quiet   suppress error messages\n"
133                    "  -w, --nowarnings        suppress warnings\n"
134                    "  -v, --verbose           output extra diagnostics\n"
135                    "  -c, --config=filename   specify a configuration file\n"
136                    "  -j, --just-check-config stop after reading "
137                    "configuration file\n"
138                    "  -s, --sites-key=name    configuration key that "
139                    "specifies active sites\n"
140                    "  -n, --nodetach          do not run in background\n"
141                    "  -m, --managed           running under a supervisor\n"
142                    "  -d, --debug             output debug messages\n"
143                    "      --help              display this help and exit\n"
144                    "      --version           output version information "
145                    "and exit\n"
146                 );
147             exit(0);
148             break;
149       
150         case 1:
151             /* Version */
152             printf("%s\n",version);
153             exit(0);
154             break;
155
156         case 'd':
157             message_level|=M_DEBUG_CONFIG|M_DEBUG_PHASE|M_DEBUG;
158             /* fall through */
159         case 'v':
160             message_level|=M_INFO|M_NOTICE|M_WARNING|M_ERR|M_SECURITY|
161                 M_FATAL;
162             break;
163
164         case 'w':
165             message_level&=(~M_WARNING);
166             break;
167
168         case 'f':
169             message_level=M_FATAL;
170             break;
171
172         case 'n':
173             background=False;
174             break;
175
176         case 'm':
177             secnet_is_daemon=True;
178             break;
179
180         case 'c':
181             if (optarg)
182                 configfile=safe_strdup(optarg,"config_filename");
183             else
184                 fatal("secnet: no config filename specified");
185             break;
186
187         case 'j':
188             just_check_config=True;
189             break;
190
191         case 's':
192             if (optarg)
193                 sites_key=safe_strdup(optarg,"sites-key");
194             else
195                 fatal("secnet: no sites key specified");
196             break;
197
198         case '?':
199             exit(1);
200             break;
201
202         default:
203             Message(M_ERR,"secnet: Unknown getopt code %c\n",c);
204         }
205     }
206
207     if (argc-optind != 0) {
208         Message(M_ERR,"secnet: You gave extra command line parameters, "
209                 "which were ignored.\n");
210     }
211 }
212
213 static void setup(dict_t *config)
214 {
215     list_t *l;
216     dict_t *system;
217     struct passwd *pw;
218     struct cloc loc;
219
220     l=dict_lookup(config,"system");
221
222     if (!l || list_elem(l,0)->type!=t_dict) {
223         fatal("configuration does not include a \"system\" dictionary");
224     }
225     system=list_elem(l,0)->data.dict;
226     loc=list_elem(l,0)->loc;
227
228     /* Arrange systemwide log facility */
229     l=dict_lookup(system,"log");
230     if (!l) {
231         fatal("configuration does not include a system/log facility");
232     }
233     system_log=init_log(l);
234
235     /* Who are we supposed to run as? */
236     userid=dict_read_string(system,"userid",False,"system",loc);
237     if (userid) {
238         if (!(pw=getpwnam(userid)))
239             fatal("userid \"%s\" not found",userid);
240         uid=pw->pw_uid;
241         gid=pw->pw_gid;
242     }
243
244     /* Pidfile name */
245     pidfile=dict_read_string(system,"pidfile",False,"system",loc);
246
247     /* Check whether we need root privileges */
248     if (require_root_privileges && uid!=0) {
249         fatal("the configured feature \"%s\" requires "
250               "that secnet retain root privileges while running.",
251               require_root_privileges_explanation);
252     }
253 }
254
255 static void start_sites(dict_t *config) {
256     int i;
257     list_t *l;
258     item_t *site;
259
260     /* Go along site list, starting sites */
261     l=dict_lookup(config,sites_key);
262     if (!l) {
263         Message(M_WARNING,"secnet: configuration key \"%s\" is missing; no "
264                 "remote sites are defined\n",sites_key);
265     } else {
266         i=0;
267         while ((site=list_elem(l, i++))) {
268             struct site_if *s;
269             if (site->type!=t_closure) {
270                 cfgfatal(site->loc,"system","non-closure in site list");
271             }
272             if (site->data.closure->type!=CL_SITE) {
273                 cfgfatal(site->loc,"system","non-site closure in site list");
274             }
275             s=site->data.closure->interface;
276             s->startup(s->st);
277         }
278     }
279 }
280
281 struct poll_interest *register_for_poll(void *st, beforepoll_fn *before,
282                        afterpoll_fn *after, cstring_t desc)
283 {
284     struct poll_interest *i;
285
286     NEW(i);
287     i->before=before;
288     i->after=after;
289     i->state=st;
290     i->nfds=0;
291     i->desc=desc;
292     LIST_INSERT_HEAD(&reg, i, entry);
293     return i;
294 }
295
296 void deregister_for_poll(struct poll_interest *i)
297 {
298     /* We cannot simply throw this away because we're reentrantly
299      * inside the main loop, which needs to remember which range of
300      * fds corresponds to this now-obsolete interest */
301     i->before=0;
302 }
303
304 static void system_phase_hook(void *sst, uint32_t newphase)
305 {
306     if (newphase==PHASE_SHUTDOWN && pidfile) {
307         /* Try to unlink the pidfile; don't care if it fails */
308         unlink(pidfile);
309     }
310 }
311
312 #if USE_SELECT
313 static int fakepoll(struct pollfd *fds, int nfds, int timeout) {
314     fd_set infds[1], outfds[1];
315     int maxfd = -1, i, rc;
316     struct timeval tvtimeout;
317     FD_ZERO(infds);
318     FD_ZERO(outfds);
319     for(i = 0; i < nfds; ++i) {
320         if(fds[i].events & POLLIN)
321             FD_SET(fds[i].fd, infds);
322         if(fds[i].events & POLLOUT)
323             FD_SET(fds[i].fd, outfds);
324         if(fds[i].fd > maxfd)
325             maxfd = fds[i].fd;
326     }
327     if(timeout != -1) {
328         tvtimeout.tv_sec = timeout / 1000;
329         tvtimeout.tv_usec = 1000 * (timeout % 1000);
330     }
331     rc = select(maxfd + 1, infds, outfds, NULL, 
332                 timeout == -1 ? NULL : &tvtimeout);
333     if(rc >= 0) {
334         for(i = 0; i < nfds; ++i) {
335             int revents = 0;
336             if(FD_ISSET(fds[i].fd, infds))
337                 revents |= POLLIN;
338             if(FD_ISSET(fds[i].fd, outfds))
339                 revents |= POLLOUT;
340             fds[i].revents = revents;
341         }
342     }
343     return rc;
344 }
345 #endif
346
347 struct timeval tv_now_global;
348 uint64_t now_global;
349
350 static void run(void)
351 {
352     struct poll_interest *i, *itmp;
353     int rv, nfds, idx;
354     int timeout;
355     struct pollfd *fds=0;
356     int allocdfds=0, shortfall=0;
357
358     do {
359         if (gettimeofday(&tv_now_global, NULL)!=0) {
360             fatal_perror("main loop: gettimeofday");
361         }
362         now_global=((uint64_t)tv_now_global.tv_sec*(uint64_t)1000)+
363                    ((uint64_t)tv_now_global.tv_usec/(uint64_t)1000);
364         idx=0;
365         LIST_FOREACH(i, &reg, entry) {
366             int check;
367             if (interest_isregistered(i)) {
368                 for (check=0; check<i->nfds; check++) {
369                     if(fds[idx+check].revents & POLLNVAL) {
370                         fatal("run: poll (%s#%d) set POLLNVAL", i->desc, check);
371                     }
372                 }
373                 i->after(i->state, fds+idx, i->nfds);
374             }
375             idx+=i->nfds;
376         }
377         if (shortfall) {
378             allocdfds *= 2;
379             allocdfds += shortfall;
380             REALLOC_ARY(fds,allocdfds);
381         }
382         shortfall=0;
383         idx=0;
384         timeout=-1;
385         LIST_FOREACH_SAFE(i, &reg, entry, itmp) {
386             int remain=allocdfds-idx;
387             nfds=remain;
388             if (interest_isregistered(i)) {
389                 rv=i->before(i->state, fds+idx, &nfds, &timeout);
390                 if (rv!=0) {
391                     if (rv!=ERANGE)
392                         fatal("run: beforepoll_fn (%s) returns %d",i->desc,rv);
393                     assert(nfds < INT_MAX/4 - shortfall);
394                     shortfall += nfds-remain;
395                     nfds=0;
396                     timeout=0;
397                 }
398             } else {
399                 nfds=0;
400             }
401             if (timeout<-1) {
402                 fatal("run: beforepoll_fn (%s) set timeout to %d",
403                       i->desc,timeout);
404             }
405             if (!interest_isregistered(i)) {
406                 /* check this here, rather than earlier, so that we
407                    handle the case where i->before() calls deregister */
408                 LIST_REMOVE(i, entry);
409                 free(i);
410                 continue;
411             }
412             idx+=nfds;
413             i->nfds=nfds;
414         }
415         do {
416             if (finished) break;
417 #if USE_SELECT
418             rv=fakepoll(fds, idx, timeout);
419 #else
420             rv=poll(fds, idx, timeout);
421 #endif
422             if (rv<0) {
423                 if (errno!=EINTR) {
424                     fatal_perror("run: poll");
425                 }
426             }
427         } while (rv<0);
428     } while (!finished);
429     free(fds);
430 }
431
432 bool_t will_droppriv(void)
433 {
434     assert(current_phase >= PHASE_SETUP);
435     return !!uid;
436 }
437
438 /* Surrender privileges, if necessary */
439 static void droppriv(void)
440 {
441     if (userid) {
442         if (setgid(gid)!=0)
443             fatal_perror("can't set gid to %ld",(long)gid);
444         if (initgroups(userid, gid) < 0)
445             fatal_perror("initgroups"); 
446         if (setuid(uid)!=0) {
447             fatal_perror("can't set uid to \"%s\"",userid);
448         }
449         assert(getuid() == uid);
450         assert(geteuid() == uid);
451         assert(getgid() == gid);
452         assert(getegid() == gid);
453     }
454 }
455
456 /* Become a daemon, if necessary */
457 static void become_daemon(void)
458 {
459     FILE *pf=NULL;
460     pid_t p;
461     int errfds[2];
462
463     add_hook(PHASE_SHUTDOWN,system_phase_hook,NULL);
464
465     /* We only want to become a daemon if we are not one
466      already */
467     if (background && !secnet_is_daemon) {
468         p=fork();
469         if (p>0) {
470             /* Parent process - just exit */
471             _exit(0);
472         } else if (p==0) {
473             /* Child process - all done, just carry on */
474             secnet_is_daemon=True;
475             if (setsid() < 0)
476                 fatal_perror("setsid");
477         } else {
478             /* Error */
479             fatal_perror("cannot fork");
480             exit(1);
481         }
482     }
483     if (secnet_is_daemon) {
484         /* stderr etc are redirected to the system/log facility */
485         pipe_cloexec(errfds);
486         if (dup2(errfds[1],0) < 0
487             || dup2(errfds[1],1) < 0
488             || dup2(errfds[1],2) < 0)
489             fatal_perror("can't dup2 pipe");
490         if (close(errfds[1]) < 0)
491             fatal_perror("can't close redundant pipe endpoint");
492         log_from_fd(errfds[0],"stderr",system_log);
493     }
494     secnet_pid=getpid();
495     
496     /* Now we can write the pidfile */
497     if (pidfile) {
498         pf=fopen(pidfile,"w");
499         if (!pf) {
500             fatal_perror("cannot open pidfile \"%s\"",pidfile);
501         }
502         if (fprintf(pf,"%ld\n",(long)secnet_pid) < 0
503             || fclose(pf) < 0)
504             fatal_perror("cannot write to pidfile \"%s\"",pidfile);
505     }
506 }
507
508 static signal_notify_fn finish,ignore_hup;
509 static void finish(void *st, int signum)
510 {
511     finished=True;
512     Message(M_NOTICE,"%s [%d]: received %s\n",version,secnet_pid,(string_t)st);
513 }
514 static void ignore_hup(void *st, int signum)
515 {
516     Message(M_INFO,"%s [%d]: received SIGHUP\n",version,secnet_pid);
517     return;
518 }
519
520 int main(int argc, char **argv)
521 {
522     dict_t *config;
523
524     log_early_init();
525     phase_hooks_init();
526
527     enter_phase(PHASE_GETOPTS);
528     parse_options(argc,argv);
529     log_early_setlevel();
530
531     enter_phase(PHASE_READCONFIG);
532     config=read_conffile(configfile);
533
534     enter_phase(PHASE_SETUP);
535     setup(config);
536     start_sites(config);
537
538     if (just_check_config) {
539         Message(M_INFO,"configuration file check complete\n");
540         exit(0);
541     }
542
543     enter_phase(PHASE_DAEMONIZE);
544     become_daemon();
545     Message(M_NOTICE,"%s [%d]: starting\n",version,secnet_pid);
546     
547     enter_phase(PHASE_GETRESOURCES);
548     /* Appropriate phase hooks will have been run */
549     
550     enter_phase(PHASE_DROPPRIV);
551     droppriv();
552
553     start_signal_handling();
554     request_signal_notification(SIGTERM,finish,safe_strdup("SIGTERM","run"));
555     if (!background) request_signal_notification(SIGINT,finish,
556                                                  safe_strdup("SIGINT","run"));
557     request_signal_notification(SIGHUP,ignore_hup,NULL);
558     enter_phase(PHASE_RUN);
559     run();
560
561     enter_phase(PHASE_SHUTDOWN);
562     Message(M_NOTICE,"%s [%d]: finished\n",version,secnet_pid);
563
564     return 0;
565 }