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