chiark / gitweb /
Small tweaks. Support no-network configuration option, and rearrange
[become] / src / daemon.c
1 /* -*-c-*-
2  *
3  * $Id: daemon.c,v 1.9 1998/01/12 16:45:59 mdw Exp $
4  *
5  * Running a `become' daemon
6  *
7  * (c) 1998 EBI
8  */
9
10 /*----- Licensing notice --------------------------------------------------*
11  *
12  * This file is part of `become'
13  *
14  * `Become' is free software; you can redistribute it and/or modify
15  * it under the terms of the GNU General Public License as published by
16  * the Free Software Foundation; either version 2 of the License, or
17  * (at your option) any later version.
18  *
19  * `Become' is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  * GNU General Public License for more details.
23  *
24  * You should have received a copy of the GNU General Public License
25  * along with `become'; if not, write to the Free Software Foundation,
26  * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
27  */
28
29 /*----- Revision history --------------------------------------------------*
30  *
31  * $Log: daemon.c,v $
32  * Revision 1.9  1998/01/12 16:45:59  mdw
33  * Fix copyright date.
34  *
35  * Revision 1.8  1997/09/26 09:14:58  mdw
36  * Merged blowfish branch into trunk.
37  *
38  * Revision 1.7.2.1  1997/09/26 09:08:05  mdw
39  * Use the Blowfish encryption algorithm instead of IDEA.  This is partly
40  * because I prefer Blowfish (without any particularly strong evidence) but
41  * mainly because IDEA is patented and Blowfish isn't.
42  *
43  * Revision 1.7  1997/09/17 10:23:23  mdw
44  * Fix a typo.  Port numbers are in network order now, so don't change them.
45  *
46  * Revision 1.6  1997/09/09 18:17:06  mdw
47  * Allow default port to be given as a service name or port number.
48  *
49  * Revision 1.5  1997/08/20  16:17:10  mdw
50  * More sensible restart routine: `_reinit' functions replaced by `_end' and
51  * `_init' functions.
52  *
53  * Revision 1.4  1997/08/07 10:00:37  mdw
54  * (Log entry for previous version is bogus.)  Read netgroups database.
55  * Give up privileges permanently on startup.
56  *
57  * Revision 1.2  1997/08/04 10:24:21  mdw
58  * Sources placed under CVS control.
59  *
60  * Revision 1.1  1997/07/21  13:47:50  mdw
61  * Initial revision
62  *
63  */
64
65 /*----- Header files ------------------------------------------------------*/
66
67 /* --- ANSI headers --- */
68
69 #include <errno.h>
70 #include <signal.h>
71 #include <setjmp.h>
72 #include <stdio.h>
73 #include <stdlib.h>
74 #include <string.h>
75
76 /* --- Unix headers --- */
77
78 #include <sys/types.h>
79 #include <sys/time.h>
80 #include <sys/socket.h>
81
82 #include <netinet/in.h>
83
84 #include <arpa/inet.h>
85
86 #include <netdb.h>
87 #include <syslog.h>
88 #include <unistd.h>
89
90 /* --- Local headers --- */
91
92 #include "become.h"
93 #include "blowfish.h"
94 #include "config.h"
95 #include "crypt.h"
96 #include "daemon.h"
97 #include "lexer.h"
98 #include "name.h"
99 #include "netg.h"
100 #include "parser.h"
101 #include "rule.h"
102 #include "tx.h"
103 #include "userdb.h"
104 #include "utils.h"
105
106 /*----- Arbitrary constants -----------------------------------------------*/
107
108 #define daemon__awakeEvery (30 * 60)    /* Awaken this often to rescan */
109
110 /*----- Static variables --------------------------------------------------*/
111
112 static int daemon__running = 0;         /* Am I running as a daemon? */
113 static int daemon__port = -1;           /* No particular port yet */
114 static volatile sig_atomic_t daemon__rescan = 0; /* Rescan as soon as poss */
115 #define daemon__signum daemon__rescan   /* Alias for readbility */
116 static int daemon__readKey = 0;         /* Have I read a key? */
117 static unsigned char daemon__key[BLOWFISH_KEYSIZE]; /* Encryption key */
118 static jmp_buf daemon__dieBuf;          /* Jump here to kill the daemon */
119
120 /*----- Main code ---------------------------------------------------------*/
121
122 /* --- @daemon_usePort@ --- *
123  *
124  * Arguments:   @int port@ = port to use, please
125  *
126  * Returns:     ---
127  *
128  * Use:         Instructs the daemon to listen to the given port.
129  */
130
131 void daemon_usePort(int port)
132 {
133   daemon__port = port;
134 }
135
136 /* --- @daemon_readKey@ --- *
137  *
138  * Arguments:   @const char *kf@ = name of file containing key
139  *
140  * Returns:     ---
141  *
142  * Use:         Instructs the daemon to read the named key file.
143  */
144
145 void daemon_readKey(const char *kf)
146 {
147   FILE *fp;
148
149   if (!daemon__running)
150     return;
151
152   if ((fp = fopen(kf, "r")) == 0) {
153     syslog(LOG_WARNING, "couldn't read key file: %e");
154     return;
155   }
156   tx_getBits(daemon__key, 128, fp);
157   fclose(fp);
158   daemon__readKey = 1;
159   return;
160 }
161
162 /* --- @daemon__readConfig@ --- *
163  *
164  * Arguments:   @const char *cf@ = pointer to configuration file to use
165  *
166  * Returns:     Zero if it worked, nonzero if it hurt...
167  *
168  * Use:         Reads the configuration file, and other things.
169  */
170
171 static int daemon__readConfig(const char *cf)
172 {
173   FILE *fp;
174
175   daemon__readKey = 0;
176   if ((fp = fopen(cf, "r")) == 0)
177     return (-1);
178   lexer_scan(fp);
179   yyparse();
180   fclose(fp);
181   if (!daemon__readKey)
182     daemon_readKey(file_KEY);
183   daemon__rescan = 0;
184   T( trace(TRACE_DAEMON, "daemon: read config file"); )
185   return (0);
186 }
187
188 /* --- @daemon__restart@ --- *
189  *
190  * Arguments:   @int sig@ = the signal number
191  *
192  * Returns:     ---
193  *
194  * Use:         Handles signals.  Causes the configuration file to be reread.
195  */
196
197 static void daemon__restart(int sig)
198 {
199   daemon__rescan = 1;
200   signal(sig, daemon__restart);
201 }
202
203 /* --- @daemon__die@ --- *
204  *
205  * Arguments:   @int sig@ = the signal number
206  *
207  * Returns:     via @longjmp@
208  *
209  * Use:         Handles other signals.  Causes the daemon to die.
210  */
211
212 static void daemon__die(int sig)
213 {
214   daemon__signum = sig;
215   longjmp(daemon__dieBuf, 1);
216 }
217
218 /* --- @daemon__read@ --- *
219  *
220  * Arguments:   @int fd@ = socket handle
221  *
222  * Returns:     ---
223  *
224  * Use:         Examines a buffer, and returns a response.
225  */
226
227 void daemon__read(int fd)
228 {
229   unsigned char buff[65536];            /* Buffer for incoming packets */
230   unsigned char rpl[crp_size];          /* Buffer for outgoing replies */
231   struct sockaddr_in sin;               /* Address of packet sender */
232   char sender[64];                      /* Sender's hostname (resolved) */
233   unsigned char sk[BLOWFISH_KEYSIZE];   /* Session key for reply */
234   request rq;                           /* Request buffer for verification */
235
236   /* --- Read the message --- */
237
238   {
239     int slen = sizeof(sin);
240
241     if (recvfrom(fd, (char *)buff, sizeof(buff), 0,
242                  (struct sockaddr *)&sin, &slen) < 0) {
243       T( trace(TRACE_DAEMON, "daemon: error reading packet: %s",
244                strerror(errno)); )
245       syslog(LOG_INFO, "duff packet received: %e");
246       return;
247     }
248   }
249
250   /* --- Resolve the host name --- */
251
252   {
253     struct hostent *he = gethostbyaddr((char *)&sin.sin_addr,
254                                        sizeof(sin.sin_addr),
255                                        AF_INET);
256     sender[0] = 0;
257     strncat(sender,
258             he ? he->h_name : inet_ntoa(sin.sin_addr),
259             sizeof(sender));
260     syslog(LOG_DEBUG, "packet received from %s", sender);
261     T( trace(TRACE_DAEMON, "daemon: received request from %s", sender); )
262   }
263
264   /* --- Unpack the block --- */
265
266   if (crypt_unpackRequest(&rq, buff, daemon__key, sk, rpl) == 0) {
267     burn(buff);
268     T( trace(TRACE_DAEMON, "daemon: received corrupt or invalid request"); )
269     syslog(LOG_INFO, "packet from %s rejected", sender);
270     return;
271   }
272   burn(buff);
273
274   /* --- Fill in the sender's address in the request block --- */
275
276   rq.host = sin.sin_addr;
277
278   /* --- Build a reply block --- */
279
280   {
281     int answer = rule_check(&rq);
282     syslog(LOG_INFO, "request from %s for %i to become %i to run %s %s",
283            sender, rq.from, rq.to, rq.cmd, answer ? "granted" : "denied");
284     crypt_packReply(rpl, sk, answer);
285     burn(sk);
286   }
287
288   /* --- Send the reply off --- */
289
290   sendto(fd, (char *)rpl, crp_size, 0, (struct sockaddr *)&sin, sizeof(sin));
291   T( trace(TRACE_DAEMON, "daemon: reply sent"); )
292   burn(rpl);
293 }
294
295 /* --- @daemon_init@ --- *
296  *
297  * Arguments:   @const char *cf@ = pointer to name of configuration file
298  *              @int port@ = port to listen to, or %$-1$% for default
299  *
300  * Returns:     Never.
301  *
302  * Use:         Starts `become' up in daemon mode.
303  */
304
305 void daemon_init(const char *cf, int port)
306 {
307   int s;
308
309   /* --- Remove my root privileges --- *
310    *
311    * Just in case there's anything dodgy in my configuration file, or the
312    * user wants me to start on a funny port.
313    */
314
315   setuid(getuid());
316
317   /* --- Initialise bits of the program --- */
318
319   daemon__running = 1;
320   daemon__port = port;
321   userdb_init();
322   userdb_local();
323   userdb_yp();
324   netg_init();
325   name_init();
326   rule_init();
327   openlog(quis(), 0, LOG_DAEMON);
328   syslog(LOG_NOTICE, "starting up");
329
330   if (daemon__readConfig(cf))
331     die("couldn't read configuration file");
332
333   /* --- Decide on a port to use --- *
334    *
335    * If I don't have a port yet (e.g., from the configuration file) then
336    * look it up in /etc/services under whatever name I was started as.
337    */
338
339   if (daemon__port == 0) {
340     struct servent *se = getservbyname(quis(), "udp");
341     if (!se)
342       die("no idea which port to listen to");
343     daemon__port = se->s_port;
344   }
345
346   /* --- Now set up a socket --- */
347
348   {
349     struct sockaddr_in sin;
350
351     if ((s = socket(PF_INET, SOCK_DGRAM, 0)) == -1)
352       die("couldn't create socket: %s", strerror(errno));
353     sin.sin_family = AF_INET;
354     sin.sin_port = daemon__port;
355     sin.sin_addr.s_addr = htonl(INADDR_ANY);
356     if (bind(s, (struct sockaddr *)&sin, sizeof(sin))) {
357       die("couldn't bind socket to port %i: %s",
358           ntohs(daemon__port), strerror(errno));
359     }
360   }
361
362   /* --- Fork off into the sunset --- */
363
364 #ifdef NDEBUG
365   {
366     int pid = fork();
367     FILE *fp;
368
369     /* --- Make a background process --- */
370
371     if (pid == -1)
372       die("couldn't fork daemon: %s", strerror(errno));
373     else if (pid != 0)
374       return;
375
376     /* --- Disconnect from the terminal --- */
377
378     setsid();
379
380     /* --- Write my process id to a file --- */
381
382     if ((fp = fopen(file_PID, "w")) != 0) {
383       fprintf(fp, "%lu\n", (unsigned long)getpid());
384       fclose(fp);
385     }
386     T( trace(TRACE_DAEMON, "daemon: forked to pid %li", (long)getpid()); )
387   }
388 #endif
389
390   /* --- Program in daemon death mode --- */
391
392   if (setjmp(daemon__dieBuf)) {
393 #ifdef TRACING
394     if (daemon__signum == SIGQUIT && tracing() & TRACE_RULE) {
395       T( rule_dump(); )
396       signal(SIGQUIT, daemon__die);
397     } else
398 #endif
399     {
400       T( trace(TRACE_DAEMON, "daemon: killed by signal %i",
401                daemon__signum); )
402       syslog(LOG_NOTICE, "killed by signal type %i", daemon__signum);
403       remove(file_PID);
404       exit(0);
405     }
406   } else {
407
408     /* --- Set signal handlers --- */
409
410     signal(SIGHUP, daemon__restart);
411     signal(SIGQUIT, daemon__die);
412     signal(SIGINT, daemon__die);
413     signal(SIGTERM, daemon__die);
414     signal(SIGSEGV, daemon__die);
415     signal(SIGFPE, daemon__die);
416     signal(SIGBUS, daemon__die);
417   }
418
419   /* --- Now wait for something exciting to happen --- *
420    *
421    * Actually, every so often (5 minutes, perhaps) I need to wake up and
422    * rescan the users to see whether they've changed.  Time to play with
423    * @select@.
424    */
425
426   {
427     time_t when;
428
429     /* --- Find when I am, and thus when I need to be awoken again --- */
430
431     when = time(0) + daemon__awakeEvery;
432
433     for (;;) {
434       fd_set fds;
435       int i;
436
437       /* --- Set up the file descriptor tables --- */
438
439       FD_ZERO(&fds);
440       FD_SET(s, &fds);
441
442       /* --- Now wait for something interesting --- */
443
444       T( trace(TRACE_DAEMON, "daemon: waiting for requests"); )
445       i = select(FD_SETSIZE, &fds, 0, 0, 0);
446
447       /* --- Now, see if I need to rescan the config --- */
448
449       if (daemon__rescan || time(0) - when > 0) {
450         daemon__rescan = 0;
451         syslog(LOG_INFO, "rescanning configuration file");
452         name_end();
453         rule_end();
454         netg_end();
455         userdb_end();
456         userdb_init();
457         userdb_local();
458         userdb_yp();
459         netg_init();
460         rule_init();
461         name_init();
462         if (daemon__readConfig(cf))
463           syslog(LOG_ERR, "error reading configuration file");
464         when = time(0) + daemon__awakeEvery;
465       }
466
467       /* --- Read the data from the request --- */
468
469       if (i > 0)
470         daemon__read(s);
471     }
472   }
473 }
474
475 /*----- That's all, folks -------------------------------------------------*/