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