secnet: provide will_droppriv
[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; /* 0 if deregistered and waiting to be deleted */
40 afterpoll_fn *after;
41 void *state;
42 int32_t nfds;
43 cstring_t desc;
44 LIST_ENTRY(poll_interest) entry;
45 };
46 static LIST_HEAD(, poll_interest) reg = LIST_HEAD_INITIALIZER(&reg);
47
48 static bool_t interest_isregistered(const struct poll_interest *i)
49 {
50 return !!i->before;
51 }
52
53 static bool_t finished=False;
54
55 /* Parse the command line options */
56 static 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'},
68 {"managed", 0, 0, 'm'},
69 {"silent", 0, 0, 'f'},
70 {"quiet", 0, 0, 'f'},
71 {"debug", 0, 0, 'd'},
72 {"config", 1, 0, 'c'},
73 {"just-check-config", 0, 0, 'j'},
74 {"sites-key", 1, 0, 's'},
75 {0,0,0,0}
76 };
77
78 c=getopt_long(argc, argv, "vwdnjc:ft:s:m",
79 long_options, &option_index);
80 if (c==-1)
81 break;
82
83 switch(c) {
84 case 2:
85 /* Help */
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"
96 " -m, --managed running under a supervisor\n"
97 " -d, --debug output debug messages\n"
98 " --help display this help and exit\n"
99 " --version output version information "
100 "and exit\n"
101 );
102 exit(0);
103 break;
104
105 case 1:
106 /* Version */
107 printf("%s\n",version);
108 exit(0);
109 break;
110
111 case 'v':
112 message_level|=M_INFO|M_NOTICE|M_WARNING|M_ERR|M_SECURITY|
113 M_FATAL;
114 break;
115
116 case 'w':
117 message_level&=(~M_WARNING);
118 break;
119
120 case 'd':
121 message_level|=M_DEBUG_CONFIG|M_DEBUG_PHASE|M_DEBUG;
122 break;
123
124 case 'f':
125 message_level=M_FATAL;
126 break;
127
128 case 'n':
129 background=False;
130 break;
131
132 case 'm':
133 secnet_is_daemon=True;
134 break;
135
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
143 case 'j':
144 just_check_config=True;
145 break;
146
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
154 case '?':
155 exit(1);
156 break;
157
158 default:
159 Message(M_ERR,"secnet: Unknown getopt code %c\n",c);
160 }
161 }
162
163 if (argc-optind != 0) {
164 Message(M_ERR,"secnet: You gave extra command line parameters, "
165 "which were ignored.\n");
166 }
167 }
168
169 static void setup(dict_t *config)
170 {
171 list_t *l;
172 item_t *site;
173 dict_t *system;
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) {
181 fatal("configuration does not include a \"system\" dictionary");
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) {
189 fatal("configuration does not include a system/log facility");
190 }
191 system_log=init_log(l);
192
193 /* Who are we supposed to run as? */
194 userid=dict_read_string(system,"userid",False,"system",loc);
195 if (userid) {
196 if (!(pw=getpwnam(userid)))
197 fatal("userid \"%s\" not found",userid);
198 uid=pw->pw_uid;
199 gid=pw->pw_gid;
200 }
201
202 /* Pidfile name */
203 pidfile=dict_read_string(system,"pidfile",False,"system",loc);
204
205 /* Check whether we need root privileges */
206 if (require_root_privileges && uid!=0) {
207 fatal("the configured feature \"%s\" requires "
208 "that secnet retain root privileges while running.",
209 require_root_privileges_explanation);
210 }
211
212 /* Go along site list, starting sites */
213 l=dict_lookup(config,sites_key);
214 if (!l) {
215 Message(M_WARNING,"secnet: configuration key \"%s\" is missing; no "
216 "remote sites are defined\n",sites_key);
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);
229 }
230 }
231 }
232
233 struct poll_interest *register_for_poll(void *st, beforepoll_fn *before,
234 afterpoll_fn *after, cstring_t desc)
235 {
236 struct poll_interest *i;
237
238 i=safe_malloc(sizeof(*i),"register_for_poll");
239 i->before=before;
240 i->after=after;
241 i->state=st;
242 i->nfds=0;
243 i->desc=desc;
244 LIST_INSERT_HEAD(&reg, i, entry);
245 return i;
246 }
247
248 void 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;
254 }
255
256 static 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
264 #if USE_SELECT
265 static 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
299 struct timeval tv_now_global;
300 uint64_t now_global;
301
302 static void run(void)
303 {
304 struct poll_interest *i, *itmp;
305 int rv, nfds, idx;
306 int timeout;
307 struct pollfd *fds=0;
308 int allocdfds=0, shortfall=0;
309
310 Message(M_NOTICE,"%s [%d]: starting\n",version,secnet_pid);
311
312 do {
313 if (gettimeofday(&tv_now_global, NULL)!=0) {
314 fatal_perror("main loop: gettimeofday");
315 }
316 now_global=((uint64_t)tv_now_global.tv_sec*(uint64_t)1000)+
317 ((uint64_t)tv_now_global.tv_usec/(uint64_t)1000);
318 idx=0;
319 LIST_FOREACH(i, &reg, entry) {
320 int check;
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 }
326 }
327 i->after(i->state, fds+idx, i->nfds);
328 }
329 idx+=i->nfds;
330 }
331 if (shortfall) {
332 allocdfds *= 2;
333 allocdfds += shortfall;
334 fds=safe_realloc_ary(fds,sizeof(*fds),allocdfds, "run");
335 }
336 shortfall=0;
337 idx=0;
338 timeout=-1;
339 LIST_FOREACH_SAFE(i, &reg, entry, itmp) {
340 int remain=allocdfds-idx;
341 nfds=remain;
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 {
353 nfds=0;
354 }
355 if (timeout<-1) {
356 fatal("run: beforepoll_fn (%s) set timeout to %d",
357 i->desc,timeout);
358 }
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 }
366 idx+=nfds;
367 i->nfds=nfds;
368 }
369 do {
370 if (finished) break;
371 #if USE_SELECT
372 rv=fakepoll(fds, idx, timeout);
373 #else
374 rv=poll(fds, idx, timeout);
375 #endif
376 if (rv<0) {
377 if (errno!=EINTR) {
378 fatal_perror("run: poll");
379 }
380 }
381 } while (rv<0);
382 } while (!finished);
383 free(fds);
384 }
385
386 bool_t will_droppriv(void)
387 {
388 assert(current_phase >= PHASE_SETUP);
389 return !!uid;
390 }
391
392 /* Surrender privileges, if necessary */
393 static void droppriv(void)
394 {
395 if (userid) {
396 if (setgid(gid)!=0)
397 fatal_perror("can't set gid to %ld",(long)gid);
398 if (initgroups(userid, gid) < 0)
399 fatal_perror("initgroups");
400 if (setuid(uid)!=0) {
401 fatal_perror("can't set uid to \"%s\"",userid);
402 }
403 assert(getuid() == uid);
404 assert(geteuid() == uid);
405 assert(getgid() == gid);
406 assert(getegid() == gid);
407 }
408 }
409
410 /* Become a daemon, if necessary */
411 static 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) {
422 p=fork();
423 if (p>0) {
424 /* Parent process - just exit */
425 _exit(0);
426 } else if (p==0) {
427 /* Child process - all done, just carry on */
428 secnet_is_daemon=True;
429 if (setsid() < 0)
430 fatal_perror("setsid");
431 } else {
432 /* Error */
433 fatal_perror("cannot fork");
434 exit(1);
435 }
436 }
437 if (secnet_is_daemon) {
438 /* stderr etc are redirected to the system/log facility */
439 pipe_cloexec(errfds);
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 }
448 secnet_pid=getpid();
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 }
460 }
461
462 static signal_notify_fn finish,ignore_hup;
463 static 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 }
468 static void ignore_hup(void *st, int signum)
469 {
470 Message(M_INFO,"%s [%d]: received SIGHUP\n",version,secnet_pid);
471 return;
472 }
473
474 int main(int argc, char **argv)
475 {
476 dict_t *config;
477
478 enter_phase(PHASE_GETOPTS);
479 parse_options(argc,argv);
480
481 enter_phase(PHASE_READCONFIG);
482 config=read_conffile(configfile);
483
484 enter_phase(PHASE_SETUP);
485 setup(config);
486
487 if (just_check_config) {
488 Message(M_INFO,"configuration file check complete\n");
489 exit(0);
490 }
491
492 enter_phase(PHASE_DAEMONIZE);
493 become_daemon();
494
495 enter_phase(PHASE_GETRESOURCES);
496 /* Appropriate phase hooks will have been run */
497
498 enter_phase(PHASE_DROPPRIV);
499 droppriv();
500
501 start_signal_handling();
502 request_signal_notification(SIGTERM,finish,safe_strdup("SIGTERM","run"));
503 if (!background) request_signal_notification(SIGINT,finish,
504 safe_strdup("SIGINT","run"));
505 request_signal_notification(SIGHUP,ignore_hup,NULL);
506 enter_phase(PHASE_RUN);
507 run();
508
509 enter_phase(PHASE_SHUTDOWN);
510 Message(M_NOTICE,"%s [%d]: finished\n",version,secnet_pid);
511
512 return 0;
513 }