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