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