chiark / gitweb /
changelog: start 0.6.8
[secnet.git] / secnet.c
1 /*
2  * This file is part of secnet.
3  * See README for full list of copyright holders.
4  *
5  * secnet is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  * 
10  * secnet is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  * 
15  * You should have received a copy of the GNU General Public License
16  * version 3 along with secnet; if not, see
17  * https://www.gnu.org/licenses/gpl.html.
18  */
19
20 #include "secnet.h"
21 #include <stdio.h>
22 #include <assert.h>
23 #include <limits.h>
24 #include <string.h>
25 #include <getopt.h>
26 #include <errno.h>
27 #include <time.h>
28 #include <unistd.h>
29 #include <sys/socket.h>
30 #include <arpa/inet.h>
31 #include <pwd.h>
32 #include <grp.h>
33
34 #include "util.h"
35 #include "conffile.h"
36 #include "process.h"
37
38 #if __APPLE__
39 /* apple's poll() does not work on char devs */
40 # define USE_SELECT 1
41 #endif
42
43 /* XXX should be from autoconf */
44 static const char *configfile="/etc/secnet/secnet.conf";
45 static const char *sites_key="sites";
46 bool_t just_check_config=False;
47 static char *userid=NULL;
48 static uid_t uid=0;
49 static gid_t gid;
50 bool_t background=True;
51 static char *pidfile=NULL;
52 bool_t require_root_privileges=False;
53 cstring_t require_root_privileges_explanation=NULL;
54
55 const char *const closure_type_names[] = {
56  [ CL_PURE       ] = "PURE"       ,
57  [ CL_RESOLVER   ] = "RESOLVER"   ,
58  [ CL_RANDOMSRC  ] = "RANDOMSRC"  ,
59  [ CL_SIGPUBKEY  ] = "SIGPUBKEY"  ,
60  [ CL_SIGPRIVKEY ] = "SIGPRIVKEY" ,
61  [ CL_COMM       ] = "COMM"       ,
62  [ CL_IPIF       ] = "IPIF"       ,
63  [ CL_LOG        ] = "LOG"        ,
64  [ CL_SITE       ] = "SITE"       ,
65  [ CL_TRANSFORM  ] = "TRANSFORM"  ,
66  [ CL_DH         ] = "DH"         ,
67  [ CL_HASH       ] = "HASH"       ,
68  [ CL_BUFFER     ] = "BUFFER"     ,
69  [ CL_NETLINK    ] = "NETLINK"    ,
70  [ CL_PRIVCACHE  ] = "PRIVCACHE"  ,
71 };
72
73 const char *closure_type_name(uint32_t ty, char buf[]) {
74     if (ty < ARRAY_SIZE(closure_type_names))
75         return closure_type_names[ty];
76     sprintf(buf, "CL#%.6u", (unsigned)ty);
77     buf[9] = 0;
78     return buf;
79 }
80
81 static pid_t secnet_pid;
82
83 /* Structures dealing with poll() call */
84 struct poll_interest {
85     beforepoll_fn *before; /* 0 if deregistered and waiting to be deleted */
86     afterpoll_fn *after;
87     void *state;
88     int32_t nfds;
89     cstring_t desc;
90     LIST_ENTRY(poll_interest) entry;
91 };
92 static LIST_HEAD(, poll_interest) reg = LIST_HEAD_INITIALIZER(&reg);
93
94 static bool_t interest_isregistered(const struct poll_interest *i)
95 {
96     return !!i->before;
97 }
98
99 static bool_t finished=False;
100
101 /* Parse the command line options */
102 static void parse_options(int argc, char **argv)
103 {
104     int c;
105
106     while (True) {
107         int option_index = 0;
108         static struct option long_options[] = {
109             {"verbose", 0, 0, 'v'},
110             {"nowarnings", 0, 0, 'w'},
111             {"help", 0, 0, 2},
112             {"version", 0, 0, 1},
113             {"nodetach", 0, 0, 'n'},
114             {"managed", 0, 0, 'm'},
115             {"silent", 0, 0, 'f'},
116             {"quiet", 0, 0, 'f'},
117             {"debug", 0, 0, 'd'},
118             {"config", 1, 0, 'c'},
119             {"just-check-config", 0, 0, 'j'},
120             {"sites-key", 1, 0, 's'},
121             {0,0,0,0}
122         };
123
124         c=getopt_long(argc, argv, "vwdnjc:ft:s:m",
125                       long_options, &option_index);
126         if (c==-1)
127             break;
128
129         switch(c) {
130         case 2:
131             /* Help */
132             printf("Usage: secnet [OPTION]...\n\n"
133                    "  -f, --silent, --quiet   suppress error messages\n"
134                    "  -w, --nowarnings        suppress warnings\n"
135                    "  -v, --verbose           output extra diagnostics\n"
136                    "  -c, --config=filename   specify a configuration file\n"
137                    "  -j, --just-check-config stop after reading "
138                    "configuration file\n"
139                    "  -s, --sites-key=name    configuration key that "
140                    "specifies active sites\n"
141                    "  -n, --nodetach          do not run in background\n"
142                    "  -m, --managed           running under a supervisor\n"
143                    "  -d, --debug             output debug messages\n"
144                    "      --help              display this help and exit\n"
145                    "      --version           output version information "
146                    "and exit\n"
147                 );
148             exit(0);
149             break;
150       
151         case 1:
152             /* Version */
153             printf("%s\n",version);
154             exit(0);
155             break;
156
157         case 'd':
158             message_level|=M_DEBUG_CONFIG|M_DEBUG_PHASE|M_DEBUG;
159             /* fall through */
160         case 'v':
161             message_level|=M_INFO|M_NOTICE|M_WARNING|M_ERR|M_SECURITY|
162                 M_FATAL;
163             break;
164
165         case 'w':
166             message_level&=(~M_WARNING);
167             break;
168
169         case 'f':
170             message_level=M_FATAL;
171             break;
172
173         case 'n':
174             background=False;
175             break;
176
177         case 'm':
178             secnet_is_daemon=True;
179             break;
180
181         case 'c':
182             if (optarg)
183                 configfile=safe_strdup(optarg,"config_filename");
184             else
185                 fatal("secnet: no config filename specified");
186             break;
187
188         case 'j':
189             just_check_config=True;
190             break;
191
192         case 's':
193             if (optarg)
194                 sites_key=safe_strdup(optarg,"sites-key");
195             else
196                 fatal("secnet: no sites key specified");
197             break;
198
199         case '?':
200             exit(1);
201             break;
202
203         default:
204             Message(M_ERR,"secnet: Unknown getopt code %c\n",c);
205         }
206     }
207
208     if (argc-optind != 0) {
209         Message(M_ERR,"secnet: You gave extra command line parameters, "
210                 "which were ignored.\n");
211     }
212 }
213
214 static void setup(dict_t *config)
215 {
216     list_t *l;
217     dict_t *system;
218     struct passwd *pw;
219     struct cloc loc;
220
221     l=dict_lookup(config,"system");
222
223     if (!l || list_elem(l,0)->type!=t_dict) {
224         fatal("configuration does not include a \"system\" dictionary");
225     }
226     system=list_elem(l,0)->data.dict;
227     loc=list_elem(l,0)->loc;
228
229     /* Arrange systemwide log facility */
230     l=dict_lookup(system,"log");
231     if (!l) {
232         fatal("configuration does not include a system/log facility");
233     }
234     system_log=init_log(l);
235
236     /* Who are we supposed to run as? */
237     userid=dict_read_string(system,"userid",False,"system",loc);
238     if (userid) {
239         if (!(pw=getpwnam(userid)))
240             fatal("userid \"%s\" not found",userid);
241         uid=pw->pw_uid;
242         gid=pw->pw_gid;
243     }
244
245     /* Pidfile name */
246     pidfile=dict_read_string(system,"pidfile",False,"system",loc);
247
248     /* Check whether we need root privileges */
249     if (require_root_privileges && uid!=0) {
250         fatal("the configured feature \"%s\" requires "
251               "that secnet retain root privileges while running.",
252               require_root_privileges_explanation);
253     }
254 }
255
256 static void start_sites(dict_t *config) {
257     int i;
258     list_t *l;
259     item_t *site;
260
261     /* Go along site list, starting sites */
262     l=dict_lookup(config,sites_key);
263     if (!l) {
264         Message(M_WARNING,"secnet: configuration key \"%s\" is missing; no "
265                 "remote sites are defined\n",sites_key);
266     } else {
267         i=0;
268         while ((site=list_elem(l, i++))) {
269             struct site_if *s;
270             if (site->type!=t_closure) {
271                 cfgfatal(site->loc,"system","non-closure in site list");
272             }
273             if (site->data.closure->type!=CL_SITE) {
274                 cfgfatal(site->loc,"system","non-site closure in site list");
275             }
276             s=site->data.closure->interface;
277             s->startup(s->st);
278         }
279     }
280 }
281
282 struct poll_interest *register_for_poll(void *st, beforepoll_fn *before,
283                        afterpoll_fn *after, cstring_t desc)
284 {
285     struct poll_interest *i;
286
287     NEW(i);
288     i->before=before;
289     i->after=after;
290     i->state=st;
291     i->nfds=0;
292     i->desc=desc;
293     LIST_INSERT_HEAD(&reg, i, entry);
294     return i;
295 }
296
297 void deregister_for_poll(struct poll_interest *i)
298 {
299     /* We cannot simply throw this away because we're reentrantly
300      * inside the main loop, which needs to remember which range of
301      * fds corresponds to this now-obsolete interest */
302     i->before=0;
303 }
304
305 static void system_phase_hook(void *sst, uint32_t newphase)
306 {
307     if (newphase==PHASE_SHUTDOWN && pidfile) {
308         /* Try to unlink the pidfile; don't care if it fails */
309         unlink(pidfile);
310     }
311 }
312
313 #if USE_SELECT
314 static int fakepoll(struct pollfd *fds, int nfds, int timeout) {
315     fd_set infds[1], outfds[1];
316     int maxfd = -1, i, rc;
317     struct timeval tvtimeout;
318     FD_ZERO(infds);
319     FD_ZERO(outfds);
320     for(i = 0; i < nfds; ++i) {
321         if(fds[i].events & POLLIN)
322             FD_SET(fds[i].fd, infds);
323         if(fds[i].events & POLLOUT)
324             FD_SET(fds[i].fd, outfds);
325         if(fds[i].fd > maxfd)
326             maxfd = fds[i].fd;
327     }
328     if(timeout != -1) {
329         tvtimeout.tv_sec = timeout / 1000;
330         tvtimeout.tv_usec = 1000 * (timeout % 1000);
331     }
332     rc = select(maxfd + 1, infds, outfds, NULL, 
333                 timeout == -1 ? NULL : &tvtimeout);
334     if(rc >= 0) {
335         for(i = 0; i < nfds; ++i) {
336             int revents = 0;
337             if(FD_ISSET(fds[i].fd, infds))
338                 revents |= POLLIN;
339             if(FD_ISSET(fds[i].fd, outfds))
340                 revents |= POLLOUT;
341             fds[i].revents = revents;
342         }
343     }
344     return rc;
345 }
346 #endif
347
348 struct timeval tv_now_global;
349 uint64_t now_global;
350
351 static void run(void)
352 {
353     struct poll_interest *i, *itmp;
354     int rv, nfds, idx;
355     int timeout;
356     struct pollfd *fds=0;
357     int allocdfds=0, shortfall=0;
358
359     do {
360 #if USE_MONOTONIC
361         struct timespec ts;
362         if (clock_gettime(CLOCK_MONOTONIC, &ts)!=0) {
363             fatal_perror("main loop: clock_gettime(CLOCK_MONOTONIC,)");
364         }
365         tv_now_global.tv_sec =  ts.tv_sec;
366         tv_now_global.tv_usec = ts.tv_nsec / 1000;
367 #else /* !USE_MONOTONIC */
368         if (gettimeofday(&tv_now_global, NULL)!=0) {
369             fatal_perror("main loop: gettimeofday");
370         }
371 #endif /* !USE_MONOTONIC */
372         now_global=((uint64_t)tv_now_global.tv_sec*(uint64_t)1000)+
373                    ((uint64_t)tv_now_global.tv_usec/(uint64_t)1000);
374         idx=0;
375         LIST_FOREACH(i, &reg, entry) {
376             int check;
377             if (interest_isregistered(i)) {
378                 for (check=0; check<i->nfds; check++) {
379                     if(fds[idx+check].revents & POLLNVAL) {
380                         fatal("run: poll (%s#%d) set POLLNVAL", i->desc, check);
381                     }
382                 }
383                 i->after(i->state, fds+idx, i->nfds);
384             }
385             idx+=i->nfds;
386         }
387         if (shortfall) {
388             allocdfds *= 2;
389             allocdfds += shortfall;
390             REALLOC_ARY(fds,allocdfds);
391         }
392         shortfall=0;
393         idx=0;
394         timeout=-1;
395         LIST_FOREACH_SAFE(i, &reg, entry, itmp) {
396             int remain=allocdfds-idx;
397             nfds=remain;
398             if (interest_isregistered(i)) {
399                 rv=i->before(i->state, fds+idx, &nfds, &timeout);
400                 if (rv!=0) {
401                     if (rv!=ERANGE)
402                         fatal("run: beforepoll_fn (%s) returns %d",i->desc,rv);
403                     assert(nfds < INT_MAX/4 - shortfall);
404                     shortfall += nfds-remain;
405                     nfds=0;
406                     timeout=0;
407                 }
408             } else {
409                 nfds=0;
410             }
411             if (timeout<-1) {
412                 fatal("run: beforepoll_fn (%s) set timeout to %d",
413                       i->desc,timeout);
414             }
415             if (!interest_isregistered(i)) {
416                 /* check this here, rather than earlier, so that we
417                    handle the case where i->before() calls deregister */
418                 LIST_REMOVE(i, entry);
419                 free(i);
420                 continue;
421             }
422             idx+=nfds;
423             i->nfds=nfds;
424         }
425         do {
426             if (finished) break;
427 #if USE_SELECT
428             rv=fakepoll(fds, idx, timeout);
429 #else
430             rv=poll(fds, idx, timeout);
431 #endif
432             if (rv<0) {
433                 if (errno!=EINTR) {
434                     fatal_perror("run: poll");
435                 }
436             }
437         } while (rv<0);
438     } while (!finished);
439     free(fds);
440 }
441
442 bool_t will_droppriv(void)
443 {
444     assert(current_phase >= PHASE_SETUP);
445     return !!uid;
446 }
447
448 /* Surrender privileges, if necessary */
449 static void droppriv(void)
450 {
451     if (userid) {
452         if (setgid(gid)!=0)
453             fatal_perror("can't set gid to %ld",(long)gid);
454         if (initgroups(userid, gid) < 0)
455             fatal_perror("initgroups"); 
456         if (setuid(uid)!=0) {
457             fatal_perror("can't set uid to \"%s\"",userid);
458         }
459         assert(getuid() == uid);
460         assert(geteuid() == uid);
461         assert(getgid() == gid);
462         assert(getegid() == gid);
463     }
464 }
465
466 /* Become a daemon, if necessary */
467 static void become_daemon(void)
468 {
469     FILE *pf=NULL;
470     pid_t p;
471     int errfds[2];
472
473     add_hook(PHASE_SHUTDOWN,system_phase_hook,NULL);
474
475     /* We only want to become a daemon if we are not one
476      already */
477     if (background && !secnet_is_daemon) {
478         p=fork();
479         if (p>0) {
480             /* Parent process - just exit */
481             _exit(0);
482         } else if (p==0) {
483             /* Child process - all done, just carry on */
484             secnet_is_daemon=True;
485             if (setsid() < 0)
486                 fatal_perror("setsid");
487         } else {
488             /* Error */
489             fatal_perror("cannot fork");
490             exit(1);
491         }
492     }
493     if (secnet_is_daemon) {
494         /* stderr etc are redirected to the system/log facility */
495         pipe_cloexec(errfds);
496         if (dup2(errfds[1],0) < 0
497             || dup2(errfds[1],1) < 0
498             || dup2(errfds[1],2) < 0)
499             fatal_perror("can't dup2 pipe");
500         if (close(errfds[1]) < 0)
501             fatal_perror("can't close redundant pipe endpoint");
502         log_from_fd(errfds[0],"stderr",system_log);
503     }
504     secnet_pid=getpid();
505     
506     /* Now we can write the pidfile */
507     if (pidfile) {
508         pf=fopen(pidfile,"w");
509         if (!pf) {
510             fatal_perror("cannot open pidfile \"%s\"",pidfile);
511         }
512         if (fprintf(pf,"%ld\n",(long)secnet_pid) < 0
513             || fclose(pf) < 0)
514             fatal_perror("cannot write to pidfile \"%s\"",pidfile);
515     }
516 }
517
518 static signal_notify_fn finish,ignore_hup;
519 static void finish(void *st, int signum)
520 {
521     finished=True;
522     Message(M_NOTICE,"%s [%d]: received %s\n",version,secnet_pid,(string_t)st);
523 }
524 static void ignore_hup(void *st, int signum)
525 {
526     Message(M_INFO,"%s [%d]: received SIGHUP\n",version,secnet_pid);
527     return;
528 }
529
530 int main(int argc, char **argv)
531 {
532     dict_t *config;
533
534     log_early_init();
535     phase_hooks_init();
536
537     enter_phase(PHASE_GETOPTS);
538     parse_options(argc,argv);
539     log_early_setlevel();
540
541     enter_phase(PHASE_READCONFIG);
542     config=read_conffile(configfile);
543
544     enter_phase(PHASE_SETUP);
545     setup(config);
546     start_sites(config);
547
548     if (just_check_config) {
549         Message(M_INFO,"configuration file check complete\n");
550         exit(0);
551     }
552
553     enter_phase(PHASE_DAEMONIZE);
554     become_daemon();
555     Message(M_NOTICE,"%s [%d]: starting\n",version,secnet_pid);
556     
557     enter_phase(PHASE_GETRESOURCES);
558     /* Appropriate phase hooks will have been run */
559     
560     enter_phase(PHASE_DROPPRIV);
561     droppriv();
562
563     start_signal_handling();
564     request_signal_notification(SIGTERM,finish,safe_strdup("SIGTERM","run"));
565     if (!background) request_signal_notification(SIGINT,finish,
566                                                  safe_strdup("SIGINT","run"));
567     request_signal_notification(SIGHUP,ignore_hup,NULL);
568     enter_phase(PHASE_RUN);
569     run();
570
571     enter_phase(PHASE_SHUTDOWN);
572     Message(M_NOTICE,"%s [%d]: finished\n",version,secnet_pid);
573
574     return 0;
575 }