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.
28 #include <sys/socket.h>
29 #include <arpa/inet.h>
38 /* apple's poll() does not work on char devs */
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;
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;
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" ,
63 [ CL_SITE ] = "SITE" ,
64 [ CL_TRANSFORM ] = "TRANSFORM" ,
66 [ CL_HASH ] = "HASH" ,
67 [ CL_BUFFER ] = "BUFFER" ,
68 [ CL_NETLINK ] = "NETLINK" ,
69 [ CL_PRIVCACHE ] = "PRIVCACHE" ,
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);
80 static pid_t secnet_pid;
82 /* Structures dealing with poll() call */
83 struct poll_interest {
84 beforepoll_fn *before; /* 0 if deregistered and waiting to be deleted */
89 LIST_ENTRY(poll_interest) entry;
91 static LIST_HEAD(, poll_interest) reg = LIST_HEAD_INITIALIZER(®);
93 static bool_t interest_isregistered(const struct poll_interest *i)
98 static bool_t finished=False;
100 /* Parse the command line options */
101 static void parse_options(int argc, char **argv)
106 int option_index = 0;
107 static struct option long_options[] = {
108 {"verbose", 0, 0, 'v'},
109 {"nowarnings", 0, 0, 'w'},
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'},
123 c=getopt_long(argc, argv, "vwdnjc:ft:s:m",
124 long_options, &option_index);
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 "
152 printf("%s\n",version);
157 message_level|=M_DEBUG_CONFIG|M_DEBUG_PHASE|M_DEBUG;
160 message_level|=M_INFO|M_NOTICE|M_WARNING|M_ERR|M_SECURITY|
165 message_level&=(~M_WARNING);
169 message_level=M_FATAL;
177 secnet_is_daemon=True;
182 configfile=safe_strdup(optarg,"config_filename");
184 fatal("secnet: no config filename specified");
188 just_check_config=True;
193 sites_key=safe_strdup(optarg,"sites-key");
195 fatal("secnet: no sites key specified");
203 Message(M_ERR,"secnet: Unknown getopt code %c\n",c);
207 if (argc-optind != 0) {
208 Message(M_ERR,"secnet: You gave extra command line parameters, "
209 "which were ignored.\n");
213 static void setup(dict_t *config)
220 l=dict_lookup(config,"system");
222 if (!l || list_elem(l,0)->type!=t_dict) {
223 fatal("configuration does not include a \"system\" dictionary");
225 system=list_elem(l,0)->data.dict;
226 loc=list_elem(l,0)->loc;
228 /* Arrange systemwide log facility */
229 l=dict_lookup(system,"log");
231 fatal("configuration does not include a system/log facility");
233 system_log=init_log(l);
235 /* Who are we supposed to run as? */
236 userid=dict_read_string(system,"userid",False,"system",loc);
238 if (!(pw=getpwnam(userid)))
239 fatal("userid \"%s\" not found",userid);
245 pidfile=dict_read_string(system,"pidfile",False,"system",loc);
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);
255 static void start_sites(dict_t *config) {
260 /* Go along site list, starting sites */
261 l=dict_lookup(config,sites_key);
263 Message(M_WARNING,"secnet: configuration key \"%s\" is missing; no "
264 "remote sites are defined\n",sites_key);
267 while ((site=list_elem(l, i++))) {
269 if (site->type!=t_closure) {
270 cfgfatal(site->loc,"system","non-closure in site list");
272 if (site->data.closure->type!=CL_SITE) {
273 cfgfatal(site->loc,"system","non-site closure in site list");
275 s=site->data.closure->interface;
281 struct poll_interest *register_for_poll(void *st, beforepoll_fn *before,
282 afterpoll_fn *after, cstring_t desc)
284 struct poll_interest *i;
292 LIST_INSERT_HEAD(®, i, entry);
296 void deregister_for_poll(struct poll_interest *i)
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 */
304 static void system_phase_hook(void *sst, uint32_t newphase)
306 if (newphase==PHASE_SHUTDOWN && pidfile) {
307 /* Try to unlink the pidfile; don't care if it fails */
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;
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)
328 tvtimeout.tv_sec = timeout / 1000;
329 tvtimeout.tv_usec = 1000 * (timeout % 1000);
331 rc = select(maxfd + 1, infds, outfds, NULL,
332 timeout == -1 ? NULL : &tvtimeout);
334 for(i = 0; i < nfds; ++i) {
336 if(FD_ISSET(fds[i].fd, infds))
338 if(FD_ISSET(fds[i].fd, outfds))
340 fds[i].revents = revents;
347 struct timeval tv_now_global;
350 static void run(void)
352 struct poll_interest *i, *itmp;
355 struct pollfd *fds=0;
356 int allocdfds=0, shortfall=0;
359 if (gettimeofday(&tv_now_global, NULL)!=0) {
360 fatal_perror("main loop: gettimeofday");
362 now_global=((uint64_t)tv_now_global.tv_sec*(uint64_t)1000)+
363 ((uint64_t)tv_now_global.tv_usec/(uint64_t)1000);
365 LIST_FOREACH(i, ®, entry) {
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);
373 i->after(i->state, fds+idx, i->nfds);
379 allocdfds += shortfall;
380 REALLOC_ARY(fds,allocdfds);
385 LIST_FOREACH_SAFE(i, ®, entry, itmp) {
386 int remain=allocdfds-idx;
388 if (interest_isregistered(i)) {
389 rv=i->before(i->state, fds+idx, &nfds, &timeout);
392 fatal("run: beforepoll_fn (%s) returns %d",i->desc,rv);
393 assert(nfds < INT_MAX/4 - shortfall);
394 shortfall += nfds-remain;
402 fatal("run: beforepoll_fn (%s) set timeout to %d",
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);
418 rv=fakepoll(fds, idx, timeout);
420 rv=poll(fds, idx, timeout);
424 fatal_perror("run: poll");
432 bool_t will_droppriv(void)
434 assert(current_phase >= PHASE_SETUP);
438 /* Surrender privileges, if necessary */
439 static void droppriv(void)
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);
449 assert(getuid() == uid);
450 assert(geteuid() == uid);
451 assert(getgid() == gid);
452 assert(getegid() == gid);
456 /* Become a daemon, if necessary */
457 static void become_daemon(void)
463 add_hook(PHASE_SHUTDOWN,system_phase_hook,NULL);
465 /* We only want to become a daemon if we are not one
467 if (background && !secnet_is_daemon) {
470 /* Parent process - just exit */
473 /* Child process - all done, just carry on */
474 secnet_is_daemon=True;
476 fatal_perror("setsid");
479 fatal_perror("cannot fork");
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);
496 /* Now we can write the pidfile */
498 pf=fopen(pidfile,"w");
500 fatal_perror("cannot open pidfile \"%s\"",pidfile);
502 if (fprintf(pf,"%ld\n",(long)secnet_pid) < 0
504 fatal_perror("cannot write to pidfile \"%s\"",pidfile);
508 static signal_notify_fn finish,ignore_hup;
509 static void finish(void *st, int signum)
512 Message(M_NOTICE,"%s [%d]: received %s\n",version,secnet_pid,(string_t)st);
514 static void ignore_hup(void *st, int signum)
516 Message(M_INFO,"%s [%d]: received SIGHUP\n",version,secnet_pid);
520 int main(int argc, char **argv)
527 enter_phase(PHASE_GETOPTS);
528 parse_options(argc,argv);
529 log_early_setlevel();
531 enter_phase(PHASE_READCONFIG);
532 config=read_conffile(configfile);
534 enter_phase(PHASE_SETUP);
538 if (just_check_config) {
539 Message(M_INFO,"configuration file check complete\n");
543 enter_phase(PHASE_DAEMONIZE);
545 Message(M_NOTICE,"%s [%d]: starting\n",version,secnet_pid);
547 enter_phase(PHASE_GETRESOURCES);
548 /* Appropriate phase hooks will have been run */
550 enter_phase(PHASE_DROPPRIV);
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);
561 enter_phase(PHASE_SHUTDOWN);
562 Message(M_NOTICE,"%s [%d]: finished\n",version,secnet_pid);