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