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