chiark / gitweb /
Import release 0.1.14
[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 char *configfile="/etc/secnet/secnet.conf";
19 static 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 string_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     string_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, string_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=alloca(sizeof(*fds)*total_nfds);
267     if (!fds) {
268         fatal("run: couldn't alloca");
269     }
270
271     Message(M_NOTICE,"%s [%d]: starting\n",version,secnet_pid);
272
273     do {
274         if (gettimeofday(&tv_now, NULL)!=0) {
275             fatal_perror("main loop: gettimeofday");
276         }
277         now=((uint64_t)tv_now.tv_sec*(uint64_t)1000)+
278             ((uint64_t)tv_now.tv_usec/(uint64_t)1000);
279         idx=0;
280         for (i=reg; i; i=i->next) {
281             i->after(i->state, fds+idx, i->nfds, &tv_now, &now);
282             idx+=i->nfds;
283         }
284         remain=total_nfds;
285         idx=0;
286         timeout=-1;
287         for (i=reg; i; i=i->next) {
288             nfds=remain;
289             rv=i->before(i->state, fds+idx, &nfds, &timeout, &tv_now, &now);
290             if (rv!=0) {
291                 /* XXX we need to handle this properly: increase the
292                    nfds available */
293                 fatal("run: beforepoll_fn (%s) returns %d",i->desc,rv);
294             }
295             if (timeout<-1) {
296                 fatal("run: beforepoll_fn (%s) set timeout to %d",timeout);
297             }
298             idx+=nfds;
299             remain-=nfds;
300             i->nfds=nfds;
301         }
302         do {
303             if (finished) break;
304             rv=poll(fds, idx, timeout);
305             if (rv<0) {
306                 if (errno!=EINTR) {
307                     fatal_perror("run: poll");
308                 }
309             }
310         } while (rv<0);
311     } while (!finished);
312 }
313
314 static void droppriv(void)
315 {
316     FILE *pf=NULL;
317     pid_t p;
318
319     add_hook(PHASE_SHUTDOWN,system_phase_hook,NULL);
320
321     /* Open the pidfile for writing now: we may be unable to do so
322        once we drop privileges. */
323     if (pidfile) {
324         pf=fopen(pidfile,"w");
325         if (!pf) {
326             fatal_perror("cannot open pidfile \"%s\"",pidfile);
327         }
328     }
329     if (!background && pf) {
330         fprintf(pf,"%d\n",getpid());
331         fclose(pf);
332     }
333
334     /* Now drop privileges */
335     if (uid!=0) {
336         if (setuid(uid)!=0) {
337             fatal_perror("can't set uid to \"%s\"",userid);
338         }
339     }
340     if (background) {
341         p=fork();
342         if (p>0) {
343             if (pf) {
344                 /* Parent process - write pidfile, exit */
345                 fprintf(pf,"%d\n",p);
346                 fclose(pf);
347             }
348             exit(0);
349         } else if (p==0) {
350             /* Child process - all done, just carry on */
351             if (pf) fclose(pf);
352             /* Close stdin, stdout and stderr; we don't need them any more */
353             /* XXX we must leave stderr pointing to something useful -
354                a pipe to a log destination, for example, or just leave
355                it alone. */
356             close(0);
357             close(1);
358             /* XXX close(2); */
359             secnet_is_daemon=True;
360             setsid();
361         } else {
362             /* Error */
363             fatal_perror("cannot fork");
364             exit(1);
365         }
366     }
367     secnet_pid=getpid();
368 }
369
370 static signal_notify_fn finish,ignore_hup;
371 static void finish(void *st, int signum)
372 {
373     finished=True;
374     Message(M_NOTICE,"%s [%d]: received %s\n",version,secnet_pid,(string_t)st);
375 }
376 static void ignore_hup(void *st, int signum)
377 {
378     Message(M_INFO,"%s [%d]: received SIGHUP\n",version,secnet_pid);
379     return;
380 }
381
382 int main(int argc, char **argv)
383 {
384     dict_t *config;
385
386     enter_phase(PHASE_GETOPTS);
387     parse_options(argc,argv);
388
389     enter_phase(PHASE_READCONFIG);
390     config=read_conffile(configfile);
391
392     enter_phase(PHASE_SETUP);
393     setup(config);
394
395     if (just_check_config) {
396         Message(M_INFO,"configuration file check complete\n");
397         exit(0);
398     }
399
400     enter_phase(PHASE_GETRESOURCES);
401     /* Appropriate phase hooks will have been run */
402     
403     enter_phase(PHASE_DROPPRIV);
404     droppriv();
405
406     start_signal_handling();
407     request_signal_notification(SIGTERM,finish,"SIGTERM");
408     if (!background) request_signal_notification(SIGINT,finish,"SIGINT");
409     request_signal_notification(SIGHUP,ignore_hup,NULL);
410     enter_phase(PHASE_RUN);
411     run();
412
413     enter_phase(PHASE_SHUTDOWN);
414     Message(M_NOTICE,"%s [%d]: finished\n",version,secnet_pid);
415
416     return 0;
417 }