2 * This file is part of secnet.
3 * See README for full list of copyright holders.
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.
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.
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.
29 #include <sys/socket.h>
30 #include <arpa/inet.h>
39 /* apple's poll() does not work on char devs */
43 /* XXX should be from autoconf */
44 static const char *configfile="/etc/secnet/secnet.conf";
45 static const char *sites_key="sites";
46 bool_t just_check_config=False;
47 static char *userid=NULL;
50 bool_t background=True;
51 static char *pidfile=NULL;
52 bool_t require_root_privileges=False;
53 cstring_t require_root_privileges_explanation=NULL;
55 const char *const closure_type_names[] = {
56 [ CL_PURE ] = "PURE" ,
57 [ CL_RESOLVER ] = "RESOLVER" ,
58 [ CL_RANDOMSRC ] = "RANDOMSRC" ,
59 [ CL_SIGPUBKEY ] = "SIGPUBKEY" ,
60 [ CL_SIGPRIVKEY ] = "SIGPRIVKEY" ,
61 [ CL_COMM ] = "COMM" ,
62 [ CL_IPIF ] = "IPIF" ,
64 [ CL_SITE ] = "SITE" ,
65 [ CL_TRANSFORM ] = "TRANSFORM" ,
67 [ CL_HASH ] = "HASH" ,
68 [ CL_BUFFER ] = "BUFFER" ,
69 [ CL_NETLINK ] = "NETLINK" ,
70 [ CL_PRIVCACHE ] = "PRIVCACHE" ,
73 const char *closure_type_name(uint32_t ty, char buf[]) {
74 if (ty < ARRAY_SIZE(closure_type_names))
75 return closure_type_names[ty];
76 sprintf(buf, "CL#%.6u", (unsigned)ty);
81 static pid_t secnet_pid;
83 /* Structures dealing with poll() call */
84 struct poll_interest {
85 beforepoll_fn *before; /* 0 if deregistered and waiting to be deleted */
90 LIST_ENTRY(poll_interest) entry;
92 static LIST_HEAD(, poll_interest) reg = LIST_HEAD_INITIALIZER(®);
94 static bool_t interest_isregistered(const struct poll_interest *i)
99 static bool_t finished=False;
101 /* Parse the command line options */
102 static void parse_options(int argc, char **argv)
107 int option_index = 0;
108 static struct option long_options[] = {
109 {"verbose", 0, 0, 'v'},
110 {"nowarnings", 0, 0, 'w'},
112 {"version", 0, 0, 1},
113 {"nodetach", 0, 0, 'n'},
114 {"managed", 0, 0, 'm'},
115 {"silent", 0, 0, 'f'},
116 {"quiet", 0, 0, 'f'},
117 {"debug", 0, 0, 'd'},
118 {"config", 1, 0, 'c'},
119 {"just-check-config", 0, 0, 'j'},
120 {"sites-key", 1, 0, 's'},
124 c=getopt_long(argc, argv, "vwdnjc:ft:s:m",
125 long_options, &option_index);
132 printf("Usage: secnet [OPTION]...\n\n"
133 " -f, --silent, --quiet suppress error messages\n"
134 " -w, --nowarnings suppress warnings\n"
135 " -v, --verbose output extra diagnostics\n"
136 " -c, --config=filename specify a configuration file\n"
137 " -j, --just-check-config stop after reading "
138 "configuration file\n"
139 " -s, --sites-key=name configuration key that "
140 "specifies active sites\n"
141 " -n, --nodetach do not run in background\n"
142 " -m, --managed running under a supervisor\n"
143 " -d, --debug output debug messages\n"
144 " --help display this help and exit\n"
145 " --version output version information "
153 printf("%s\n",version);
158 message_level|=M_DEBUG_CONFIG|M_DEBUG_PHASE|M_DEBUG;
161 message_level|=M_INFO|M_NOTICE|M_WARNING|M_ERR|M_SECURITY|
166 message_level&=(~M_WARNING);
170 message_level=M_FATAL;
178 secnet_is_daemon=True;
183 configfile=safe_strdup(optarg,"config_filename");
185 fatal("secnet: no config filename specified");
189 just_check_config=True;
194 sites_key=safe_strdup(optarg,"sites-key");
196 fatal("secnet: no sites key specified");
204 Message(M_ERR,"secnet: Unknown getopt code %c\n",c);
208 if (argc-optind != 0) {
209 Message(M_ERR,"secnet: You gave extra command line parameters, "
210 "which were ignored.\n");
214 static void setup(dict_t *config)
221 l=dict_lookup(config,"system");
223 if (!l || list_elem(l,0)->type!=t_dict) {
224 fatal("configuration does not include a \"system\" dictionary");
226 system=list_elem(l,0)->data.dict;
227 loc=list_elem(l,0)->loc;
229 /* Arrange systemwide log facility */
230 l=dict_lookup(system,"log");
232 fatal("configuration does not include a system/log facility");
234 system_log=init_log(l);
236 /* Who are we supposed to run as? */
237 userid=dict_read_string(system,"userid",False,"system",loc);
239 if (!(pw=getpwnam(userid)))
240 fatal("userid \"%s\" not found",userid);
246 pidfile=dict_read_string(system,"pidfile",False,"system",loc);
248 /* Check whether we need root privileges */
249 if (require_root_privileges && uid!=0) {
250 fatal("the configured feature \"%s\" requires "
251 "that secnet retain root privileges while running.",
252 require_root_privileges_explanation);
256 static void start_sites(dict_t *config) {
261 /* Go along site list, starting sites */
262 l=dict_lookup(config,sites_key);
264 Message(M_WARNING,"secnet: configuration key \"%s\" is missing; no "
265 "remote sites are defined\n",sites_key);
268 while ((site=list_elem(l, i++))) {
270 if (site->type!=t_closure) {
271 cfgfatal(site->loc,"system","non-closure in site list");
273 if (site->data.closure->type!=CL_SITE) {
274 cfgfatal(site->loc,"system","non-site closure in site list");
276 s=site->data.closure->interface;
282 struct poll_interest *register_for_poll(void *st, beforepoll_fn *before,
283 afterpoll_fn *after, cstring_t desc)
285 struct poll_interest *i;
293 LIST_INSERT_HEAD(®, i, entry);
297 void deregister_for_poll(struct poll_interest *i)
299 /* We cannot simply throw this away because we're reentrantly
300 * inside the main loop, which needs to remember which range of
301 * fds corresponds to this now-obsolete interest */
305 static void system_phase_hook(void *sst, uint32_t newphase)
307 if (newphase==PHASE_SHUTDOWN && pidfile) {
308 /* Try to unlink the pidfile; don't care if it fails */
314 static int fakepoll(struct pollfd *fds, int nfds, int timeout) {
315 fd_set infds[1], outfds[1];
316 int maxfd = -1, i, rc;
317 struct timeval tvtimeout;
320 for(i = 0; i < nfds; ++i) {
321 if(fds[i].events & POLLIN)
322 FD_SET(fds[i].fd, infds);
323 if(fds[i].events & POLLOUT)
324 FD_SET(fds[i].fd, outfds);
325 if(fds[i].fd > maxfd)
329 tvtimeout.tv_sec = timeout / 1000;
330 tvtimeout.tv_usec = 1000 * (timeout % 1000);
332 rc = select(maxfd + 1, infds, outfds, NULL,
333 timeout == -1 ? NULL : &tvtimeout);
335 for(i = 0; i < nfds; ++i) {
337 if(FD_ISSET(fds[i].fd, infds))
339 if(FD_ISSET(fds[i].fd, outfds))
341 fds[i].revents = revents;
348 struct timeval tv_now_global;
351 static void run(void)
353 struct poll_interest *i, *itmp;
356 struct pollfd *fds=0;
357 int allocdfds=0, shortfall=0;
362 if (clock_gettime(CLOCK_MONOTONIC, &ts)!=0) {
363 fatal_perror("main loop: clock_gettime(CLOCK_MONOTONIC,)");
365 tv_now_global.tv_sec = ts.tv_sec;
366 tv_now_global.tv_usec = ts.tv_nsec / 1000;
367 #else /* !USE_MONOTONIC */
368 if (gettimeofday(&tv_now_global, NULL)!=0) {
369 fatal_perror("main loop: gettimeofday");
371 #endif /* !USE_MONOTONIC */
372 now_global=((uint64_t)tv_now_global.tv_sec*(uint64_t)1000)+
373 ((uint64_t)tv_now_global.tv_usec/(uint64_t)1000);
375 LIST_FOREACH(i, ®, entry) {
377 if (interest_isregistered(i)) {
378 for (check=0; check<i->nfds; check++) {
379 if(fds[idx+check].revents & POLLNVAL) {
380 fatal("run: poll (%s#%d) set POLLNVAL", i->desc, check);
383 i->after(i->state, fds+idx, i->nfds);
389 allocdfds += shortfall;
390 REALLOC_ARY(fds,allocdfds);
395 LIST_FOREACH_SAFE(i, ®, entry, itmp) {
396 int remain=allocdfds-idx;
398 if (interest_isregistered(i)) {
399 rv=i->before(i->state, fds+idx, &nfds, &timeout);
402 fatal("run: beforepoll_fn (%s) returns %d",i->desc,rv);
403 assert(nfds < INT_MAX/4 - shortfall);
404 shortfall += nfds-remain;
412 fatal("run: beforepoll_fn (%s) set timeout to %d",
415 if (!interest_isregistered(i)) {
416 /* check this here, rather than earlier, so that we
417 handle the case where i->before() calls deregister */
418 LIST_REMOVE(i, entry);
428 rv=fakepoll(fds, idx, timeout);
430 rv=poll(fds, idx, timeout);
434 fatal_perror("run: poll");
442 bool_t will_droppriv(void)
444 assert(current_phase >= PHASE_SETUP);
448 /* Surrender privileges, if necessary */
449 static void droppriv(void)
453 fatal_perror("can't set gid to %ld",(long)gid);
454 if (initgroups(userid, gid) < 0)
455 fatal_perror("initgroups");
456 if (setuid(uid)!=0) {
457 fatal_perror("can't set uid to \"%s\"",userid);
459 assert(getuid() == uid);
460 assert(geteuid() == uid);
461 assert(getgid() == gid);
462 assert(getegid() == gid);
466 /* Become a daemon, if necessary */
467 static void become_daemon(void)
473 add_hook(PHASE_SHUTDOWN,system_phase_hook,NULL);
475 /* We only want to become a daemon if we are not one
477 if (background && !secnet_is_daemon) {
480 /* Parent process - just exit */
483 /* Child process - all done, just carry on */
484 secnet_is_daemon=True;
486 fatal_perror("setsid");
489 fatal_perror("cannot fork");
493 if (secnet_is_daemon) {
494 /* stderr etc are redirected to the system/log facility */
495 pipe_cloexec(errfds);
496 if (dup2(errfds[1],0) < 0
497 || dup2(errfds[1],1) < 0
498 || dup2(errfds[1],2) < 0)
499 fatal_perror("can't dup2 pipe");
500 if (close(errfds[1]) < 0)
501 fatal_perror("can't close redundant pipe endpoint");
502 log_from_fd(errfds[0],"stderr",system_log);
506 /* Now we can write the pidfile */
508 pf=fopen(pidfile,"w");
510 fatal_perror("cannot open pidfile \"%s\"",pidfile);
512 if (fprintf(pf,"%ld\n",(long)secnet_pid) < 0
514 fatal_perror("cannot write to pidfile \"%s\"",pidfile);
518 static signal_notify_fn finish,ignore_hup;
519 static void finish(void *st, int signum)
522 Message(M_NOTICE,"%s [%d]: received %s\n",version,secnet_pid,(string_t)st);
524 static void ignore_hup(void *st, int signum)
526 Message(M_INFO,"%s [%d]: received SIGHUP\n",version,secnet_pid);
530 int main(int argc, char **argv)
537 enter_phase(PHASE_GETOPTS);
538 parse_options(argc,argv);
539 log_early_setlevel();
541 enter_phase(PHASE_READCONFIG);
542 config=read_conffile(configfile);
544 enter_phase(PHASE_SETUP);
548 if (just_check_config) {
549 Message(M_INFO,"configuration file check complete\n");
553 enter_phase(PHASE_DAEMONIZE);
555 Message(M_NOTICE,"%s [%d]: starting\n",version,secnet_pid);
557 enter_phase(PHASE_GETRESOURCES);
558 /* Appropriate phase hooks will have been run */
560 enter_phase(PHASE_DROPPRIV);
563 start_signal_handling();
564 request_signal_notification(SIGTERM,finish,safe_strdup("SIGTERM","run"));
565 if (!background) request_signal_notification(SIGINT,finish,
566 safe_strdup("SIGINT","run"));
567 request_signal_notification(SIGHUP,ignore_hup,NULL);
568 enter_phase(PHASE_RUN);
571 enter_phase(PHASE_SHUTDOWN);
572 Message(M_NOTICE,"%s [%d]: finished\n",version,secnet_pid);