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