xref: /netbsd-src/usr.sbin/rbootd/utils.c (revision 6a9b3088d8d2341ca1454531d365c15fe9c1c589)
1 /*	$NetBSD: utils.c,v 1.16 2009/04/18 09:18:17 lukem Exp $	*/
2 
3 /*
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. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  *	from: @(#)utils.c	8.1 (Berkeley) 6/4/93
38  *
39  * From: Utah Hdr: utils.c 3.1 92/07/06
40  * Author: Jeff Forys, University of Utah CSS
41  */
42 
43 /*
44  * Copyright (c) 1988, 1992 The University of Utah and the Center
45  *	for Software Science (CSS).
46  *
47  * This code is derived from software contributed to Berkeley by
48  * the Center for Software Science of the University of Utah Computer
49  * Science Department.  CSS requests users of this software to return
50  * to css-dist@cs.utah.edu any improvements that they make and grant
51  * CSS redistribution rights.
52  *
53  * Redistribution and use in source and binary forms, with or without
54  * modification, are permitted provided that the following conditions
55  * are met:
56  * 1. Redistributions of source code must retain the above copyright
57  *    notice, this list of conditions and the following disclaimer.
58  * 2. Redistributions in binary form must reproduce the above copyright
59  *    notice, this list of conditions and the following disclaimer in the
60  *    documentation and/or other materials provided with the distribution.
61  * 3. All advertising materials mentioning features or use of this software
62  *    must display the following acknowledgement:
63  *	This product includes software developed by the University of
64  *	California, Berkeley and its contributors.
65  * 4. Neither the name of the University nor the names of its contributors
66  *    may be used to endorse or promote products derived from this software
67  *    without specific prior written permission.
68  *
69  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
70  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
71  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
72  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
73  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
74  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
75  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
76  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
77  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
78  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
79  * SUCH DAMAGE.
80  *
81  *	from: @(#)utils.c	8.1 (Berkeley) 6/4/93
82  *
83  * From: Utah Hdr: utils.c 3.1 92/07/06
84  * Author: Jeff Forys, University of Utah CSS
85  */
86 
87 #include <sys/cdefs.h>
88 #ifndef lint
89 #if 0
90 static char sccsid[] = "@(#)utils.c	8.1 (Berkeley) 6/4/93";
91 #else
92 __RCSID("$NetBSD: utils.c,v 1.16 2009/04/18 09:18:17 lukem Exp $");
93 #endif
94 #endif /* not lint */
95 
96 #include <sys/param.h>
97 #include <sys/time.h>
98 
99 #include <fcntl.h>
100 #include <signal.h>
101 #include <stdio.h>
102 #include <stdlib.h>
103 #include <string.h>
104 #include <syslog.h>
105 #include <time.h>
106 #include <unistd.h>
107 #include "defs.h"
108 
109 /*
110 **  DispPkt -- Display the contents of an RMPCONN packet.
111 **
112 **	Parameters:
113 **		rconn - packet to be displayed.
114 **		direct - direction packet is going (DIR_*).
115 **
116 **	Returns:
117 **		Nothing.
118 **
119 **	Side Effects:
120 **		None.
121 */
122 void
123 DispPkt(rconn, direct)
124 	RMPCONN *rconn;
125 	int direct;
126 {
127 	static const char BootFmt[] = "\t\tRetCode:%u SeqNo:%lx SessID:%x Vers:%u";
128 	static const char ReadFmt[] = "\t\tRetCode:%u Offset:%lx SessID:%x\n";
129 
130 	struct tm *tmp;
131 	struct rmp_packet *rmp;
132 	int i, omask;
133 	u_int32_t t;
134 
135 	/*
136 	 *  Since we will be working with RmpConns as well as DbgFp, we
137 	 *  must block signals that can affect either.
138 	 */
139 	omask = sigblock(sigmask(SIGHUP)|sigmask(SIGUSR1)|sigmask(SIGUSR2));
140 
141 	if (DbgFp == NULL) {			/* sanity */
142 		(void) sigsetmask(omask);
143 		return;
144 	}
145 
146 	/* display direction packet is going using '>>>' or '<<<' */
147 	fputs((direct==DIR_RCVD)?"<<< ":(direct==DIR_SENT)?">>> ":"", DbgFp);
148 
149 	/* display packet timestamp */
150 	tmp = localtime((time_t *)&rconn->tstamp.tv_sec);
151 	fprintf(DbgFp, "%02d:%02d:%02d.%06ld   ", tmp->tm_hour, tmp->tm_min,
152 	        tmp->tm_sec, (long int)rconn->tstamp.tv_usec);
153 
154 	/* display src or dst addr and information about network interface */
155 	fprintf(DbgFp, "Addr: %s   Intf: %s\n", EnetStr(rconn), IntfName);
156 
157 	rmp = &rconn->rmp;
158 
159 	/* display IEEE 802.2 Logical Link Control header */
160 	(void) fprintf(DbgFp, "\t802.2 LLC: DSAP:%x SSAP:%x CTRL:%x\n",
161                rmp->hp_llc.dsap, rmp->hp_llc.ssap, ntohs(rmp->hp_llc.cntrl));
162 
163 	/* display HP extensions to 802.2 Logical Link Control header */
164 	(void) fprintf(DbgFp, "\tHP Ext:    DXSAP:%x SXSAP:%x\n",
165 	               ntohs(rmp->hp_llc.dxsap), ntohs(rmp->hp_llc.sxsap));
166 
167 	/*
168 	 *  Display information about RMP packet using type field to
169 	 *  determine what kind of packet this is.
170 	 */
171 	switch(rmp->r_type) {
172 		case RMP_BOOT_REQ:		/* boot request */
173 			(void) fprintf(DbgFp, "\tBoot Request:");
174 			GETWORD(rmp->r_brq.rmp_seqno, t);
175 			if (ntohs(rmp->r_brq.rmp_session) == RMP_PROBESID) {
176 				if (WORDZE(rmp->r_brq.rmp_seqno))
177 					fputs(" (Send Server ID)", DbgFp);
178 				else
179 					fprintf(DbgFp," (Send Filename #%u)",t);
180 			}
181 			(void) fputc('\n', DbgFp);
182 			(void) fprintf(DbgFp, BootFmt, rmp->r_brq.rmp_retcode,
183 			        (unsigned long)t, ntohs(rmp->r_brq.rmp_session),
184 			        ntohs(rmp->r_brq.rmp_version));
185 			(void) fprintf(DbgFp, "\n\t\tMachine Type: ");
186 			for (i = 0; i < RMP_MACHLEN; i++)
187 				(void) fputc(rmp->r_brq.rmp_machtype[i], DbgFp);
188 			DspFlnm(rmp->r_brq.rmp_flnmsize, &rmp->r_brq.rmp_flnm);
189 			break;
190 		case RMP_BOOT_REPL:		/* boot reply */
191 			fprintf(DbgFp, "\tBoot Reply:\n");
192 			GETWORD(rmp->r_brpl.rmp_seqno, t);
193 			(void) fprintf(DbgFp, BootFmt, rmp->r_brpl.rmp_retcode,
194 			        (unsigned long)t, ntohs(rmp->r_brpl.rmp_session),
195 			        ntohs(rmp->r_brpl.rmp_version));
196 			DspFlnm(rmp->r_brpl.rmp_flnmsize,&rmp->r_brpl.rmp_flnm);
197 			break;
198 		case RMP_READ_REQ:		/* read request */
199 			(void) fprintf(DbgFp, "\tRead Request:\n");
200 			GETWORD(rmp->r_rrq.rmp_offset, t);
201 			(void) fprintf(DbgFp, ReadFmt, rmp->r_rrq.rmp_retcode,
202 			        (unsigned long)t, ntohs(rmp->r_rrq.rmp_session));
203 			(void) fprintf(DbgFp, "\t\tNoOfBytes: %u\n",
204 			        ntohs(rmp->r_rrq.rmp_size));
205 			break;
206 		case RMP_READ_REPL:		/* read reply */
207 			(void) fprintf(DbgFp, "\tRead Reply:\n");
208 			GETWORD(rmp->r_rrpl.rmp_offset, t);
209 			(void) fprintf(DbgFp, ReadFmt, rmp->r_rrpl.rmp_retcode,
210 			        (unsigned long)t, ntohs(rmp->r_rrpl.rmp_session));
211 			(void) fprintf(DbgFp, "\t\tNoOfBytesSent: %ld\n",
212 			        (long)(rconn->rmplen - RMPREADSIZE(0)));
213 			break;
214 		case RMP_BOOT_DONE:		/* boot complete */
215 			(void) fprintf(DbgFp, "\tBoot Complete:\n");
216 			(void) fprintf(DbgFp, "\t\tRetCode:%u SessID:%x\n",
217 			        rmp->r_done.rmp_retcode,
218 			        ntohs(rmp->r_done.rmp_session));
219 			break;
220 		default:			/* ??? */
221 			(void) fprintf(DbgFp, "\tUnknown Type:(%d)\n",
222 				rmp->r_type);
223 	}
224 	(void) fputc('\n', DbgFp);
225 	(void) fflush(DbgFp);
226 
227 	(void) sigsetmask(omask);		/* reset old signal mask */
228 }
229 
230 
231 /*
232 **  GetEtherAddr -- convert an RMP (Ethernet) address into a string.
233 **
234 **	An RMP BOOT packet has been received.  Look at the type field
235 **	and process Boot Requests, Read Requests, and Boot Complete
236 **	packets.  Any other type will be dropped with a warning msg.
237 **
238 **	Parameters:
239 **		addr - array of RMP_ADDRLEN bytes.
240 **
241 **	Returns:
242 **		Pointer to static string representation of `addr'.
243 **
244 **	Side Effects:
245 **		None.
246 **
247 **	Warnings:
248 **		- The return value points to a static buffer; it must
249 **		  be copied if it's to be saved.
250 */
251 char *
252 GetEtherAddr(addr)
253 	u_int8_t *addr;
254 {
255 	static char Hex[] = "0123456789abcdef";
256 	static char etherstr[RMP_ADDRLEN*3];
257 	int i;
258 	char *cp;
259 
260 	/*
261 	 *  For each byte in `addr', convert it to "<hexchar><hexchar>:".
262 	 *  The last byte does not get a trailing `:' appended.
263 	 */
264 	i = 0;
265 	cp = etherstr;
266 	for(;;) {
267 		*cp++ = Hex[*addr >> 4 & 0xf];
268 		*cp++ = Hex[*addr++ & 0xf];
269 		if (++i == RMP_ADDRLEN)
270 			break;
271 		*cp++ = ':';
272 	}
273 	*cp = '\0';
274 
275 	return(etherstr);
276 }
277 
278 
279 /*
280 **  DispFlnm -- Print a string of bytes to DbgFp (often, a file name).
281 **
282 **	Parameters:
283 **		size - number of bytes to print.
284 **		flnm - address of first byte.
285 **
286 **	Returns:
287 **		Nothing.
288 **
289 **	Side Effects:
290 **		- Characters are sent to `DbgFp'.
291 */
292 void
293 DspFlnm(size, flnm)
294 	u_int size;
295 	char *flnm;
296 {
297 	size_t i;
298 
299 	(void) fprintf(DbgFp, "\n\t\tFile Name (%u): <", size);
300 	for (i = 0; i < size; i++)
301 		(void) fputc(*flnm++, DbgFp);
302 	(void) fputs(">\n", DbgFp);
303 }
304 
305 
306 /*
307 **  NewClient -- allocate memory for a new CLIENT.
308 **
309 **	Parameters:
310 **		addr - RMP (Ethernet) address of new client.
311 **
312 **	Returns:
313 **		Ptr to new CLIENT or NULL if we ran out of memory.
314 **
315 **	Side Effects:
316 **		- Memory will be malloc'd for the new CLIENT.
317 **		- If malloc() fails, a log message will be generated.
318 */
319 CLIENT *
320 NewClient(addr)
321 	u_int8_t *addr;
322 {
323 	CLIENT *ctmp;
324 
325 	if ((ctmp = (CLIENT *) malloc(sizeof(CLIENT))) == NULL) {
326 		syslog(LOG_ERR, "NewClient: out of memory (%s)",
327 		       GetEtherAddr(addr));
328 		return(NULL);
329 	}
330 
331 	memset(ctmp, 0, sizeof(CLIENT));
332 	memmove(&ctmp->addr[0], addr, RMP_ADDRLEN);
333 	return(ctmp);
334 }
335 
336 /*
337 **  FreeClients -- free linked list of Clients.
338 **
339 **	Parameters:
340 **		None.
341 **
342 **	Returns:
343 **		Nothing.
344 **
345 **	Side Effects:
346 **		- All malloc'd memory associated with the linked list of
347 **		  CLIENTS will be free'd; `Clients' will be set to NULL.
348 **
349 **	Warnings:
350 **		- This routine must be called with SIGHUP blocked.
351 */
352 void
353 FreeClients()
354 {
355 	CLIENT *ctmp;
356 
357 	while (Clients != NULL) {
358 		ctmp = Clients;
359 		Clients = Clients->next;
360 		FreeClient(ctmp);
361 	}
362 }
363 
364 /*
365 **  NewStr -- allocate memory for a character array.
366 **
367 **	Parameters:
368 **		str - null terminated character array.
369 **
370 **	Returns:
371 **		Ptr to new character array or NULL if we ran out of memory.
372 **
373 **	Side Effects:
374 **		- Memory will be malloc'd for the new character array.
375 **		- If malloc() fails, a log message will be generated.
376 */
377 char *
378 NewStr(str)
379 	char *str;
380 {
381 	char *stmp;
382 
383 	if ((stmp = strdup(str)) == NULL) {
384 		syslog(LOG_ERR, "NewStr: out of memory (%s)", str);
385 		return(NULL);
386 	}
387 
388 	return(stmp);
389 }
390 
391 /*
392 **  To save time, NewConn and FreeConn maintain a cache of one RMPCONN
393 **  in `LastFree' (defined below).
394 */
395 
396 static RMPCONN *LastFree = NULL;
397 
398 /*
399 **  NewConn -- allocate memory for a new RMPCONN connection.
400 **
401 **	Parameters:
402 **		rconn - initialization template for new connection.
403 **
404 **	Returns:
405 **		Ptr to new RMPCONN or NULL if we ran out of memory.
406 **
407 **	Side Effects:
408 **		- Memory may be malloc'd for the new RMPCONN (if not cached).
409 **		- If malloc() fails, a log message will be generated.
410 */
411 RMPCONN *
412 NewConn(rconn)
413 	RMPCONN *rconn;
414 {
415 	RMPCONN *rtmp;
416 
417 	if (LastFree == NULL) {		/* nothing cached; make a new one */
418 		if ((rtmp = (RMPCONN *) malloc(sizeof(RMPCONN))) == NULL) {
419 			syslog(LOG_ERR, "NewConn: out of memory (%s)",
420 			       EnetStr(rconn));
421 			return(NULL);
422 		}
423 	} else {			/* use the cached RMPCONN */
424 		rtmp = LastFree;
425 		LastFree = NULL;
426 	}
427 
428 	/*
429 	 *  Copy template into `rtmp', init file descriptor to `-1' and
430 	 *  set ptr to next elem NULL.
431 	 */
432 	memmove((char *)rtmp, (char *)rconn, sizeof(RMPCONN));
433 	rtmp->bootfd = -1;
434 	rtmp->next = NULL;
435 
436 	return(rtmp);
437 }
438 
439 /*
440 **  FreeConn -- Free memory associated with an RMPCONN connection.
441 **
442 **	Parameters:
443 **		rtmp - ptr to RMPCONN to be free'd.
444 **
445 **	Returns:
446 **		Nothing.
447 **
448 **	Side Effects:
449 **		- Memory associated with `rtmp' may be free'd (or cached).
450 **		- File desc associated with `rtmp->bootfd' will be closed.
451 */
452 void
453 FreeConn(rtmp)
454 	RMPCONN *rtmp;
455 {
456 	/*
457 	 *  If the file descriptor is in use, close the file.
458 	 */
459 	if (rtmp->bootfd >= 0) {
460 		(void) close(rtmp->bootfd);
461 		rtmp->bootfd = -1;
462 	}
463 
464 	if (LastFree == NULL)		/* cache for next time */
465 		LastFree = rtmp;
466 	else				/* already one cached; free this one */
467 		free((char *)rtmp);
468 }
469 
470 /*
471 **  FreeConns -- free linked list of RMPCONN connections.
472 **
473 **	Parameters:
474 **		None.
475 **
476 **	Returns:
477 **		Nothing.
478 **
479 **	Side Effects:
480 **		- All malloc'd memory associated with the linked list of
481 **		  connections will be free'd; `RmpConns' will be set to NULL.
482 **		- If LastFree is != NULL, it too will be free'd & NULL'd.
483 **
484 **	Warnings:
485 **		- This routine must be called with SIGHUP blocked.
486 */
487 void
488 FreeConns()
489 {
490 	RMPCONN *rtmp;
491 
492 	while (RmpConns != NULL) {
493 		rtmp = RmpConns;
494 		RmpConns = RmpConns->next;
495 		FreeConn(rtmp);
496 	}
497 
498 	if (LastFree != NULL) {
499 		free((char *)LastFree);
500 		LastFree = NULL;
501 	}
502 }
503 
504 /*
505 **  AddConn -- Add a connection to the linked list of connections.
506 **
507 **	Parameters:
508 **		rconn - connection to be added.
509 **
510 **	Returns:
511 **		Nothing.
512 **
513 **	Side Effects:
514 **		- RmpConn will point to new connection.
515 **
516 **	Warnings:
517 **		- This routine must be called with SIGHUP blocked.
518 */
519 void
520 AddConn(rconn)
521 	RMPCONN *rconn;
522 {
523 	if (RmpConns != NULL)
524 		rconn->next = RmpConns;
525 	RmpConns = rconn;
526 }
527 
528 /*
529 **  FindConn -- Find a connection in the linked list of connections.
530 **
531 **	We use the RMP (Ethernet) address as the basis for determining
532 **	if this is the same connection.  According to the Remote Maint
533 **	Protocol, we can only have one connection with any machine.
534 **
535 **	Parameters:
536 **		rconn - connection to be found.
537 **
538 **	Returns:
539 **		Matching connection from linked list or NULL if not found.
540 **
541 **	Side Effects:
542 **		None.
543 **
544 **	Warnings:
545 **		- This routine must be called with SIGHUP blocked.
546 */
547 RMPCONN *
548 FindConn(rconn)
549 	RMPCONN *rconn;
550 {
551 	RMPCONN *rtmp;
552 
553 	for (rtmp = RmpConns; rtmp != NULL; rtmp = rtmp->next)
554 		if (memcmp((char *)&rconn->rmp.hp_hdr.saddr[0],
555 		         (char *)&rtmp->rmp.hp_hdr.saddr[0], RMP_ADDRLEN) == 0)
556 			break;
557 
558 	return(rtmp);
559 }
560 
561 /*
562 **  RemoveConn -- Remove a connection from the linked list of connections.
563 **
564 **	Parameters:
565 **		rconn - connection to be removed.
566 **
567 **	Returns:
568 **		Nothing.
569 **
570 **	Side Effects:
571 **		- If found, an RMPCONN will cease to exist and it will
572 **		  be removed from the linked list.
573 **
574 **	Warnings:
575 **		- This routine must be called with SIGHUP blocked.
576 */
577 void
578 RemoveConn(rconn)
579 	RMPCONN *rconn;
580 {
581 	RMPCONN *thisrconn, *lastrconn;
582 
583 	if (RmpConns == rconn) {		/* easy case */
584 		RmpConns = RmpConns->next;
585 		FreeConn(rconn);
586 	} else {				/* must traverse linked list */
587 		lastrconn = RmpConns;			/* set back ptr */
588 		thisrconn = lastrconn->next;		/* set current ptr */
589 		while (thisrconn != NULL) {
590 			if (rconn == thisrconn) {		/* found it */
591 				lastrconn->next = thisrconn->next;
592 				FreeConn(thisrconn);
593 				break;
594 			}
595 			lastrconn = thisrconn;
596 			thisrconn = thisrconn->next;
597 		}
598 	}
599 }
600