9 #include <sys/socket.h>
10 #include <arpa/inet.h>
19 /* apple's poll() does not work on char devs */
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;
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;
35 static pid_t secnet_pid;
37 /* Structures dealing with poll() call */
38 struct poll_interest {
39 beforepoll_fn *before; /* 0 if deregistered and waiting to be deleted */
44 LIST_ENTRY(poll_interest) entry;
46 static LIST_HEAD(, poll_interest) reg = LIST_HEAD_INITIALIZER(®);
48 static bool_t interest_isregistered(const struct poll_interest *i)
53 static bool_t finished=False;
55 /* Parse the command line options */
56 static void parse_options(int argc, char **argv)
62 static struct option long_options[] = {
63 {"verbose", 0, 0, 'v'},
64 {"nowarnings", 0, 0, 'w'},
67 {"nodetach", 0, 0, 'n'},
68 {"managed", 0, 0, 'm'},
69 {"silent", 0, 0, 'f'},
72 {"config", 1, 0, 'c'},
73 {"just-check-config", 0, 0, 'j'},
74 {"sites-key", 1, 0, 's'},
78 c=getopt_long(argc, argv, "vwdnjc:ft:s:m",
79 long_options, &option_index);
86 printf("Usage: secnet [OPTION]...\n\n"
87 " -f, --silent, --quiet suppress error messages\n"
88 " -w, --nowarnings suppress warnings\n"
89 " -v, --verbose output extra diagnostics\n"
90 " -c, --config=filename specify a configuration file\n"
91 " -j, --just-check-config stop after reading "
92 "configuration file\n"
93 " -s, --sites-key=name configuration key that "
94 "specifies active sites\n"
95 " -n, --nodetach do not run in background\n"
96 " -m, --managed running under a supervisor\n"
97 " -d, --debug output debug messages\n"
98 " --help display this help and exit\n"
99 " --version output version information "
107 printf("%s\n",version);
112 message_level|=M_INFO|M_NOTICE|M_WARNING|M_ERR|M_SECURITY|
117 message_level&=(~M_WARNING);
121 message_level|=M_DEBUG_CONFIG|M_DEBUG_PHASE|M_DEBUG;
125 message_level=M_FATAL;
133 secnet_is_daemon=True;
138 configfile=safe_strdup(optarg,"config_filename");
140 fatal("secnet: no config filename specified");
144 just_check_config=True;
149 sites_key=safe_strdup(optarg,"sites-key");
151 fatal("secnet: no sites key specified");
159 Message(M_ERR,"secnet: Unknown getopt code %c\n",c);
163 if (argc-optind != 0) {
164 Message(M_ERR,"secnet: You gave extra command line parameters, "
165 "which were ignored.\n");
169 static void setup(dict_t *config)
178 l=dict_lookup(config,"system");
180 if (!l || list_elem(l,0)->type!=t_dict) {
181 fatal("configuration does not include a \"system\" dictionary");
183 system=list_elem(l,0)->data.dict;
184 loc=list_elem(l,0)->loc;
186 /* Arrange systemwide log facility */
187 l=dict_lookup(system,"log");
189 fatal("configuration does not include a system/log facility");
191 system_log=init_log(l);
193 /* Who are we supposed to run as? */
194 userid=dict_read_string(system,"userid",False,"system",loc);
196 if (!(pw=getpwnam(userid)))
197 fatal("userid \"%s\" not found",userid);
203 pidfile=dict_read_string(system,"pidfile",False,"system",loc);
205 /* Check whether we need root privileges */
206 if (require_root_privileges && uid!=0) {
207 fatal("the configured feature \"%s\" requires "
208 "that secnet retain root privileges while running.",
209 require_root_privileges_explanation);
212 /* Go along site list, starting sites */
213 l=dict_lookup(config,sites_key);
215 Message(M_WARNING,"secnet: configuration key \"%s\" is missing; no "
216 "remote sites are defined\n",sites_key);
219 while ((site=list_elem(l, i++))) {
221 if (site->type!=t_closure) {
222 cfgfatal(site->loc,"system","non-closure in site list");
224 if (site->data.closure->type!=CL_SITE) {
225 cfgfatal(site->loc,"system","non-site closure in site list");
227 s=site->data.closure->interface;
228 s->control(s->st,True);
233 struct poll_interest *register_for_poll(void *st, beforepoll_fn *before,
234 afterpoll_fn *after, cstring_t desc)
236 struct poll_interest *i;
238 i=safe_malloc(sizeof(*i),"register_for_poll");
244 LIST_INSERT_HEAD(®, i, entry);
248 void deregister_for_poll(struct poll_interest *i)
250 /* We cannot simply throw this away because we're reentrantly
251 * inside the main loop, which needs to remember which range of
252 * fds corresponds to this now-obsolete interest */
256 static void system_phase_hook(void *sst, uint32_t newphase)
258 if (newphase==PHASE_SHUTDOWN && pidfile) {
259 /* Try to unlink the pidfile; don't care if it fails */
265 static int fakepoll(struct pollfd *fds, int nfds, int timeout) {
266 fd_set infds[1], outfds[1];
267 int maxfd = -1, i, rc;
268 struct timeval tvtimeout;
271 for(i = 0; i < nfds; ++i) {
272 if(fds[i].events & POLLIN)
273 FD_SET(fds[i].fd, infds);
274 if(fds[i].events & POLLOUT)
275 FD_SET(fds[i].fd, outfds);
276 if(fds[i].fd > maxfd)
280 tvtimeout.tv_sec = timeout / 1000;
281 tvtimeout.tv_usec = 1000 * (timeout % 1000);
283 rc = select(maxfd + 1, infds, outfds, NULL,
284 timeout == -1 ? NULL : &tvtimeout);
286 for(i = 0; i < nfds; ++i) {
288 if(FD_ISSET(fds[i].fd, infds))
290 if(FD_ISSET(fds[i].fd, outfds))
292 fds[i].revents = revents;
299 struct timeval tv_now_global;
302 static void run(void)
304 struct poll_interest *i, *itmp;
307 struct pollfd *fds=0;
308 int allocdfds=0, shortfall=0;
310 Message(M_NOTICE,"%s [%d]: starting\n",version,secnet_pid);
313 if (gettimeofday(&tv_now_global, NULL)!=0) {
314 fatal_perror("main loop: gettimeofday");
316 now_global=((uint64_t)tv_now_global.tv_sec*(uint64_t)1000)+
317 ((uint64_t)tv_now_global.tv_usec/(uint64_t)1000);
319 LIST_FOREACH(i, ®, entry) {
321 if (interest_isregistered(i)) {
322 for (check=0; check<i->nfds; check++) {
323 if(fds[idx+check].revents & POLLNVAL) {
324 fatal("run: poll (%s#%d) set POLLNVAL", i->desc, check);
327 i->after(i->state, fds+idx, i->nfds);
333 allocdfds += shortfall;
334 fds=safe_realloc_ary(fds,sizeof(*fds),allocdfds, "run");
339 LIST_FOREACH_SAFE(i, ®, entry, itmp) {
340 int remain=allocdfds-idx;
342 if (interest_isregistered(i)) {
343 rv=i->before(i->state, fds+idx, &nfds, &timeout);
346 fatal("run: beforepoll_fn (%s) returns %d",i->desc,rv);
347 assert(nfds < INT_MAX/4 - shortfall);
348 shortfall += nfds-remain;
356 fatal("run: beforepoll_fn (%s) set timeout to %d",
359 if (!interest_isregistered(i)) {
360 /* check this here, rather than earlier, so that we
361 handle the case where i->before() calls deregister */
362 LIST_REMOVE(i, entry);
372 rv=fakepoll(fds, idx, timeout);
374 rv=poll(fds, idx, timeout);
378 fatal_perror("run: poll");
386 bool_t will_droppriv(void)
388 assert(current_phase >= PHASE_SETUP);
392 /* Surrender privileges, if necessary */
393 static void droppriv(void)
397 fatal_perror("can't set gid to %ld",(long)gid);
398 if (initgroups(userid, gid) < 0)
399 fatal_perror("initgroups");
400 if (setuid(uid)!=0) {
401 fatal_perror("can't set uid to \"%s\"",userid);
403 assert(getuid() == uid);
404 assert(geteuid() == uid);
405 assert(getgid() == gid);
406 assert(getegid() == gid);
410 /* Become a daemon, if necessary */
411 static void become_daemon(void)
417 add_hook(PHASE_SHUTDOWN,system_phase_hook,NULL);
419 /* We only want to become a daemon if we are not one
421 if (background && !secnet_is_daemon) {
424 /* Parent process - just exit */
427 /* Child process - all done, just carry on */
428 secnet_is_daemon=True;
430 fatal_perror("setsid");
433 fatal_perror("cannot fork");
437 if (secnet_is_daemon) {
438 /* stderr etc are redirected to the system/log facility */
439 pipe_cloexec(errfds);
440 if (dup2(errfds[1],0) < 0
441 || dup2(errfds[1],1) < 0
442 || dup2(errfds[1],2) < 0)
443 fatal_perror("can't dup2 pipe");
444 if (close(errfds[1]) < 0)
445 fatal_perror("can't close redundant pipe endpoint");
446 log_from_fd(errfds[0],"stderr",system_log);
450 /* Now we can write the pidfile */
452 pf=fopen(pidfile,"w");
454 fatal_perror("cannot open pidfile \"%s\"",pidfile);
456 if (fprintf(pf,"%ld\n",(long)secnet_pid) < 0
458 fatal_perror("cannot write to pidfile \"%s\"",pidfile);
462 static signal_notify_fn finish,ignore_hup;
463 static void finish(void *st, int signum)
466 Message(M_NOTICE,"%s [%d]: received %s\n",version,secnet_pid,(string_t)st);
468 static void ignore_hup(void *st, int signum)
470 Message(M_INFO,"%s [%d]: received SIGHUP\n",version,secnet_pid);
474 int main(int argc, char **argv)
480 enter_phase(PHASE_GETOPTS);
481 parse_options(argc,argv);
483 enter_phase(PHASE_READCONFIG);
484 config=read_conffile(configfile);
486 enter_phase(PHASE_SETUP);
489 if (just_check_config) {
490 Message(M_INFO,"configuration file check complete\n");
494 enter_phase(PHASE_DAEMONIZE);
497 enter_phase(PHASE_GETRESOURCES);
498 /* Appropriate phase hooks will have been run */
500 enter_phase(PHASE_DROPPRIV);
503 start_signal_handling();
504 request_signal_notification(SIGTERM,finish,safe_strdup("SIGTERM","run"));
505 if (!background) request_signal_notification(SIGINT,finish,
506 safe_strdup("SIGINT","run"));
507 request_signal_notification(SIGHUP,ignore_hup,NULL);
508 enter_phase(PHASE_RUN);
511 enter_phase(PHASE_SHUTDOWN);
512 Message(M_NOTICE,"%s [%d]: finished\n",version,secnet_pid);