Ricardo Muggli:
[obnox/wireshark/wip.git] / epan / addr_resolv.c
1 /* addr_resolv.c
2  * Routines for network object lookup
3  *
4  * $Id$
5  *
6  * Laurent Deniel <laurent.deniel@free.fr>
7  *
8  * Ethereal - Network traffic analyzer
9  * By Gerald Combs <gerald@ethereal.com>
10  * Copyright 1998 Gerald Combs
11  *
12  * This program is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU General Public License
14  * as published by the Free Software Foundation; either version 2
15  * of the License, or (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
25  */
26
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
30
31 #include <ctype.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <errno.h>
36
37 /*
38  * Win32 doesn't have SIGALRM (and it's the OS where name lookup calls
39  * are most likely to take a long time, given the way address-to-name
40  * lookups are done over NBNS).
41  *
42  * Mac OS X does have SIGALRM, but if you longjmp() out of a name resolution
43  * call in a signal handler, you might crash, because the state of the
44  * resolution code that sends messages to lookupd might be inconsistent
45  * if you jump out of it in middle of a call.
46  *
47  * In at least some Linux distributions (e.g., RedHat Linux 9), if ADNS
48  * is used, we appear to hang in host_name_lookup6() in a gethostbyaddr()
49  * call (and possibly in other gethostbyaddr() calls), because there's
50  * a mutex lock held in gethostbyaddr() and it doesn't get released
51  * if we longjmp out of it.
52  *
53  * There's no guarantee that longjmp()ing out of name resolution calls
54  * will work on *any* platform; OpenBSD got rid of the alarm/longjmp
55  * code in tcpdump, to avoid those sorts of problems, and that was
56  * picked up by tcpdump.org tcpdump.
57  *
58  * So, for now, we do not define AVOID_DNS_TIMEOUT.  If we get a
59  * significantly more complaints about lookups taking a long time,
60  * we can reconsider that decision.  (Note that tcpdump originally
61  * added that for the benefit of systems using NIS to look up host
62  * names; that might now be fixed in NIS implementations, for those
63  * sites still using NIS rather than DNS for that....)
64  */
65
66 #ifdef HAVE_UNISTD_H
67 #include <unistd.h>
68 #endif
69
70 #ifdef HAVE_NETINET_IN_H
71 # include <netinet/in.h>
72 #endif
73
74 #ifdef HAVE_NETDB_H
75 #include <netdb.h>
76 #endif
77
78 #ifdef HAVE_ARPA_INET_H
79 #include <arpa/inet.h>
80 #endif
81
82 #include <signal.h>
83
84 #ifdef HAVE_SYS_SOCKET_H
85 #include <sys/socket.h>         /* needed to define AF_ values on UNIX */
86 #endif
87
88 #ifdef HAVE_WINSOCK2_H
89 #include <winsock2.h>           /* needed to define AF_ values on Windows */
90 #endif
91
92 #ifdef AVOID_DNS_TIMEOUT
93 # include <setjmp.h>
94 #endif
95
96 #ifdef NEED_INET_ATON_H
97 # include "inet_aton.h"
98 #endif
99
100 #ifdef NEED_INET_V6DEFS_H
101 # include "inet_v6defs.h"
102 #endif
103
104 #ifdef HAVE_GNU_ADNS
105 # include <errno.h>
106 # include <adns.h>
107 # ifdef inet_aton
108 #  undef inet_aton
109 # endif
110 #endif
111
112 #if defined(_WIN32) && defined(INET6)
113 # include <ws2tcpip.h>
114 #endif
115
116 #include <glib.h>
117
118 #include "report_err.h"
119 #include "packet.h"
120 #include "ipv6-utils.h"
121 #include "addr_resolv.h"
122 #include "filesystem.h"
123 #include <wiretap/file_util.h>
124 #include <epan/prefs.h>
125 #include <epan/emem.h>
126
127 #define ENAME_HOSTS             "hosts"
128 #define ENAME_ETHERS            "ethers"
129 #define ENAME_IPXNETS           "ipxnets"
130 #define ENAME_MANUF             "manuf"
131
132 #define MAXMANUFLEN     9       /* max vendor name length with ending '\0' */
133 #define HASHETHSIZE     1024
134 #define HASHHOSTSIZE    1024
135 #define HASHIPXNETSIZE  256
136 #define HASHMANUFSIZE   256
137 #define HASHPORTSIZE    256
138
139 /* hash table used for IPv4 lookup */
140
141 #define HASH_IPV4_ADDRESS(addr) ((addr) & (HASHHOSTSIZE - 1))
142
143 typedef struct hashipv4 {
144   guint                 addr;
145   gchar                 name[MAXNAMELEN];
146   gboolean              is_dummy_entry; /* name is IPv4 address in dot format */
147   struct hashipv4       *next;
148 } hashipv4_t;
149
150 /* hash table used for IPv6 lookup */
151
152 #define HASH_IPV6_ADDRESS(addr) \
153         ((((addr).bytes[14] << 8)|((addr).bytes[15])) & (HASHHOSTSIZE - 1))
154
155 typedef struct hashipv6 {
156   struct e_in6_addr     addr;
157   gchar                 name[MAXNAMELEN];
158   gboolean              is_dummy_entry; /* name is IPv6 address in colon format */
159   struct hashipv6       *next;
160 } hashipv6_t;
161
162 /* hash table used for TCP/UDP/SCTP port lookup */
163
164 #define HASH_PORT(port) ((port) & (HASHPORTSIZE - 1))
165
166 typedef struct hashport {
167   guint16               port;
168   gchar                 name[MAXNAMELEN];
169   struct hashport       *next;
170 } hashport_t;
171
172 /* hash table used for IPX network lookup */
173
174 /* XXX - check goodness of hash function */
175
176 #define HASH_IPX_NET(net)       ((net) & (HASHIPXNETSIZE - 1))
177
178 typedef struct hashipxnet {
179   guint                 addr;
180   gchar                 name[MAXNAMELEN];
181   struct hashipxnet     *next;
182 } hashipxnet_t;
183
184 /* hash tables used for ethernet and manufacturer lookup */
185
186 #define HASH_ETH_ADDRESS(addr) \
187         (((((addr)[2] << 8) | (addr)[3]) ^ (((addr)[4] << 8) | (addr)[5])) & \
188          (HASHETHSIZE - 1))
189
190 #define HASH_ETH_MANUF(addr) (((int)(addr)[2]) & (HASHMANUFSIZE - 1))
191
192 typedef struct hashmanuf {
193   guint8                addr[3];
194   char                  name[MAXMANUFLEN];
195   struct hashmanuf      *next;
196 } hashmanuf_t;
197
198 typedef struct hashether {
199   guint8                addr[6];
200   char                  name[MAXNAMELEN];
201   gboolean              is_dummy_entry;         /* not a complete entry */
202   struct hashether      *next;
203 } hashether_t;
204
205 /* internal ethernet type */
206
207 typedef struct _ether
208 {
209   guint8                addr[6];
210   char                  name[MAXNAMELEN];
211 } ether_t;
212
213 /* internal ipxnet type */
214
215 typedef struct _ipxnet
216 {
217   guint                 addr;
218   char                  name[MAXNAMELEN];
219 } ipxnet_t;
220
221 static hashipv4_t       *ipv4_table[HASHHOSTSIZE];
222 static hashipv6_t       *ipv6_table[HASHHOSTSIZE];
223 static hashport_t       *udp_port_table[HASHPORTSIZE];
224 static hashport_t       *tcp_port_table[HASHPORTSIZE];
225 static hashport_t       *sctp_port_table[HASHPORTSIZE];
226 static hashport_t       *dccp_port_table[HASHPORTSIZE];
227 static hashether_t      *eth_table[HASHETHSIZE];
228 static hashmanuf_t      *manuf_table[HASHMANUFSIZE];
229 static hashether_t      *(*wka_table[48])[HASHETHSIZE];
230 static hashipxnet_t     *ipxnet_table[HASHIPXNETSIZE];
231
232 static int              eth_resolution_initialized = 0;
233 static int              ipxnet_resolution_initialized = 0;
234
235 static hashether_t *add_eth_name(const guint8 *addr, const gchar *name);
236
237 /*
238  * Flag controlling what names to resolve.
239  */
240 guint32 g_resolv_flags;
241
242 /*
243  *  Global variables (can be changed in GUI sections)
244  *  XXX - they could be changed in GUI code, but there's currently no
245  *  GUI code to change them.
246  */
247
248 gchar *g_ethers_path  = NULL;           /* global ethers file    */
249 gchar *g_pethers_path = NULL;           /* personal ethers file  */
250 gchar *g_ipxnets_path  = NULL;          /* global ipxnets file   */
251 gchar *g_pipxnets_path = NULL;          /* personal ipxnets file */
252                                         /* first resolving call  */
253
254 /* GNU ADNS */
255
256 #ifdef HAVE_GNU_ADNS
257
258 static gboolean gnu_adns_initialized = FALSE;
259
260 adns_state ads;
261
262 int adns_currently_queued = 0;
263
264 typedef struct _adns_queue_msg
265 {
266   gboolean          submitted;
267   guint32           ip4_addr;
268   struct e_in6_addr ip6_addr;
269   int               type;
270   adns_query        query;
271 } adns_queue_msg_t;
272
273 GList *adns_queue_head = NULL;
274
275 #endif /* HAVE_GNU_ADNS */
276
277 /*
278  *  Local function definitions
279  */
280
281 static gchar *serv_name_lookup(guint port, port_type proto)
282 {
283   int hash_idx;
284   hashport_t *tp;
285   hashport_t **table;
286   const char *serv_proto = NULL;
287   struct servent *servp;
288
289   switch(proto) {
290   case PT_UDP:
291     table = udp_port_table;
292     serv_proto = "udp";
293     break;
294   case PT_TCP:
295     table = tcp_port_table;
296     serv_proto = "tcp";
297     break;
298   case PT_SCTP:
299     table = sctp_port_table;
300     serv_proto = "sctp";
301     break;
302   case PT_DCCP:
303     table = dccp_port_table;
304     serv_proto = "dcp";
305     break;
306   default:
307     /* not yet implemented */
308     return NULL;
309     /*NOTREACHED*/
310     break;
311   } /* proto */
312
313   hash_idx = HASH_PORT(port);
314   tp = table[hash_idx];
315
316   if( tp == NULL ) {
317     tp = table[hash_idx] = (hashport_t *)g_malloc(sizeof(hashport_t));
318   } else {
319     while(1) {
320       if( tp->port == port ) {
321         return tp->name;
322       }
323       if (tp->next == NULL) {
324         tp->next = (hashport_t *)g_malloc(sizeof(hashport_t));
325         tp = tp->next;
326         break;
327       }
328       tp = tp->next;
329     }
330   }
331
332   /* fill in a new entry */
333   tp->port = port;
334   tp->next = NULL;
335
336   if (!(g_resolv_flags & RESOLV_TRANSPORT) ||
337       (servp = getservbyport(g_htons(port), serv_proto)) == NULL) {
338     /* unknown port */
339     g_snprintf(tp->name, MAXNAMELEN, "%d", port);
340   } else {
341     strncpy(tp->name, servp->s_name, MAXNAMELEN);
342     tp->name[MAXNAMELEN-1] = '\0';
343   }
344
345   return (tp->name);
346
347 } /* serv_name_lookup */
348
349
350 #ifdef AVOID_DNS_TIMEOUT
351
352 #define DNS_TIMEOUT     2       /* max sec per call */
353
354 jmp_buf hostname_env;
355
356 static void abort_network_query(int sig _U_)
357 {
358   longjmp(hostname_env, 1);
359 }
360 #endif /* AVOID_DNS_TIMEOUT */
361
362 static gchar *host_name_lookup(guint addr, gboolean *found)
363 {
364   int hash_idx;
365   hashipv4_t * volatile tp;
366   struct hostent *hostp;
367 #ifdef HAVE_GNU_ADNS
368   adns_queue_msg_t *qmsg;
369 #endif
370
371   *found = TRUE;
372
373   hash_idx = HASH_IPV4_ADDRESS(addr);
374
375   tp = ipv4_table[hash_idx];
376
377   if( tp == NULL ) {
378     tp = ipv4_table[hash_idx] = (hashipv4_t *)g_malloc(sizeof(hashipv4_t));
379   } else {
380     while(1) {
381       if( tp->addr == addr ) {
382         if (tp->is_dummy_entry)
383           *found = FALSE;
384         return tp->name;
385       }
386       if (tp->next == NULL) {
387         tp->next = (hashipv4_t *)g_malloc(sizeof(hashipv4_t));
388         tp = tp->next;
389         break;
390       }
391       tp = tp->next;
392     }
393   }
394
395   /* fill in a new entry */
396   tp->addr = addr;
397   tp->next = NULL;
398
399 #ifdef HAVE_GNU_ADNS
400   if ((g_resolv_flags & RESOLV_CONCURRENT) &&
401       prefs.name_resolve_concurrency > 0 &&
402       gnu_adns_initialized) {
403     qmsg = g_malloc(sizeof(adns_queue_msg_t));
404     qmsg->type = AF_INET;
405     qmsg->ip4_addr = addr;
406     qmsg->submitted = FALSE;
407     adns_queue_head = g_list_append(adns_queue_head, (gpointer) qmsg);
408
409     tp->is_dummy_entry = TRUE;
410     ip_to_str_buf((guint8 *)&addr, tp->name);
411     return tp->name;
412   }
413 #endif /* HAVE_GNU_ADNS */
414
415   /*
416    * The Windows "gethostbyaddr()" insists on translating 0.0.0.0 to
417    * the name of the host on which it's running; to work around that
418    * botch, we don't try to translate an all-zero IP address to a host
419    * name.
420    */
421   if (addr != 0 && (g_resolv_flags & RESOLV_NETWORK)) {
422   /* Use async DNS if possible, else fall back to timeouts,
423    * else call gethostbyaddr and hope for the best
424    */
425
426 # ifdef AVOID_DNS_TIMEOUT
427
428     /* Quick hack to avoid DNS/YP timeout */
429
430     if (!setjmp(hostname_env)) {
431       signal(SIGALRM, abort_network_query);
432       alarm(DNS_TIMEOUT);
433 # endif /* AVOID_DNS_TIMEOUT */
434
435       hostp = gethostbyaddr((char *)&addr, 4, AF_INET);
436
437 # ifdef AVOID_DNS_TIMEOUT
438       alarm(0);
439 # endif /* AVOID_DNS_TIMEOUT */
440
441       if (hostp != NULL) {
442         strncpy(tp->name, hostp->h_name, MAXNAMELEN);
443         tp->name[MAXNAMELEN-1] = '\0';
444         tp->is_dummy_entry = FALSE;
445         return tp->name;
446       }
447
448 # ifdef AVOID_DNS_TIMEOUT
449     }
450 # endif /* AVOID_DNS_TIMEOUT */
451
452   }
453
454   /* unknown host or DNS timeout */
455
456   ip_to_str_buf((guint8 *)&addr, tp->name);
457   tp->is_dummy_entry = TRUE;
458   *found = FALSE;
459
460   return (tp->name);
461
462 } /* host_name_lookup */
463
464 static gchar *host_name_lookup6(struct e_in6_addr *addr, gboolean *found)
465 {
466   int hash_idx;
467   hashipv6_t * volatile tp;
468 #ifdef INET6
469   struct hostent *hostp;
470 #endif
471
472   *found = TRUE;
473
474   hash_idx = HASH_IPV6_ADDRESS(*addr);
475
476   tp = ipv6_table[hash_idx];
477
478   if( tp == NULL ) {
479     tp = ipv6_table[hash_idx] = (hashipv6_t *)g_malloc(sizeof(hashipv6_t));
480   } else {
481     while(1) {
482       if( memcmp(&tp->addr, addr, sizeof (struct e_in6_addr)) == 0 ) {
483         if (tp->is_dummy_entry)
484           *found = FALSE;
485         return tp->name;
486       }
487       if (tp->next == NULL) {
488         tp->next = (hashipv6_t *)g_malloc(sizeof(hashipv6_t));
489         tp = tp->next;
490         break;
491       }
492       tp = tp->next;
493     }
494   }
495
496   /* fill in a new entry */
497   tp->addr = *addr;
498   tp->next = NULL;
499
500 #ifdef INET6
501   if (g_resolv_flags & RESOLV_NETWORK) {
502 #ifdef AVOID_DNS_TIMEOUT
503
504     /* Quick hack to avoid DNS/YP timeout */
505
506     if (!setjmp(hostname_env)) {
507       signal(SIGALRM, abort_network_query);
508       alarm(DNS_TIMEOUT);
509 #endif /* AVOID_DNS_TIMEOUT */
510       hostp = gethostbyaddr((char *)addr, sizeof(*addr), AF_INET6);
511 #ifdef AVOID_DNS_TIMEOUT
512       alarm(0);
513 # endif /* AVOID_DNS_TIMEOUT */
514
515       if (hostp != NULL) {
516         strncpy(tp->name, hostp->h_name, MAXNAMELEN);
517         tp->name[MAXNAMELEN-1] = '\0';
518         tp->is_dummy_entry = FALSE;
519         return tp->name;
520       }
521
522 #ifdef AVOID_DNS_TIMEOUT
523     }
524 # endif /* AVOID_DNS_TIMEOUT */
525
526   }
527
528   /* unknown host or DNS timeout */
529 #endif /* INET6 */
530   ip6_to_str_buf(addr, tp->name);
531   tp->is_dummy_entry = TRUE;
532   *found = FALSE;
533   return (tp->name);
534
535 } /* host_name_lookup6 */
536
537 static const gchar *solve_address_to_name(address *addr)
538 {
539   guint32 ipv4_addr;
540   struct e_in6_addr ipv6_addr;
541
542   switch (addr->type) {
543
544   case AT_ETHER:
545     return get_ether_name(addr->data);
546
547   case AT_IPv4:
548     memcpy(&ipv4_addr, addr->data, sizeof ipv4_addr);
549     return get_hostname(ipv4_addr);
550
551   case AT_IPv6:
552     memcpy(&ipv6_addr.bytes, addr->data, sizeof ipv6_addr.bytes);
553     return get_hostname6(&ipv6_addr);
554
555   case AT_STRINGZ:
556     return addr->data;
557
558   default:
559     return NULL;
560   }
561 } /* solve_address_to_name */
562
563
564 /*
565  *  Miscellaneous functions
566  */
567
568 static int fgetline(char **buf, int *size, FILE *fp)
569 {
570   int len;
571   int c;
572
573   if (fp == NULL)
574     return -1;
575
576   if (*buf == NULL) {
577     if (*size == 0)
578       *size = BUFSIZ;
579
580     if ((*buf = g_malloc(*size)) == NULL)
581       return -1;
582   }
583
584   if (feof(fp))
585     return -1;
586
587   len = 0;
588   while ((c = getc(fp)) != EOF && c != '\n') {
589     if (len+1 >= *size) {
590       if ((*buf = g_realloc(*buf, *size += BUFSIZ)) == NULL)
591         return -1;
592     }
593     (*buf)[len++] = c;
594   }
595
596   if (len == 0 && c == EOF)
597     return -1;
598
599   (*buf)[len] = '\0';
600
601   return len;
602
603 } /* fgetline */
604
605
606 /*
607  * Ethernet / manufacturer resolution
608  *
609  * The following functions implement ethernet address resolution and
610  * ethers files parsing (see ethers(4)).
611  *
612  * The manuf file has the same format as ethers(4) except that names are
613  * truncated to MAXMANUFLEN-1 characters and that an address contains
614  * only 3 bytes (instead of 6).
615  *
616  * Notes:
617  *
618  * I decide to not use the existing functions (see ethers(3) on some
619  * operating systems) for the following reasons:
620  * - performance gains (use of hash tables and some other enhancements),
621  * - use of two ethers files (system-wide and per user),
622  * - avoid the use of NIS maps,
623  * - lack of these functions on some systems.
624  *
625  * So the following functions do _not_ behave as the standard ones.
626  *
627  * -- Laurent.
628  */
629
630
631 /*
632  * If "manuf_file" is FALSE, parse a 6-byte MAC address.
633  * If "manuf_file" is TRUE, parse an up-to-6-byte sequence with an optional
634  * mask.
635  */
636 static gboolean
637 parse_ether_address(const char *cp, ether_t *eth, unsigned int *mask,
638                     gboolean manuf_file)
639 {
640   int i;
641   unsigned long num;
642   char *p;
643   char sep = '\0';
644
645   for (i = 0; i < 6; i++) {
646     /* Get a hex number, 1 or 2 digits, no sign characters allowed. */
647     if (!isxdigit((unsigned char)*cp))
648       return FALSE;
649     num = strtoul(cp, &p, 16);
650     if (p == cp)
651       return FALSE;     /* failed */
652     if (num > 0xFF)
653       return FALSE;     /* not a valid octet */
654     eth->addr[i] = (guint8) num;
655     cp = p;             /* skip past the number */
656
657     /* OK, what character terminated the octet? */
658     if (*cp == '/') {
659       /* "/" - this has a mask. */
660       if (!manuf_file) {
661         /* Entries with masks are allowed only in the "manuf" files. */
662         return FALSE;
663       }
664       cp++;     /* skip past the '/' to get to the mask */
665       if (!isdigit((unsigned char)*cp))
666         return FALSE;   /* no sign allowed */
667       num = strtoul(cp, &p, 10);
668       if (p == cp)
669         return FALSE;   /* failed */
670       cp = p;   /* skip past the number */
671       if (*cp != '\0' && !isspace((unsigned char)*cp))
672         return FALSE;   /* bogus terminator */
673       if (num == 0 || num >= 48)
674         return FALSE;   /* bogus mask */
675       /* Mask out the bits not covered by the mask */
676       *mask = num;
677       for (i = 0; num >= 8; i++, num -= 8)
678         ;       /* skip octets entirely covered by the mask */
679       /* Mask out the first masked octet */
680       eth->addr[i] &= (0xFF << (8 - num));
681       i++;
682       /* Mask out completely-masked-out octets */
683       for (; i < 6; i++)
684         eth->addr[i] = 0;
685       return TRUE;
686     }
687     if (*cp == '\0') {
688       /* We're at the end of the address, and there's no mask. */
689       if (i == 2) {
690         /* We got 3 bytes, so this is a manufacturer ID. */
691         if (!manuf_file) {
692           /* Manufacturer IDs are only allowed in the "manuf"
693              files. */
694           return FALSE;
695         }
696         /* Indicate that this is a manufacturer ID (0 is not allowed
697            as a mask). */
698         *mask = 0;
699         return TRUE;
700       }
701
702       if (i == 5) {
703         /* We got 6 bytes, so this is a MAC address.
704            If we're reading one of the "manuf" files, indicate that
705            this is a MAC address (48 is not allowed as a mask). */
706         if (manuf_file)
707           *mask = 48;
708         return TRUE;
709       }
710
711       /* We didn't get 3 or 6 bytes, and there's no mask; this is
712          illegal. */
713       return FALSE;
714     } else {
715       if (sep == '\0') {
716         /* We don't know the separator used in this number; it can either
717            be ':', '-', or '.'. */
718         if (*cp != ':' && *cp != '-' && *cp != '.')
719           return FALSE;
720         sep = *cp;      /* subsequent separators must be the same */
721       } else {
722           /* It has to be the same as the first separator */
723           if (*cp != sep)
724             return FALSE;
725       }
726     }
727     cp++;
728   }
729
730   return TRUE;
731 }
732
733 static int parse_ether_line(char *line, ether_t *eth, unsigned int *mask,
734                             gboolean manuf_file)
735 {
736   /*
737    *  See the ethers(4) or ethers(5) man page for ethers file format
738    *  (not available on all systems).
739    *  We allow both ethernet address separators (':' and '-'),
740    *  as well as Ethereal's '.' separator.
741    */
742
743   gchar *cp;
744
745   if ((cp = strchr(line, '#')))
746     *cp = '\0';
747
748   if ((cp = strtok(line, " \t")) == NULL)
749     return -1;
750
751   if (!parse_ether_address(cp, eth, mask, manuf_file))
752     return -1;
753
754   if ((cp = strtok(NULL, " \t")) == NULL)
755     return -1;
756
757   strncpy(eth->name, cp, MAXNAMELEN);
758   eth->name[MAXNAMELEN-1] = '\0';
759
760   return 0;
761
762 } /* parse_ether_line */
763
764 static FILE *eth_p = NULL;
765
766 static void set_ethent(char *path)
767 {
768   if (eth_p)
769     rewind(eth_p);
770   else
771     eth_p = eth_fopen(path, "r");
772 }
773
774 static void end_ethent(void)
775 {
776   if (eth_p) {
777     fclose(eth_p);
778     eth_p = NULL;
779   }
780 }
781
782 static ether_t *get_ethent(unsigned int *mask, gboolean manuf_file)
783 {
784
785   static ether_t eth;
786   static int     size = 0;
787   static char   *buf = NULL;
788
789   if (eth_p == NULL)
790     return NULL;
791
792   while (fgetline(&buf, &size, eth_p) >= 0) {
793     if (parse_ether_line(buf, &eth, mask, manuf_file) == 0) {
794       return &eth;
795     }
796   }
797
798   return NULL;
799
800 } /* get_ethent */
801
802 static ether_t *get_ethbyname(const gchar *name)
803 {
804   ether_t *eth;
805
806   set_ethent(g_pethers_path);
807
808   while ((eth = get_ethent(NULL, FALSE)) && strncmp(name, eth->name, MAXNAMELEN) != 0)
809     ;
810
811   if (eth == NULL) {
812     end_ethent();
813
814     set_ethent(g_ethers_path);
815
816     while ((eth = get_ethent(NULL, FALSE)) && strncmp(name, eth->name, MAXNAMELEN) != 0)
817       ;
818
819     end_ethent();
820   }
821
822   return eth;
823
824 } /* get_ethbyname */
825
826 static ether_t *get_ethbyaddr(const guint8 *addr)
827 {
828
829   ether_t *eth;
830
831   set_ethent(g_pethers_path);
832
833   while ((eth = get_ethent(NULL, FALSE)) && memcmp(addr, eth->addr, 6) != 0)
834     ;
835
836   if (eth == NULL) {
837     end_ethent();
838
839     set_ethent(g_ethers_path);
840
841     while ((eth = get_ethent(NULL, FALSE)) && memcmp(addr, eth->addr, 6) != 0)
842       ;
843
844     end_ethent();
845   }
846
847   return eth;
848
849 } /* get_ethbyaddr */
850
851 static int hash_eth_wka(const guint8 *addr, unsigned int mask)
852 {
853   if (mask <= 8) {
854     /* All but the topmost byte is masked out */
855     return (addr[0] & (0xFF << (8 - mask))) & (HASHETHSIZE - 1);
856   }
857   mask -= 8;
858   if (mask <= 8) {
859     /* All but the topmost 2 bytes are masked out */
860     return ((addr[0] << 8) | (addr[1] & (0xFF << (8 - mask)))) &
861             (HASHETHSIZE - 1);
862   }
863   mask -= 8;
864   if (mask <= 8) {
865     /* All but the topmost 3 bytes are masked out */
866     return ((addr[0] << 16) | (addr[1] << 8) | (addr[2] & (0xFF << (8 - mask))))
867      & (HASHETHSIZE - 1);
868   }
869   mask -= 8;
870   if (mask <= 8) {
871     /* All but the topmost 4 bytes are masked out */
872     return ((((addr[0] << 8) | addr[1]) ^
873              ((addr[2] << 8) | (addr[3] & (0xFF << (8 - mask)))))) &
874          (HASHETHSIZE - 1);
875   }
876   mask -= 8;
877   if (mask <= 8) {
878     /* All but the topmost 5 bytes are masked out */
879     return ((((addr[1] << 8) | addr[2]) ^
880              ((addr[3] << 8) | (addr[4] & (0xFF << (8 - mask)))))) &
881          (HASHETHSIZE - 1);
882   }
883   mask -= 8;
884   /* No bytes are fully masked out */
885   return ((((addr[1] << 8) | addr[2]) ^
886            ((addr[3] << 8) | (addr[4] & (0xFF << (8 - mask)))))) &
887             (HASHETHSIZE - 1);
888 }
889
890 static void add_manuf_name(guint8 *addr, unsigned int mask, gchar *name)
891 {
892   int hash_idx;
893   hashmanuf_t *tp;
894   hashether_t *(*wka_tp)[HASHETHSIZE], *etp;
895
896   if (mask == 48) {
897     /* This is a well-known MAC address; just add this to the Ethernet
898        hash table */
899     add_eth_name(addr, name);
900     return;
901   }
902
903   if (mask == 0) {
904     /* This is a manufacturer ID; add it to the manufacturer ID hash table */
905
906     hash_idx = HASH_ETH_MANUF(addr);
907
908     tp = manuf_table[hash_idx];
909
910     if( tp == NULL ) {
911       tp = manuf_table[hash_idx] = (hashmanuf_t *)g_malloc(sizeof(hashmanuf_t));
912     } else {
913       while(1) {
914         if (tp->next == NULL) {
915           tp->next = (hashmanuf_t *)g_malloc(sizeof(hashmanuf_t));
916           tp = tp->next;
917           break;
918         }
919         tp = tp->next;
920       }
921     }
922
923     memcpy(tp->addr, addr, sizeof(tp->addr));
924     strncpy(tp->name, name, MAXMANUFLEN);
925     tp->name[MAXMANUFLEN-1] = '\0';
926     tp->next = NULL;
927     return;
928   }
929
930   /* This is a range of well-known addresses; add it to the appropriate
931      well-known-address table, creating that table if necessary. */
932   wka_tp = wka_table[mask];
933   if (wka_tp == NULL)
934     wka_tp = wka_table[mask] = g_malloc0(sizeof *wka_table[mask]);
935
936   hash_idx = hash_eth_wka(addr, mask);
937
938   etp = (*wka_tp)[hash_idx];
939
940   if( etp == NULL ) {
941     etp = (*wka_tp)[hash_idx] = (hashether_t *)g_malloc(sizeof(hashether_t));
942   } else {
943     while(1) {
944       if (memcmp(etp->addr, addr, sizeof(etp->addr)) == 0) {
945         /* address already known */
946         return;
947       }
948       if (etp->next == NULL) {
949         etp->next = (hashether_t *)g_malloc(sizeof(hashether_t));
950         etp = etp->next;
951         break;
952       }
953       etp = etp->next;
954     }
955   }
956
957   memcpy(etp->addr, addr, sizeof(etp->addr));
958   strncpy(etp->name, name, MAXNAMELEN);
959   etp->name[MAXNAMELEN-1] = '\0';
960   etp->next = NULL;
961   etp->is_dummy_entry = FALSE;
962
963 } /* add_manuf_name */
964
965 static hashmanuf_t *manuf_name_lookup(const guint8 *addr)
966 {
967   int hash_idx;
968   hashmanuf_t *tp;
969
970   hash_idx = HASH_ETH_MANUF(addr);
971
972   tp = manuf_table[hash_idx];
973
974   while(tp != NULL) {
975     if (memcmp(tp->addr, addr, sizeof(tp->addr)) == 0) {
976       return tp;
977     }
978     tp = tp->next;
979   }
980
981   return NULL;
982
983 } /* manuf_name_lookup */
984
985 static hashether_t *wka_name_lookup(const guint8 *addr, unsigned int mask)
986 {
987   int hash_idx;
988   hashether_t *(*wka_tp)[HASHETHSIZE];
989   hashether_t *tp;
990   guint8 masked_addr[6];
991   unsigned int num;
992   int i;
993
994   wka_tp = wka_table[mask];
995   if (wka_tp == NULL) {
996     /* There are no entries in the table for that mask value, as there is
997        no table for that mask value. */
998     return NULL;
999   }
1000
1001   /* Get the part of the address covered by the mask. */
1002   for (i = 0, num = mask; num >= 8; i++, num -= 8)
1003     masked_addr[i] = addr[i];   /* copy octets entirely covered by the mask */
1004   /* Mask out the first masked octet */
1005   masked_addr[i] = addr[i] & (0xFF << (8 - num));
1006   i++;
1007   /* Zero out completely-masked-out octets */
1008   for (; i < 6; i++)
1009     masked_addr[i] = 0;
1010
1011   hash_idx = hash_eth_wka(masked_addr, mask);
1012
1013   tp = (*wka_tp)[hash_idx];
1014
1015   while(tp != NULL) {
1016     if (memcmp(tp->addr, masked_addr, sizeof(tp->addr)) == 0) {
1017       return tp;
1018     }
1019     tp = tp->next;
1020   }
1021
1022   return NULL;
1023
1024 } /* wka_name_lookup */
1025
1026 static void initialize_ethers(void)
1027 {
1028   ether_t *eth;
1029   char *manuf_path;
1030   unsigned int mask;
1031
1032   /* Compute the pathname of the ethers file. */
1033   if (g_ethers_path == NULL) {
1034     g_ethers_path = g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s",
1035             get_systemfile_dir(), ENAME_ETHERS);
1036   }
1037
1038   /* Set g_pethers_path here, but don't actually do anything
1039    * with it. It's used in get_ethbyname() and get_ethbyaddr()
1040    */
1041   if (g_pethers_path == NULL)
1042     g_pethers_path = get_persconffile_path(ENAME_ETHERS, FALSE);
1043
1044   /* manuf hash table initialization */
1045
1046   /* Compute the pathname of the manuf file */
1047   manuf_path = get_datafile_path(ENAME_MANUF);
1048
1049   /* Read it and initialize the hash table */
1050   set_ethent(manuf_path);
1051
1052   while ((eth = get_ethent(&mask, TRUE))) {
1053     add_manuf_name(eth->addr, mask, eth->name);
1054   }
1055
1056   end_ethent();
1057
1058   g_free(manuf_path);
1059
1060 } /* initialize_ethers */
1061
1062 static hashether_t *add_eth_name(const guint8 *addr, const gchar *name)
1063 {
1064   int hash_idx;
1065   hashether_t *tp;
1066
1067   hash_idx = HASH_ETH_ADDRESS(addr);
1068
1069   tp = eth_table[hash_idx];
1070
1071   if( tp == NULL ) {
1072     tp = eth_table[hash_idx] = (hashether_t *)g_malloc(sizeof(hashether_t));
1073   } else {
1074     while(1) {
1075       if (memcmp(tp->addr, addr, sizeof(tp->addr)) == 0) {
1076         /* address already known */
1077         if (!tp->is_dummy_entry) {
1078           return tp;
1079         } else {
1080           /* replace this dummy (manuf) entry with a real name */
1081           break;
1082         }
1083       }
1084       if (tp->next == NULL) {
1085         tp->next = (hashether_t *)g_malloc(sizeof(hashether_t));
1086         tp = tp->next;
1087         break;
1088       }
1089       tp = tp->next;
1090     }
1091   }
1092
1093   memcpy(tp->addr, addr, sizeof(tp->addr));
1094   strncpy(tp->name, name, MAXNAMELEN);
1095   tp->name[MAXNAMELEN-1] = '\0';
1096   tp->next = NULL;
1097   tp->is_dummy_entry = FALSE;
1098
1099   return tp;
1100
1101 } /* add_eth_name */
1102
1103 static gchar *eth_name_lookup(const guint8 *addr)
1104 {
1105   int hash_idx;
1106   hashmanuf_t *manufp;
1107   hashether_t *tp;
1108   ether_t *eth;
1109   hashether_t *etp;
1110   unsigned int mask;
1111
1112   hash_idx = HASH_ETH_ADDRESS(addr);
1113
1114   tp = eth_table[hash_idx];
1115
1116   if( tp == NULL ) {
1117     tp = eth_table[hash_idx] = (hashether_t *)g_malloc(sizeof(hashether_t));
1118   } else {
1119     while(1) {
1120       if (memcmp(tp->addr, addr, sizeof(tp->addr)) == 0) {
1121         return tp->name;
1122       }
1123       if (tp->next == NULL) {
1124         tp->next = (hashether_t *)g_malloc(sizeof(hashether_t));
1125         tp = tp->next;
1126         break;
1127       }
1128       tp = tp->next;
1129     }
1130   }
1131
1132   /* fill in a new entry */
1133
1134   memcpy(tp->addr, addr, sizeof(tp->addr));
1135   tp->next = NULL;
1136
1137   if ( (eth = get_ethbyaddr(addr)) == NULL) {
1138     /* Unknown name.  Try looking for it in the well-known-address
1139        tables for well-known address ranges smaller than 2^24. */
1140     mask = 7;
1141     for (;;) {
1142       /* Only the topmost 5 bytes participate fully */
1143       if ((etp = wka_name_lookup(addr, mask+40)) != NULL) {
1144         g_snprintf(tp->name, MAXNAMELEN, "%s_%02x",
1145               etp->name, addr[5] & (0xFF >> mask));
1146         tp->is_dummy_entry = TRUE;
1147         return (tp->name);
1148       }
1149       if (mask == 0)
1150         break;
1151       mask--;
1152     }
1153
1154     mask = 7;
1155     for (;;) {
1156       /* Only the topmost 4 bytes participate fully */
1157       if ((etp = wka_name_lookup(addr, mask+32)) != NULL) {
1158         g_snprintf(tp->name, MAXNAMELEN, "%s_%02x:%02x",
1159               etp->name, addr[4] & (0xFF >> mask), addr[5]);
1160         tp->is_dummy_entry = TRUE;
1161         return (tp->name);
1162       }
1163       if (mask == 0)
1164         break;
1165       mask--;
1166     }
1167
1168     mask = 7;
1169     for (;;) {
1170       /* Only the topmost 3 bytes participate fully */
1171       if ((etp = wka_name_lookup(addr, mask+24)) != NULL) {
1172         g_snprintf(tp->name, MAXNAMELEN, "%s_%02x:%02x:%02x",
1173               etp->name, addr[3] & (0xFF >> mask), addr[4], addr[5]);
1174         tp->is_dummy_entry = TRUE;
1175         return (tp->name);
1176       }
1177       if (mask == 0)
1178         break;
1179       mask--;
1180     }
1181
1182     /* Now try looking in the manufacturer table. */
1183     if ((manufp = manuf_name_lookup(addr)) != NULL) {
1184       g_snprintf(tp->name, MAXNAMELEN, "%s_%02x:%02x:%02x",
1185               manufp->name, addr[3], addr[4], addr[5]);
1186       tp->is_dummy_entry = TRUE;
1187       return (tp->name);
1188     }
1189
1190     /* Now try looking for it in the well-known-address
1191        tables for well-known address ranges larger than 2^24. */
1192     mask = 7;
1193     for (;;) {
1194       /* Only the topmost 2 bytes participate fully */
1195       if ((etp = wka_name_lookup(addr, mask+16)) != NULL) {
1196         g_snprintf(tp->name, MAXNAMELEN, "%s_%02x:%02x:%02x:%02x",
1197               etp->name, addr[2] & (0xFF >> mask), addr[3], addr[4],
1198               addr[5]);
1199         tp->is_dummy_entry = TRUE;
1200         return (tp->name);
1201       }
1202       if (mask == 0)
1203         break;
1204       mask--;
1205     }
1206
1207     mask = 7;
1208     for (;;) {
1209       /* Only the topmost byte participates fully */
1210       if ((etp = wka_name_lookup(addr, mask+8)) != NULL) {
1211         g_snprintf(tp->name, MAXNAMELEN, "%s_%02x:%02x:%02x:%02x:%02x",
1212               etp->name, addr[1] & (0xFF >> mask), addr[2], addr[3],
1213               addr[4], addr[5]);
1214         tp->is_dummy_entry = TRUE;
1215         return (tp->name);
1216       }
1217       if (mask == 0)
1218         break;
1219       mask--;
1220     }
1221
1222     for (mask = 7; mask > 0; mask--) {
1223       /* Not even the topmost byte participates fully */
1224       if ((etp = wka_name_lookup(addr, mask)) != NULL) {
1225         g_snprintf(tp->name, MAXNAMELEN, "%s_%02x:%02x:%02x:%02x:%02x:%02x",
1226               etp->name, addr[0] & (0xFF >> mask), addr[1], addr[2],
1227               addr[3], addr[4], addr[5]);
1228         tp->is_dummy_entry = TRUE;
1229         return (tp->name);
1230       }
1231     }
1232
1233     /* No match whatsoever. */
1234     g_snprintf(tp->name, MAXNAMELEN, "%s", ether_to_str(addr));
1235     tp->is_dummy_entry = TRUE;
1236
1237   } else {
1238     strncpy(tp->name, eth->name, MAXNAMELEN);
1239     tp->name[MAXNAMELEN-1] = '\0';
1240     tp->is_dummy_entry = FALSE;
1241   }
1242
1243   return (tp->name);
1244
1245 } /* eth_name_lookup */
1246
1247 static guint8 *eth_addr_lookup(const gchar *name)
1248 {
1249   ether_t *eth;
1250   hashether_t *tp;
1251   hashether_t **table = eth_table;
1252   int i;
1253
1254   /* to be optimized (hash table from name to addr) */
1255   for (i = 0; i < HASHETHSIZE; i++) {
1256     tp = table[i];
1257     while (tp) {
1258       if (strcmp(tp->name, name) == 0)
1259         return tp->addr;
1260       tp = tp->next;
1261     }
1262   }
1263
1264   /* not in hash table : performs a file lookup */
1265
1266   if ((eth = get_ethbyname(name)) == NULL)
1267     return NULL;
1268
1269   /* add new entry in hash table */
1270
1271   tp = add_eth_name(eth->addr, name);
1272
1273   return tp->addr;
1274
1275 } /* eth_addr_lookup */
1276
1277
1278 /* IPXNETS */
1279 static int parse_ipxnets_line(char *line, ipxnet_t *ipxnet)
1280 {
1281   /*
1282    *  We allow three address separators (':', '-', and '.'),
1283    *  as well as no separators
1284    */
1285
1286   gchar         *cp;
1287   guint32       a, a0, a1, a2, a3;
1288   gboolean      found_single_number = FALSE;
1289
1290   if ((cp = strchr(line, '#')))
1291     *cp = '\0';
1292
1293   if ((cp = strtok(line, " \t\n")) == NULL)
1294     return -1;
1295
1296   /* Either fill a0,a1,a2,a3 and found_single_number is FALSE,
1297    * fill a and found_single_number is TRUE,
1298    * or return -1
1299    */
1300   if (sscanf(cp, "%x:%x:%x:%x", &a0, &a1, &a2, &a3) != 4) {
1301     if (sscanf(cp, "%x-%x-%x-%x", &a0, &a1, &a2, &a3) != 4) {
1302       if (sscanf(cp, "%x.%x.%x.%x", &a0, &a1, &a2, &a3) != 4) {
1303         if (sscanf(cp, "%x", &a) == 1) {
1304           found_single_number = TRUE;
1305         }
1306         else {
1307           return -1;
1308         }
1309       }
1310     }
1311   }
1312
1313   if ((cp = strtok(NULL, " \t\n")) == NULL)
1314     return -1;
1315
1316   if (found_single_number) {
1317         ipxnet->addr = a;
1318   }
1319   else {
1320         ipxnet->addr = (a0 << 24) | (a1 << 16) | (a2 << 8) | a3;
1321   }
1322
1323   strncpy(ipxnet->name, cp, MAXNAMELEN);
1324   ipxnet->name[MAXNAMELEN-1] = '\0';
1325
1326   return 0;
1327
1328 } /* parse_ipxnets_line */
1329
1330 static FILE *ipxnet_p = NULL;
1331
1332 static void set_ipxnetent(char *path)
1333 {
1334   if (ipxnet_p)
1335     rewind(ipxnet_p);
1336   else
1337     ipxnet_p = eth_fopen(path, "r");
1338 }
1339
1340 static void end_ipxnetent(void)
1341 {
1342   if (ipxnet_p) {
1343     fclose(ipxnet_p);
1344     ipxnet_p = NULL;
1345   }
1346 }
1347
1348 static ipxnet_t *get_ipxnetent(void)
1349 {
1350
1351   static ipxnet_t ipxnet;
1352   static int     size = 0;
1353   static char   *buf = NULL;
1354
1355   if (ipxnet_p == NULL)
1356     return NULL;
1357
1358   while (fgetline(&buf, &size, ipxnet_p) >= 0) {
1359     if (parse_ipxnets_line(buf, &ipxnet) == 0) {
1360       return &ipxnet;
1361     }
1362   }
1363
1364   return NULL;
1365
1366 } /* get_ipxnetent */
1367
1368 static ipxnet_t *get_ipxnetbyname(const gchar *name)
1369 {
1370   ipxnet_t *ipxnet;
1371
1372   set_ipxnetent(g_ipxnets_path);
1373
1374   while ((ipxnet = get_ipxnetent()) && strncmp(name, ipxnet->name, MAXNAMELEN) != 0)
1375     ;
1376
1377   if (ipxnet == NULL) {
1378     end_ipxnetent();
1379
1380     set_ipxnetent(g_pipxnets_path);
1381
1382     while ((ipxnet = get_ipxnetent()) && strncmp(name, ipxnet->name, MAXNAMELEN) != 0)
1383       ;
1384
1385     end_ipxnetent();
1386   }
1387
1388   return ipxnet;
1389
1390 } /* get_ipxnetbyname */
1391
1392 static ipxnet_t *get_ipxnetbyaddr(guint32 addr)
1393 {
1394
1395   ipxnet_t *ipxnet;
1396
1397   set_ipxnetent(g_ipxnets_path);
1398
1399   while ((ipxnet = get_ipxnetent()) && (addr != ipxnet->addr) ) ;
1400
1401   if (ipxnet == NULL) {
1402     end_ipxnetent();
1403
1404     set_ipxnetent(g_pipxnets_path);
1405
1406     while ((ipxnet = get_ipxnetent()) && (addr != ipxnet->addr) )
1407       ;
1408
1409     end_ipxnetent();
1410   }
1411
1412   return ipxnet;
1413
1414 } /* get_ipxnetbyaddr */
1415
1416 static void initialize_ipxnets(void)
1417 {
1418   /* Compute the pathname of the ipxnets file.
1419    *
1420    * XXX - is there a notion of an "ipxnets file" in any flavor of
1421    * UNIX, or with any add-on Netware package for UNIX?  If not,
1422    * should the UNIX version of the ipxnets file be in the datafile
1423    * directory as well?
1424    */
1425   if (g_ipxnets_path == NULL) {
1426         g_ipxnets_path = g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s",
1427             get_systemfile_dir(), ENAME_IPXNETS);
1428   }
1429
1430   /* Set g_pipxnets_path here, but don't actually do anything
1431    * with it. It's used in get_ipxnetbyname() and get_ipxnetbyaddr()
1432    */
1433   if (g_pipxnets_path == NULL)
1434     g_pipxnets_path = get_persconffile_path(ENAME_IPXNETS, FALSE);
1435
1436 } /* initialize_ipxnets */
1437
1438 static hashipxnet_t *add_ipxnet_name(guint addr, const gchar *name)
1439 {
1440   int hash_idx;
1441   hashipxnet_t *tp;
1442
1443   hash_idx = HASH_IPX_NET(addr);
1444
1445   tp = ipxnet_table[hash_idx];
1446
1447   if( tp == NULL ) {
1448     tp = ipxnet_table[hash_idx] = (hashipxnet_t *)g_malloc(sizeof(hashipxnet_t));
1449   } else {
1450     while(1) {
1451       if (tp->next == NULL) {
1452         tp->next = (hashipxnet_t *)g_malloc(sizeof(hashipxnet_t));
1453         tp = tp->next;
1454         break;
1455       }
1456       tp = tp->next;
1457     }
1458   }
1459
1460   tp->addr = addr;
1461   strncpy(tp->name, name, MAXNAMELEN);
1462   tp->name[MAXNAMELEN-1] = '\0';
1463   tp->next = NULL;
1464
1465   return tp;
1466
1467 } /* add_ipxnet_name */
1468
1469 static gchar *ipxnet_name_lookup(const guint addr)
1470 {
1471   int hash_idx;
1472   hashipxnet_t *tp;
1473   ipxnet_t *ipxnet;
1474
1475   hash_idx = HASH_IPX_NET(addr);
1476
1477   tp = ipxnet_table[hash_idx];
1478
1479   if( tp == NULL ) {
1480     tp = ipxnet_table[hash_idx] = (hashipxnet_t *)g_malloc(sizeof(hashipxnet_t));
1481   } else {
1482     while(1) {
1483       if (tp->addr == addr) {
1484         return tp->name;
1485       }
1486       if (tp->next == NULL) {
1487         tp->next = (hashipxnet_t *)g_malloc(sizeof(hashipxnet_t));
1488         tp = tp->next;
1489         break;
1490       }
1491       tp = tp->next;
1492     }
1493   }
1494
1495   /* fill in a new entry */
1496
1497   tp->addr = addr;
1498   tp->next = NULL;
1499
1500   if ( (ipxnet = get_ipxnetbyaddr(addr)) == NULL) {
1501     /* unknown name */
1502       g_snprintf(tp->name, MAXNAMELEN, "%X", addr);
1503
1504   } else {
1505     strncpy(tp->name, ipxnet->name, MAXNAMELEN);
1506     tp->name[MAXNAMELEN-1] = '\0';
1507   }
1508
1509   return (tp->name);
1510
1511 } /* ipxnet_name_lookup */
1512
1513 static guint ipxnet_addr_lookup(const gchar *name, gboolean *success)
1514 {
1515   ipxnet_t *ipxnet;
1516   hashipxnet_t *tp;
1517   hashipxnet_t **table = ipxnet_table;
1518   int i;
1519
1520   /* to be optimized (hash table from name to addr) */
1521   for (i = 0; i < HASHIPXNETSIZE; i++) {
1522     tp = table[i];
1523     while (tp) {
1524       if (strcmp(tp->name, name) == 0) {
1525         *success = TRUE;
1526         return tp->addr;
1527       }
1528       tp = tp->next;
1529     }
1530   }
1531
1532   /* not in hash table : performs a file lookup */
1533
1534   if ((ipxnet = get_ipxnetbyname(name)) == NULL) {
1535     *success = FALSE;
1536     return 0;
1537   }
1538
1539   /* add new entry in hash table */
1540
1541   tp = add_ipxnet_name(ipxnet->addr, name);
1542
1543   *success = TRUE;
1544   return tp->addr;
1545
1546 } /* ipxnet_addr_lookup */
1547
1548 static gboolean
1549 read_hosts_file (const char *hostspath)
1550 {
1551   FILE *hf;
1552   char *line = NULL;
1553   int size = 0;
1554   gchar *cp;
1555   guint32 host_addr[4]; /* IPv4 or IPv6 */
1556   struct e_in6_addr ipv6_addr;
1557   gboolean is_ipv6;
1558   int ret;
1559
1560   /*
1561    *  See the hosts(4) or hosts(5) man page for hosts file format
1562    *  (not available on all systems).
1563    */
1564   if ((hf = eth_fopen(hostspath, "r")) == NULL)
1565     return FALSE;
1566
1567   while (fgetline(&line, &size, hf) >= 0) {
1568     if ((cp = strchr(line, '#')))
1569       *cp = '\0';
1570
1571     if ((cp = strtok(line, " \t")) == NULL)
1572       continue; /* no tokens in the line */
1573
1574     ret = inet_pton(AF_INET6, cp, &host_addr);
1575     if (ret == -1)
1576       continue; /* error parsing */
1577     if (ret == 1) {
1578       /* Valid IPv6 */
1579       is_ipv6 = TRUE;
1580     } else {
1581       /* Not valid IPv6 - valid IPv4? */
1582       if (inet_pton(AF_INET, cp, &host_addr) != 1)
1583         continue; /* no */
1584       is_ipv6 = FALSE;
1585     }
1586
1587     if ((cp = strtok(NULL, " \t")) == NULL)
1588       continue; /* no host name */
1589
1590     if (is_ipv6) {
1591       memcpy(&ipv6_addr, host_addr, sizeof ipv6_addr);
1592       add_ipv6_name(&ipv6_addr, cp);
1593     } else
1594       add_ipv4_name(host_addr[0], cp);
1595
1596     /*
1597      * Add the aliases, too, if there are any.
1598      */
1599     while ((cp = strtok(NULL, " \t")) != NULL) {
1600       if (is_ipv6) {
1601         memcpy(&ipv6_addr, host_addr, sizeof ipv6_addr);
1602         add_ipv6_name(&ipv6_addr, cp);
1603       } else
1604         add_ipv4_name(host_addr[0], cp);
1605     }
1606   }
1607   if (line != NULL)
1608     g_free(line);
1609
1610   fclose(hf);
1611   return TRUE;
1612 } /* read_hosts_file */
1613
1614 /*
1615  *  External Functions
1616  */
1617
1618 void
1619 host_name_lookup_init(void) {
1620   char *hostspath;
1621
1622 #ifdef HAVE_GNU_ADNS
1623 #ifdef WIN32
1624   char *sysroot;
1625   static char rootpath_nt[] = "\\system32\\drivers\\etc\\hosts";
1626   static char rootpath_ot[] = "\\hosts";
1627 #endif /* WIN32 */
1628 #endif /*GNU_ADNS */
1629
1630   /*
1631    * Load the user's hosts file, if they have one.
1632    */
1633   hostspath = get_persconffile_path(ENAME_HOSTS, FALSE);
1634   if (!read_hosts_file(hostspath) && errno != ENOENT) {
1635     report_open_failure(hostspath, errno, FALSE);
1636   }
1637   g_free(hostspath);
1638
1639 #ifdef HAVE_GNU_ADNS
1640   /*
1641    * We're using GNU ADNS, which doesn't check the system hosts file;
1642    * we load that file ourselves.
1643    */
1644 #ifdef WIN32
1645
1646   sysroot = getenv_utf8("WINDIR");
1647   if (sysroot != NULL) {
1648     /*
1649      * The file should be under WINDIR.
1650      * If this is Windows NT (NT 4.0,2K,XP,Server2K3), it's in
1651      * %WINDIR%\system32\drivers\etc\hosts.
1652      * If this is Windows OT (95,98,Me), it's in %WINDIR%\hosts.
1653      * Try both.
1654      * XXX - should we base it on the dwPlatformId value from
1655      * GetVersionEx()?
1656      */
1657     hostspath = g_strconcat(sysroot, rootpath_nt, NULL);
1658     if (!read_hosts_file(hostspath)) {
1659       g_free(hostspath);
1660       hostspath = g_strconcat(sysroot, rootpath_ot, NULL);
1661       read_hosts_file(hostspath);
1662     }
1663     g_free(hostspath);
1664   }
1665 #else /* WIN32 */
1666   read_hosts_file("/etc/hosts");
1667 #endif /* WIN32 */
1668
1669   /* XXX - Any flags we should be using? */
1670   /* XXX - We could provide config settings for DNS servers, and
1671            pass them to ADNS with adns_init_strcfg */
1672   if (adns_init(&ads, 0, 0 /*0=>stderr*/) != 0) {
1673     /*
1674      * XXX - should we report the error?  I'm assuming that some crashes
1675      * reported on a Windows machine with TCP/IP not configured are due
1676      * to "adns_init()" failing (due to the lack of TCP/IP) and leaving
1677      * ADNS in a state where it crashes due to that.  We'll still try
1678      * doing name resolution anyway.
1679      */
1680     return;
1681   }
1682   gnu_adns_initialized = TRUE;
1683   adns_currently_queued = 0;
1684 #endif /* HAVE_GNU_ADNS */
1685 }
1686
1687 #ifdef HAVE_GNU_ADNS
1688
1689 /* XXX - The ADNS "documentation" isn't very clear:
1690  * - Do we need to keep our query structures around?
1691  */
1692 gint
1693 host_name_lookup_process(gpointer data _U_) {
1694   adns_queue_msg_t *almsg;
1695   GList *cur;
1696   char addr_str[] = "111.222.333.444.in-addr.arpa.";
1697   guint8 *addr_bytes;
1698   adns_answer *ans;
1699   int ret;
1700   gboolean dequeue;
1701
1702   adns_queue_head = g_list_first(adns_queue_head);
1703
1704   cur = adns_queue_head;
1705   while (cur && adns_currently_queued <= prefs.name_resolve_concurrency) {
1706     almsg = (adns_queue_msg_t *) cur->data;
1707     if (! almsg->submitted && almsg->type == AF_INET) {
1708       addr_bytes = (guint8 *) &almsg->ip4_addr;
1709       g_snprintf(addr_str, sizeof addr_str, "%u.%u.%u.%u.in-addr.arpa.", addr_bytes[3],
1710           addr_bytes[2], addr_bytes[1], addr_bytes[0]);
1711       /* XXX - what if it fails? */
1712       adns_submit (ads, addr_str, adns_r_ptr, 0, NULL, &almsg->query);
1713       almsg->submitted = TRUE;
1714       adns_currently_queued++;
1715     }
1716     cur = cur->next;
1717   }
1718
1719   cur = adns_queue_head;
1720   while (cur) {
1721     dequeue = FALSE;
1722     almsg = (adns_queue_msg_t *) cur->data;
1723     if (almsg->submitted) {
1724       ret = adns_check(ads, &almsg->query, &ans, NULL);
1725       if (ret == 0) {
1726         if (ans->status == adns_s_ok) {
1727           add_ipv4_name(almsg->ip4_addr, *ans->rrs.str);
1728         }
1729         dequeue = TRUE;
1730       }
1731     }
1732     cur = cur->next;
1733     if (dequeue) {
1734       adns_queue_head = g_list_remove(adns_queue_head, (void *) almsg);
1735       g_free(almsg);
1736       adns_currently_queued--;
1737     }
1738   }
1739
1740   /* Keep the timeout in place */
1741   return 1;
1742 }
1743
1744 void
1745 host_name_lookup_cleanup(void) {
1746   void *qdata;
1747
1748   adns_queue_head = g_list_first(adns_queue_head);
1749   while (adns_queue_head) {
1750     qdata = adns_queue_head->data;
1751     adns_queue_head = g_list_remove(adns_queue_head, qdata);
1752     g_free(qdata);
1753   }
1754
1755   if (gnu_adns_initialized)
1756     adns_finish(ads);
1757 }
1758
1759 #else
1760
1761 gint
1762 host_name_lookup_process(gpointer data _U_) {
1763   /* Kill the timeout, as there's nothing for it to do */
1764   return 0;
1765 }
1766
1767 void
1768 host_name_lookup_cleanup(void) {
1769 }
1770
1771 #endif /* HAVE_GNU_ADNS */
1772
1773 extern gchar *get_hostname(guint addr)
1774 {
1775   gboolean found;
1776
1777   if (!(g_resolv_flags & RESOLV_NETWORK))
1778     return ip_to_str((guint8 *)&addr);
1779
1780   return host_name_lookup(addr, &found);
1781 }
1782
1783 extern const gchar *get_hostname6(struct e_in6_addr *addr)
1784 {
1785   gboolean found;
1786
1787   if (!(g_resolv_flags & RESOLV_NETWORK))
1788     return ip6_to_str(addr);
1789   if (E_IN6_IS_ADDR_LINKLOCAL(addr) || E_IN6_IS_ADDR_MULTICAST(addr))
1790     return ip6_to_str(addr);
1791   return host_name_lookup6(addr, &found);
1792 }
1793
1794 extern void add_ipv4_name(guint addr, const gchar *name)
1795 {
1796   int hash_idx;
1797   hashipv4_t *tp;
1798
1799   hash_idx = HASH_IPV4_ADDRESS(addr);
1800
1801   tp = ipv4_table[hash_idx];
1802
1803   if( tp == NULL ) {
1804     tp = ipv4_table[hash_idx] = (hashipv4_t *)g_malloc(sizeof(hashipv4_t));
1805   } else {
1806     while(1) {
1807       if (tp->addr == addr) {
1808         /* address already known */
1809         if (!tp->is_dummy_entry) {
1810           return;
1811         } else {
1812           /* replace this dummy entry with the new one */
1813           break;
1814         }
1815       }
1816       if (tp->next == NULL) {
1817         tp->next = (hashipv4_t *)g_malloc(sizeof(hashipv4_t));
1818         tp = tp->next;
1819         break;
1820       }
1821       tp = tp->next;
1822     }
1823   }
1824
1825   strncpy(tp->name, name, MAXNAMELEN);
1826   tp->name[MAXNAMELEN-1] = '\0';
1827   tp->addr = addr;
1828   tp->next = NULL;
1829   tp->is_dummy_entry = FALSE;
1830
1831 } /* add_ipv4_name */
1832
1833 extern void add_ipv6_name(struct e_in6_addr *addrp, const gchar *name)
1834 {
1835   int hash_idx;
1836   hashipv6_t *tp;
1837
1838   hash_idx = HASH_IPV6_ADDRESS(*addrp);
1839
1840   tp = ipv6_table[hash_idx];
1841
1842   if( tp == NULL ) {
1843     tp = ipv6_table[hash_idx] = (hashipv6_t *)g_malloc(sizeof(hashipv6_t));
1844   } else {
1845     while(1) {
1846       if (memcmp(&tp->addr, addrp, sizeof (struct e_in6_addr)) == 0) {
1847         /* address already known */
1848         if (!tp->is_dummy_entry) {
1849           return;
1850         } else {
1851           /* replace this dummy entry with the new one */
1852           break;
1853         }
1854       }
1855       if (tp->next == NULL) {
1856         tp->next = (hashipv6_t *)g_malloc(sizeof(hashipv6_t));
1857         tp = tp->next;
1858         break;
1859       }
1860       tp = tp->next;
1861     }
1862   }
1863
1864   strncpy(tp->name, name, MAXNAMELEN);
1865   tp->name[MAXNAMELEN-1] = '\0';
1866   tp->addr = *addrp;
1867   tp->next = NULL;
1868   tp->is_dummy_entry = FALSE;
1869
1870 } /* add_ipv6_name */
1871
1872 extern gchar *get_udp_port(guint port)
1873 {
1874   gchar *cur;
1875
1876   if (!(g_resolv_flags & RESOLV_TRANSPORT)) {
1877     cur=ep_alloc(MAXNAMELEN);
1878     g_snprintf(cur, MAXNAMELEN, "%u", port);
1879     return cur;
1880   }
1881
1882   return serv_name_lookup(port, PT_UDP);
1883
1884 } /* get_udp_port */
1885
1886 extern gchar *get_dccp_port(guint port)
1887 {
1888   gchar *cur;
1889
1890   if (!(g_resolv_flags & RESOLV_TRANSPORT)) {
1891     cur=ep_alloc(MAXNAMELEN);
1892     g_snprintf(cur, MAXNAMELEN, "%u", port);
1893     return cur;
1894   }
1895
1896   return serv_name_lookup(port, PT_DCCP);
1897
1898 } /* get_dccp_port */
1899
1900
1901 extern gchar *get_tcp_port(guint port)
1902 {
1903   gchar *cur;
1904
1905   if (!(g_resolv_flags & RESOLV_TRANSPORT)) {
1906     cur=ep_alloc(MAXNAMELEN);
1907     g_snprintf(cur, MAXNAMELEN, "%u", port);
1908     return cur;
1909   }
1910
1911   return serv_name_lookup(port, PT_TCP);
1912
1913 } /* get_tcp_port */
1914
1915 extern gchar *get_sctp_port(guint port)
1916 {
1917   gchar *cur;
1918
1919   if (!(g_resolv_flags & RESOLV_TRANSPORT)) {
1920     cur=ep_alloc(MAXNAMELEN);
1921     g_snprintf(cur, MAXNAMELEN, "%u", port);
1922     return cur;
1923   }
1924
1925   return serv_name_lookup(port, PT_SCTP);
1926
1927 } /* get_sctp_port */
1928
1929
1930 const gchar *get_addr_name(address *addr)
1931 {
1932   const gchar *result;
1933
1934   result = solve_address_to_name(addr);
1935
1936   if (result!=NULL){
1937           return result;
1938   }
1939
1940   /* if it gets here, either it is of type AT_NONE, */
1941   /* or it should be solvable in address_to_str -unless addr->type is wrongly defined- */
1942
1943   if (addr->type == AT_NONE){
1944           return "NONE";
1945   }
1946
1947   return(address_to_str(addr));
1948 } /* get_addr_name */
1949
1950
1951 void get_addr_name_buf(address *addr, gchar *buf, guint size)
1952 {
1953   const gchar *result;
1954
1955   result = get_addr_name(addr);
1956
1957   strncpy(buf,result,size);
1958   buf[size]='\0';
1959   return;
1960
1961 } /* get_addr_name_buf */
1962
1963
1964 extern gchar *get_ether_name(const guint8 *addr)
1965 {
1966   if (!(g_resolv_flags & RESOLV_MAC))
1967     return ether_to_str(addr);
1968
1969   if (!eth_resolution_initialized) {
1970     initialize_ethers();
1971     eth_resolution_initialized = 1;
1972   }
1973
1974   return eth_name_lookup(addr);
1975
1976 } /* get_ether_name */
1977
1978 /* Look for an ether name in the hash, and return it if found.
1979  * If it's not found, simply return NULL. We DO NOT make a new
1980  * hash entry for it with the hex digits turned into a string.
1981  */
1982 gchar *get_ether_name_if_known(const guint8 *addr)
1983 {
1984   int hash_idx;
1985   hashether_t *tp;
1986
1987   /* Initialize ether structs if we're the first
1988    * ether-related function called */
1989   if (!(g_resolv_flags & RESOLV_MAC))
1990     return NULL;
1991
1992   if (!eth_resolution_initialized) {
1993     initialize_ethers();
1994     eth_resolution_initialized = 1;
1995   }
1996
1997   hash_idx = HASH_ETH_ADDRESS(addr);
1998
1999   tp = eth_table[hash_idx];
2000
2001   if( tp == NULL ) {
2002           /* Hash key not found in table.
2003            * Force a lookup (and a hash entry) for addr, then call
2004            * myself. I plan on not getting into an infinite loop because
2005            * eth_name_lookup() is guaranteed to make a hashtable entry,
2006            * so when I call myself again, I can never get into this
2007            * block of code again. Knock on wood...
2008            */
2009           (void) eth_name_lookup(addr);
2010           return get_ether_name_if_known(addr); /* a well-placed goto would suffice */
2011   }
2012   else {
2013     while(1) {
2014       if (memcmp(tp->addr, addr, sizeof(tp->addr)) == 0) {
2015               if (!tp->is_dummy_entry) {
2016                 /* A name was found, and its origin is an ethers file */
2017                 return tp->name;
2018               }
2019               else {
2020                 /* A name was found, but it was created, not found in a file */
2021                 return NULL;
2022               }
2023       }
2024       if (tp->next == NULL) {
2025           /* Read my reason above for why I'm sure I can't get into an infinite loop */
2026           (void) eth_name_lookup(addr);
2027           return get_ether_name_if_known(addr); /* a well-placed goto would suffice */
2028       }
2029       tp = tp->next;
2030     }
2031   }
2032   g_assert_not_reached();
2033   return NULL;
2034 }
2035
2036
2037 extern guint8 *get_ether_addr(const gchar *name)
2038 {
2039
2040   /* force resolution (do not check g_resolv_flags) */
2041
2042   if (!eth_resolution_initialized) {
2043     initialize_ethers();
2044     eth_resolution_initialized = 1;
2045   }
2046
2047   return eth_addr_lookup(name);
2048
2049 } /* get_ether_addr */
2050
2051 extern void add_ether_byip(guint ip, const guint8 *eth)
2052 {
2053
2054   gchar *host;
2055   gboolean found;
2056
2057   /* first check that IP address can be resolved */
2058
2059   if (!(g_resolv_flags & RESOLV_NETWORK) || ((host = host_name_lookup(ip, &found)) == NULL))
2060     return;
2061
2062   /* ok, we can add this entry in the ethers hashtable */
2063
2064   if (found)
2065     add_eth_name(eth, host);
2066
2067 } /* add_ether_byip */
2068
2069 extern const gchar *get_ipxnet_name(const guint32 addr)
2070 {
2071
2072   if (!(g_resolv_flags & RESOLV_NETWORK)) {
2073           return ipxnet_to_str_punct(addr, '\0');
2074   }
2075
2076   if (!ipxnet_resolution_initialized) {
2077     initialize_ipxnets();
2078     ipxnet_resolution_initialized = 1;
2079   }
2080
2081   return ipxnet_name_lookup(addr);
2082
2083 } /* get_ipxnet_name */
2084
2085 extern guint32 get_ipxnet_addr(const gchar *name, gboolean *known)
2086 {
2087   guint32 addr;
2088   gboolean success;
2089
2090   /* force resolution (do not check g_resolv_flags) */
2091
2092   if (!ipxnet_resolution_initialized) {
2093     initialize_ipxnets();
2094     ipxnet_resolution_initialized = 1;
2095   }
2096
2097   addr =  ipxnet_addr_lookup(name, &success);
2098
2099   *known = success;
2100   return addr;
2101
2102 } /* get_ipxnet_addr */
2103
2104 extern const gchar *get_manuf_name(const guint8 *addr)
2105 {
2106   gchar *cur;
2107   hashmanuf_t  *manufp;
2108
2109   if ((g_resolv_flags & RESOLV_MAC) && !eth_resolution_initialized) {
2110     initialize_ethers();
2111     eth_resolution_initialized = 1;
2112   }
2113
2114   if (!(g_resolv_flags & RESOLV_MAC) || ((manufp = manuf_name_lookup(addr)) == NULL)) {
2115     cur=ep_alloc(MAXMANUFLEN);
2116     g_snprintf(cur, MAXMANUFLEN, "%02x:%02x:%02x", addr[0], addr[1], addr[2]);
2117     return cur;
2118   }
2119
2120   return manufp->name;
2121
2122 } /* get_manuf_name */
2123
2124
2125 const gchar *get_manuf_name_if_known(const guint8 *addr)
2126 {
2127   hashmanuf_t  *manufp;
2128
2129   if (!eth_resolution_initialized) {
2130     initialize_ethers();
2131     eth_resolution_initialized = 1;
2132   }
2133
2134   if ((manufp = manuf_name_lookup(addr)) == NULL) {
2135     return NULL;
2136   }
2137
2138   return manufp->name;
2139
2140 } /* get_manuf_name_if_known */
2141
2142
2143 /* Translate a string, assumed either to be a dotted-quad IP address or
2144  * a host name, to a numeric IP address.  Return TRUE if we succeed and
2145  * set "*addrp" to that numeric IP address; return FALSE if we fail.
2146  * Used more in the dfilter parser rather than in packet dissectors */
2147 gboolean get_host_ipaddr(const char *host, guint32 *addrp)
2148 {
2149         struct in_addr          ipaddr;
2150         struct hostent          *hp;
2151
2152         /*
2153          * don't change it to inet_pton(AF_INET), they are not 100% compatible.
2154          * inet_pton(AF_INET) does not support hexadecimal notation nor
2155          * less-than-4 octet notation.
2156          */
2157         if (!inet_aton(host, &ipaddr)) {
2158                 /* It's not a valid dotted-quad IP address; is it a valid
2159                  * host name? */
2160                 hp = gethostbyname(host);
2161                 if (hp == NULL) {
2162                         /* No. */
2163                         return FALSE;
2164                         /* Apparently, some versions of gethostbyaddr can
2165                          * return IPv6 addresses. */
2166                 } else if (hp->h_length <= (int) sizeof (struct in_addr)) {
2167                         memcpy(&ipaddr, hp->h_addr, hp->h_length);
2168                 } else {
2169                         return FALSE;
2170                 }
2171         } else {
2172                 /* Does the string really contain dotted-quad IP?
2173                  * Check against inet_atons that accept strings such as
2174                  * "130.230" as valid addresses and try to convert them
2175                  * to some form of a classful (host.net) notation.
2176                  */
2177                 unsigned int a0, a1, a2, a3;
2178                 if (sscanf(host, "%u.%u.%u.%u", &a0, &a1, &a2, &a3) != 4)
2179                         return FALSE;
2180         }
2181
2182         *addrp = g_ntohl(ipaddr.s_addr);
2183         return TRUE;
2184 }
2185
2186 /*
2187  * Translate IPv6 numeric address or FQDN hostname, into binary IPv6 address.
2188  * Return TRUE if we succeed and set "*addrp" to that numeric IP address;
2189  * return FALSE if we fail.
2190  */
2191 gboolean get_host_ipaddr6(const char *host, struct e_in6_addr *addrp)
2192 {
2193         struct hostent *hp;
2194
2195         if (inet_pton(AF_INET6, host, addrp) == 1)
2196                 return TRUE;
2197
2198         /* try FQDN */
2199 #ifdef HAVE_GETHOSTBYNAME2
2200         hp = gethostbyname2(host, AF_INET6);
2201 #else
2202         hp = NULL;
2203 #endif
2204         if (hp != NULL && hp->h_length == sizeof(struct e_in6_addr)) {
2205                 memcpy(addrp, hp->h_addr, hp->h_length);
2206                 return TRUE;
2207         }
2208
2209         return FALSE;
2210 }
2211
2212 /*
2213  * Find out whether a hostname resolves to an ip or ipv6 address
2214  * Return "ip6" if it is IPv6, "ip" otherwise (including the case
2215  * that we don't know)
2216  */
2217 const char* host_ip_af(const char *host
2218 #ifndef HAVE_GETHOSTBYNAME2
2219 _U_
2220 #endif
2221 )
2222 {
2223 #ifdef HAVE_GETHOSTBYNAME2
2224         struct hostent *h;
2225         return (h = gethostbyname2(host, AF_INET6)) && h->h_addrtype == AF_INET6 ? "ip6" : "ip";
2226 #else
2227         return "ip";
2228 #endif
2229 }