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