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