xref: /netbsd-src/usr.sbin/rbootd/rbootd.c (revision dc306354b0b29af51801a7632f1e95265a68cd81)
1 /*	$NetBSD: rbootd.c,v 1.9 1998/07/06 06:57:52 mrg Exp $	*/
2 
3 /*
4  * Copyright (c) 1988, 1992 The University of Utah and the Center
5  *	for Software Science (CSS).
6  * Copyright (c) 1992, 1993
7  *	The Regents of the University of California.  All rights reserved.
8  *
9  * This code is derived from software contributed to Berkeley by
10  * the Center for Software Science of the University of Utah Computer
11  * Science Department.  CSS requests users of this software to return
12  * to css-dist@cs.utah.edu any improvements that they make and grant
13  * CSS redistribution rights.
14  *
15  * Redistribution and use in source and binary forms, with or without
16  * modification, are permitted provided that the following conditions
17  * are met:
18  * 1. Redistributions of source code must retain the above copyright
19  *    notice, this list of conditions and the following disclaimer.
20  * 2. Redistributions in binary form must reproduce the above copyright
21  *    notice, this list of conditions and the following disclaimer in the
22  *    documentation and/or other materials provided with the distribution.
23  * 3. All advertising materials mentioning features or use of this software
24  *    must display the following acknowledgement:
25  *	This product includes software developed by the University of
26  *	California, Berkeley and its contributors.
27  * 4. Neither the name of the University nor the names of its contributors
28  *    may be used to endorse or promote products derived from this software
29  *    without specific prior written permission.
30  *
31  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
32  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
33  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
34  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
35  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
36  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
37  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
38  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
39  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
40  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
41  * SUCH DAMAGE.
42  *
43  *	from: @(#)rbootd.c	8.1 (Berkeley) 6/4/93
44  *
45  * From: Utah Hdr: rbootd.c 3.1 92/07/06
46  * Author: Jeff Forys, University of Utah CSS
47  */
48 
49 #include <sys/cdefs.h>
50 #ifndef lint
51 __COPYRIGHT(
52 "@(#) Copyright (c) 1992, 1993\n\
53 	The Regents of the University of California.  All rights reserved.\n");
54 #endif /* not lint */
55 
56 #ifndef lint
57 #if 0
58 static char sccsid[] = "@(#)rbootd.c	8.1 (Berkeley) 6/4/93";
59 #else
60 __RCSID("$NetBSD: rbootd.c,v 1.9 1998/07/06 06:57:52 mrg Exp $");
61 #endif
62 #endif /* not lint */
63 
64 #include <sys/param.h>
65 #include <sys/time.h>
66 #include <ctype.h>
67 #include <err.h>
68 #include <errno.h>
69 #include <fcntl.h>
70 #include <signal.h>
71 #include <stdio.h>
72 #include <stdlib.h>
73 #include <string.h>
74 #include <syslog.h>
75 #include <unistd.h>
76 #include "defs.h"
77 
78 int	main __P((int, char *[]));
79 
80 extern	char *__progname;	/* from crt0.o */
81 
82 int
83 main(argc, argv)
84 	int argc;
85 	char *argv[];
86 {
87 	int c, fd, omask, maxfds;
88 	fd_set rset;
89 
90 	/*
91 	 *  Close any open file descriptors.
92 	 *  Temporarily leave stdin & stdout open for `-d',
93 	 *  and stderr open for any pre-syslog error messages.
94 	 */
95 	{
96 		int i, nfds = getdtablesize();
97 
98 		for (i = 0; i < nfds; i++)
99 			if (i != fileno(stdin) && i != fileno(stdout) &&
100 			    i != fileno(stderr))
101 				(void) close(i);
102 	}
103 
104 	/*
105 	 *  Parse any arguments.
106 	 */
107 	while ((c = getopt(argc, argv, "adi:")) != -1)
108 		switch(c) {
109 		    case 'a':
110 			BootAny++;
111 			break;
112 		    case 'd':
113 			DebugFlg++;
114 			break;
115 		    case 'i':
116 			IntfName = optarg;
117 			break;
118 		}
119 	for (; optind < argc; optind++) {
120 		if (ConfigFile == NULL)
121 			ConfigFile = argv[optind];
122 		else {
123 			warnx("too many config files (`%s' ignored)\n",
124 			    argv[optind]);
125 		}
126 	}
127 
128 	if (ConfigFile == NULL)			/* use default config file */
129 		ConfigFile = DfltConfig;
130 
131 	if (DebugFlg) {
132 		DbgFp = stdout;				/* output to stdout */
133 
134 		(void) signal(SIGUSR1, SIG_IGN);	/* dont muck w/DbgFp */
135 		(void) signal(SIGUSR2, SIG_IGN);
136 		(void) fclose(stderr);			/* finished with it */
137 	} else {
138 		if (daemon(0, 0))
139 			err(1, "can't detach from terminal");
140 
141 		(void) signal(SIGUSR1, DebugOn);
142 		(void) signal(SIGUSR2, DebugOff);
143 	}
144 
145 	openlog(__progname, LOG_PID, LOG_DAEMON);
146 
147 	/*
148 	 *  If no interface was specified, get one now.
149 	 *
150 	 *  This is convoluted because we want to get the default interface
151 	 *  name for the syslog("restarted") message.  If BpfGetIntfName()
152 	 *  runs into an error, it will return a syslog-able error message
153 	 *  (in `errmsg') which will be displayed here.
154 	 */
155 	if (IntfName == NULL) {
156 		char *errmsg;
157 
158 		if ((IntfName = BpfGetIntfName(&errmsg)) == NULL) {
159 			syslog(LOG_NOTICE, "restarted (??)");
160 			syslog(LOG_ERR, errmsg);
161 			Exit(0);
162 		}
163 	}
164 
165 	syslog(LOG_NOTICE, "restarted (%s)", IntfName);
166 
167 	(void) signal(SIGHUP, ReConfig);
168 	(void) signal(SIGINT, Exit);
169 	(void) signal(SIGTERM, Exit);
170 
171 	/*
172 	 *  Grab our host name and pid.
173 	 */
174 	if (gethostname(MyHost, sizeof MyHost) < 0) {
175 		syslog(LOG_ERR, "gethostname: %m");
176 		Exit(0);
177 	}
178 	MyHost[sizeof(MyHost) - 1] = '\0';
179 
180 	MyPid = getpid();
181 
182 	/*
183 	 *  Write proc's pid to a file.
184 	 */
185 	{
186 		FILE *fp;
187 
188 		if ((fp = fopen(PidFile, "w")) != NULL) {
189 			(void) fprintf(fp, "%d\n", (int) MyPid);
190 			(void) fclose(fp);
191 		} else {
192 			syslog(LOG_WARNING, "fopen: failed (%s)", PidFile);
193 		}
194 	}
195 
196 	/*
197 	 *  All boot files are relative to the boot directory, we might
198 	 *  as well chdir() there to make life easier.
199 	 */
200 	if (chdir(BootDir) < 0) {
201 		syslog(LOG_ERR, "chdir: %m (%s)", BootDir);
202 		Exit(0);
203 	}
204 
205 	/*
206 	 *  Initial configuration.
207 	 */
208 	omask = sigblock(sigmask(SIGHUP));	/* prevent reconfig's */
209 	if (GetBootFiles() == 0)		/* get list of boot files */
210 		Exit(0);
211 	if (ParseConfig() == 0)			/* parse config file */
212 		Exit(0);
213 
214 	/*
215 	 *  Open and initialize a BPF device for the appropriate interface.
216 	 *  If an error is encountered, a message is displayed and Exit()
217 	 *  is called.
218 	 */
219 	fd = BpfOpen();
220 
221 	(void) sigsetmask(omask);		/* allow reconfig's */
222 
223 	/*
224 	 *  Main loop: receive a packet, determine where it came from,
225 	 *  and if we service this host, call routine to handle request.
226 	 */
227 	maxfds = fd + 1;
228 	FD_ZERO(&rset);
229 	FD_SET(fd, &rset);
230 	for (;;) {
231 		struct timeval timeout;
232 		fd_set r;
233 		int nsel;
234 
235 		r = rset;
236 
237 		if (RmpConns == NULL) {		/* timeout isnt necessary */
238 			nsel = select(maxfds, &r, NULL, NULL, NULL);
239 		} else {
240 			timeout.tv_sec = RMP_TIMEOUT;
241 			timeout.tv_usec = 0;
242 			nsel = select(maxfds, &r, NULL, NULL, &timeout);
243 		}
244 
245 		if (nsel < 0) {
246 			if (errno == EINTR)
247 				continue;
248 			syslog(LOG_ERR, "select: %m");
249 			Exit(0);
250 		} else if (nsel == 0) {		/* timeout */
251 			DoTimeout();			/* clear stale conns */
252 			continue;
253 		}
254 
255 		if (FD_ISSET(fd, &r)) {
256 			RMPCONN rconn;
257 			CLIENT *client;
258 			int doread = 1;
259 
260 			while (BpfRead(&rconn, doread)) {
261 				doread = 0;
262 
263 				if (DbgFp != NULL)	/* display packet */
264 					DispPkt(&rconn,DIR_RCVD);
265 
266 				omask = sigblock(sigmask(SIGHUP));
267 
268 				/*
269 				 *  If we do not restrict service, set the
270 				 *  client to NULL (ProcessPacket() handles
271 				 *  this).  Otherwise, check that we can
272 				 *  service this host; if not, log a message
273 				 *  and ignore the packet.
274 				 */
275 				if (BootAny) {
276 					client = NULL;
277 				} else if ((client=FindClient(&rconn))==NULL) {
278 					syslog(LOG_INFO,
279 					       "%s: boot packet ignored",
280 					       EnetStr(&rconn));
281 					(void) sigsetmask(omask);
282 					continue;
283 				}
284 
285 				ProcessPacket(&rconn,client);
286 
287 				(void) sigsetmask(omask);
288 			}
289 		}
290 	}
291 }
292 
293 /*
294 **  DoTimeout -- Free any connections that have timed out.
295 **
296 **	Parameters:
297 **		None.
298 **
299 **	Returns:
300 **		Nothing.
301 **
302 **	Side Effects:
303 **		- Timed out connections in `RmpConns' will be freed.
304 */
305 void
306 DoTimeout()
307 {
308 	RMPCONN *rtmp;
309 	struct timeval now;
310 
311 	(void) gettimeofday(&now, (struct timezone *)0);
312 
313 	/*
314 	 *  For each active connection, if RMP_TIMEOUT seconds have passed
315 	 *  since the last packet was sent, delete the connection.
316 	 */
317 	for (rtmp = RmpConns; rtmp != NULL; rtmp = rtmp->next)
318 		if ((rtmp->tstamp.tv_sec + RMP_TIMEOUT) < now.tv_sec) {
319 			syslog(LOG_WARNING, "%s: connection timed out (%u)",
320 			       EnetStr(rtmp), rtmp->rmp.r_type);
321 			RemoveConn(rtmp);
322 		}
323 }
324 
325 /*
326 **  FindClient -- Find client associated with a packet.
327 **
328 **	Parameters:
329 **		rconn - the new packet.
330 **
331 **	Returns:
332 **		Pointer to client info if found, NULL otherwise.
333 **
334 **	Side Effects:
335 **		None.
336 **
337 **	Warnings:
338 **		- This routine must be called with SIGHUP blocked since
339 **		  a reconfigure can invalidate the information returned.
340 */
341 
342 CLIENT *
343 FindClient(rconn)
344 	RMPCONN *rconn;
345 {
346 	CLIENT *ctmp;
347 
348 	for (ctmp = Clients; ctmp != NULL; ctmp = ctmp->next)
349 		if (memcmp((char *)&rconn->rmp.hp_hdr.saddr[0],
350 		         (char *)&ctmp->addr[0], RMP_ADDRLEN) == 0)
351 			break;
352 
353 	return(ctmp);
354 }
355 
356 /*
357 **  Exit -- Log an error message and exit.
358 **
359 **	Parameters:
360 **		sig - caught signal (or zero if not dying on a signal).
361 **
362 **	Returns:
363 **		Does not return.
364 **
365 **	Side Effects:
366 **		- This process ceases to exist.
367 */
368 void
369 Exit(sig)
370 	int sig;
371 {
372 	if (sig > 0)
373 		syslog(LOG_ERR, "going down on signal %d", sig);
374 	else
375 		syslog(LOG_ERR, "going down with fatal error");
376 	BpfClose();
377 	exit(1);
378 }
379 
380 /*
381 **  ReConfig -- Get new list of boot files and reread config files.
382 **
383 **	Parameters:
384 **		None.
385 **
386 **	Returns:
387 **		Nothing.
388 **
389 **	Side Effects:
390 **		- All active connections are dropped.
391 **		- List of boot-able files is changed.
392 **		- List of clients is changed.
393 **
394 **	Warnings:
395 **		- This routine must be called with SIGHUP blocked.
396 */
397 void
398 ReConfig(signo)
399 	int signo;
400 {
401 	syslog(LOG_NOTICE, "reconfiguring boot server");
402 
403 	FreeConns();
404 
405 	if (GetBootFiles() == 0)
406 		Exit(0);
407 
408 	if (ParseConfig() == 0)
409 		Exit(0);
410 }
411 
412 /*
413 **  DebugOff -- Turn off debugging.
414 **
415 **	Parameters:
416 **		None.
417 **
418 **	Returns:
419 **		Nothing.
420 **
421 **	Side Effects:
422 **		- Debug file is closed.
423 */
424 void
425 DebugOff(signo)
426 	int signo;
427 {
428 	if (DbgFp != NULL)
429 		(void) fclose(DbgFp);
430 
431 	DbgFp = NULL;
432 }
433 
434 /*
435 **  DebugOn -- Turn on debugging.
436 **
437 **	Parameters:
438 **		None.
439 **
440 **	Returns:
441 **		Nothing.
442 **
443 **	Side Effects:
444 **		- Debug file is opened/truncated if not already opened,
445 **		  otherwise do nothing.
446 */
447 void
448 DebugOn(signo)
449 	int signo;
450 {
451 	if (DbgFp == NULL) {
452 		if ((DbgFp = fopen(DbgFile, "w")) == NULL)
453 			syslog(LOG_ERR, "can't open debug file (%s)", DbgFile);
454 	}
455 }
456