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