chiark / gitweb /
4520b3e5ed91644939a7f9824a8c9a377e564a9a
[secnet.git] / 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;
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 finished=False;
49
50 /* Parse the command line options */
51 static 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'},
63             {"managed", 0, 0, 'm'},
64             {"silent", 0, 0, 'f'},
65             {"quiet", 0, 0, 'f'},
66             {"debug", 0, 0, 'd'},
67             {"config", 1, 0, 'c'},
68             {"just-check-config", 0, 0, 'j'},
69             {"sites-key", 1, 0, 's'},
70             {0,0,0,0}
71         };
72
73         c=getopt_long(argc, argv, "vwdnjc:ft:s:m",
74                       long_options, &option_index);
75         if (c==-1)
76             break;
77
78         switch(c) {
79         case 2:
80             /* Help */
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"
91                    "  -m, --managed           running under a supervisor\n"
92                    "  -d, --debug             output debug messages\n"
93                    "      --help              display this help and exit\n"
94                    "      --version           output version information "
95                    "and exit\n"
96                 );
97             exit(0);
98             break;
99       
100         case 1:
101             /* Version */
102             printf("%s\n",version);
103             exit(0);
104             break;
105
106         case 'v':
107             message_level|=M_INFO|M_NOTICE|M_WARNING|M_ERR|M_SECURITY|
108                 M_FATAL;
109             break;
110
111         case 'w':
112             message_level&=(~M_WARNING);
113             break;
114
115         case 'd':
116             message_level|=M_DEBUG_CONFIG|M_DEBUG_PHASE|M_DEBUG;
117             break;
118
119         case 'f':
120             message_level=M_FATAL;
121             break;
122
123         case 'n':
124             background=False;
125             break;
126
127         case 'm':
128             secnet_is_daemon=True;
129             break;
130
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
138         case 'j':
139             just_check_config=True;
140             break;
141
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
149         case '?':
150             exit(1);
151             break;
152
153         default:
154             Message(M_ERR,"secnet: Unknown getopt code %c\n",c);
155         }
156     }
157
158     if (argc-optind != 0) {
159         Message(M_ERR,"secnet: You gave extra command line parameters, "
160                 "which were ignored.\n");
161     }
162 }
163
164 static void setup(dict_t *config)
165 {
166     list_t *l;
167     item_t *site;
168     dict_t *system;
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) {
176         fatal("configuration does not include a \"system\" dictionary");
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) {
184         fatal("configuration does not include a system/log facility");
185     }
186     system_log=init_log(l);
187
188     /* Who are we supposed to run as? */
189     userid=dict_read_string(system,"userid",False,"system",loc);
190     if (userid) {
191         if (!(pw=getpwnam(userid)))
192             fatal("userid \"%s\" not found",userid);
193         uid=pw->pw_uid;
194         gid=pw->pw_gid;
195     }
196
197     /* Pidfile name */
198     pidfile=dict_read_string(system,"pidfile",False,"system",loc);
199
200     /* Check whether we need root privileges */
201     if (require_root_privileges && uid!=0) {
202         fatal("the configured feature \"%s\" requires "
203               "that secnet retain root privileges while running.",
204               require_root_privileges_explanation);
205     }
206
207     /* Go along site list, starting sites */
208     l=dict_lookup(config,sites_key);
209     if (!l) {
210         Message(M_WARNING,"secnet: configuration key \"%s\" is missing; no "
211                 "remote sites are defined\n",sites_key);
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);
224         }
225     }
226 }
227
228 void register_for_poll(void *st, beforepoll_fn *before,
229                        afterpoll_fn *after, cstring_t desc)
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;
237     i->nfds=0;
238     i->desc=desc;
239     LIST_INSERT_HEAD(&reg, i, entry);
240     return;
241 }
242
243 static 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
251 #if USE_SELECT
252 static 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
286 struct timeval tv_now_global;
287 uint64_t now_global;
288
289 static void run(void)
290 {
291     struct poll_interest *i;
292     int rv, nfds, idx;
293     int timeout;
294     struct pollfd *fds=0;
295     int allocdfds=0, shortfall=0;
296
297     Message(M_NOTICE,"%s [%d]: starting\n",version,secnet_pid);
298
299     do {
300         if (gettimeofday(&tv_now_global, NULL)!=0) {
301             fatal_perror("main loop: gettimeofday");
302         }
303         now_global=((uint64_t)tv_now_global.tv_sec*(uint64_t)1000)+
304                    ((uint64_t)tv_now_global.tv_usec/(uint64_t)1000);
305         idx=0;
306         LIST_FOREACH(i, &reg, entry) {
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                 }
312             }
313             i->after(i->state, fds+idx, i->nfds);
314             idx+=i->nfds;
315         }
316         if (shortfall) {
317             allocdfds *= 2;
318             allocdfds += shortfall;
319             fds=safe_realloc_ary(fds,sizeof(*fds),allocdfds, "run");
320         }
321         shortfall=0;
322         idx=0;
323         timeout=-1;
324         LIST_FOREACH(i, &reg, entry) {
325             int remain=allocdfds-idx;
326             nfds=remain;
327             rv=i->before(i->state, fds+idx, &nfds, &timeout);
328             if (rv!=0) {
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;
335             }
336             if (timeout<-1) {
337                 fatal("run: beforepoll_fn (%s) set timeout to %d",
338                       i->desc,timeout);
339             }
340             idx+=nfds;
341             i->nfds=nfds;
342         }
343         do {
344             if (finished) break;
345 #if USE_SELECT
346             rv=fakepoll(fds, idx, timeout);
347 #else
348             rv=poll(fds, idx, timeout);
349 #endif
350             if (rv<0) {
351                 if (errno!=EINTR) {
352                     fatal_perror("run: poll");
353                 }
354             }
355         } while (rv<0);
356     } while (!finished);
357     free(fds);
358 }
359
360 /* Surrender privileges, if necessary */
361 static void droppriv(void)
362 {
363     if (userid) {
364         if (setgid(gid)!=0)
365             fatal_perror("can't set gid to %ld",(long)gid);
366         if (initgroups(userid, gid) < 0)
367             fatal_perror("initgroups"); 
368         if (setuid(uid)!=0) {
369             fatal_perror("can't set uid to \"%s\"",userid);
370         }
371         assert(getuid() == uid);
372         assert(geteuid() == uid);
373         assert(getgid() == gid);
374         assert(getegid() == gid);
375     }
376 }
377
378 /* Become a daemon, if necessary */
379 static 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) {
390         p=fork();
391         if (p>0) {
392             /* Parent process - just exit */
393             _exit(0);
394         } else if (p==0) {
395             /* Child process - all done, just carry on */
396             secnet_is_daemon=True;
397             if (setsid() < 0)
398                 fatal_perror("setsid");
399         } else {
400             /* Error */
401             fatal_perror("cannot fork");
402             exit(1);
403         }
404     }
405     if (secnet_is_daemon) {
406         /* stderr etc are redirected to the system/log facility */
407         pipe_cloexec(errfds);
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     }
416     secnet_pid=getpid();
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     }
428 }
429
430 static signal_notify_fn finish,ignore_hup;
431 static 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 }
436 static void ignore_hup(void *st, int signum)
437 {
438     Message(M_INFO,"%s [%d]: received SIGHUP\n",version,secnet_pid);
439     return;
440 }
441
442 int 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);
454
455     if (just_check_config) {
456         Message(M_INFO,"configuration file check complete\n");
457         exit(0);
458     }
459
460     enter_phase(PHASE_DAEMONIZE);
461     become_daemon();
462     
463     enter_phase(PHASE_GETRESOURCES);
464     /* Appropriate phase hooks will have been run */
465     
466     enter_phase(PHASE_DROPPRIV);
467     droppriv();
468
469     start_signal_handling();
470     request_signal_notification(SIGTERM,finish,safe_strdup("SIGTERM","run"));
471     if (!background) request_signal_notification(SIGINT,finish,
472                                                  safe_strdup("SIGINT","run"));
473     request_signal_notification(SIGHUP,ignore_hup,NULL);
474     enter_phase(PHASE_RUN);
475     run();
476
477     enter_phase(PHASE_SHUTDOWN);
478     Message(M_NOTICE,"%s [%d]: finished\n",version,secnet_pid);
479
480     return 0;
481 }