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