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