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