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