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