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