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