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