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