xref: /freebsd/libexec/rbootd/utils.c (revision 44d4804d1945435745518cd09eb8ae6ab22ecef4)
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: @(#)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 #ifndef lint
46 #if 0
47 static const char sccsid[] = "@(#)utils.c	8.1 (Berkeley) 6/4/93";
48 #endif
49 static const char rcsid[] =
50   "$FreeBSD$";
51 #endif /* not lint */
52 
53 #include <sys/param.h>
54 #include <sys/time.h>
55 #include <netinet/in.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
81 DispPkt(RMPCONN *rconn, int direct)
82 {
83 	static const char BootFmt[] = "\t\tRetCode:%u SeqNo:%x SessID:%x Vers:%u";
84 	static const char ReadFmt[] = "\t\tRetCode:%u Offset:%x 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, 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 			        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 			        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 			        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 			        t, ntohs(rmp->r_rrpl.rmp_session));
167 			(void) fprintf(DbgFp, "\t\tNoOfBytesSent: %zu\n",
168 			        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 *
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
248 DspFlnm(u_int size, char *flnm)
249 {
250 	int 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 *
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 **  FreeClient -- 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
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 *
330 NewStr(char *str)
331 {
332 	char *stmp;
333 
334 	if ((stmp = (char *)malloc((unsigned) (strlen(str)+1))) == NULL) {
335 		syslog(LOG_ERR, "NewStr: out of memory (%s)", str);
336 		return(NULL);
337 	}
338 
339 	(void) strcpy(stmp, str);
340 	return(stmp);
341 }
342 
343 /*
344 **  To save time, NewConn and FreeConn maintain a cache of one RMPCONN
345 **  in `LastFree' (defined below).
346 */
347 
348 static RMPCONN *LastFree = NULL;
349 
350 /*
351 **  NewConn -- allocate memory for a new RMPCONN connection.
352 **
353 **	Parameters:
354 **		rconn - initialization template for new connection.
355 **
356 **	Returns:
357 **		Ptr to new RMPCONN or NULL if we ran out of memory.
358 **
359 **	Side Effects:
360 **		- Memory may be malloc'd for the new RMPCONN (if not cached).
361 **		- If malloc() fails, a log message will be generated.
362 */
363 RMPCONN *
364 NewConn(RMPCONN *rconn)
365 {
366 	RMPCONN *rtmp;
367 
368 	if (LastFree == NULL) {		/* nothing cached; make a new one */
369 		if ((rtmp = (RMPCONN *) malloc(sizeof(RMPCONN))) == NULL) {
370 			syslog(LOG_ERR, "NewConn: out of memory (%s)",
371 			       EnetStr(rconn));
372 			return(NULL);
373 		}
374 	} else {			/* use the cached RMPCONN */
375 		rtmp = LastFree;
376 		LastFree = NULL;
377 	}
378 
379 	/*
380 	 *  Copy template into `rtmp', init file descriptor to `-1' and
381 	 *  set ptr to next elem NULL.
382 	 */
383 	memmove((char *)rtmp, (char *)rconn, sizeof(RMPCONN));
384 	rtmp->bootfd = -1;
385 	rtmp->next = NULL;
386 
387 	return(rtmp);
388 }
389 
390 /*
391 **  FreeConn -- Free memory associated with an RMPCONN connection.
392 **
393 **	Parameters:
394 **		rtmp - ptr to RMPCONN to be free'd.
395 **
396 **	Returns:
397 **		Nothing.
398 **
399 **	Side Effects:
400 **		- Memory associated with `rtmp' may be free'd (or cached).
401 **		- File desc associated with `rtmp->bootfd' will be closed.
402 */
403 void
404 FreeConn(RMPCONN *rtmp)
405 {
406 	/*
407 	 *  If the file descriptor is in use, close the file.
408 	 */
409 	if (rtmp->bootfd >= 0) {
410 		(void) close(rtmp->bootfd);
411 		rtmp->bootfd = -1;
412 	}
413 
414 	if (LastFree == NULL)		/* cache for next time */
415 		rtmp = LastFree;
416 	else				/* already one cached; free this one */
417 		free((char *)rtmp);
418 }
419 
420 /*
421 **  FreeConns -- free linked list of RMPCONN connections.
422 **
423 **	Parameters:
424 **		None.
425 **
426 **	Returns:
427 **		Nothing.
428 **
429 **	Side Effects:
430 **		- All malloc'd memory associated with the linked list of
431 **		  connections will be free'd; `RmpConns' will be set to NULL.
432 **		- If LastFree is != NULL, it too will be free'd & NULL'd.
433 **
434 **	Warnings:
435 **		- This routine must be called with SIGHUP blocked.
436 */
437 void
438 FreeConns(void)
439 {
440 	RMPCONN *rtmp;
441 
442 	while (RmpConns != NULL) {
443 		rtmp = RmpConns;
444 		RmpConns = RmpConns->next;
445 		FreeConn(rtmp);
446 	}
447 
448 	if (LastFree != NULL) {
449 		free((char *)LastFree);
450 		LastFree = NULL;
451 	}
452 }
453 
454 /*
455 **  AddConn -- Add a connection to the linked list of connections.
456 **
457 **	Parameters:
458 **		rconn - connection to be added.
459 **
460 **	Returns:
461 **		Nothing.
462 **
463 **	Side Effects:
464 **		- RmpConn will point to new connection.
465 **
466 **	Warnings:
467 **		- This routine must be called with SIGHUP blocked.
468 */
469 void
470 AddConn(RMPCONN *rconn)
471 {
472 	if (RmpConns != NULL)
473 		rconn->next = RmpConns;
474 	RmpConns = rconn;
475 }
476 
477 /*
478 **  FindConn -- Find a connection in the linked list of connections.
479 **
480 **	We use the RMP (Ethernet) address as the basis for determining
481 **	if this is the same connection.  According to the Remote Maint
482 **	Protocol, we can only have one connection with any machine.
483 **
484 **	Parameters:
485 **		rconn - connection to be found.
486 **
487 **	Returns:
488 **		Matching connection from linked list or NULL if not found.
489 **
490 **	Side Effects:
491 **		None.
492 **
493 **	Warnings:
494 **		- This routine must be called with SIGHUP blocked.
495 */
496 RMPCONN *
497 FindConn(RMPCONN *rconn)
498 {
499 	RMPCONN *rtmp;
500 
501 	for (rtmp = RmpConns; rtmp != NULL; rtmp = rtmp->next)
502 		if (bcmp((char *)&rconn->rmp.hp_hdr.saddr[0],
503 		         (char *)&rtmp->rmp.hp_hdr.saddr[0], RMP_ADDRLEN) == 0)
504 			break;
505 
506 	return(rtmp);
507 }
508 
509 /*
510 **  RemoveConn -- Remove a connection from the linked list of connections.
511 **
512 **	Parameters:
513 **		rconn - connection to be removed.
514 **
515 **	Returns:
516 **		Nothing.
517 **
518 **	Side Effects:
519 **		- If found, an RMPCONN will cease to exist and it will
520 **		  be removed from the linked list.
521 **
522 **	Warnings:
523 **		- This routine must be called with SIGHUP blocked.
524 */
525 void
526 RemoveConn(RMPCONN *rconn)
527 {
528 	RMPCONN *thisrconn, *lastrconn;
529 
530 	if (RmpConns == rconn) {		/* easy case */
531 		RmpConns = RmpConns->next;
532 		FreeConn(rconn);
533 	} else {				/* must traverse linked list */
534 		lastrconn = RmpConns;			/* set back ptr */
535 		thisrconn = lastrconn->next;		/* set current ptr */
536 		while (thisrconn != NULL) {
537 			if (rconn == thisrconn) {		/* found it */
538 				lastrconn->next = thisrconn->next;
539 				FreeConn(thisrconn);
540 				break;
541 			}
542 			lastrconn = thisrconn;
543 			thisrconn = thisrconn->next;
544 		}
545 	}
546 }
547