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