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