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