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