chiark / gitweb /
md5: correct size arg to memset().
[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
13 #include "util.h"
14 #include "conffile.h"
15 #include "process.h"
16
17 #if __APPLE__
18 /* apple's poll() does not work on char devs */
19 # define USE_SELECT 1
20 #endif
21
22 /* XXX should be from autoconf */
23 static const char *configfile="/etc/secnet/secnet.conf";
24 static const char *sites_key="sites";
25 bool_t just_check_config=False;
26 static char *userid=NULL;
27 static uid_t uid=0;
28 bool_t background=True;
29 static char *pidfile=NULL;
30 bool_t require_root_privileges=False;
31 cstring_t require_root_privileges_explanation=NULL;
32
33 static pid_t secnet_pid;
34
35 /* Structures dealing with poll() call */
36 struct poll_interest {
37     beforepoll_fn *before;
38     afterpoll_fn *after;
39     void *state;
40     int32_t max_nfds;
41     int32_t nfds;
42     cstring_t desc;
43     struct poll_interest *next;
44 };
45 static struct poll_interest *reg=NULL;
46 static int32_t total_nfds=10;
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             {"silent", 0, 0, 'f'},
64             {"quiet", 0, 0, 'f'},
65             {"debug", 0, 0, 'd'},
66             {"config", 1, 0, 'c'},
67             {"just-check-config", 0, 0, 'j'},
68             {"sites-key", 1, 0, 's'},
69             {0,0,0,0}
70         };
71
72         c=getopt_long(argc, argv, "vwdnjc:ft:s:",
73                       long_options, &option_index);
74         if (c==-1)
75             break;
76
77         switch(c) {
78         case 2:
79             /* Help */
80             printf("Usage: secnet [OPTION]...\n\n"
81                    "  -f, --silent, --quiet   suppress error messages\n"
82                    "  -w, --nowarnings        suppress warnings\n"
83                    "  -v, --verbose           output extra diagnostics\n"
84                    "  -c, --config=filename   specify a configuration file\n"
85                    "  -j, --just-check-config stop after reading "
86                    "configuration file\n"
87                    "  -s, --sites-key=name    configuration key that "
88                    "specifies active sites\n"
89                    "  -n, --nodetach          do not run in background\n"
90                    "  -d, --debug             output debug messages\n"
91                    "      --help              display this help and exit\n"
92                    "      --version           output version information "
93                    "and exit\n"
94                 );
95             exit(0);
96             break;
97       
98         case 1:
99             /* Version */
100             printf("%s\n",version);
101             exit(0);
102             break;
103
104         case 'v':
105             message_level|=M_INFO|M_NOTICE|M_WARNING|M_ERR|M_SECURITY|
106                 M_FATAL;
107             break;
108
109         case 'w':
110             message_level&=(~M_WARNING);
111             break;
112
113         case 'd':
114             message_level|=M_DEBUG_CONFIG|M_DEBUG_PHASE|M_DEBUG;
115             break;
116
117         case 'f':
118             message_level=M_FATAL;
119             break;
120
121         case 'n':
122             background=False;
123             break;
124
125         case 'c':
126             if (optarg)
127                 configfile=safe_strdup(optarg,"config_filename");
128             else
129                 fatal("secnet: no config filename specified");
130             break;
131
132         case 'j':
133             just_check_config=True;
134             break;
135
136         case 's':
137             if (optarg)
138                 sites_key=safe_strdup(optarg,"sites-key");
139             else
140                 fatal("secnet: no sites key specified");
141             break;
142
143         case '?':
144             exit(1);
145             break;
146
147         default:
148             Message(M_ERR,"secnet: Unknown getopt code %c\n",c);
149         }
150     }
151
152     if (argc-optind != 0) {
153         Message(M_ERR,"secnet: You gave extra command line parameters, "
154                 "which were ignored.\n");
155     }
156 }
157
158 static void setup(dict_t *config)
159 {
160     list_t *l;
161     item_t *site;
162     dict_t *system;
163     struct passwd *pw;
164     struct cloc loc;
165     int i;
166
167     l=dict_lookup(config,"system");
168
169     if (!l || list_elem(l,0)->type!=t_dict) {
170         fatal("configuration does not include a \"system\" dictionary");
171     }
172     system=list_elem(l,0)->data.dict;
173     loc=list_elem(l,0)->loc;
174
175     /* Arrange systemwide log facility */
176     l=dict_lookup(system,"log");
177     if (!l) {
178         fatal("configuration does not include a system/log facility");
179     }
180     system_log=init_log(l);
181
182     /* Who are we supposed to run as? */
183     userid=dict_read_string(system,"userid",False,"system",loc);
184     if (userid) {
185         do {
186             pw=getpwent();
187             if (pw && strcmp(pw->pw_name,userid)==0) {
188                 uid=pw->pw_uid;
189                 break;
190             }
191         } while(pw);
192         endpwent();
193         if (uid==0) {
194             fatal("userid \"%s\" not found",userid);
195         }
196     }
197
198     /* Pidfile name */
199     pidfile=dict_read_string(system,"pidfile",False,"system",loc);
200
201     /* Check whether we need root privileges */
202     if (require_root_privileges && uid!=0) {
203         fatal("the configured feature \"%s\" requires "
204               "that secnet retain root privileges while running.",
205               require_root_privileges_explanation);
206     }
207
208     /* Go along site list, starting sites */
209     l=dict_lookup(config,sites_key);
210     if (!l) {
211         Message(M_WARNING,"secnet: configuration key \"%s\" is missing; no "
212                 "remote sites are defined\n",sites_key);
213     } else {
214         i=0;
215         while ((site=list_elem(l, i++))) {
216             struct site_if *s;
217             if (site->type!=t_closure) {
218                 cfgfatal(site->loc,"system","non-closure in site list");
219             }
220             if (site->data.closure->type!=CL_SITE) {
221                 cfgfatal(site->loc,"system","non-site closure in site list");
222             }
223             s=site->data.closure->interface;
224             s->control(s->st,True);
225         }
226     }
227 }
228
229 void register_for_poll(void *st, beforepoll_fn *before,
230                        afterpoll_fn *after, int32_t max_nfds, cstring_t desc)
231 {
232     struct poll_interest *i;
233
234     i=safe_malloc(sizeof(*i),"register_for_poll");
235     i->before=before;
236     i->after=after;
237     i->state=st;
238     i->max_nfds=max_nfds;
239     i->nfds=0;
240     i->desc=desc;
241     assert(total_nfds < INT_MAX - max_nfds);
242     total_nfds+=max_nfds;
243     i->next=reg;
244     reg=i;
245     return;
246 }
247
248 static void system_phase_hook(void *sst, uint32_t newphase)
249 {
250     if (newphase==PHASE_SHUTDOWN && pidfile) {
251         /* Try to unlink the pidfile; don't care if it fails */
252         unlink(pidfile);
253     }
254 }
255
256 #if USE_SELECT
257 static int fakepoll(struct pollfd *fds, int nfds, int timeout) {
258     fd_set infds[1], outfds[1];
259     int maxfd = -1, i, rc;
260     struct timeval tvtimeout;
261     FD_ZERO(infds);
262     FD_ZERO(outfds);
263     for(i = 0; i < nfds; ++i) {
264         if(fds[i].events & POLLIN)
265             FD_SET(fds[i].fd, infds);
266         if(fds[i].events & POLLOUT)
267             FD_SET(fds[i].fd, outfds);
268         if(fds[i].fd > maxfd)
269             maxfd = fds[i].fd;
270     }
271     if(timeout != -1) {
272         tvtimeout.tv_sec = timeout / 1000;
273         tvtimeout.tv_usec = 1000 * (timeout % 1000);
274     }
275     rc = select(maxfd + 1, infds, outfds, NULL, 
276                 timeout == -1 ? NULL : &tvtimeout);
277     if(rc >= 0) {
278         for(i = 0; i < nfds; ++i) {
279             int revents = 0;
280             if(FD_ISSET(fds[i].fd, infds))
281                 revents |= POLLIN;
282             if(FD_ISSET(fds[i].fd, outfds))
283                 revents |= POLLOUT;
284             fds[i].revents = revents;
285         }
286     }
287     return rc;
288 }
289 #endif
290
291 struct timeval tv_now_global;
292 uint64_t now_global;
293
294 static void run(void)
295 {
296     struct poll_interest *i;
297     int rv, nfds, remain, idx;
298     int timeout;
299     struct pollfd *fds;
300
301     fds=safe_malloc(sizeof(*fds)*total_nfds, "run");
302
303     Message(M_NOTICE,"%s [%d]: starting\n",version,secnet_pid);
304
305     do {
306         if (gettimeofday(&tv_now_global, NULL)!=0) {
307             fatal_perror("main loop: gettimeofday");
308         }
309         now_global=((uint64_t)tv_now_global.tv_sec*(uint64_t)1000)+
310                    ((uint64_t)tv_now_global.tv_usec/(uint64_t)1000);
311         idx=0;
312         for (i=reg; i; i=i->next) {
313             int check;
314             for (check=0; check<i->nfds; check++) {
315                 if(fds[idx+check].revents & POLLNVAL) {
316                     fatal("run: poll (%s#%d) set POLLNVAL", i->desc, check);
317                 }
318             }
319             i->after(i->state, fds+idx, i->nfds);
320             idx+=i->nfds;
321         }
322         remain=total_nfds;
323         idx=0;
324         timeout=-1;
325         for (i=reg; i; i=i->next) {
326             nfds=remain;
327             rv=i->before(i->state, fds+idx, &nfds, &timeout);
328             if (rv!=0) {
329                 /* XXX we need to handle this properly: increase the
330                    nfds available */
331                 fatal("run: beforepoll_fn (%s) returns %d",i->desc,rv);
332             }
333             if (timeout<-1) {
334                 fatal("run: beforepoll_fn (%s) set timeout to %d",timeout);
335             }
336             idx+=nfds;
337             remain-=nfds;
338             i->nfds=nfds;
339         }
340         do {
341             if (finished) break;
342 #if USE_SELECT
343             rv=fakepoll(fds, idx, timeout);
344 #else
345             rv=poll(fds, idx, timeout);
346 #endif
347             if (rv<0) {
348                 if (errno!=EINTR) {
349                     fatal_perror("run: poll");
350                 }
351             }
352         } while (rv<0);
353     } while (!finished);
354     free(fds);
355 }
356
357 static void droppriv(void)
358 {
359     FILE *pf=NULL;
360     pid_t p;
361     int errfds[2];
362
363     add_hook(PHASE_SHUTDOWN,system_phase_hook,NULL);
364
365     /* Open the pidfile for writing now: we may be unable to do so
366        once we drop privileges. */
367     if (pidfile) {
368         pf=fopen(pidfile,"w");
369         if (!pf) {
370             fatal_perror("cannot open pidfile \"%s\"",pidfile);
371         }
372     }
373     if (!background && pf) {
374         fprintf(pf,"%d\n",getpid());
375         fclose(pf);
376     }
377
378     /* Now drop privileges */
379     if (uid!=0) {
380         if (setuid(uid)!=0) {
381             fatal_perror("can't set uid to \"%s\"",userid);
382         }
383     }
384     if (background) {
385         p=fork();
386         if (p>0) {
387             if (pf) {
388                 /* Parent process - write pidfile, exit */
389                 fprintf(pf,"%d\n",p);
390                 fclose(pf);
391             }
392             exit(0);
393         } else if (p==0) {
394             /* Child process - all done, just carry on */
395             if (pf) fclose(pf);
396             /* Close stdin and stdout; we don't need them any more.
397                stderr is redirected to the system/log facility */
398             if (pipe(errfds)!=0) {
399                 fatal_perror("can't create pipe for stderr");
400             }
401             close(0);
402             close(1);
403             close(2);
404             dup2(errfds[1],0);
405             dup2(errfds[1],1);
406             dup2(errfds[1],2);
407             secnet_is_daemon=True;
408             setsid();
409             log_from_fd(errfds[0],"stderr",system_log);
410         } else {
411             /* Error */
412             fatal_perror("cannot fork");
413             exit(1);
414         }
415     }
416     secnet_pid=getpid();
417 }
418
419 static signal_notify_fn finish,ignore_hup;
420 static void finish(void *st, int signum)
421 {
422     finished=True;
423     Message(M_NOTICE,"%s [%d]: received %s\n",version,secnet_pid,(string_t)st);
424 }
425 static void ignore_hup(void *st, int signum)
426 {
427     Message(M_INFO,"%s [%d]: received SIGHUP\n",version,secnet_pid);
428     return;
429 }
430
431 int main(int argc, char **argv)
432 {
433     dict_t *config;
434
435     enter_phase(PHASE_GETOPTS);
436     parse_options(argc,argv);
437
438     enter_phase(PHASE_READCONFIG);
439     config=read_conffile(configfile);
440
441     enter_phase(PHASE_SETUP);
442     setup(config);
443
444     if (just_check_config) {
445         Message(M_INFO,"configuration file check complete\n");
446         exit(0);
447     }
448
449     enter_phase(PHASE_GETRESOURCES);
450     /* Appropriate phase hooks will have been run */
451     
452     enter_phase(PHASE_DROPPRIV);
453     droppriv();
454
455     start_signal_handling();
456     request_signal_notification(SIGTERM,finish,safe_strdup("SIGTERM","run"));
457     if (!background) request_signal_notification(SIGINT,finish,
458                                                  safe_strdup("SIGINT","run"));
459     request_signal_notification(SIGHUP,ignore_hup,NULL);
460     enter_phase(PHASE_RUN);
461     run();
462
463     enter_phase(PHASE_SHUTDOWN);
464     Message(M_NOTICE,"%s [%d]: finished\n",version,secnet_pid);
465
466     return 0;
467 }