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