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