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