xref: /netbsd-src/usr.sbin/rbootd/rbootd.c (revision 4472dbe5e3bd91ef2540bada7a7ca7384627ff9b)
1 /*	$NetBSD: rbootd.c,v 1.10 1999/06/06 03:11:40 thorpej 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.10 1999/06/06 03:11:40 thorpej 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 <util.h>
77 #include "defs.h"
78 
79 int	main __P((int, char *[]));
80 
81 extern	char *__progname;	/* from crt0.o */
82 
83 int
84 main(argc, argv)
85 	int argc;
86 	char *argv[];
87 {
88 	int c, fd, omask, maxfds;
89 	fd_set rset;
90 
91 	/*
92 	 *  Close any open file descriptors.
93 	 *  Temporarily leave stdin & stdout open for `-d',
94 	 *  and stderr open for any pre-syslog error messages.
95 	 */
96 	{
97 		int i, nfds = getdtablesize();
98 
99 		for (i = 0; i < nfds; i++)
100 			if (i != fileno(stdin) && i != fileno(stdout) &&
101 			    i != fileno(stderr))
102 				(void) close(i);
103 	}
104 
105 	/*
106 	 *  Parse any arguments.
107 	 */
108 	while ((c = getopt(argc, argv, "adi:")) != -1)
109 		switch(c) {
110 		    case 'a':
111 			BootAny++;
112 			break;
113 		    case 'd':
114 			DebugFlg++;
115 			break;
116 		    case 'i':
117 			IntfName = optarg;
118 			break;
119 		}
120 	for (; optind < argc; optind++) {
121 		if (ConfigFile == NULL)
122 			ConfigFile = argv[optind];
123 		else {
124 			warnx("too many config files (`%s' ignored)\n",
125 			    argv[optind]);
126 		}
127 	}
128 
129 	if (ConfigFile == NULL)			/* use default config file */
130 		ConfigFile = DfltConfig;
131 
132 	if (DebugFlg) {
133 		DbgFp = stdout;				/* output to stdout */
134 
135 		(void) signal(SIGUSR1, SIG_IGN);	/* dont muck w/DbgFp */
136 		(void) signal(SIGUSR2, SIG_IGN);
137 		(void) fclose(stderr);			/* finished with it */
138 	} else {
139 		if (daemon(0, 0))
140 			err(1, "can't detach from terminal");
141 		pidfile(NULL);
142 
143 		(void) signal(SIGUSR1, DebugOn);
144 		(void) signal(SIGUSR2, DebugOff);
145 	}
146 
147 	openlog(__progname, LOG_PID, LOG_DAEMON);
148 
149 	/*
150 	 *  If no interface was specified, get one now.
151 	 *
152 	 *  This is convoluted because we want to get the default interface
153 	 *  name for the syslog("restarted") message.  If BpfGetIntfName()
154 	 *  runs into an error, it will return a syslog-able error message
155 	 *  (in `errmsg') which will be displayed here.
156 	 */
157 	if (IntfName == NULL) {
158 		char *errmsg;
159 
160 		if ((IntfName = BpfGetIntfName(&errmsg)) == NULL) {
161 			syslog(LOG_NOTICE, "restarted (??)");
162 			syslog(LOG_ERR, errmsg);
163 			Exit(0);
164 		}
165 	}
166 
167 	syslog(LOG_NOTICE, "restarted (%s)", IntfName);
168 
169 	(void) signal(SIGHUP, ReConfig);
170 	(void) signal(SIGINT, Exit);
171 	(void) signal(SIGTERM, Exit);
172 
173 	/*
174 	 *  Grab our host name and pid.
175 	 */
176 	if (gethostname(MyHost, sizeof MyHost) < 0) {
177 		syslog(LOG_ERR, "gethostname: %m");
178 		Exit(0);
179 	}
180 	MyHost[sizeof(MyHost) - 1] = '\0';
181 
182 	/*
183 	 *  All boot files are relative to the boot directory, we might
184 	 *  as well chdir() there to make life easier.
185 	 */
186 	if (chdir(BootDir) < 0) {
187 		syslog(LOG_ERR, "chdir: %m (%s)", BootDir);
188 		Exit(0);
189 	}
190 
191 	/*
192 	 *  Initial configuration.
193 	 */
194 	omask = sigblock(sigmask(SIGHUP));	/* prevent reconfig's */
195 	if (GetBootFiles() == 0)		/* get list of boot files */
196 		Exit(0);
197 	if (ParseConfig() == 0)			/* parse config file */
198 		Exit(0);
199 
200 	/*
201 	 *  Open and initialize a BPF device for the appropriate interface.
202 	 *  If an error is encountered, a message is displayed and Exit()
203 	 *  is called.
204 	 */
205 	fd = BpfOpen();
206 
207 	(void) sigsetmask(omask);		/* allow reconfig's */
208 
209 	/*
210 	 *  Main loop: receive a packet, determine where it came from,
211 	 *  and if we service this host, call routine to handle request.
212 	 */
213 	maxfds = fd + 1;
214 	FD_ZERO(&rset);
215 	FD_SET(fd, &rset);
216 	for (;;) {
217 		struct timeval timeout;
218 		fd_set r;
219 		int nsel;
220 
221 		r = rset;
222 
223 		if (RmpConns == NULL) {		/* timeout isnt necessary */
224 			nsel = select(maxfds, &r, NULL, NULL, NULL);
225 		} else {
226 			timeout.tv_sec = RMP_TIMEOUT;
227 			timeout.tv_usec = 0;
228 			nsel = select(maxfds, &r, NULL, NULL, &timeout);
229 		}
230 
231 		if (nsel < 0) {
232 			if (errno == EINTR)
233 				continue;
234 			syslog(LOG_ERR, "select: %m");
235 			Exit(0);
236 		} else if (nsel == 0) {		/* timeout */
237 			DoTimeout();			/* clear stale conns */
238 			continue;
239 		}
240 
241 		if (FD_ISSET(fd, &r)) {
242 			RMPCONN rconn;
243 			CLIENT *client;
244 			int doread = 1;
245 
246 			while (BpfRead(&rconn, doread)) {
247 				doread = 0;
248 
249 				if (DbgFp != NULL)	/* display packet */
250 					DispPkt(&rconn,DIR_RCVD);
251 
252 				omask = sigblock(sigmask(SIGHUP));
253 
254 				/*
255 				 *  If we do not restrict service, set the
256 				 *  client to NULL (ProcessPacket() handles
257 				 *  this).  Otherwise, check that we can
258 				 *  service this host; if not, log a message
259 				 *  and ignore the packet.
260 				 */
261 				if (BootAny) {
262 					client = NULL;
263 				} else if ((client=FindClient(&rconn))==NULL) {
264 					syslog(LOG_INFO,
265 					       "%s: boot packet ignored",
266 					       EnetStr(&rconn));
267 					(void) sigsetmask(omask);
268 					continue;
269 				}
270 
271 				ProcessPacket(&rconn,client);
272 
273 				(void) sigsetmask(omask);
274 			}
275 		}
276 	}
277 }
278 
279 /*
280 **  DoTimeout -- Free any connections that have timed out.
281 **
282 **	Parameters:
283 **		None.
284 **
285 **	Returns:
286 **		Nothing.
287 **
288 **	Side Effects:
289 **		- Timed out connections in `RmpConns' will be freed.
290 */
291 void
292 DoTimeout()
293 {
294 	RMPCONN *rtmp;
295 	struct timeval now;
296 
297 	(void) gettimeofday(&now, (struct timezone *)0);
298 
299 	/*
300 	 *  For each active connection, if RMP_TIMEOUT seconds have passed
301 	 *  since the last packet was sent, delete the connection.
302 	 */
303 	for (rtmp = RmpConns; rtmp != NULL; rtmp = rtmp->next)
304 		if ((rtmp->tstamp.tv_sec + RMP_TIMEOUT) < now.tv_sec) {
305 			syslog(LOG_WARNING, "%s: connection timed out (%u)",
306 			       EnetStr(rtmp), rtmp->rmp.r_type);
307 			RemoveConn(rtmp);
308 		}
309 }
310 
311 /*
312 **  FindClient -- Find client associated with a packet.
313 **
314 **	Parameters:
315 **		rconn - the new packet.
316 **
317 **	Returns:
318 **		Pointer to client info if found, NULL otherwise.
319 **
320 **	Side Effects:
321 **		None.
322 **
323 **	Warnings:
324 **		- This routine must be called with SIGHUP blocked since
325 **		  a reconfigure can invalidate the information returned.
326 */
327 
328 CLIENT *
329 FindClient(rconn)
330 	RMPCONN *rconn;
331 {
332 	CLIENT *ctmp;
333 
334 	for (ctmp = Clients; ctmp != NULL; ctmp = ctmp->next)
335 		if (memcmp((char *)&rconn->rmp.hp_hdr.saddr[0],
336 		         (char *)&ctmp->addr[0], RMP_ADDRLEN) == 0)
337 			break;
338 
339 	return(ctmp);
340 }
341 
342 /*
343 **  Exit -- Log an error message and exit.
344 **
345 **	Parameters:
346 **		sig - caught signal (or zero if not dying on a signal).
347 **
348 **	Returns:
349 **		Does not return.
350 **
351 **	Side Effects:
352 **		- This process ceases to exist.
353 */
354 void
355 Exit(sig)
356 	int sig;
357 {
358 	if (sig > 0)
359 		syslog(LOG_ERR, "going down on signal %d", sig);
360 	else
361 		syslog(LOG_ERR, "going down with fatal error");
362 	BpfClose();
363 	exit(1);
364 }
365 
366 /*
367 **  ReConfig -- Get new list of boot files and reread config files.
368 **
369 **	Parameters:
370 **		None.
371 **
372 **	Returns:
373 **		Nothing.
374 **
375 **	Side Effects:
376 **		- All active connections are dropped.
377 **		- List of boot-able files is changed.
378 **		- List of clients is changed.
379 **
380 **	Warnings:
381 **		- This routine must be called with SIGHUP blocked.
382 */
383 void
384 ReConfig(signo)
385 	int signo;
386 {
387 	syslog(LOG_NOTICE, "reconfiguring boot server");
388 
389 	FreeConns();
390 
391 	if (GetBootFiles() == 0)
392 		Exit(0);
393 
394 	if (ParseConfig() == 0)
395 		Exit(0);
396 }
397 
398 /*
399 **  DebugOff -- Turn off debugging.
400 **
401 **	Parameters:
402 **		None.
403 **
404 **	Returns:
405 **		Nothing.
406 **
407 **	Side Effects:
408 **		- Debug file is closed.
409 */
410 void
411 DebugOff(signo)
412 	int signo;
413 {
414 	if (DbgFp != NULL)
415 		(void) fclose(DbgFp);
416 
417 	DbgFp = NULL;
418 }
419 
420 /*
421 **  DebugOn -- Turn on debugging.
422 **
423 **	Parameters:
424 **		None.
425 **
426 **	Returns:
427 **		Nothing.
428 **
429 **	Side Effects:
430 **		- Debug file is opened/truncated if not already opened,
431 **		  otherwise do nothing.
432 */
433 void
434 DebugOn(signo)
435 	int signo;
436 {
437 	if (DbgFp == NULL) {
438 		if ((DbgFp = fopen(DbgFile, "w")) == NULL)
439 			syslog(LOG_ERR, "can't open debug file (%s)", DbgFile);
440 	}
441 }
442