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