chiark / gitweb /
Make -d option consistent.
[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             break;
145
146         default:
147             Message(M_ERR,"secnet: Unknown getopt code %c\n",c);
148         }
149     }
150
151     if (argc-optind != 0) {
152         Message(M_ERR,"secnet: You gave extra command line parameters, "
153                 "which were ignored.\n");
154     }
155 }
156
157 static void setup(dict_t *config)
158 {
159     list_t *l;
160     item_t *site;
161     dict_t *system;
162     struct passwd *pw;
163     struct cloc loc;
164     int i;
165
166     l=dict_lookup(config,"system");
167
168     if (!l || list_elem(l,0)->type!=t_dict) {
169         fatal("configuration does not include a \"system\" dictionary");
170     }
171     system=list_elem(l,0)->data.dict;
172     loc=list_elem(l,0)->loc;
173
174     /* Arrange systemwide log facility */
175     l=dict_lookup(system,"log");
176     if (!l) {
177         fatal("configuration does not include a system/log facility");
178     }
179     system_log=init_log(l);
180
181     /* Who are we supposed to run as? */
182     userid=dict_read_string(system,"userid",False,"system",loc);
183     if (userid) {
184         do {
185             pw=getpwent();
186             if (pw && strcmp(pw->pw_name,userid)==0) {
187                 uid=pw->pw_uid;
188                 break;
189             }
190         } while(pw);
191         endpwent();
192         if (uid==0) {
193             fatal("userid \"%s\" not found",userid);
194         }
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, int32_t max_nfds, 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->max_nfds=max_nfds;
238     i->nfds=0;
239     i->desc=desc;
240     assert(total_nfds < INT_MAX - max_nfds);
241     total_nfds+=max_nfds;
242     i->next=reg;
243     reg=i;
244     return;
245 }
246
247 static void system_phase_hook(void *sst, uint32_t newphase)
248 {
249     if (newphase==PHASE_SHUTDOWN && pidfile) {
250         /* Try to unlink the pidfile; don't care if it fails */
251         unlink(pidfile);
252     }
253 }
254
255 #if USE_SELECT
256 static int fakepoll(struct pollfd *fds, int nfds, int timeout) {
257     fd_set infds[1], outfds[1];
258     int maxfd = -1, i, rc;
259     struct timeval tvtimeout;
260     FD_ZERO(infds);
261     FD_ZERO(outfds);
262     for(i = 0; i < nfds; ++i) {
263         if(fds[i].events & POLLIN)
264             FD_SET(fds[i].fd, infds);
265         if(fds[i].events & POLLOUT)
266             FD_SET(fds[i].fd, outfds);
267         if(fds[i].fd > maxfd)
268             maxfd = fds[i].fd;
269     }
270     if(timeout != -1) {
271         tvtimeout.tv_sec = timeout / 1000;
272         tvtimeout.tv_usec = 1000 * (timeout % 1000);
273     }
274     rc = select(maxfd + 1, infds, outfds, NULL, 
275                 timeout == -1 ? NULL : &tvtimeout);
276     if(rc >= 0) {
277         for(i = 0; i < nfds; ++i) {
278             int revents = 0;
279             if(FD_ISSET(fds[i].fd, infds))
280                 revents |= POLLIN;
281             if(FD_ISSET(fds[i].fd, outfds))
282                 revents |= POLLOUT;
283             fds[i].revents = revents;
284         }
285     }
286     return rc;
287 }
288 #endif
289
290 struct timeval tv_now_global;
291 uint64_t now_global;
292
293 static void run(void)
294 {
295     struct poll_interest *i;
296     int rv, nfds, remain, idx;
297     int timeout;
298     struct pollfd *fds;
299
300     fds=safe_malloc(sizeof(*fds)*total_nfds, "run");
301
302     Message(M_NOTICE,"%s [%d]: starting\n",version,secnet_pid);
303
304     do {
305         if (gettimeofday(&tv_now_global, NULL)!=0) {
306             fatal_perror("main loop: gettimeofday");
307         }
308         now_global=((uint64_t)tv_now_global.tv_sec*(uint64_t)1000)+
309                    ((uint64_t)tv_now_global.tv_usec/(uint64_t)1000);
310         idx=0;
311         for (i=reg; i; i=i->next) {
312             int check;
313             for (check=0; check<i->nfds; check++) {
314                 if(fds[idx+check].revents & POLLNVAL) {
315                     fatal("run: poll (%s#%d) set POLLNVAL", i->desc, check);
316                 }
317             }
318             i->after(i->state, fds+idx, i->nfds);
319             idx+=i->nfds;
320         }
321         remain=total_nfds;
322         idx=0;
323         timeout=-1;
324         for (i=reg; i; i=i->next) {
325             nfds=remain;
326             rv=i->before(i->state, fds+idx, &nfds, &timeout);
327             if (rv!=0) {
328                 /* XXX we need to handle this properly: increase the
329                    nfds available */
330                 fatal("run: beforepoll_fn (%s) returns %d",i->desc,rv);
331             }
332             if (timeout<-1) {
333                 fatal("run: beforepoll_fn (%s) set timeout to %d",timeout);
334             }
335             idx+=nfds;
336             remain-=nfds;
337             i->nfds=nfds;
338         }
339         do {
340             if (finished) break;
341 #if USE_SELECT
342             rv=fakepoll(fds, idx, timeout);
343 #else
344             rv=poll(fds, idx, timeout);
345 #endif
346             if (rv<0) {
347                 if (errno!=EINTR) {
348                     fatal_perror("run: poll");
349                 }
350             }
351         } while (rv<0);
352     } while (!finished);
353     free(fds);
354 }
355
356 static void droppriv(void)
357 {
358     FILE *pf=NULL;
359     pid_t p;
360     int errfds[2];
361
362     add_hook(PHASE_SHUTDOWN,system_phase_hook,NULL);
363
364     /* Open the pidfile for writing now: we may be unable to do so
365        once we drop privileges. */
366     if (pidfile) {
367         pf=fopen(pidfile,"w");
368         if (!pf) {
369             fatal_perror("cannot open pidfile \"%s\"",pidfile);
370         }
371     }
372     if (!background && pf) {
373         fprintf(pf,"%d\n",getpid());
374         fclose(pf);
375     }
376
377     /* Now drop privileges */
378     if (uid!=0) {
379         if (setuid(uid)!=0) {
380             fatal_perror("can't set uid to \"%s\"",userid);
381         }
382     }
383     if (background) {
384         p=fork();
385         if (p>0) {
386             if (pf) {
387                 /* Parent process - write pidfile, exit */
388                 fprintf(pf,"%d\n",p);
389                 fclose(pf);
390             }
391             exit(0);
392         } else if (p==0) {
393             /* Child process - all done, just carry on */
394             if (pf) fclose(pf);
395             /* Close stdin and stdout; we don't need them any more.
396                stderr is redirected to the system/log facility */
397             if (pipe(errfds)!=0) {
398                 fatal_perror("can't create pipe for stderr");
399             }
400             close(0);
401             close(1);
402             close(2);
403             dup2(errfds[1],0);
404             dup2(errfds[1],1);
405             dup2(errfds[1],2);
406             secnet_is_daemon=True;
407             setsid();
408             log_from_fd(errfds[0],"stderr",system_log);
409         } else {
410             /* Error */
411             fatal_perror("cannot fork");
412             exit(1);
413         }
414     }
415     secnet_pid=getpid();
416 }
417
418 static signal_notify_fn finish,ignore_hup;
419 static void finish(void *st, int signum)
420 {
421     finished=True;
422     Message(M_NOTICE,"%s [%d]: received %s\n",version,secnet_pid,(string_t)st);
423 }
424 static void ignore_hup(void *st, int signum)
425 {
426     Message(M_INFO,"%s [%d]: received SIGHUP\n",version,secnet_pid);
427     return;
428 }
429
430 int main(int argc, char **argv)
431 {
432     dict_t *config;
433
434     enter_phase(PHASE_GETOPTS);
435     parse_options(argc,argv);
436
437     enter_phase(PHASE_READCONFIG);
438     config=read_conffile(configfile);
439
440     enter_phase(PHASE_SETUP);
441     setup(config);
442
443     if (just_check_config) {
444         Message(M_INFO,"configuration file check complete\n");
445         exit(0);
446     }
447
448     enter_phase(PHASE_GETRESOURCES);
449     /* Appropriate phase hooks will have been run */
450     
451     enter_phase(PHASE_DROPPRIV);
452     droppriv();
453
454     start_signal_handling();
455     request_signal_notification(SIGTERM,finish,safe_strdup("SIGTERM","run"));
456     if (!background) request_signal_notification(SIGINT,finish,
457                                                  safe_strdup("SIGINT","run"));
458     request_signal_notification(SIGHUP,ignore_hup,NULL);
459     enter_phase(PHASE_RUN);
460     run();
461
462     enter_phase(PHASE_SHUTDOWN);
463     Message(M_NOTICE,"%s [%d]: finished\n",version,secnet_pid);
464
465     return 0;
466 }