]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/tcpdump/addrtoname.c
Copy elftoolchain binutils replacements from vendor branch
[FreeBSD/FreeBSD.git] / contrib / tcpdump / addrtoname.c
1 /*
2  * Copyright (c) 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that: (1) source code distributions
7  * retain the above copyright notice and this paragraph in its entirety, (2)
8  * distributions including binary code include the above copyright notice and
9  * this paragraph in its entirety in the documentation or other materials
10  * provided with the distribution, and (3) all advertising materials mentioning
11  * features or use of this software display the following acknowledgement:
12  * ``This product includes software developed by the University of California,
13  * Lawrence Berkeley Laboratory and its contributors.'' Neither the name of
14  * the University nor the names of its contributors may be used to endorse
15  * or promote products derived from this software without specific prior
16  * written permission.
17  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
18  * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
19  * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
20  *
21  *  Internet, ethernet, port, and protocol string to address
22  *  and address to string conversion routines
23  *
24  * $FreeBSD$
25  */
26 #ifndef lint
27 static const char rcsid[] _U_ =
28     "@(#) $Header: /tcpdump/master/tcpdump/addrtoname.c,v 1.119 2007-08-08 14:06:34 hannes Exp $ (LBL)";
29 #endif
30
31 #ifdef HAVE_CONFIG_H
32 #include "config.h"
33 #endif
34
35 #ifdef __FreeBSD__
36 #ifdef HAVE_LIBCAPSICUM
37 #include <libcapsicum.h>
38 #include <libcapsicum_dns.h>
39 #endif /* HAVE_LIBCAPSICUM */
40 #endif
41 #include <tcpdump-stdinc.h>
42
43 #ifdef USE_ETHER_NTOHOST
44 #ifdef HAVE_NETINET_IF_ETHER_H
45 struct mbuf;            /* Squelch compiler warnings on some platforms for */
46 struct rtentry;         /* declarations in <net/if.h> */
47 #include <net/if.h>     /* for "struct ifnet" in "struct arpcom" on Solaris */
48 #include <netinet/if_ether.h>
49 #endif /* HAVE_NETINET_IF_ETHER_H */
50 #ifdef NETINET_ETHER_H_DECLARES_ETHER_NTOHOST
51 #include <netinet/ether.h>
52 #endif /* NETINET_ETHER_H_DECLARES_ETHER_NTOHOST */
53
54 #if !defined(HAVE_DECL_ETHER_NTOHOST) || !HAVE_DECL_ETHER_NTOHOST
55 #ifndef HAVE_STRUCT_ETHER_ADDR
56 struct ether_addr {
57         unsigned char ether_addr_octet[6];
58 };
59 #endif
60 extern int ether_ntohost(char *, const struct ether_addr *);
61 #endif
62
63 #endif /* USE_ETHER_NTOHOST */
64
65 #include <pcap.h>
66 #include <pcap-namedb.h>
67 #include <signal.h>
68 #include <stdio.h>
69 #include <string.h>
70 #include <stdlib.h>
71
72 #include "interface.h"
73 #include "addrtoname.h"
74 #include "llc.h"
75 #include "setsignal.h"
76 #include "extract.h"
77 #include "oui.h"
78
79 #ifndef ETHER_ADDR_LEN
80 #define ETHER_ADDR_LEN  6
81 #endif
82
83 /*
84  * hash tables for whatever-to-name translations
85  *
86  * XXX there has to be error checks against strdup(3) failure
87  */
88
89 #define HASHNAMESIZE 4096
90
91 struct hnamemem {
92         u_int32_t addr;
93         const char *name;
94         struct hnamemem *nxt;
95 };
96
97 static struct hnamemem hnametable[HASHNAMESIZE];
98 static struct hnamemem tporttable[HASHNAMESIZE];
99 static struct hnamemem uporttable[HASHNAMESIZE];
100 static struct hnamemem eprototable[HASHNAMESIZE];
101 static struct hnamemem dnaddrtable[HASHNAMESIZE];
102 static struct hnamemem ipxsaptable[HASHNAMESIZE];
103
104 #if defined(INET6) && defined(WIN32)
105 /*
106  * fake gethostbyaddr for Win2k/XP
107  * gethostbyaddr() returns incorrect value when AF_INET6 is passed
108  * to 3rd argument.
109  *
110  * h_name in struct hostent is only valid.
111  */
112 static struct hostent *
113 win32_gethostbyaddr(const char *addr, int len, int type)
114 {
115         static struct hostent host;
116         static char hostbuf[NI_MAXHOST];
117         char hname[NI_MAXHOST];
118         struct sockaddr_in6 addr6;
119
120         host.h_name = hostbuf;
121         switch (type) {
122         case AF_INET:
123                 return gethostbyaddr(addr, len, type);
124                 break;
125         case AF_INET6:
126                 memset(&addr6, 0, sizeof(addr6));
127                 addr6.sin6_family = AF_INET6;
128                 memcpy(&addr6.sin6_addr, addr, len);
129                 if (getnameinfo((struct sockaddr *)&addr6, sizeof(addr6),
130                     hname, sizeof(hname), NULL, 0, 0)) {
131                         return NULL;
132                 } else {
133                         strcpy(host.h_name, hname);
134                         return &host;
135                 }
136                 break;
137         default:
138                 return NULL;
139         }
140 }
141 #define gethostbyaddr win32_gethostbyaddr
142 #endif /* INET6 & WIN32 */
143
144 #ifdef INET6
145 struct h6namemem {
146         struct in6_addr addr;
147         char *name;
148         struct h6namemem *nxt;
149 };
150
151 static struct h6namemem h6nametable[HASHNAMESIZE];
152 #endif /* INET6 */
153
154 struct enamemem {
155         u_short e_addr0;
156         u_short e_addr1;
157         u_short e_addr2;
158         const char *e_name;
159         u_char *e_nsap;                 /* used only for nsaptable[] */
160 #define e_bs e_nsap                     /* for bytestringtable */
161         struct enamemem *e_nxt;
162 };
163
164 static struct enamemem enametable[HASHNAMESIZE];
165 static struct enamemem nsaptable[HASHNAMESIZE];
166 static struct enamemem bytestringtable[HASHNAMESIZE];
167
168 struct protoidmem {
169         u_int32_t p_oui;
170         u_short p_proto;
171         const char *p_name;
172         struct protoidmem *p_nxt;
173 };
174
175 static struct protoidmem protoidtable[HASHNAMESIZE];
176
177 /*
178  * A faster replacement for inet_ntoa().
179  */
180 const char *
181 intoa(u_int32_t addr)
182 {
183         register char *cp;
184         register u_int byte;
185         register int n;
186         static char buf[sizeof(".xxx.xxx.xxx.xxx")];
187
188         NTOHL(addr);
189         cp = buf + sizeof(buf);
190         *--cp = '\0';
191
192         n = 4;
193         do {
194                 byte = addr & 0xff;
195                 *--cp = byte % 10 + '0';
196                 byte /= 10;
197                 if (byte > 0) {
198                         *--cp = byte % 10 + '0';
199                         byte /= 10;
200                         if (byte > 0)
201                                 *--cp = byte + '0';
202                 }
203                 *--cp = '.';
204                 addr >>= 8;
205         } while (--n > 0);
206
207         return cp + 1;
208 }
209
210 static u_int32_t f_netmask;
211 static u_int32_t f_localnet;
212 #ifdef HAVE_LIBCAPSICUM
213 extern cap_channel_t *capdns;
214 #endif
215
216 /*
217  * Return a name for the IP address pointed to by ap.  This address
218  * is assumed to be in network byte order.
219  *
220  * NOTE: ap is *NOT* necessarily part of the packet data (not even if
221  * this is being called with the "ipaddr_string()" macro), so you
222  * *CANNOT* use the TCHECK{2}/TTEST{2} macros on it.  Furthermore,
223  * even in cases where it *is* part of the packet data, the caller
224  * would still have to check for a null return value, even if it's
225  * just printing the return value with "%s" - not all versions of
226  * printf print "(null)" with "%s" and a null pointer, some of them
227  * don't check for a null pointer and crash in that case.
228  *
229  * The callers of this routine should, before handing this routine
230  * a pointer to packet data, be sure that the data is present in
231  * the packet buffer.  They should probably do those checks anyway,
232  * as other data at that layer might not be IP addresses, and it
233  * also needs to check whether they're present in the packet buffer.
234  */
235 const char *
236 getname(const u_char *ap)
237 {
238         register struct hostent *hp;
239         u_int32_t addr;
240         static struct hnamemem *p;              /* static for longjmp() */
241
242         memcpy(&addr, ap, sizeof(addr));
243         p = &hnametable[addr & (HASHNAMESIZE-1)];
244         for (; p->nxt; p = p->nxt) {
245                 if (p->addr == addr)
246                         return (p->name);
247         }
248         p->addr = addr;
249         p->nxt = newhnamemem();
250
251         /*
252          * Print names unless:
253          *      (1) -n was given.
254          *      (2) Address is foreign and -f was given. (If -f was not
255          *          given, f_netmask and f_localnet are 0 and the test
256          *          evaluates to true)
257          */
258         if (!nflag &&
259             (addr & f_netmask) == f_localnet) {
260 #ifdef HAVE_LIBCAPSICUM
261                 if (capdns != NULL) {
262                         hp = cap_gethostbyaddr(capdns, (char *)&addr, 4,
263                             AF_INET);
264                 } else
265 #endif
266                         hp = gethostbyaddr((char *)&addr, 4, AF_INET);
267                 if (hp) {
268                         char *dotp;
269
270                         p->name = strdup(hp->h_name);
271                         if (Nflag) {
272                                 /* Remove domain qualifications */
273                                 dotp = strchr(p->name, '.');
274                                 if (dotp)
275                                         *dotp = '\0';
276                         }
277                         return (p->name);
278                 }
279         }
280         p->name = strdup(intoa(addr));
281         return (p->name);
282 }
283
284 #ifdef INET6
285 /*
286  * Return a name for the IP6 address pointed to by ap.  This address
287  * is assumed to be in network byte order.
288  */
289 const char *
290 getname6(const u_char *ap)
291 {
292         register struct hostent *hp;
293         struct in6_addr addr;
294         static struct h6namemem *p;             /* static for longjmp() */
295         register const char *cp;
296         char ntop_buf[INET6_ADDRSTRLEN];
297
298         memcpy(&addr, ap, sizeof(addr));
299         p = &h6nametable[*(u_int16_t *)&addr.s6_addr[14] & (HASHNAMESIZE-1)];
300         for (; p->nxt; p = p->nxt) {
301                 if (memcmp(&p->addr, &addr, sizeof(addr)) == 0)
302                         return (p->name);
303         }
304         p->addr = addr;
305         p->nxt = newh6namemem();
306
307         /*
308          * Do not print names if -n was given.
309          */
310         if (!nflag) {
311 #ifdef HAVE_LIBCAPSICUM
312                 if (capdns != NULL) {
313                         hp = cap_gethostbyaddr(capdns, (char *)&addr,
314                             sizeof(addr), AF_INET6);
315                 } else
316 #endif
317                         hp = gethostbyaddr((char *)&addr, sizeof(addr), AF_INET6);
318                 if (hp) {
319                         char *dotp;
320
321                         p->name = strdup(hp->h_name);
322                         if (Nflag) {
323                                 /* Remove domain qualifications */
324                                 dotp = strchr(p->name, '.');
325                                 if (dotp)
326                                         *dotp = '\0';
327                         }
328                         return (p->name);
329                 }
330         }
331         cp = inet_ntop(AF_INET6, &addr, ntop_buf, sizeof(ntop_buf));
332         p->name = strdup(cp);
333         return (p->name);
334 }
335 #endif /* INET6 */
336
337 static const char hex[] = "0123456789abcdef";
338
339
340 /* Find the hash node that corresponds the ether address 'ep' */
341
342 static inline struct enamemem *
343 lookup_emem(const u_char *ep)
344 {
345         register u_int i, j, k;
346         struct enamemem *tp;
347
348         k = (ep[0] << 8) | ep[1];
349         j = (ep[2] << 8) | ep[3];
350         i = (ep[4] << 8) | ep[5];
351
352         tp = &enametable[(i ^ j) & (HASHNAMESIZE-1)];
353         while (tp->e_nxt)
354                 if (tp->e_addr0 == i &&
355                     tp->e_addr1 == j &&
356                     tp->e_addr2 == k)
357                         return tp;
358                 else
359                         tp = tp->e_nxt;
360         tp->e_addr0 = i;
361         tp->e_addr1 = j;
362         tp->e_addr2 = k;
363         tp->e_nxt = (struct enamemem *)calloc(1, sizeof(*tp));
364         if (tp->e_nxt == NULL)
365                 error("lookup_emem: calloc");
366
367         return tp;
368 }
369
370 /*
371  * Find the hash node that corresponds to the bytestring 'bs'
372  * with length 'nlen'
373  */
374
375 static inline struct enamemem *
376 lookup_bytestring(register const u_char *bs, const unsigned int nlen)
377 {
378         struct enamemem *tp;
379         register u_int i, j, k;
380
381         if (nlen >= 6) {
382                 k = (bs[0] << 8) | bs[1];
383                 j = (bs[2] << 8) | bs[3];
384                 i = (bs[4] << 8) | bs[5];
385         } else if (nlen >= 4) {
386                 k = (bs[0] << 8) | bs[1];
387                 j = (bs[2] << 8) | bs[3];
388                 i = 0;
389         } else
390                 i = j = k = 0;
391
392         tp = &bytestringtable[(i ^ j) & (HASHNAMESIZE-1)];
393         while (tp->e_nxt)
394                 if (tp->e_addr0 == i &&
395                     tp->e_addr1 == j &&
396                     tp->e_addr2 == k &&
397                     memcmp((const char *)bs, (const char *)(tp->e_bs), nlen) == 0)
398                         return tp;
399                 else
400                         tp = tp->e_nxt;
401
402         tp->e_addr0 = i;
403         tp->e_addr1 = j;
404         tp->e_addr2 = k;
405
406         tp->e_bs = (u_char *) calloc(1, nlen + 1);
407         if (tp->e_bs == NULL)
408                 error("lookup_bytestring: calloc");
409
410         memcpy(tp->e_bs, bs, nlen);
411         tp->e_nxt = (struct enamemem *)calloc(1, sizeof(*tp));
412         if (tp->e_nxt == NULL)
413                 error("lookup_bytestring: calloc");
414
415         return tp;
416 }
417
418 /* Find the hash node that corresponds the NSAP 'nsap' */
419
420 static inline struct enamemem *
421 lookup_nsap(register const u_char *nsap)
422 {
423         register u_int i, j, k;
424         unsigned int nlen = *nsap;
425         struct enamemem *tp;
426         const u_char *ensap = nsap + nlen - 6;
427
428         if (nlen > 6) {
429                 k = (ensap[0] << 8) | ensap[1];
430                 j = (ensap[2] << 8) | ensap[3];
431                 i = (ensap[4] << 8) | ensap[5];
432         }
433         else
434                 i = j = k = 0;
435
436         tp = &nsaptable[(i ^ j) & (HASHNAMESIZE-1)];
437         while (tp->e_nxt)
438                 if (tp->e_addr0 == i &&
439                     tp->e_addr1 == j &&
440                     tp->e_addr2 == k &&
441                     tp->e_nsap[0] == nlen &&
442                     memcmp((const char *)&(nsap[1]),
443                         (char *)&(tp->e_nsap[1]), nlen) == 0)
444                         return tp;
445                 else
446                         tp = tp->e_nxt;
447         tp->e_addr0 = i;
448         tp->e_addr1 = j;
449         tp->e_addr2 = k;
450         tp->e_nsap = (u_char *)malloc(nlen + 1);
451         if (tp->e_nsap == NULL)
452                 error("lookup_nsap: malloc");
453         memcpy((char *)tp->e_nsap, (const char *)nsap, nlen + 1);
454         tp->e_nxt = (struct enamemem *)calloc(1, sizeof(*tp));
455         if (tp->e_nxt == NULL)
456                 error("lookup_nsap: calloc");
457
458         return tp;
459 }
460
461 /* Find the hash node that corresponds the protoid 'pi'. */
462
463 static inline struct protoidmem *
464 lookup_protoid(const u_char *pi)
465 {
466         register u_int i, j;
467         struct protoidmem *tp;
468
469         /* 5 octets won't be aligned */
470         i = (((pi[0] << 8) + pi[1]) << 8) + pi[2];
471         j =   (pi[3] << 8) + pi[4];
472         /* XXX should be endian-insensitive, but do big-endian testing  XXX */
473
474         tp = &protoidtable[(i ^ j) & (HASHNAMESIZE-1)];
475         while (tp->p_nxt)
476                 if (tp->p_oui == i && tp->p_proto == j)
477                         return tp;
478                 else
479                         tp = tp->p_nxt;
480         tp->p_oui = i;
481         tp->p_proto = j;
482         tp->p_nxt = (struct protoidmem *)calloc(1, sizeof(*tp));
483         if (tp->p_nxt == NULL)
484                 error("lookup_protoid: calloc");
485
486         return tp;
487 }
488
489 const char *
490 etheraddr_string(register const u_char *ep)
491 {
492         register int i;
493         register char *cp;
494         register struct enamemem *tp;
495         int oui;
496         char buf[BUFSIZE];
497
498         tp = lookup_emem(ep);
499         if (tp->e_name)
500                 return (tp->e_name);
501 #ifdef USE_ETHER_NTOHOST
502         if (!nflag) {
503                 char buf2[BUFSIZE];
504
505                 /*
506                  * We don't cast it to "const struct ether_addr *"
507                  * because some systems fail to declare the second
508                  * argument as a "const" pointer, even though they
509                  * don't modify what it points to.
510                  */
511                 if (ether_ntohost(buf2, (struct ether_addr *)ep) == 0) {
512                         tp->e_name = strdup(buf2);
513                         return (tp->e_name);
514                 }
515         }
516 #endif
517         cp = buf;
518         oui = EXTRACT_24BITS(ep);
519         *cp++ = hex[*ep >> 4 ];
520         *cp++ = hex[*ep++ & 0xf];
521         for (i = 5; --i >= 0;) {
522                 *cp++ = ':';
523                 *cp++ = hex[*ep >> 4 ];
524                 *cp++ = hex[*ep++ & 0xf];
525         }
526
527         if (!nflag) {
528                 snprintf(cp, BUFSIZE - (2 + 5*3), " (oui %s)",
529                     tok2str(oui_values, "Unknown", oui));
530         } else
531                 *cp = '\0';
532         tp->e_name = strdup(buf);
533         return (tp->e_name);
534 }
535
536 const char *
537 le64addr_string(const u_char *ep)
538 {
539         const unsigned int len = 8;
540         register u_int i;
541         register char *cp;
542         register struct enamemem *tp;
543         char buf[BUFSIZE];
544
545         tp = lookup_bytestring(ep, len);
546         if (tp->e_name)
547                 return (tp->e_name);
548
549         cp = buf;
550         for (i = len; i > 0 ; --i) {
551                 *cp++ = hex[*(ep + i - 1) >> 4];
552                 *cp++ = hex[*(ep + i - 1) & 0xf];
553                 *cp++ = ':';
554         }
555         cp --;
556
557         *cp = '\0';
558
559         tp->e_name = strdup(buf);
560
561         return (tp->e_name);
562 }
563
564 const char *
565 linkaddr_string(const u_char *ep, const unsigned int type, const unsigned int len)
566 {
567         register u_int i;
568         register char *cp;
569         register struct enamemem *tp;
570
571         if (len == 0)
572                 return ("<empty>");
573
574         if (type == LINKADDR_ETHER && len == ETHER_ADDR_LEN)
575                 return (etheraddr_string(ep));
576
577         if (type == LINKADDR_FRELAY)
578                 return (q922_string(ep));
579
580         tp = lookup_bytestring(ep, len);
581         if (tp->e_name)
582                 return (tp->e_name);
583
584         tp->e_name = cp = (char *)malloc(len*3);
585         if (tp->e_name == NULL)
586                 error("linkaddr_string: malloc");
587         *cp++ = hex[*ep >> 4];
588         *cp++ = hex[*ep++ & 0xf];
589         for (i = len-1; i > 0 ; --i) {
590                 *cp++ = ':';
591                 *cp++ = hex[*ep >> 4];
592                 *cp++ = hex[*ep++ & 0xf];
593         }
594         *cp = '\0';
595         return (tp->e_name);
596 }
597
598 const char *
599 etherproto_string(u_short port)
600 {
601         register char *cp;
602         register struct hnamemem *tp;
603         register u_int32_t i = port;
604         char buf[sizeof("0000")];
605
606         for (tp = &eprototable[i & (HASHNAMESIZE-1)]; tp->nxt; tp = tp->nxt)
607                 if (tp->addr == i)
608                         return (tp->name);
609
610         tp->addr = i;
611         tp->nxt = newhnamemem();
612
613         cp = buf;
614         NTOHS(port);
615         *cp++ = hex[port >> 12 & 0xf];
616         *cp++ = hex[port >> 8 & 0xf];
617         *cp++ = hex[port >> 4 & 0xf];
618         *cp++ = hex[port & 0xf];
619         *cp++ = '\0';
620         tp->name = strdup(buf);
621         return (tp->name);
622 }
623
624 const char *
625 protoid_string(register const u_char *pi)
626 {
627         register u_int i, j;
628         register char *cp;
629         register struct protoidmem *tp;
630         char buf[sizeof("00:00:00:00:00")];
631
632         tp = lookup_protoid(pi);
633         if (tp->p_name)
634                 return tp->p_name;
635
636         cp = buf;
637         if ((j = *pi >> 4) != 0)
638                 *cp++ = hex[j];
639         *cp++ = hex[*pi++ & 0xf];
640         for (i = 4; (int)--i >= 0;) {
641                 *cp++ = ':';
642                 if ((j = *pi >> 4) != 0)
643                         *cp++ = hex[j];
644                 *cp++ = hex[*pi++ & 0xf];
645         }
646         *cp = '\0';
647         tp->p_name = strdup(buf);
648         return (tp->p_name);
649 }
650
651 #define ISONSAP_MAX_LENGTH 20
652 const char *
653 isonsap_string(const u_char *nsap, register u_int nsap_length)
654 {
655         register u_int nsap_idx;
656         register char *cp;
657         register struct enamemem *tp;
658
659         if (nsap_length < 1 || nsap_length > ISONSAP_MAX_LENGTH)
660                 return ("isonsap_string: illegal length");
661
662         tp = lookup_nsap(nsap);
663         if (tp->e_name)
664                 return tp->e_name;
665
666         tp->e_name = cp = (char *)malloc(sizeof("xx.xxxx.xxxx.xxxx.xxxx.xxxx.xxxx.xxxx.xxxx.xxxx.xx"));
667         if (cp == NULL)
668                 error("isonsap_string: malloc");
669
670         for (nsap_idx = 0; nsap_idx < nsap_length; nsap_idx++) {
671                 *cp++ = hex[*nsap >> 4];
672                 *cp++ = hex[*nsap++ & 0xf];
673                 if (((nsap_idx & 1) == 0) &&
674                      (nsap_idx + 1 < nsap_length)) {
675                         *cp++ = '.';
676                 }
677         }
678         *cp = '\0';
679         return (tp->e_name);
680 }
681
682 const char *
683 tcpport_string(u_short port)
684 {
685         register struct hnamemem *tp;
686         register u_int32_t i = port;
687         char buf[sizeof("00000")];
688
689         for (tp = &tporttable[i & (HASHNAMESIZE-1)]; tp->nxt; tp = tp->nxt)
690                 if (tp->addr == i)
691                         return (tp->name);
692
693         tp->addr = i;
694         tp->nxt = newhnamemem();
695
696         (void)snprintf(buf, sizeof(buf), "%u", i);
697         tp->name = strdup(buf);
698         return (tp->name);
699 }
700
701 const char *
702 udpport_string(register u_short port)
703 {
704         register struct hnamemem *tp;
705         register u_int32_t i = port;
706         char buf[sizeof("00000")];
707
708         for (tp = &uporttable[i & (HASHNAMESIZE-1)]; tp->nxt; tp = tp->nxt)
709                 if (tp->addr == i)
710                         return (tp->name);
711
712         tp->addr = i;
713         tp->nxt = newhnamemem();
714
715         (void)snprintf(buf, sizeof(buf), "%u", i);
716         tp->name = strdup(buf);
717         return (tp->name);
718 }
719
720 const char *
721 ipxsap_string(u_short port)
722 {
723         register char *cp;
724         register struct hnamemem *tp;
725         register u_int32_t i = port;
726         char buf[sizeof("0000")];
727
728         for (tp = &ipxsaptable[i & (HASHNAMESIZE-1)]; tp->nxt; tp = tp->nxt)
729                 if (tp->addr == i)
730                         return (tp->name);
731
732         tp->addr = i;
733         tp->nxt = newhnamemem();
734
735         cp = buf;
736         NTOHS(port);
737         *cp++ = hex[port >> 12 & 0xf];
738         *cp++ = hex[port >> 8 & 0xf];
739         *cp++ = hex[port >> 4 & 0xf];
740         *cp++ = hex[port & 0xf];
741         *cp++ = '\0';
742         tp->name = strdup(buf);
743         return (tp->name);
744 }
745
746 static void
747 init_servarray(void)
748 {
749         struct servent *sv;
750         register struct hnamemem *table;
751         register int i;
752         char buf[sizeof("0000000000")];
753
754         while ((sv = getservent()) != NULL) {
755                 int port = ntohs(sv->s_port);
756                 i = port & (HASHNAMESIZE-1);
757                 if (strcmp(sv->s_proto, "tcp") == 0)
758                         table = &tporttable[i];
759                 else if (strcmp(sv->s_proto, "udp") == 0)
760                         table = &uporttable[i];
761                 else
762                         continue;
763
764                 while (table->name)
765                         table = table->nxt;
766                 if (nflag) {
767                         (void)snprintf(buf, sizeof(buf), "%d", port);
768                         table->name = strdup(buf);
769                 } else
770                         table->name = strdup(sv->s_name);
771                 table->addr = port;
772                 table->nxt = newhnamemem();
773         }
774         endservent();
775 }
776
777 /* in libpcap.a (nametoaddr.c) */
778 #if defined(WIN32) && !defined(USE_STATIC_LIBPCAP)
779 __declspec(dllimport)
780 #else
781 extern
782 #endif
783 const struct eproto {
784         const char *s;
785         u_short p;
786 } eproto_db[];
787
788 static void
789 init_eprotoarray(void)
790 {
791         register int i;
792         register struct hnamemem *table;
793
794         for (i = 0; eproto_db[i].s; i++) {
795                 int j = htons(eproto_db[i].p) & (HASHNAMESIZE-1);
796                 table = &eprototable[j];
797                 while (table->name)
798                         table = table->nxt;
799                 table->name = eproto_db[i].s;
800                 table->addr = htons(eproto_db[i].p);
801                 table->nxt = newhnamemem();
802         }
803 }
804
805 static const struct protoidlist {
806         const u_char protoid[5];
807         const char *name;
808 } protoidlist[] = {
809         {{ 0x00, 0x00, 0x0c, 0x01, 0x07 }, "CiscoMLS" },
810         {{ 0x00, 0x00, 0x0c, 0x20, 0x00 }, "CiscoCDP" },
811         {{ 0x00, 0x00, 0x0c, 0x20, 0x01 }, "CiscoCGMP" },
812         {{ 0x00, 0x00, 0x0c, 0x20, 0x03 }, "CiscoVTP" },
813         {{ 0x00, 0xe0, 0x2b, 0x00, 0xbb }, "ExtremeEDP" },
814         {{ 0x00, 0x00, 0x00, 0x00, 0x00 }, NULL }
815 };
816
817 /*
818  * SNAP proto IDs with org code 0:0:0 are actually encapsulated Ethernet
819  * types.
820  */
821 static void
822 init_protoidarray(void)
823 {
824         register int i;
825         register struct protoidmem *tp;
826         const struct protoidlist *pl;
827         u_char protoid[5];
828
829         protoid[0] = 0;
830         protoid[1] = 0;
831         protoid[2] = 0;
832         for (i = 0; eproto_db[i].s; i++) {
833                 u_short etype = htons(eproto_db[i].p);
834
835                 memcpy((char *)&protoid[3], (char *)&etype, 2);
836                 tp = lookup_protoid(protoid);
837                 tp->p_name = strdup(eproto_db[i].s);
838         }
839         /* Hardwire some SNAP proto ID names */
840         for (pl = protoidlist; pl->name != NULL; ++pl) {
841                 tp = lookup_protoid(pl->protoid);
842                 /* Don't override existing name */
843                 if (tp->p_name != NULL)
844                         continue;
845
846                 tp->p_name = pl->name;
847         }
848 }
849
850 static const struct etherlist {
851         const u_char addr[6];
852         const char *name;
853 } etherlist[] = {
854         {{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }, "Broadcast" },
855         {{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, NULL }
856 };
857
858 /*
859  * Initialize the ethers hash table.  We take two different approaches
860  * depending on whether or not the system provides the ethers name
861  * service.  If it does, we just wire in a few names at startup,
862  * and etheraddr_string() fills in the table on demand.  If it doesn't,
863  * then we suck in the entire /etc/ethers file at startup.  The idea
864  * is that parsing the local file will be fast, but spinning through
865  * all the ethers entries via NIS & next_etherent might be very slow.
866  *
867  * XXX pcap_next_etherent doesn't belong in the pcap interface, but
868  * since the pcap module already does name-to-address translation,
869  * it's already does most of the work for the ethernet address-to-name
870  * translation, so we just pcap_next_etherent as a convenience.
871  */
872 static void
873 init_etherarray(void)
874 {
875         register const struct etherlist *el;
876         register struct enamemem *tp;
877 #ifdef USE_ETHER_NTOHOST
878         char name[256];
879 #else
880         register struct pcap_etherent *ep;
881         register FILE *fp;
882
883         /* Suck in entire ethers file */
884         fp = fopen(PCAP_ETHERS_FILE, "r");
885         if (fp != NULL) {
886                 while ((ep = pcap_next_etherent(fp)) != NULL) {
887                         tp = lookup_emem(ep->addr);
888                         tp->e_name = strdup(ep->name);
889                 }
890                 (void)fclose(fp);
891         }
892 #endif
893
894         /* Hardwire some ethernet names */
895         for (el = etherlist; el->name != NULL; ++el) {
896                 tp = lookup_emem(el->addr);
897                 /* Don't override existing name */
898                 if (tp->e_name != NULL)
899                         continue;
900
901 #ifdef USE_ETHER_NTOHOST
902                 /*
903                  * Use YP/NIS version of name if available.
904                  *
905                  * We don't cast it to "const struct ether_addr *"
906                  * because some systems don't modify the Ethernet
907                  * address but fail to declare the second argument
908                  * as a "const" pointer.
909                  */
910                 if (ether_ntohost(name, (struct ether_addr *)el->addr) == 0) {
911                         tp->e_name = strdup(name);
912                         continue;
913                 }
914 #endif
915                 tp->e_name = el->name;
916         }
917 }
918
919 static const struct tok ipxsap_db[] = {
920         { 0x0000, "Unknown" },
921         { 0x0001, "User" },
922         { 0x0002, "User Group" },
923         { 0x0003, "PrintQueue" },
924         { 0x0004, "FileServer" },
925         { 0x0005, "JobServer" },
926         { 0x0006, "Gateway" },
927         { 0x0007, "PrintServer" },
928         { 0x0008, "ArchiveQueue" },
929         { 0x0009, "ArchiveServer" },
930         { 0x000a, "JobQueue" },
931         { 0x000b, "Administration" },
932         { 0x000F, "Novell TI-RPC" },
933         { 0x0017, "Diagnostics" },
934         { 0x0020, "NetBIOS" },
935         { 0x0021, "NAS SNA Gateway" },
936         { 0x0023, "NACS AsyncGateway" },
937         { 0x0024, "RemoteBridge/RoutingService" },
938         { 0x0026, "BridgeServer" },
939         { 0x0027, "TCP/IP Gateway" },
940         { 0x0028, "Point-to-point X.25 BridgeServer" },
941         { 0x0029, "3270 Gateway" },
942         { 0x002a, "CHI Corp" },
943         { 0x002c, "PC Chalkboard" },
944         { 0x002d, "TimeSynchServer" },
945         { 0x002e, "ARCserve5.0/PalindromeBackup" },
946         { 0x0045, "DI3270 Gateway" },
947         { 0x0047, "AdvertisingPrintServer" },
948         { 0x004a, "NetBlazerModems" },
949         { 0x004b, "BtrieveVAP" },
950         { 0x004c, "NetwareSQL" },
951         { 0x004d, "XtreeNetwork" },
952         { 0x0050, "BtrieveVAP4.11" },
953         { 0x0052, "QuickLink" },
954         { 0x0053, "PrintQueueUser" },
955         { 0x0058, "Multipoint X.25 Router" },
956         { 0x0060, "STLB/NLM" },
957         { 0x0064, "ARCserve" },
958         { 0x0066, "ARCserve3.0" },
959         { 0x0072, "WAN CopyUtility" },
960         { 0x007a, "TES-NetwareVMS" },
961         { 0x0092, "WATCOM Debugger/EmeraldTapeBackupServer" },
962         { 0x0095, "DDA OBGYN" },
963         { 0x0098, "NetwareAccessServer" },
964         { 0x009a, "Netware for VMS II/NamedPipeServer" },
965         { 0x009b, "NetwareAccessServer" },
966         { 0x009e, "PortableNetwareServer/SunLinkNVT" },
967         { 0x00a1, "PowerchuteAPC UPS" },
968         { 0x00aa, "LAWserve" },
969         { 0x00ac, "CompaqIDA StatusMonitor" },
970         { 0x0100, "PIPE STAIL" },
971         { 0x0102, "LAN ProtectBindery" },
972         { 0x0103, "OracleDataBaseServer" },
973         { 0x0107, "Netware386/RSPX RemoteConsole" },
974         { 0x010f, "NovellSNA Gateway" },
975         { 0x0111, "TestServer" },
976         { 0x0112, "HP PrintServer" },
977         { 0x0114, "CSA MUX" },
978         { 0x0115, "CSA LCA" },
979         { 0x0116, "CSA CM" },
980         { 0x0117, "CSA SMA" },
981         { 0x0118, "CSA DBA" },
982         { 0x0119, "CSA NMA" },
983         { 0x011a, "CSA SSA" },
984         { 0x011b, "CSA STATUS" },
985         { 0x011e, "CSA APPC" },
986         { 0x0126, "SNA TEST SSA Profile" },
987         { 0x012a, "CSA TRACE" },
988         { 0x012b, "NetwareSAA" },
989         { 0x012e, "IKARUS VirusScan" },
990         { 0x0130, "CommunicationsExecutive" },
991         { 0x0133, "NNS DomainServer/NetwareNamingServicesDomain" },
992         { 0x0135, "NetwareNamingServicesProfile" },
993         { 0x0137, "Netware386 PrintQueue/NNS PrintQueue" },
994         { 0x0141, "LAN SpoolServer" },
995         { 0x0152, "IRMALAN Gateway" },
996         { 0x0154, "NamedPipeServer" },
997         { 0x0166, "NetWareManagement" },
998         { 0x0168, "Intel PICKIT CommServer/Intel CAS TalkServer" },
999         { 0x0173, "Compaq" },
1000         { 0x0174, "Compaq SNMP Agent" },
1001         { 0x0175, "Compaq" },
1002         { 0x0180, "XTreeServer/XTreeTools" },
1003         { 0x018A, "NASI ServicesBroadcastServer" },
1004         { 0x01b0, "GARP Gateway" },
1005         { 0x01b1, "Binfview" },
1006         { 0x01bf, "IntelLanDeskManager" },
1007         { 0x01ca, "AXTEC" },
1008         { 0x01cb, "ShivaNetModem/E" },
1009         { 0x01cc, "ShivaLanRover/E" },
1010         { 0x01cd, "ShivaLanRover/T" },
1011         { 0x01ce, "ShivaUniversal" },
1012         { 0x01d8, "CastelleFAXPressServer" },
1013         { 0x01da, "CastelleLANPressPrintServer" },
1014         { 0x01dc, "CastelleFAX/Xerox7033 FaxServer/ExcelLanFax" },
1015         { 0x01f0, "LEGATO" },
1016         { 0x01f5, "LEGATO" },
1017         { 0x0233, "NMS Agent/NetwareManagementAgent" },
1018         { 0x0237, "NMS IPX Discovery/LANternReadWriteChannel" },
1019         { 0x0238, "NMS IP Discovery/LANternTrapAlarmChannel" },
1020         { 0x023a, "LANtern" },
1021         { 0x023c, "MAVERICK" },
1022         { 0x023f, "NovellSMDR" },
1023         { 0x024e, "NetwareConnect" },
1024         { 0x024f, "NASI ServerBroadcast Cisco" },
1025         { 0x026a, "NMS ServiceConsole" },
1026         { 0x026b, "TimeSynchronizationServer Netware 4.x" },
1027         { 0x0278, "DirectoryServer Netware 4.x" },
1028         { 0x027b, "NetwareManagementAgent" },
1029         { 0x0280, "Novell File and Printer Sharing Service for PC" },
1030         { 0x0304, "NovellSAA Gateway" },
1031         { 0x0308, "COM/VERMED" },
1032         { 0x030a, "GalacticommWorldgroupServer" },
1033         { 0x030c, "IntelNetport2/HP JetDirect/HP Quicksilver" },
1034         { 0x0320, "AttachmateGateway" },
1035         { 0x0327, "MicrosoftDiagnostiocs" },
1036         { 0x0328, "WATCOM SQL Server" },
1037         { 0x0335, "MultiTechSystems MultisynchCommServer" },
1038         { 0x0343, "Xylogics RemoteAccessServer/LANModem" },
1039         { 0x0355, "ArcadaBackupExec" },
1040         { 0x0358, "MSLCD1" },
1041         { 0x0361, "NETINELO" },
1042         { 0x037e, "Powerchute UPS Monitoring" },
1043         { 0x037f, "ViruSafeNotify" },
1044         { 0x0386, "HP Bridge" },
1045         { 0x0387, "HP Hub" },
1046         { 0x0394, "NetWare SAA Gateway" },
1047         { 0x039b, "LotusNotes" },
1048         { 0x03b7, "CertusAntiVirus" },
1049         { 0x03c4, "ARCserve4.0" },
1050         { 0x03c7, "LANspool3.5" },
1051         { 0x03d7, "LexmarkPrinterServer" },
1052         { 0x03d8, "LexmarkXLE PrinterServer" },
1053         { 0x03dd, "BanyanENS NetwareClient" },
1054         { 0x03de, "GuptaSequelBaseServer/NetWareSQL" },
1055         { 0x03e1, "UnivelUnixware" },
1056         { 0x03e4, "UnivelUnixware" },
1057         { 0x03fc, "IntelNetport" },
1058         { 0x03fd, "PrintServerQueue" },
1059         { 0x040A, "ipnServer" },
1060         { 0x040D, "LVERRMAN" },
1061         { 0x040E, "LVLIC" },
1062         { 0x0414, "NET Silicon (DPI)/Kyocera" },
1063         { 0x0429, "SiteLockVirus" },
1064         { 0x0432, "UFHELPR???" },
1065         { 0x0433, "Synoptics281xAdvancedSNMPAgent" },
1066         { 0x0444, "MicrosoftNT SNA Server" },
1067         { 0x0448, "Oracle" },
1068         { 0x044c, "ARCserve5.01" },
1069         { 0x0457, "CanonGP55" },
1070         { 0x045a, "QMS Printers" },
1071         { 0x045b, "DellSCSI Array" },
1072         { 0x0491, "NetBlazerModems" },
1073         { 0x04ac, "OnTimeScheduler" },
1074         { 0x04b0, "CD-Net" },
1075         { 0x0513, "EmulexNQA" },
1076         { 0x0520, "SiteLockChecks" },
1077         { 0x0529, "SiteLockChecks" },
1078         { 0x052d, "CitrixOS2 AppServer" },
1079         { 0x0535, "Tektronix" },
1080         { 0x0536, "Milan" },
1081         { 0x055d, "Attachmate SNA gateway" },
1082         { 0x056b, "IBM8235 ModemServer" },
1083         { 0x056c, "ShivaLanRover/E PLUS" },
1084         { 0x056d, "ShivaLanRover/T PLUS" },
1085         { 0x0580, "McAfeeNetShield" },
1086         { 0x05B8, "NLM to workstation communication (Revelation Software)" },
1087         { 0x05BA, "CompatibleSystemsRouters" },
1088         { 0x05BE, "CheyenneHierarchicalStorageManager" },
1089         { 0x0606, "JCWatermarkImaging" },
1090         { 0x060c, "AXISNetworkPrinter" },
1091         { 0x0610, "AdaptecSCSIManagement" },
1092         { 0x0621, "IBM AntiVirus" },
1093         { 0x0640, "Windows95 RemoteRegistryService" },
1094         { 0x064e, "MicrosoftIIS" },
1095         { 0x067b, "Microsoft Win95/98 File and Print Sharing for NetWare" },
1096         { 0x067c, "Microsoft Win95/98 File and Print Sharing for NetWare" },
1097         { 0x076C, "Xerox" },
1098         { 0x079b, "ShivaLanRover/E 115" },
1099         { 0x079c, "ShivaLanRover/T 115" },
1100         { 0x07B4, "CubixWorldDesk" },
1101         { 0x07c2, "Quarterdeck IWare Connect V2.x NLM" },
1102         { 0x07c1, "Quarterdeck IWare Connect V3.x NLM" },
1103         { 0x0810, "ELAN License Server Demo" },
1104         { 0x0824, "ShivaLanRoverAccessSwitch/E" },
1105         { 0x086a, "ISSC Collector" },
1106         { 0x087f, "ISSC DAS AgentAIX" },
1107         { 0x0880, "Intel Netport PRO" },
1108         { 0x0881, "Intel Netport PRO" },
1109         { 0x0b29, "SiteLock" },
1110         { 0x0c29, "SiteLockApplications" },
1111         { 0x0c2c, "LicensingServer" },
1112         { 0x2101, "PerformanceTechnologyInstantInternet" },
1113         { 0x2380, "LAI SiteLock" },
1114         { 0x238c, "MeetingMaker" },
1115         { 0x4808, "SiteLockServer/SiteLockMetering" },
1116         { 0x5555, "SiteLockUser" },
1117         { 0x6312, "Tapeware" },
1118         { 0x6f00, "RabbitGateway" },
1119         { 0x7703, "MODEM" },
1120         { 0x8002, "NetPortPrinters" },
1121         { 0x8008, "WordPerfectNetworkVersion" },
1122         { 0x85BE, "Cisco EIGRP" },
1123         { 0x8888, "WordPerfectNetworkVersion/QuickNetworkManagement" },
1124         { 0x9000, "McAfeeNetShield" },
1125         { 0x9604, "CSA-NT_MON" },
1126         { 0xb6a8, "OceanIsleReachoutRemoteControl" },
1127         { 0xf11f, "SiteLockMetering" },
1128         { 0xf1ff, "SiteLock" },
1129         { 0xf503, "Microsoft SQL Server" },
1130         { 0xF905, "IBM TimeAndPlace" },
1131         { 0xfbfb, "TopCallIII FaxServer" },
1132         { 0xffff, "AnyService/Wildcard" },
1133         { 0, (char *)0 }
1134 };
1135
1136 static void
1137 init_ipxsaparray(void)
1138 {
1139         register int i;
1140         register struct hnamemem *table;
1141
1142         for (i = 0; ipxsap_db[i].s != NULL; i++) {
1143                 int j = htons(ipxsap_db[i].v) & (HASHNAMESIZE-1);
1144                 table = &ipxsaptable[j];
1145                 while (table->name)
1146                         table = table->nxt;
1147                 table->name = ipxsap_db[i].s;
1148                 table->addr = htons(ipxsap_db[i].v);
1149                 table->nxt = newhnamemem();
1150         }
1151 }
1152
1153 /*
1154  * Initialize the address to name translation machinery.  We map all
1155  * non-local IP addresses to numeric addresses if fflag is true (i.e.,
1156  * to prevent blocking on the nameserver).  localnet is the IP address
1157  * of the local network.  mask is its subnet mask.
1158  */
1159 void
1160 init_addrtoname(u_int32_t localnet, u_int32_t mask)
1161 {
1162         if (fflag) {
1163                 f_localnet = localnet;
1164                 f_netmask = mask;
1165         }
1166         if (nflag)
1167                 /*
1168                  * Simplest way to suppress names.
1169                  */
1170                 return;
1171
1172         init_etherarray();
1173         init_servarray();
1174         init_eprotoarray();
1175         init_protoidarray();
1176         init_ipxsaparray();
1177 }
1178
1179 const char *
1180 dnaddr_string(u_short dnaddr)
1181 {
1182         register struct hnamemem *tp;
1183
1184         for (tp = &dnaddrtable[dnaddr & (HASHNAMESIZE-1)]; tp->nxt != 0;
1185              tp = tp->nxt)
1186                 if (tp->addr == dnaddr)
1187                         return (tp->name);
1188
1189         tp->addr = dnaddr;
1190         tp->nxt = newhnamemem();
1191         if (nflag)
1192                 tp->name = dnnum_string(dnaddr);
1193         else
1194                 tp->name = dnname_string(dnaddr);
1195
1196         return(tp->name);
1197 }
1198
1199 /* Return a zero'ed hnamemem struct and cuts down on calloc() overhead */
1200 struct hnamemem *
1201 newhnamemem(void)
1202 {
1203         register struct hnamemem *p;
1204         static struct hnamemem *ptr = NULL;
1205         static u_int num = 0;
1206
1207         if (num  <= 0) {
1208                 num = 64;
1209                 ptr = (struct hnamemem *)calloc(num, sizeof (*ptr));
1210                 if (ptr == NULL)
1211                         error("newhnamemem: calloc");
1212         }
1213         --num;
1214         p = ptr++;
1215         return (p);
1216 }
1217
1218 #ifdef INET6
1219 /* Return a zero'ed h6namemem struct and cuts down on calloc() overhead */
1220 struct h6namemem *
1221 newh6namemem(void)
1222 {
1223         register struct h6namemem *p;
1224         static struct h6namemem *ptr = NULL;
1225         static u_int num = 0;
1226
1227         if (num  <= 0) {
1228                 num = 64;
1229                 ptr = (struct h6namemem *)calloc(num, sizeof (*ptr));
1230                 if (ptr == NULL)
1231                         error("newh6namemem: calloc");
1232         }
1233         --num;
1234         p = ptr++;
1235         return (p);
1236 }
1237 #endif /* INET6 */