Move the file utility functions from wiretap to libwsutil so that
[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  * Wireshark - Network traffic analyzer
9  * By Gerald Combs <gerald@wireshark.org>
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_GNU_ADNS
67 # include <errno.h>
68 # include <adns.h>
69 # ifdef inet_aton
70 #  undef inet_aton
71 # endif
72 #endif
73
74 #ifdef HAVE_UNISTD_H
75 #include <unistd.h>
76 #endif
77
78 #ifdef HAVE_NETINET_IN_H
79 # include <netinet/in.h>
80 #endif
81
82 #ifdef HAVE_NETDB_H
83 #include <netdb.h>
84 #endif
85
86 #ifdef HAVE_ARPA_INET_H
87 #include <arpa/inet.h>
88 #endif
89
90 #include <signal.h>
91
92 #ifdef HAVE_SYS_SOCKET_H
93 #include <sys/socket.h>         /* needed to define AF_ values on UNIX */
94 #endif
95
96 #ifdef HAVE_WINSOCK2_H
97 #include <winsock2.h>           /* needed to define AF_ values on Windows */
98 #endif
99
100 #ifdef AVOID_DNS_TIMEOUT
101 # include <setjmp.h>
102 #endif
103
104 #ifdef NEED_INET_ATON_H
105 # include "inet_aton.h"
106 #endif
107
108 #ifdef NEED_INET_V6DEFS_H
109 # include "inet_v6defs.h"
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
124 #include <epan/strutil.h>
125 #include <wsutil/file_util.h>
126 #include <epan/prefs.h>
127 #include <epan/emem.h>
128
129 #define ENAME_HOSTS             "hosts"
130 #define ENAME_SUBNETS   "subnets"
131 #define ENAME_ETHERS            "ethers"
132 #define ENAME_IPXNETS           "ipxnets"
133 #define ENAME_MANUF             "manuf"
134 #define ENAME_SERVICES  "services"
135
136 #define MAXMANUFLEN     9       /* max vendor name length with ending '\0' */
137 #define HASHETHSIZE     1024
138 #define HASHHOSTSIZE    1024
139 #define HASHIPXNETSIZE  256
140 #define HASHMANUFSIZE   256
141 #define HASHPORTSIZE    256
142 #define SUBNETLENGTHSIZE 32 /*1-32 inc.*/
143
144 /* hash table used for IPv4 lookup */
145
146 #define HASH_IPV4_ADDRESS(addr) ((addr) & (HASHHOSTSIZE - 1))
147
148 typedef struct hashipv4 {
149   guint                 addr;
150   gboolean              is_dummy_entry; /* name is IPv4 address in dot format */
151   struct hashipv4       *next;
152   gchar                 name[MAXNAMELEN];
153 } hashipv4_t;
154
155 /* hash table used for IPv6 lookup */
156
157 #define HASH_IPV6_ADDRESS(addr) \
158         ((((addr).bytes[14] << 8)|((addr).bytes[15])) & (HASHHOSTSIZE - 1))
159
160 typedef struct hashipv6 {
161   struct e_in6_addr     addr;
162   gchar                 name[MAXNAMELEN];
163   gboolean              is_dummy_entry; /* name is IPv6 address in colon format */
164   struct hashipv6       *next;
165 } hashipv6_t;
166
167 /* Array of entries of subnets of different lengths */
168 typedef struct {
169     gsize mask_length; /*1-32*/
170     guint32 mask;        /* e.g. 255.255.255.*/
171     hashipv4_t** subnet_addresses; /* Hash table of subnet addresses */
172 } subnet_length_entry_t;
173
174 /* hash table used for TCP/UDP/SCTP port lookup */
175
176 #define HASH_PORT(port) ((port) & (HASHPORTSIZE - 1))
177
178 typedef struct hashport {
179   guint16               port;
180   gchar                 name[MAXNAMELEN];
181   struct hashport       *next;
182 } hashport_t;
183
184 /* hash table used for IPX network lookup */
185
186 /* XXX - check goodness of hash function */
187
188 #define HASH_IPX_NET(net)       ((net) & (HASHIPXNETSIZE - 1))
189
190 typedef struct hashipxnet {
191   guint                 addr;
192   gchar                 name[MAXNAMELEN];
193   struct hashipxnet     *next;
194 } hashipxnet_t;
195
196 /* hash tables used for ethernet and manufacturer lookup */
197
198 #define HASH_ETH_ADDRESS(addr) \
199         (((((addr)[2] << 8) | (addr)[3]) ^ (((addr)[4] << 8) | (addr)[5])) & \
200          (HASHETHSIZE - 1))
201
202 #define HASH_ETH_MANUF(addr) (((int)(addr)[2]) & (HASHMANUFSIZE - 1))
203
204 typedef struct hashmanuf {
205   guint8                addr[3];
206   char                  name[MAXMANUFLEN];
207   struct hashmanuf      *next;
208 } hashmanuf_t;
209
210 typedef struct hashether {
211   guint8                addr[6];
212   char                  name[MAXNAMELEN];
213   gboolean              is_dummy_entry;         /* not a complete entry */
214   struct hashether      *next;
215 } hashether_t;
216
217 /* internal ethernet type */
218
219 typedef struct _ether
220 {
221   guint8                addr[6];
222   char                  name[MAXNAMELEN];
223 } ether_t;
224
225 /* internal ipxnet type */
226
227 typedef struct _ipxnet
228 {
229   guint                 addr;
230   char                  name[MAXNAMELEN];
231 } ipxnet_t;
232
233 static hashipv4_t       *ipv4_table[HASHHOSTSIZE];
234 static hashipv6_t       *ipv6_table[HASHHOSTSIZE];
235
236 static hashport_t       **cb_port_table;
237 static gchar            *cb_service;
238
239 static hashport_t       *udp_port_table[HASHPORTSIZE];
240 static hashport_t       *tcp_port_table[HASHPORTSIZE];
241 static hashport_t       *sctp_port_table[HASHPORTSIZE];
242 static hashport_t       *dccp_port_table[HASHPORTSIZE];
243 static hashether_t      *eth_table[HASHETHSIZE];
244 static hashmanuf_t      *manuf_table[HASHMANUFSIZE];
245 static hashether_t      *(*wka_table[48])[HASHETHSIZE];
246 static hashipxnet_t     *ipxnet_table[HASHIPXNETSIZE];
247
248 static subnet_length_entry_t subnet_length_entries[SUBNETLENGTHSIZE]; /* Ordered array of entries */
249 static gboolean have_subnet_entry = FALSE;
250
251 static int              eth_resolution_initialized = 0;
252 static int              ipxnet_resolution_initialized = 0;
253 static int              service_resolution_initialized = 0;
254
255 static hashether_t *add_eth_name(const guint8 *addr, const gchar *name);
256 static void add_serv_port_cb(guint32 port);
257
258 /*
259  * Flag controlling what names to resolve.
260  */
261 guint32 g_resolv_flags;
262
263 /*
264  *  Global variables (can be changed in GUI sections)
265  *  XXX - they could be changed in GUI code, but there's currently no
266  *  GUI code to change them.
267  */
268
269 gchar *g_ethers_path  = NULL;           /* global ethers file    */
270 gchar *g_pethers_path = NULL;           /* personal ethers file  */
271 gchar *g_ipxnets_path  = NULL;          /* global ipxnets file   */
272 gchar *g_pipxnets_path = NULL;          /* personal ipxnets file */
273 gchar *g_services_path  = NULL;         /* global services file   */
274 gchar *g_pservices_path = NULL;         /* personal services file */
275                                         /* first resolving call  */
276
277 /* GNU ADNS */
278
279 #ifdef HAVE_GNU_ADNS
280
281 static gboolean gnu_adns_initialized = FALSE;
282
283 adns_state ads;
284
285 int adns_currently_queued = 0;
286
287 typedef struct _adns_queue_msg
288 {
289   gboolean          submitted;
290   guint32           ip4_addr;
291   struct e_in6_addr ip6_addr;
292   int               type;
293   adns_query        query;
294 } adns_queue_msg_t;
295
296 GList *adns_queue_head = NULL;
297
298 #endif /* HAVE_GNU_ADNS */
299
300 typedef struct {
301     guint32 mask;
302     gsize mask_length;
303     const gchar* name; /* Shallow copy */
304 } subnet_entry_t;
305
306 /*
307  *  Miscellaneous functions
308  */
309
310 static int fgetline(char **buf, int *size, FILE *fp)
311 {
312   int len;
313   int c;
314
315   if (fp == NULL)
316     return -1;
317
318   if (*buf == NULL) {
319     if (*size == 0)
320       *size = BUFSIZ;
321
322     if ((*buf = g_malloc(*size)) == NULL)
323       return -1;
324   }
325
326   if (feof(fp))
327     return -1;
328
329   len = 0;
330   while ((c = getc(fp)) != EOF && c != '\r' && c != '\n') {
331     if (len+1 >= *size) {
332       if ((*buf = g_realloc(*buf, *size += BUFSIZ)) == NULL)
333         return -1;
334     }
335     (*buf)[len++] = c;
336   }
337
338   if (len == 0 && c == EOF)
339     return -1;
340
341   (*buf)[len] = '\0';
342
343   return len;
344
345 } /* fgetline */
346
347
348 /*
349  *  Local function definitions
350  */
351 static subnet_entry_t subnet_lookup(const guint32 addr);
352 static void subnet_entry_set(guint32 subnet_addr, guint32 mask_length, const gchar* name);
353
354
355 static void add_service_name(hashport_t **proto_table, guint port, const char *service_name)
356 {
357   int hash_idx;
358   hashport_t *tp;
359
360
361   hash_idx = HASH_PORT(port);
362   tp = proto_table[hash_idx];
363
364   if( tp == NULL ) {
365     tp = proto_table[hash_idx] = (hashport_t *)g_malloc(sizeof(hashport_t));
366   } else {
367     while(1) {
368       if( tp->port == port ) {
369         return;
370       }
371       if (tp->next == NULL) {
372         tp->next = (hashport_t *)g_malloc(sizeof(hashport_t));
373         tp = tp->next;
374         break;
375       }
376       tp = tp->next;
377     }
378   }
379
380   /* fill in a new entry */
381   tp->port = port;
382   tp->next = NULL;
383
384   g_strlcpy(tp->name, service_name, MAXNAMELEN);
385 }
386
387
388 static void parse_service_line (char *line)
389 {
390   /*
391    *  See the services(4) or services(5) man page for services file format
392    *  (not available on all systems).
393    */
394
395   gchar *cp;
396   gchar *service;
397   gchar *port;
398
399   range_t *port_rng = NULL;
400   guint32 max_port = MAX_UDP_PORT;
401
402   if ((cp = strchr(line, '#')))
403     *cp = '\0';
404
405   if ((cp = strtok(line, " \t")) == NULL)
406     return;
407
408   service = cp;
409
410   if ((cp = strtok(NULL, " \t")) == NULL)
411     return;
412
413   port = cp;
414
415   if ((cp = strtok(cp, "/")) == NULL)
416     return;
417
418   if ((cp = strtok(NULL, "/")) == NULL)
419     return;
420
421   /* seems we got all interesting things from the file */
422   if(strcmp(cp, "tcp") == 0) {
423     max_port = MAX_TCP_PORT;
424     cb_port_table = tcp_port_table;
425   }
426   else if(strcmp(cp, "udp") == 0) {
427     max_port = MAX_UDP_PORT;
428     cb_port_table = udp_port_table;
429   }
430   else if(strcmp(cp, "sctp") == 0) {
431     max_port = MAX_SCTP_PORT;
432     cb_port_table = sctp_port_table;
433   }
434   else if(strcmp(cp, "dccp") == 0) {
435     max_port = MAX_DCCP_PORT;
436     cb_port_table = dccp_port_table;
437   } else {
438     return;
439   }
440
441   if(CVT_NO_ERROR != range_convert_str(&port_rng, port, max_port) ) {
442     /* some assertion here? */
443     return;
444   }
445
446   cb_service = service;
447   range_foreach(port_rng, add_serv_port_cb);
448
449 } /* parse_service_line */
450
451
452 static void
453 add_serv_port_cb(guint32 port)
454 {
455     if ( port ) {
456       add_service_name(cb_port_table, port, cb_service);
457     }
458 }
459
460
461 static void parse_services_file(const char * path)
462 {
463   FILE *serv_p;
464   static int     size = 0;
465   static char   *buf = NULL;
466
467   /* services hash table initialization */
468   serv_p = ws_fopen(path, "r");
469
470   if (serv_p == NULL)
471     return;
472
473   while (fgetline(&buf, &size, serv_p) >= 0) {
474     parse_service_line (buf);
475   }
476
477   fclose(serv_p);
478 }
479
480
481 static void initialize_services(void)
482 {
483
484   /* the hash table won't ignore duplicates, so use the personal path first */
485
486   /* set personal services path */
487   if (g_pservices_path == NULL)
488     g_pservices_path = get_persconffile_path(ENAME_SERVICES, FALSE, FALSE);
489
490   parse_services_file(g_pservices_path);
491
492   /* Compute the pathname of the services file. */
493   if (g_services_path == NULL) {
494     g_services_path = get_datafile_path(ENAME_SERVICES);
495   }
496
497   parse_services_file(g_services_path);
498
499 } /* initialize_services */
500
501
502
503 static gchar *serv_name_lookup(guint port, port_type proto)
504 {
505   int hash_idx;
506   hashport_t *tp;
507   hashport_t **table;
508   const char *serv_proto = NULL;
509   struct servent *servp;
510
511
512   if (!service_resolution_initialized) {
513     initialize_services();
514     service_resolution_initialized = 1;
515   }
516
517   switch(proto) {
518   case PT_UDP:
519     table = udp_port_table;
520     serv_proto = "udp";
521     break;
522   case PT_TCP:
523     table = tcp_port_table;
524     serv_proto = "tcp";
525     break;
526   case PT_SCTP:
527     table = sctp_port_table;
528     serv_proto = "sctp";
529     break;
530   case PT_DCCP:
531     table = dccp_port_table;
532     serv_proto = "dcp";
533     break;
534   default:
535     /* not yet implemented */
536     return NULL;
537     /*NOTREACHED*/
538   } /* proto */
539
540   hash_idx = HASH_PORT(port);
541   tp = table[hash_idx];
542
543   if( tp == NULL ) {
544     tp = table[hash_idx] = (hashport_t *)g_malloc(sizeof(hashport_t));
545   } else {
546     while(1) {
547       if( tp->port == port ) {
548         return tp->name;
549       }
550       if (tp->next == NULL) {
551         tp->next = (hashport_t *)g_malloc(sizeof(hashport_t));
552         tp = tp->next;
553         break;
554       }
555       tp = tp->next;
556     }
557   }
558
559   /* fill in a new entry */
560   tp->port = port;
561   tp->next = NULL;
562
563   if (!(g_resolv_flags & RESOLV_TRANSPORT) ||
564       (servp = getservbyport(g_htons(port), serv_proto)) == NULL) {
565     /* unknown port */
566     g_snprintf(tp->name, MAXNAMELEN, "%d", port);
567   } else {
568     g_strlcpy(tp->name, servp->s_name, MAXNAMELEN);
569   }
570
571   return (tp->name);
572
573 } /* serv_name_lookup */
574
575
576 #ifdef AVOID_DNS_TIMEOUT
577
578 #define DNS_TIMEOUT     2       /* max sec per call */
579
580 jmp_buf hostname_env;
581
582 static void abort_network_query(int sig _U_)
583 {
584   longjmp(hostname_env, 1);
585 }
586 #endif /* AVOID_DNS_TIMEOUT */
587
588 /* Fill in an IP4 structure with info from subnets file or just with
589  * string form of address.
590  */
591 static void fill_dummy_ip4(guint addr, hashipv4_t* volatile tp)
592 {
593   subnet_entry_t subnet_entry;
594   tp->is_dummy_entry = TRUE; /* Overwrite if we get async DNS reply */
595
596   /* Do we have a subnet for this address? */
597   subnet_entry = subnet_lookup(addr);
598   if(0 != subnet_entry.mask) {
599         /* Print name, then '.' then IP address after subnet mask */
600       guint32 host_addr;
601       gchar buffer[MAX_IP_STR_LEN];
602       gchar* paddr;
603       gsize i;
604
605       host_addr = addr & (~(guint32)subnet_entry.mask);
606       ip_to_str_buf((guint8 *)&host_addr, buffer, MAX_IP_STR_LEN);
607       paddr = buffer;
608
609       /* Skip to first octet that is not totally masked
610        * If length of mask is 32, we chomp the whole address.
611        * If the address string starts '.' (should not happen?),
612        * we skip that '.'.
613        */
614       i = subnet_entry.mask_length / 8;
615       while(*(paddr) != '\0' && i > 0) {
616         if(*(++paddr) == '.') {
617             --i;
618         }
619       }
620
621       /* There are more efficient ways to do this, but this is safe if we
622        * trust g_snprintf and MAXNAMELEN
623        */
624       g_snprintf(tp->name, MAXNAMELEN, "%s%s", subnet_entry.name, paddr);
625   } else {
626       ip_to_str_buf((guint8 *)&addr, tp->name, MAXNAMELEN);
627   }
628 }
629
630 static gchar *host_name_lookup(guint addr, gboolean *found)
631 {
632   int hash_idx;
633   hashipv4_t * volatile tp;
634   struct hostent *hostp;
635 #ifdef HAVE_GNU_ADNS
636   adns_queue_msg_t *qmsg;
637 #endif
638
639   *found = TRUE;
640
641   hash_idx = HASH_IPV4_ADDRESS(addr);
642
643   tp = ipv4_table[hash_idx];
644
645   if( tp == NULL ) {
646     tp = ipv4_table[hash_idx] = (hashipv4_t *)g_malloc(sizeof(hashipv4_t));
647   } else {
648     while(1) {
649       if( tp->addr == addr ) {
650         if (tp->is_dummy_entry)
651           *found = FALSE;
652         return tp->name;
653       }
654       if (tp->next == NULL) {
655         tp->next = (hashipv4_t *)g_malloc(sizeof(hashipv4_t));
656         tp = tp->next;
657         break;
658       }
659       tp = tp->next;
660     }
661   }
662
663   /* fill in a new entry */
664   tp->addr = addr;
665   tp->next = NULL;
666
667 #ifdef HAVE_GNU_ADNS
668   if ((g_resolv_flags & RESOLV_CONCURRENT) &&
669       prefs.name_resolve_concurrency > 0 &&
670       gnu_adns_initialized) {
671     qmsg = g_malloc(sizeof(adns_queue_msg_t));
672     qmsg->type = AF_INET;
673     qmsg->ip4_addr = addr;
674     qmsg->submitted = FALSE;
675     adns_queue_head = g_list_append(adns_queue_head, (gpointer) qmsg);
676
677     /* XXX found is set to TRUE, which seems a bit odd, but I'm not
678      * going to risk changing the semantics.
679      */
680     fill_dummy_ip4(addr, tp);
681     return tp->name;
682   }
683 #endif /* HAVE_GNU_ADNS */
684
685   /*
686    * The Windows "gethostbyaddr()" insists on translating 0.0.0.0 to
687    * the name of the host on which it's running; to work around that
688    * botch, we don't try to translate an all-zero IP address to a host
689    * name.
690    */
691   if (addr != 0 && (g_resolv_flags & RESOLV_NETWORK)) {
692   /* Use async DNS if possible, else fall back to timeouts,
693    * else call gethostbyaddr and hope for the best
694    */
695
696 # ifdef AVOID_DNS_TIMEOUT
697
698     /* Quick hack to avoid DNS/YP timeout */
699
700     if (!setjmp(hostname_env)) {
701       signal(SIGALRM, abort_network_query);
702       alarm(DNS_TIMEOUT);
703 # endif /* AVOID_DNS_TIMEOUT */
704
705       hostp = gethostbyaddr((char *)&addr, 4, AF_INET);
706
707 # ifdef AVOID_DNS_TIMEOUT
708       alarm(0);
709 # endif /* AVOID_DNS_TIMEOUT */
710
711       if (hostp != NULL) {
712         g_strlcpy(tp->name, hostp->h_name, MAXNAMELEN);
713         tp->is_dummy_entry = FALSE;
714         return tp->name;
715       }
716
717 # ifdef AVOID_DNS_TIMEOUT
718     }
719 # endif /* AVOID_DNS_TIMEOUT */
720
721   }
722
723   /* unknown host or DNS timeout */
724   *found = FALSE;
725
726   fill_dummy_ip4(addr, tp);
727   return (tp->name);
728
729 } /* host_name_lookup */
730
731 static gchar *host_name_lookup6(struct e_in6_addr *addr, gboolean *found)
732 {
733   int hash_idx;
734   hashipv6_t * volatile tp;
735 #ifdef INET6
736   struct hostent *hostp;
737 #endif
738
739   *found = TRUE;
740
741   hash_idx = HASH_IPV6_ADDRESS(*addr);
742
743   tp = ipv6_table[hash_idx];
744
745   if( tp == NULL ) {
746     tp = ipv6_table[hash_idx] = (hashipv6_t *)g_malloc(sizeof(hashipv6_t));
747   } else {
748     while(1) {
749       if( memcmp(&tp->addr, addr, sizeof (struct e_in6_addr)) == 0 ) {
750         if (tp->is_dummy_entry)
751           *found = FALSE;
752         return tp->name;
753       }
754       if (tp->next == NULL) {
755         tp->next = (hashipv6_t *)g_malloc(sizeof(hashipv6_t));
756         tp = tp->next;
757         break;
758       }
759       tp = tp->next;
760     }
761   }
762
763   /* fill in a new entry */
764   tp->addr = *addr;
765   tp->next = NULL;
766
767 #ifdef INET6
768   if (g_resolv_flags & RESOLV_NETWORK) {
769 #ifdef AVOID_DNS_TIMEOUT
770
771     /* Quick hack to avoid DNS/YP timeout */
772
773     if (!setjmp(hostname_env)) {
774       signal(SIGALRM, abort_network_query);
775       alarm(DNS_TIMEOUT);
776 #endif /* AVOID_DNS_TIMEOUT */
777       hostp = gethostbyaddr((char *)addr, sizeof(*addr), AF_INET6);
778 #ifdef AVOID_DNS_TIMEOUT
779       alarm(0);
780 # endif /* AVOID_DNS_TIMEOUT */
781
782       if (hostp != NULL) {
783         g_strlcpy(tp->name, hostp->h_name, MAXNAMELEN);
784         tp->is_dummy_entry = FALSE;
785         return tp->name;
786       }
787
788 #ifdef AVOID_DNS_TIMEOUT
789     }
790 # endif /* AVOID_DNS_TIMEOUT */
791
792   }
793
794   /* unknown host or DNS timeout */
795 #endif /* INET6 */
796   ip6_to_str_buf(addr, tp->name);
797   tp->is_dummy_entry = TRUE;
798   *found = FALSE;
799   return (tp->name);
800
801 } /* host_name_lookup6 */
802
803 static const gchar *solve_address_to_name(address *addr)
804 {
805   guint32 ipv4_addr;
806   struct e_in6_addr ipv6_addr;
807
808   switch (addr->type) {
809
810   case AT_ETHER:
811     return get_ether_name(addr->data);
812
813   case AT_IPv4:
814     memcpy(&ipv4_addr, addr->data, sizeof ipv4_addr);
815     return get_hostname(ipv4_addr);
816
817   case AT_IPv6:
818     memcpy(&ipv6_addr.bytes, addr->data, sizeof ipv6_addr.bytes);
819     return get_hostname6(&ipv6_addr);
820
821   case AT_STRINGZ:
822     return addr->data;
823
824   default:
825     return NULL;
826   }
827 } /* solve_address_to_name */
828
829
830 /*
831  * Ethernet / manufacturer resolution
832  *
833  * The following functions implement ethernet address resolution and
834  * ethers files parsing (see ethers(4)).
835  *
836  * The manuf file has the same format as ethers(4) except that names are
837  * truncated to MAXMANUFLEN-1 characters and that an address contains
838  * only 3 bytes (instead of 6).
839  *
840  * Notes:
841  *
842  * I decide to not use the existing functions (see ethers(3) on some
843  * operating systems) for the following reasons:
844  * - performance gains (use of hash tables and some other enhancements),
845  * - use of two ethers files (system-wide and per user),
846  * - avoid the use of NIS maps,
847  * - lack of these functions on some systems.
848  *
849  * So the following functions do _not_ behave as the standard ones.
850  *
851  * -- Laurent.
852  */
853
854
855 /*
856  * If "manuf_file" is FALSE, parse a 6-byte MAC address.
857  * If "manuf_file" is TRUE, parse an up-to-6-byte sequence with an optional
858  * mask.
859  */
860 static gboolean
861 parse_ether_address(const char *cp, ether_t *eth, unsigned int *mask,
862                     gboolean manuf_file)
863 {
864   int i;
865   unsigned long num;
866   char *p;
867   char sep = '\0';
868
869   for (i = 0; i < 6; i++) {
870     /* Get a hex number, 1 or 2 digits, no sign characters allowed. */
871     if (!isxdigit((unsigned char)*cp))
872       return FALSE;
873     num = strtoul(cp, &p, 16);
874     if (p == cp)
875       return FALSE;     /* failed */
876     if (num > 0xFF)
877       return FALSE;     /* not a valid octet */
878     eth->addr[i] = (guint8) num;
879     cp = p;             /* skip past the number */
880
881     /* OK, what character terminated the octet? */
882     if (*cp == '/') {
883       /* "/" - this has a mask. */
884       if (!manuf_file) {
885         /* Entries with masks are allowed only in the "manuf" files. */
886         return FALSE;
887       }
888       cp++;     /* skip past the '/' to get to the mask */
889       if (!isdigit((unsigned char)*cp))
890         return FALSE;   /* no sign allowed */
891       num = strtoul(cp, &p, 10);
892       if (p == cp)
893         return FALSE;   /* failed */
894       cp = p;   /* skip past the number */
895       if (*cp != '\0' && !isspace((unsigned char)*cp))
896         return FALSE;   /* bogus terminator */
897       if (num == 0 || num >= 48)
898         return FALSE;   /* bogus mask */
899       /* Mask out the bits not covered by the mask */
900       *mask = num;
901       for (i = 0; num >= 8; i++, num -= 8)
902         ;       /* skip octets entirely covered by the mask */
903       /* Mask out the first masked octet */
904       eth->addr[i] &= (0xFF << (8 - num));
905       i++;
906       /* Mask out completely-masked-out octets */
907       for (; i < 6; i++)
908         eth->addr[i] = 0;
909       return TRUE;
910     }
911     if (*cp == '\0') {
912       /* We're at the end of the address, and there's no mask. */
913       if (i == 2) {
914         /* We got 3 bytes, so this is a manufacturer ID. */
915         if (!manuf_file) {
916           /* Manufacturer IDs are only allowed in the "manuf"
917              files. */
918           return FALSE;
919         }
920         /* Indicate that this is a manufacturer ID (0 is not allowed
921            as a mask). */
922         *mask = 0;
923         return TRUE;
924       }
925
926       if (i == 5) {
927         /* We got 6 bytes, so this is a MAC address.
928            If we're reading one of the "manuf" files, indicate that
929            this is a MAC address (48 is not allowed as a mask). */
930         if (manuf_file)
931           *mask = 48;
932         return TRUE;
933       }
934
935       /* We didn't get 3 or 6 bytes, and there's no mask; this is
936          illegal. */
937       return FALSE;
938     } else {
939       if (sep == '\0') {
940         /* We don't know the separator used in this number; it can either
941            be ':', '-', or '.'. */
942         if (*cp != ':' && *cp != '-' && *cp != '.')
943           return FALSE;
944         sep = *cp;      /* subsequent separators must be the same */
945       } else {
946           /* It has to be the same as the first separator */
947           if (*cp != sep)
948             return FALSE;
949       }
950     }
951     cp++;
952   }
953
954   return TRUE;
955 }
956
957 static int parse_ether_line(char *line, ether_t *eth, unsigned int *mask,
958                             gboolean manuf_file)
959 {
960   /*
961    *  See the ethers(4) or ethers(5) man page for ethers file format
962    *  (not available on all systems).
963    *  We allow both ethernet address separators (':' and '-'),
964    *  as well as Wireshark's '.' separator.
965    */
966
967   gchar *cp;
968
969   if ((cp = strchr(line, '#')))
970     *cp = '\0';
971
972   if ((cp = strtok(line, " \t")) == NULL)
973     return -1;
974
975   if (!parse_ether_address(cp, eth, mask, manuf_file))
976     return -1;
977
978   if ((cp = strtok(NULL, " \t")) == NULL)
979     return -1;
980
981   g_strlcpy(eth->name, cp, MAXNAMELEN);
982
983   return 0;
984
985 } /* parse_ether_line */
986
987 static FILE *eth_p = NULL;
988
989 static void set_ethent(char *path)
990 {
991   if (eth_p)
992     rewind(eth_p);
993   else
994     eth_p = ws_fopen(path, "r");
995 }
996
997 static void end_ethent(void)
998 {
999   if (eth_p) {
1000     fclose(eth_p);
1001     eth_p = NULL;
1002   }
1003 }
1004
1005 static ether_t *get_ethent(unsigned int *mask, gboolean manuf_file)
1006 {
1007
1008   static ether_t eth;
1009   static int     size = 0;
1010   static char   *buf = NULL;
1011
1012   if (eth_p == NULL)
1013     return NULL;
1014
1015   while (fgetline(&buf, &size, eth_p) >= 0) {
1016     if (parse_ether_line(buf, &eth, mask, manuf_file) == 0) {
1017       return &eth;
1018     }
1019   }
1020
1021   return NULL;
1022
1023 } /* get_ethent */
1024
1025 static ether_t *get_ethbyname(const gchar *name)
1026 {
1027   ether_t *eth;
1028
1029   set_ethent(g_pethers_path);
1030
1031   while ((eth = get_ethent(NULL, FALSE)) && strncmp(name, eth->name, MAXNAMELEN) != 0)
1032     ;
1033
1034   if (eth == NULL) {
1035     end_ethent();
1036
1037     set_ethent(g_ethers_path);
1038
1039     while ((eth = get_ethent(NULL, FALSE)) && strncmp(name, eth->name, MAXNAMELEN) != 0)
1040       ;
1041
1042     end_ethent();
1043   }
1044
1045   return eth;
1046
1047 } /* get_ethbyname */
1048
1049 static ether_t *get_ethbyaddr(const guint8 *addr)
1050 {
1051
1052   ether_t *eth;
1053
1054   set_ethent(g_pethers_path);
1055
1056   while ((eth = get_ethent(NULL, FALSE)) && memcmp(addr, eth->addr, 6) != 0)
1057     ;
1058
1059   if (eth == NULL) {
1060     end_ethent();
1061
1062     set_ethent(g_ethers_path);
1063
1064     while ((eth = get_ethent(NULL, FALSE)) && memcmp(addr, eth->addr, 6) != 0)
1065       ;
1066
1067     end_ethent();
1068   }
1069
1070   return eth;
1071
1072 } /* get_ethbyaddr */
1073
1074 static int hash_eth_wka(const guint8 *addr, unsigned int mask)
1075 {
1076   if (mask <= 8) {
1077     /* All but the topmost byte is masked out */
1078     return (addr[0] & (0xFF << (8 - mask))) & (HASHETHSIZE - 1);
1079   }
1080   mask -= 8;
1081   if (mask <= 8) {
1082     /* All but the topmost 2 bytes are masked out */
1083     return ((addr[0] << 8) | (addr[1] & (0xFF << (8 - mask)))) &
1084             (HASHETHSIZE - 1);
1085   }
1086   mask -= 8;
1087   if (mask <= 8) {
1088     /* All but the topmost 3 bytes are masked out */
1089     return ((addr[0] << 16) | (addr[1] << 8) | (addr[2] & (0xFF << (8 - mask))))
1090      & (HASHETHSIZE - 1);
1091   }
1092   mask -= 8;
1093   if (mask <= 8) {
1094     /* All but the topmost 4 bytes are masked out */
1095     return ((((addr[0] << 8) | addr[1]) ^
1096              ((addr[2] << 8) | (addr[3] & (0xFF << (8 - mask)))))) &
1097          (HASHETHSIZE - 1);
1098   }
1099   mask -= 8;
1100   if (mask <= 8) {
1101     /* All but the topmost 5 bytes are masked out */
1102     return ((((addr[1] << 8) | addr[2]) ^
1103              ((addr[3] << 8) | (addr[4] & (0xFF << (8 - mask)))))) &
1104          (HASHETHSIZE - 1);
1105   }
1106   mask -= 8;
1107   /* No bytes are fully masked out */
1108   return ((((addr[1] << 8) | addr[2]) ^
1109            ((addr[3] << 8) | (addr[4] & (0xFF << (8 - mask)))))) &
1110             (HASHETHSIZE - 1);
1111 }
1112
1113 static void add_manuf_name(guint8 *addr, unsigned int mask, gchar *name)
1114 {
1115   int hash_idx;
1116   hashmanuf_t *tp;
1117   hashether_t *(*wka_tp)[HASHETHSIZE], *etp;
1118
1119   if (mask == 48) {
1120     /* This is a well-known MAC address; just add this to the Ethernet
1121        hash table */
1122     add_eth_name(addr, name);
1123     return;
1124   }
1125
1126   if (mask == 0) {
1127     /* This is a manufacturer ID; add it to the manufacturer ID hash table */
1128
1129     hash_idx = HASH_ETH_MANUF(addr);
1130
1131     tp = manuf_table[hash_idx];
1132
1133     if( tp == NULL ) {
1134       tp = manuf_table[hash_idx] = (hashmanuf_t *)g_malloc(sizeof(hashmanuf_t));
1135     } else {
1136       while(1) {
1137         if (tp->next == NULL) {
1138           tp->next = (hashmanuf_t *)g_malloc(sizeof(hashmanuf_t));
1139           tp = tp->next;
1140           break;
1141         }
1142         tp = tp->next;
1143       }
1144     }
1145
1146     memcpy(tp->addr, addr, sizeof(tp->addr));
1147     g_strlcpy(tp->name, name, MAXMANUFLEN);
1148     tp->next = NULL;
1149     return;
1150   }
1151
1152   /* This is a range of well-known addresses; add it to the appropriate
1153      well-known-address table, creating that table if necessary. */
1154   wka_tp = wka_table[mask];
1155   if (wka_tp == NULL)
1156     wka_tp = wka_table[mask] = g_malloc0(sizeof *wka_table[mask]);
1157
1158   hash_idx = hash_eth_wka(addr, mask);
1159
1160   etp = (*wka_tp)[hash_idx];
1161
1162   if( etp == NULL ) {
1163     etp = (*wka_tp)[hash_idx] = (hashether_t *)g_malloc(sizeof(hashether_t));
1164   } else {
1165     while(1) {
1166       if (memcmp(etp->addr, addr, sizeof(etp->addr)) == 0) {
1167         /* address already known */
1168         return;
1169       }
1170       if (etp->next == NULL) {
1171         etp->next = (hashether_t *)g_malloc(sizeof(hashether_t));
1172         etp = etp->next;
1173         break;
1174       }
1175       etp = etp->next;
1176     }
1177   }
1178
1179   memcpy(etp->addr, addr, sizeof(etp->addr));
1180   g_strlcpy(etp->name, name, MAXNAMELEN);
1181   etp->next = NULL;
1182   etp->is_dummy_entry = FALSE;
1183
1184 } /* add_manuf_name */
1185
1186 static hashmanuf_t *manuf_name_lookup(const guint8 *addr)
1187 {
1188   int hash_idx;
1189   hashmanuf_t *tp;
1190   guint8 stripped_addr[3];
1191
1192   hash_idx = HASH_ETH_MANUF(addr);
1193
1194   /* first try to find a "perfect match" */
1195   tp = manuf_table[hash_idx];
1196   while(tp != NULL) {
1197     if (memcmp(tp->addr, addr, sizeof(tp->addr)) == 0) {
1198       return tp;
1199     }
1200     tp = tp->next;
1201   }
1202
1203   /* Mask out the broadcast/multicast flag but not the locally
1204    * administered flag as localy administered means: not assigend
1205    * by the IEEE but the local administrator instead.
1206    * 0x01 multicast / broadcast bit
1207    * 0x02 locally administered bit */
1208   memcpy(stripped_addr, addr, 3);
1209   stripped_addr[0] &= 0xFE;
1210
1211   tp = manuf_table[hash_idx];
1212   while(tp != NULL) {
1213     if (memcmp(tp->addr, stripped_addr, sizeof(tp->addr)) == 0) {
1214       return tp;
1215     }
1216     tp = tp->next;
1217   }
1218
1219   return NULL;
1220
1221 } /* manuf_name_lookup */
1222
1223 static hashether_t *wka_name_lookup(const guint8 *addr, unsigned int mask)
1224 {
1225   int hash_idx;
1226   hashether_t *(*wka_tp)[HASHETHSIZE];
1227   hashether_t *tp;
1228   guint8 masked_addr[6];
1229   unsigned int num;
1230   int i;
1231
1232   wka_tp = wka_table[mask];
1233   if (wka_tp == NULL) {
1234     /* There are no entries in the table for that mask value, as there is
1235        no table for that mask value. */
1236     return NULL;
1237   }
1238
1239   /* Get the part of the address covered by the mask. */
1240   for (i = 0, num = mask; num >= 8; i++, num -= 8)
1241     masked_addr[i] = addr[i];   /* copy octets entirely covered by the mask */
1242   /* Mask out the first masked octet */
1243   masked_addr[i] = addr[i] & (0xFF << (8 - num));
1244   i++;
1245   /* Zero out completely-masked-out octets */
1246   for (; i < 6; i++)
1247     masked_addr[i] = 0;
1248
1249   hash_idx = hash_eth_wka(masked_addr, mask);
1250
1251   tp = (*wka_tp)[hash_idx];
1252
1253   while(tp != NULL) {
1254     if (memcmp(tp->addr, masked_addr, sizeof(tp->addr)) == 0) {
1255       return tp;
1256     }
1257     tp = tp->next;
1258   }
1259
1260   return NULL;
1261
1262 } /* wka_name_lookup */
1263
1264 static void initialize_ethers(void)
1265 {
1266   ether_t *eth;
1267   char *manuf_path;
1268   unsigned int mask;
1269
1270   /* Compute the pathname of the ethers file. */
1271   if (g_ethers_path == NULL) {
1272     g_ethers_path = g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s",
1273             get_systemfile_dir(), ENAME_ETHERS);
1274   }
1275
1276   /* Set g_pethers_path here, but don't actually do anything
1277    * with it. It's used in get_ethbyname() and get_ethbyaddr()
1278    */
1279   if (g_pethers_path == NULL)
1280     g_pethers_path = get_persconffile_path(ENAME_ETHERS, FALSE, FALSE);
1281
1282   /* manuf hash table initialization */
1283
1284   /* Compute the pathname of the manuf file */
1285   manuf_path = get_datafile_path(ENAME_MANUF);
1286
1287   /* Read it and initialize the hash table */
1288   set_ethent(manuf_path);
1289
1290   while ((eth = get_ethent(&mask, TRUE))) {
1291     add_manuf_name(eth->addr, mask, eth->name);
1292   }
1293
1294   end_ethent();
1295
1296   g_free(manuf_path);
1297
1298 } /* initialize_ethers */
1299
1300 static hashether_t *add_eth_name(const guint8 *addr, const gchar *name)
1301 {
1302   int hash_idx;
1303   hashether_t *tp;
1304   int new_one = TRUE;
1305
1306   hash_idx = HASH_ETH_ADDRESS(addr);
1307
1308   tp = eth_table[hash_idx];
1309
1310   if( tp == NULL ) {
1311     tp = eth_table[hash_idx] = (hashether_t *)g_malloc(sizeof(hashether_t));
1312   } else {
1313     while(1) {
1314       if (memcmp(tp->addr, addr, sizeof(tp->addr)) == 0) {
1315         /* address already known */
1316         if (!tp->is_dummy_entry) {
1317           return tp;
1318         } else {
1319           /* replace this dummy (manuf) entry with a real name */
1320           new_one = FALSE;
1321           break;
1322         }
1323       }
1324       if (tp->next == NULL) {
1325         tp->next = (hashether_t *)g_malloc(sizeof(hashether_t));
1326         tp = tp->next;
1327         break;
1328       }
1329       tp = tp->next;
1330     }
1331   }
1332
1333   g_strlcpy(tp->name, name, MAXNAMELEN);
1334   if (new_one) {
1335       memcpy(tp->addr, addr, sizeof(tp->addr));
1336       tp->next = NULL;
1337   }
1338   tp->is_dummy_entry = FALSE;
1339
1340   return tp;
1341
1342 } /* add_eth_name */
1343
1344 static gchar *eth_name_lookup(const guint8 *addr)
1345 {
1346   int hash_idx;
1347   hashmanuf_t *manufp;
1348   hashether_t *tp;
1349   ether_t *eth;
1350   hashether_t *etp;
1351   unsigned int mask;
1352
1353   hash_idx = HASH_ETH_ADDRESS(addr);
1354
1355   tp = eth_table[hash_idx];
1356
1357   if( tp == NULL ) {
1358     tp = eth_table[hash_idx] = (hashether_t *)g_malloc(sizeof(hashether_t));
1359   } else {
1360     while(1) {
1361       if (memcmp(tp->addr, addr, sizeof(tp->addr)) == 0) {
1362         return tp->name;
1363       }
1364       if (tp->next == NULL) {
1365         tp->next = (hashether_t *)g_malloc(sizeof(hashether_t));
1366         tp = tp->next;
1367         break;
1368       }
1369       tp = tp->next;
1370     }
1371   }
1372
1373   /* fill in a new entry */
1374
1375   memcpy(tp->addr, addr, sizeof(tp->addr));
1376   tp->next = NULL;
1377
1378   if ( (eth = get_ethbyaddr(addr)) == NULL) {
1379     /* Unknown name.  Try looking for it in the well-known-address
1380        tables for well-known address ranges smaller than 2^24. */
1381     mask = 7;
1382     for (;;) {
1383       /* Only the topmost 5 bytes participate fully */
1384       if ((etp = wka_name_lookup(addr, mask+40)) != NULL) {
1385         g_snprintf(tp->name, MAXNAMELEN, "%s_%02x",
1386               etp->name, addr[5] & (0xFF >> mask));
1387         tp->is_dummy_entry = TRUE;
1388         return (tp->name);
1389       }
1390       if (mask == 0)
1391         break;
1392       mask--;
1393     }
1394
1395     mask = 7;
1396     for (;;) {
1397       /* Only the topmost 4 bytes participate fully */
1398       if ((etp = wka_name_lookup(addr, mask+32)) != NULL) {
1399         g_snprintf(tp->name, MAXNAMELEN, "%s_%02x:%02x",
1400               etp->name, addr[4] & (0xFF >> mask), addr[5]);
1401         tp->is_dummy_entry = TRUE;
1402         return (tp->name);
1403       }
1404       if (mask == 0)
1405         break;
1406       mask--;
1407     }
1408
1409     mask = 7;
1410     for (;;) {
1411       /* Only the topmost 3 bytes participate fully */
1412       if ((etp = wka_name_lookup(addr, mask+24)) != NULL) {
1413         g_snprintf(tp->name, MAXNAMELEN, "%s_%02x:%02x:%02x",
1414               etp->name, addr[3] & (0xFF >> mask), addr[4], addr[5]);
1415         tp->is_dummy_entry = TRUE;
1416         return (tp->name);
1417       }
1418       if (mask == 0)
1419         break;
1420       mask--;
1421     }
1422
1423     /* Now try looking in the manufacturer table. */
1424     if ((manufp = manuf_name_lookup(addr)) != NULL) {
1425       g_snprintf(tp->name, MAXNAMELEN, "%s_%02x:%02x:%02x",
1426               manufp->name, addr[3], addr[4], addr[5]);
1427       tp->is_dummy_entry = TRUE;
1428       return (tp->name);
1429     }
1430
1431     /* Now try looking for it in the well-known-address
1432        tables for well-known address ranges larger than 2^24. */
1433     mask = 7;
1434     for (;;) {
1435       /* Only the topmost 2 bytes participate fully */
1436       if ((etp = wka_name_lookup(addr, mask+16)) != NULL) {
1437         g_snprintf(tp->name, MAXNAMELEN, "%s_%02x:%02x:%02x:%02x",
1438               etp->name, addr[2] & (0xFF >> mask), addr[3], addr[4],
1439               addr[5]);
1440         tp->is_dummy_entry = TRUE;
1441         return (tp->name);
1442       }
1443       if (mask == 0)
1444         break;
1445       mask--;
1446     }
1447
1448     mask = 7;
1449     for (;;) {
1450       /* Only the topmost byte participates fully */
1451       if ((etp = wka_name_lookup(addr, mask+8)) != NULL) {
1452         g_snprintf(tp->name, MAXNAMELEN, "%s_%02x:%02x:%02x:%02x:%02x",
1453               etp->name, addr[1] & (0xFF >> mask), addr[2], addr[3],
1454               addr[4], addr[5]);
1455         tp->is_dummy_entry = TRUE;
1456         return (tp->name);
1457       }
1458       if (mask == 0)
1459         break;
1460       mask--;
1461     }
1462
1463     for (mask = 7; mask > 0; mask--) {
1464       /* Not even the topmost byte participates fully */
1465       if ((etp = wka_name_lookup(addr, mask)) != NULL) {
1466         g_snprintf(tp->name, MAXNAMELEN, "%s_%02x:%02x:%02x:%02x:%02x:%02x",
1467               etp->name, addr[0] & (0xFF >> mask), addr[1], addr[2],
1468               addr[3], addr[4], addr[5]);
1469         tp->is_dummy_entry = TRUE;
1470         return (tp->name);
1471       }
1472     }
1473
1474     /* No match whatsoever. */
1475     g_snprintf(tp->name, MAXNAMELEN, "%s", ether_to_str(addr));
1476     tp->is_dummy_entry = TRUE;
1477
1478   } else {
1479     g_strlcpy(tp->name, eth->name, MAXNAMELEN);
1480     tp->is_dummy_entry = FALSE;
1481   }
1482
1483   return (tp->name);
1484
1485 } /* eth_name_lookup */
1486
1487 static guint8 *eth_addr_lookup(const gchar *name)
1488 {
1489   ether_t *eth;
1490   hashether_t *tp;
1491   hashether_t **table = eth_table;
1492   int i;
1493
1494   /* to be optimized (hash table from name to addr) */
1495   for (i = 0; i < HASHETHSIZE; i++) {
1496     tp = table[i];
1497     while (tp) {
1498       if (strcmp(tp->name, name) == 0)
1499         return tp->addr;
1500       tp = tp->next;
1501     }
1502   }
1503
1504   /* not in hash table : performs a file lookup */
1505
1506   if ((eth = get_ethbyname(name)) == NULL)
1507     return NULL;
1508
1509   /* add new entry in hash table */
1510
1511   tp = add_eth_name(eth->addr, name);
1512
1513   return tp->addr;
1514
1515 } /* eth_addr_lookup */
1516
1517
1518 /* IPXNETS */
1519 static int parse_ipxnets_line(char *line, ipxnet_t *ipxnet)
1520 {
1521   /*
1522    *  We allow three address separators (':', '-', and '.'),
1523    *  as well as no separators
1524    */
1525
1526   gchar         *cp;
1527   guint32       a, a0, a1, a2, a3;
1528   gboolean      found_single_number = FALSE;
1529
1530   if ((cp = strchr(line, '#')))
1531     *cp = '\0';
1532
1533   if ((cp = strtok(line, " \t\n")) == NULL)
1534     return -1;
1535
1536   /* Either fill a0,a1,a2,a3 and found_single_number is FALSE,
1537    * fill a and found_single_number is TRUE,
1538    * or return -1
1539    */
1540   if (sscanf(cp, "%x:%x:%x:%x", &a0, &a1, &a2, &a3) != 4) {
1541     if (sscanf(cp, "%x-%x-%x-%x", &a0, &a1, &a2, &a3) != 4) {
1542       if (sscanf(cp, "%x.%x.%x.%x", &a0, &a1, &a2, &a3) != 4) {
1543         if (sscanf(cp, "%x", &a) == 1) {
1544           found_single_number = TRUE;
1545         }
1546         else {
1547           return -1;
1548         }
1549       }
1550     }
1551   }
1552
1553   if ((cp = strtok(NULL, " \t\n")) == NULL)
1554     return -1;
1555
1556   if (found_single_number) {
1557         ipxnet->addr = a;
1558   }
1559   else {
1560         ipxnet->addr = (a0 << 24) | (a1 << 16) | (a2 << 8) | a3;
1561   }
1562
1563   g_strlcpy(ipxnet->name, cp, MAXNAMELEN);
1564
1565   return 0;
1566
1567 } /* parse_ipxnets_line */
1568
1569 static FILE *ipxnet_p = NULL;
1570
1571 static void set_ipxnetent(char *path)
1572 {
1573   if (ipxnet_p)
1574     rewind(ipxnet_p);
1575   else
1576     ipxnet_p = ws_fopen(path, "r");
1577 }
1578
1579 static void end_ipxnetent(void)
1580 {
1581   if (ipxnet_p) {
1582     fclose(ipxnet_p);
1583     ipxnet_p = NULL;
1584   }
1585 }
1586
1587 static ipxnet_t *get_ipxnetent(void)
1588 {
1589
1590   static ipxnet_t ipxnet;
1591   static int     size = 0;
1592   static char   *buf = NULL;
1593
1594   if (ipxnet_p == NULL)
1595     return NULL;
1596
1597   while (fgetline(&buf, &size, ipxnet_p) >= 0) {
1598     if (parse_ipxnets_line(buf, &ipxnet) == 0) {
1599       return &ipxnet;
1600     }
1601   }
1602
1603   return NULL;
1604
1605 } /* get_ipxnetent */
1606
1607 static ipxnet_t *get_ipxnetbyname(const gchar *name)
1608 {
1609   ipxnet_t *ipxnet;
1610
1611   set_ipxnetent(g_ipxnets_path);
1612
1613   while ((ipxnet = get_ipxnetent()) && strncmp(name, ipxnet->name, MAXNAMELEN) != 0)
1614     ;
1615
1616   if (ipxnet == NULL) {
1617     end_ipxnetent();
1618
1619     set_ipxnetent(g_pipxnets_path);
1620
1621     while ((ipxnet = get_ipxnetent()) && strncmp(name, ipxnet->name, MAXNAMELEN) != 0)
1622       ;
1623
1624     end_ipxnetent();
1625   }
1626
1627   return ipxnet;
1628
1629 } /* get_ipxnetbyname */
1630
1631 static ipxnet_t *get_ipxnetbyaddr(guint32 addr)
1632 {
1633
1634   ipxnet_t *ipxnet;
1635
1636   set_ipxnetent(g_ipxnets_path);
1637
1638   while ((ipxnet = get_ipxnetent()) && (addr != ipxnet->addr) ) ;
1639
1640   if (ipxnet == NULL) {
1641     end_ipxnetent();
1642
1643     set_ipxnetent(g_pipxnets_path);
1644
1645     while ((ipxnet = get_ipxnetent()) && (addr != ipxnet->addr) )
1646       ;
1647
1648     end_ipxnetent();
1649   }
1650
1651   return ipxnet;
1652
1653 } /* get_ipxnetbyaddr */
1654
1655 static void initialize_ipxnets(void)
1656 {
1657   /* Compute the pathname of the ipxnets file.
1658    *
1659    * XXX - is there a notion of an "ipxnets file" in any flavor of
1660    * UNIX, or with any add-on Netware package for UNIX?  If not,
1661    * should the UNIX version of the ipxnets file be in the datafile
1662    * directory as well?
1663    */
1664   if (g_ipxnets_path == NULL) {
1665         g_ipxnets_path = g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s",
1666             get_systemfile_dir(), ENAME_IPXNETS);
1667   }
1668
1669   /* Set g_pipxnets_path here, but don't actually do anything
1670    * with it. It's used in get_ipxnetbyname() and get_ipxnetbyaddr()
1671    */
1672   if (g_pipxnets_path == NULL)
1673     g_pipxnets_path = get_persconffile_path(ENAME_IPXNETS, FALSE, FALSE);
1674
1675 } /* initialize_ipxnets */
1676
1677 static hashipxnet_t *add_ipxnet_name(guint addr, const gchar *name)
1678 {
1679   int hash_idx;
1680   hashipxnet_t *tp;
1681
1682   hash_idx = HASH_IPX_NET(addr);
1683
1684   tp = ipxnet_table[hash_idx];
1685
1686   if( tp == NULL ) {
1687     tp = ipxnet_table[hash_idx] = (hashipxnet_t *)g_malloc(sizeof(hashipxnet_t));
1688   } else {
1689     while(1) {
1690       if (tp->next == NULL) {
1691         tp->next = (hashipxnet_t *)g_malloc(sizeof(hashipxnet_t));
1692         tp = tp->next;
1693         break;
1694       }
1695       tp = tp->next;
1696     }
1697   }
1698
1699   tp->addr = addr;
1700   g_strlcpy(tp->name, name, MAXNAMELEN);
1701   tp->next = NULL;
1702
1703   return tp;
1704
1705 } /* add_ipxnet_name */
1706
1707 static gchar *ipxnet_name_lookup(const guint addr)
1708 {
1709   int hash_idx;
1710   hashipxnet_t *tp;
1711   ipxnet_t *ipxnet;
1712
1713   hash_idx = HASH_IPX_NET(addr);
1714
1715   tp = ipxnet_table[hash_idx];
1716
1717   if( tp == NULL ) {
1718     tp = ipxnet_table[hash_idx] = (hashipxnet_t *)g_malloc(sizeof(hashipxnet_t));
1719   } else {
1720     while(1) {
1721       if (tp->addr == addr) {
1722         return tp->name;
1723       }
1724       if (tp->next == NULL) {
1725         tp->next = (hashipxnet_t *)g_malloc(sizeof(hashipxnet_t));
1726         tp = tp->next;
1727         break;
1728       }
1729       tp = tp->next;
1730     }
1731   }
1732
1733   /* fill in a new entry */
1734
1735   tp->addr = addr;
1736   tp->next = NULL;
1737
1738   if ( (ipxnet = get_ipxnetbyaddr(addr)) == NULL) {
1739     /* unknown name */
1740       g_snprintf(tp->name, MAXNAMELEN, "%X", addr);
1741
1742   } else {
1743     g_strlcpy(tp->name, ipxnet->name, MAXNAMELEN);
1744   }
1745
1746   return (tp->name);
1747
1748 } /* ipxnet_name_lookup */
1749
1750 static guint ipxnet_addr_lookup(const gchar *name, gboolean *success)
1751 {
1752   ipxnet_t *ipxnet;
1753   hashipxnet_t *tp;
1754   hashipxnet_t **table = ipxnet_table;
1755   int i;
1756
1757   /* to be optimized (hash table from name to addr) */
1758   for (i = 0; i < HASHIPXNETSIZE; i++) {
1759     tp = table[i];
1760     while (tp) {
1761       if (strcmp(tp->name, name) == 0) {
1762         *success = TRUE;
1763         return tp->addr;
1764       }
1765       tp = tp->next;
1766     }
1767   }
1768
1769   /* not in hash table : performs a file lookup */
1770
1771   if ((ipxnet = get_ipxnetbyname(name)) == NULL) {
1772     *success = FALSE;
1773     return 0;
1774   }
1775
1776   /* add new entry in hash table */
1777
1778   tp = add_ipxnet_name(ipxnet->addr, name);
1779
1780   *success = TRUE;
1781   return tp->addr;
1782
1783 } /* ipxnet_addr_lookup */
1784
1785 static gboolean
1786 read_hosts_file (const char *hostspath)
1787 {
1788   FILE *hf;
1789   char *line = NULL;
1790   int size = 0;
1791   gchar *cp;
1792   guint32 host_addr[4]; /* IPv4 or IPv6 */
1793   struct e_in6_addr ipv6_addr;
1794   gboolean is_ipv6;
1795   int ret;
1796
1797   /*
1798    *  See the hosts(4) or hosts(5) man page for hosts file format
1799    *  (not available on all systems).
1800    */
1801   if ((hf = ws_fopen(hostspath, "r")) == NULL)
1802     return FALSE;
1803
1804   while (fgetline(&line, &size, hf) >= 0) {
1805     if ((cp = strchr(line, '#')))
1806       *cp = '\0';
1807
1808     if ((cp = strtok(line, " \t")) == NULL)
1809       continue; /* no tokens in the line */
1810
1811     ret = inet_pton(AF_INET6, cp, &host_addr);
1812     if (ret == -1)
1813       continue; /* error parsing */
1814     if (ret == 1) {
1815       /* Valid IPv6 */
1816       is_ipv6 = TRUE;
1817     } else {
1818       /* Not valid IPv6 - valid IPv4? */
1819       if (inet_pton(AF_INET, cp, &host_addr) != 1)
1820         continue; /* no */
1821       is_ipv6 = FALSE;
1822     }
1823
1824     if ((cp = strtok(NULL, " \t")) == NULL)
1825       continue; /* no host name */
1826
1827     if (is_ipv6) {
1828       memcpy(&ipv6_addr, host_addr, sizeof ipv6_addr);
1829       add_ipv6_name(&ipv6_addr, cp);
1830     } else
1831       add_ipv4_name(host_addr[0], cp);
1832
1833     /*
1834      * Add the aliases, too, if there are any.
1835      */
1836     while ((cp = strtok(NULL, " \t")) != NULL) {
1837       if (is_ipv6) {
1838         memcpy(&ipv6_addr, host_addr, sizeof ipv6_addr);
1839         add_ipv6_name(&ipv6_addr, cp);
1840       } else
1841         add_ipv4_name(host_addr[0], cp);
1842     }
1843   }
1844   if (line != NULL)
1845     g_free(line);
1846
1847   fclose(hf);
1848   return TRUE;
1849 } /* read_hosts_file */
1850
1851
1852 /* Read in a list of subnet definition - name pairs.
1853  * <line> = <comment> | <entry> | <whitespace>
1854  * <comment> = <whitespace>#<any>
1855  * <entry> = <subnet_definition> <whitespace> <subnet_name> [<comment>|<whitespace><any>]
1856  * <subnet_definition> = <ipv4_address> / <subnet_mask_length>
1857  * <ipv4_address> is a full address; it will be masked to get the subnet-ID.
1858  * <subnet_mask_length> is a decimal 1-31
1859  * <subnet_name> is a string containing no whitespace.
1860  * <whitespace> = (space | tab)+
1861  * Any malformed entries are ignored.
1862  * Any trailing data after the subnet_name is ignored.
1863  *
1864  * XXX Support IPv6
1865  */
1866 static gboolean
1867 read_subnets_file (const char *subnetspath)
1868 {
1869   FILE *hf;
1870   char *line = NULL;
1871   int size = 0;
1872   gchar *cp, *cp2;
1873   guint32 host_addr; /* IPv4 ONLY */
1874   int mask_length;
1875
1876   if ((hf = ws_fopen(subnetspath, "r")) == NULL)
1877     return FALSE;
1878
1879   while (fgetline(&line, &size, hf) >= 0) {
1880     if ((cp = strchr(line, '#')))
1881       *cp = '\0';
1882
1883     if ((cp = strtok(line, " \t")) == NULL)
1884       continue; /* no tokens in the line */
1885
1886
1887     /* Expected format is <IP4 address>/<subnet length> */
1888     cp2 = strchr(cp, '/');
1889     if(NULL == cp2) {
1890         /* No length */
1891         continue;
1892     }
1893     *cp2 = '\0'; /* Cut token */
1894     ++cp2    ;
1895
1896     /* Check if this is a valid IPv4 address */
1897     if (inet_pton(AF_INET, cp, &host_addr) != 1) {
1898         continue; /* no */
1899     }
1900
1901     mask_length = atoi(cp2);
1902     if(0 >= mask_length || mask_length > 31) {
1903         continue; /* invalid mask length */
1904     }
1905
1906     if ((cp = strtok(NULL, " \t")) == NULL)
1907       continue; /* no subnet name */
1908
1909     subnet_entry_set(host_addr, (guint32)mask_length, cp);
1910   }
1911   if (line != NULL)
1912     g_free(line);
1913
1914   fclose(hf);
1915   return TRUE;
1916 } /* read_subnets_file */
1917
1918 static subnet_entry_t subnet_lookup(const guint32 addr)
1919 {
1920     subnet_entry_t subnet_entry;
1921     guint32 i;
1922
1923     /* Search mask lengths linearly, longest first */
1924
1925     i = SUBNETLENGTHSIZE;
1926     while(have_subnet_entry && i > 0) {
1927         guint32 masked_addr;
1928         subnet_length_entry_t* length_entry;
1929
1930         /* Note that we run from 31 (length 32)  to 0 (length 1)  */
1931         --i;
1932         g_assert(i < SUBNETLENGTHSIZE);
1933
1934
1935         length_entry = &subnet_length_entries[i];
1936
1937         if(NULL != length_entry->subnet_addresses) {
1938             hashipv4_t * tp;
1939             guint32 hash_idx;
1940
1941             masked_addr = addr & length_entry->mask;
1942             hash_idx = HASH_IPV4_ADDRESS(masked_addr);
1943
1944             tp = length_entry->subnet_addresses[hash_idx];
1945             while(tp != NULL && tp->addr != masked_addr) {
1946                 tp = tp->next;
1947             }
1948
1949             if(NULL != tp) {
1950                 subnet_entry.mask = length_entry->mask;
1951                 subnet_entry.mask_length = i + 1; /* Length is offset + 1 */
1952                 subnet_entry.name = tp->name;
1953                 return subnet_entry;
1954             }
1955         }
1956     }
1957
1958     subnet_entry.mask = 0;
1959     subnet_entry.mask_length = 0;
1960     subnet_entry.name = NULL;
1961
1962     return subnet_entry;
1963 }
1964
1965 /* Add a subnet-definition - name pair to the set.
1966  * The definition is taken by masking the address passed in with the mask of the
1967  * given length.
1968  */
1969 static void subnet_entry_set(guint32 subnet_addr, guint32 mask_length, const gchar* name)
1970 {
1971     subnet_length_entry_t* entry;
1972     hashipv4_t * tp;
1973     gsize hash_idx;
1974
1975     g_assert(mask_length > 0 && mask_length <= 32);
1976
1977     entry = &subnet_length_entries[mask_length - 1];
1978
1979     subnet_addr &= entry->mask;
1980
1981     hash_idx = HASH_IPV4_ADDRESS(subnet_addr);
1982
1983     if(NULL == entry->subnet_addresses) {
1984         entry->subnet_addresses = g_new0(hashipv4_t*,HASHHOSTSIZE);
1985     }
1986
1987     if(NULL != (tp = entry->subnet_addresses[hash_idx])) {
1988         if(tp->addr == subnet_addr) {
1989             return;    /* XXX provide warning that an address was repeated? */
1990         } else {
1991            hashipv4_t * new_tp = g_new(hashipv4_t,1);
1992            tp->next = new_tp;
1993            tp = new_tp;
1994         }
1995     } else {
1996         tp = entry->subnet_addresses[hash_idx] = g_new(hashipv4_t,1);
1997     }
1998
1999     tp->next = NULL;
2000     tp->addr = subnet_addr;
2001     tp->is_dummy_entry = FALSE; /*Never used again...*/
2002     strncpy(tp->name, name, MAXNAMELEN); /* This is longer than subnet names can actually be */
2003     have_subnet_entry = TRUE;
2004 }
2005
2006 static guint32 get_subnet_mask(guint32 mask_length) {
2007
2008     static guint32 masks[SUBNETLENGTHSIZE];
2009     static gboolean initialised = FALSE;
2010
2011     if(!initialised) {
2012         memset(masks, 0, sizeof(masks));
2013
2014         initialised = TRUE;
2015
2016         /* XXX There must be a better way to do this than
2017          * hand-coding the values, but I can't seem to
2018          * come up with one!
2019          */
2020
2021         inet_pton(AF_INET, "128.0.0.0", &masks[0]);
2022         inet_pton(AF_INET, "192.0.0.0", &masks[1]);
2023         inet_pton(AF_INET, "224.0.0.0", &masks[2]);
2024         inet_pton(AF_INET, "240.0.0.0", &masks[3]);
2025         inet_pton(AF_INET, "248.0.0.0", &masks[4]);
2026         inet_pton(AF_INET, "252.0.0.0", &masks[5]);
2027         inet_pton(AF_INET, "254.0.0.0", &masks[6]);
2028         inet_pton(AF_INET, "255.0.0.0", &masks[7]);
2029
2030         inet_pton(AF_INET, "255.128.0.0", &masks[8]);
2031         inet_pton(AF_INET, "255.192.0.0", &masks[9]);
2032         inet_pton(AF_INET, "255.224.0.0", &masks[10]);
2033         inet_pton(AF_INET, "255.240.0.0", &masks[11]);
2034         inet_pton(AF_INET, "255.248.0.0", &masks[12]);
2035         inet_pton(AF_INET, "255.252.0.0", &masks[13]);
2036         inet_pton(AF_INET, "255.254.0.0", &masks[14]);
2037         inet_pton(AF_INET, "255.255.0.0", &masks[15]);
2038
2039         inet_pton(AF_INET, "255.255.128.0", &masks[16]);
2040         inet_pton(AF_INET, "255.255.192.0", &masks[17]);
2041         inet_pton(AF_INET, "255.255.224.0", &masks[18]);
2042         inet_pton(AF_INET, "255.255.240.0", &masks[19]);
2043         inet_pton(AF_INET, "255.255.248.0", &masks[20]);
2044         inet_pton(AF_INET, "255.255.252.0", &masks[21]);
2045         inet_pton(AF_INET, "255.255.254.0", &masks[22]);
2046         inet_pton(AF_INET, "255.255.255.0", &masks[23]);
2047
2048         inet_pton(AF_INET, "255.255.255.128", &masks[24]);
2049         inet_pton(AF_INET, "255.255.255.192", &masks[25]);
2050         inet_pton(AF_INET, "255.255.255.224", &masks[26]);
2051         inet_pton(AF_INET, "255.255.255.240", &masks[27]);
2052         inet_pton(AF_INET, "255.255.255.248", &masks[28]);
2053         inet_pton(AF_INET, "255.255.255.252", &masks[29]);
2054         inet_pton(AF_INET, "255.255.255.254", &masks[30]);
2055         inet_pton(AF_INET, "255.255.255.255", &masks[31]);
2056     }
2057
2058     if(mask_length == 0 || mask_length > SUBNETLENGTHSIZE) {
2059         g_assert_not_reached();
2060         return 0;
2061     } else {
2062         return masks[mask_length - 1];
2063     }
2064 }
2065
2066 static void subnet_name_lookup_init()
2067 {
2068     gchar* subnetspath;
2069
2070     guint32 i;
2071     for(i = 0; i < SUBNETLENGTHSIZE; ++i) {
2072         guint32 length = i + 1;
2073
2074         subnet_length_entries[i].subnet_addresses  = NULL;
2075         subnet_length_entries[i].mask_length  = length;
2076         subnet_length_entries[i].mask = get_subnet_mask(length);
2077     }
2078
2079     subnetspath = get_persconffile_path(ENAME_SUBNETS, FALSE, FALSE);
2080     if (!read_subnets_file(subnetspath) && errno != ENOENT) {
2081         report_open_failure(subnetspath, errno, FALSE);
2082     }
2083     g_free(subnetspath);
2084
2085     /*
2086     * Load the global subnets file, if we have one.
2087     */
2088     subnetspath = get_datafile_path(ENAME_SUBNETS);
2089     if (!read_subnets_file(subnetspath) && errno != ENOENT) {
2090         report_open_failure(subnetspath, errno, FALSE);
2091     }
2092     g_free(subnetspath);
2093 }
2094
2095 /*
2096  *  External Functions
2097  */
2098
2099 void
2100 host_name_lookup_init(void) {
2101   char *hostspath;
2102
2103 #ifdef HAVE_GNU_ADNS
2104 #ifdef _WIN32
2105   char *sysroot;
2106   static char rootpath_nt[] = "\\system32\\drivers\\etc\\hosts";
2107   static char rootpath_ot[] = "\\hosts";
2108 #endif /* _WIN32 */
2109 #endif /*GNU_ADNS */
2110
2111   /*
2112    * Load the user's hosts file, if they have one.
2113    */
2114   hostspath = get_persconffile_path(ENAME_HOSTS, FALSE, FALSE);
2115   if (!read_hosts_file(hostspath) && errno != ENOENT) {
2116     report_open_failure(hostspath, errno, FALSE);
2117   }
2118   g_free(hostspath);
2119
2120   /*
2121    * Load the global hosts file, if we have one.
2122    */
2123   hostspath = get_datafile_path(ENAME_HOSTS);
2124   if (!read_hosts_file(hostspath) && errno != ENOENT) {
2125     report_open_failure(hostspath, errno, FALSE);
2126   }
2127   g_free(hostspath);
2128
2129 #ifdef HAVE_GNU_ADNS
2130   /*
2131    * We're using GNU ADNS, which doesn't check the system hosts file;
2132    * we load that file ourselves.
2133    */
2134 #ifdef _WIN32
2135
2136   sysroot = getenv_utf8("WINDIR");
2137   if (sysroot != NULL) {
2138     /*
2139      * The file should be under WINDIR.
2140      * If this is Windows NT (NT 4.0,2K,XP,Server2K3), it's in
2141      * %WINDIR%\system32\drivers\etc\hosts.
2142      * If this is Windows OT (95,98,Me), it's in %WINDIR%\hosts.
2143      * Try both.
2144      * XXX - should we base it on the dwPlatformId value from
2145      * GetVersionEx()?
2146      */
2147     hostspath = g_strconcat(sysroot, rootpath_nt, NULL);
2148     if (!read_hosts_file(hostspath)) {
2149       g_free(hostspath);
2150       hostspath = g_strconcat(sysroot, rootpath_ot, NULL);
2151       read_hosts_file(hostspath);
2152     }
2153     g_free(hostspath);
2154   }
2155 #else /* _WIN32 */
2156   read_hosts_file("/etc/hosts");
2157 #endif /* _WIN32 */
2158
2159   /* XXX - Any flags we should be using? */
2160   /* XXX - We could provide config settings for DNS servers, and
2161            pass them to ADNS with adns_init_strcfg */
2162   if (adns_init(&ads, 0, 0 /*0=>stderr*/) != 0) {
2163     /*
2164      * XXX - should we report the error?  I'm assuming that some crashes
2165      * reported on a Windows machine with TCP/IP not configured are due
2166      * to "adns_init()" failing (due to the lack of TCP/IP) and leaving
2167      * ADNS in a state where it crashes due to that.  We'll still try
2168      * doing name resolution anyway.
2169      */
2170     return;
2171   }
2172   gnu_adns_initialized = TRUE;
2173   adns_currently_queued = 0;
2174 #endif /* HAVE_GNU_ADNS */
2175
2176     subnet_name_lookup_init();
2177 }
2178
2179 #ifdef HAVE_GNU_ADNS
2180
2181 /* XXX - The ADNS "documentation" isn't very clear:
2182  * - Do we need to keep our query structures around?
2183  */
2184 gint
2185 host_name_lookup_process(gpointer data _U_) {
2186   adns_queue_msg_t *almsg;
2187   GList *cur;
2188   char addr_str[] = "111.222.333.444.in-addr.arpa.";
2189   guint8 *addr_bytes;
2190   adns_answer *ans;
2191   int ret;
2192   gboolean dequeue;
2193
2194   adns_queue_head = g_list_first(adns_queue_head);
2195
2196   cur = adns_queue_head;
2197   while (cur && adns_currently_queued <= prefs.name_resolve_concurrency) {
2198     almsg = (adns_queue_msg_t *) cur->data;
2199     if (! almsg->submitted && almsg->type == AF_INET) {
2200       addr_bytes = (guint8 *) &almsg->ip4_addr;
2201       g_snprintf(addr_str, sizeof addr_str, "%u.%u.%u.%u.in-addr.arpa.", addr_bytes[3],
2202           addr_bytes[2], addr_bytes[1], addr_bytes[0]);
2203       /* XXX - what if it fails? */
2204       adns_submit (ads, addr_str, adns_r_ptr, 0, NULL, &almsg->query);
2205       almsg->submitted = TRUE;
2206       adns_currently_queued++;
2207     }
2208     cur = cur->next;
2209   }
2210
2211   cur = adns_queue_head;
2212   while (cur) {
2213     dequeue = FALSE;
2214     almsg = (adns_queue_msg_t *) cur->data;
2215     if (almsg->submitted) {
2216       ret = adns_check(ads, &almsg->query, &ans, NULL);
2217       if (ret == 0) {
2218         if (ans->status == adns_s_ok) {
2219           add_ipv4_name(almsg->ip4_addr, *ans->rrs.str);
2220         }
2221         dequeue = TRUE;
2222       }
2223     }
2224     cur = cur->next;
2225     if (dequeue) {
2226       adns_queue_head = g_list_remove(adns_queue_head, (void *) almsg);
2227       g_free(almsg);
2228       adns_currently_queued--;
2229     }
2230   }
2231
2232   /* Keep the timeout in place */
2233   return 1;
2234 }
2235
2236 void
2237 host_name_lookup_cleanup(void) {
2238   void *qdata;
2239
2240   adns_queue_head = g_list_first(adns_queue_head);
2241   while (adns_queue_head) {
2242     qdata = adns_queue_head->data;
2243     adns_queue_head = g_list_remove(adns_queue_head, qdata);
2244     g_free(qdata);
2245   }
2246
2247   if (gnu_adns_initialized)
2248     adns_finish(ads);
2249 }
2250
2251 #else
2252
2253 gint
2254 host_name_lookup_process(gpointer data _U_) {
2255   /* Kill the timeout, as there's nothing for it to do */
2256   return 0;
2257 }
2258
2259 void
2260 host_name_lookup_cleanup(void) {
2261 }
2262
2263 #endif /* HAVE_GNU_ADNS */
2264
2265 extern gchar *get_hostname(guint addr)
2266 {
2267   gboolean found;
2268
2269   if (!(g_resolv_flags & RESOLV_NETWORK))
2270     return ip_to_str((guint8 *)&addr);
2271
2272   return host_name_lookup(addr, &found);
2273 }
2274
2275 extern const gchar *get_hostname6(struct e_in6_addr *addr)
2276 {
2277   gboolean found;
2278
2279   if (!(g_resolv_flags & RESOLV_NETWORK))
2280     return ip6_to_str(addr);
2281   if (E_IN6_IS_ADDR_LINKLOCAL(addr) || E_IN6_IS_ADDR_MULTICAST(addr))
2282     return ip6_to_str(addr);
2283   return host_name_lookup6(addr, &found);
2284 }
2285
2286 extern void add_ipv4_name(guint addr, const gchar *name)
2287 {
2288   int hash_idx;
2289   hashipv4_t *tp;
2290   int new_one = TRUE;
2291
2292   hash_idx = HASH_IPV4_ADDRESS(addr);
2293
2294   tp = ipv4_table[hash_idx];
2295
2296   if( tp == NULL ) {
2297     tp = ipv4_table[hash_idx] = (hashipv4_t *)g_malloc(sizeof(hashipv4_t));
2298   } else {
2299     while(1) {
2300       if (tp->addr == addr) {
2301         /* address already known */
2302         if (!tp->is_dummy_entry) {
2303           return;
2304         } else {
2305           /* replace this dummy entry with the new one */
2306           new_one = FALSE;
2307           break;
2308         }
2309       }
2310       if (tp->next == NULL) {
2311         tp->next = (hashipv4_t *)g_malloc(sizeof(hashipv4_t));
2312         tp = tp->next;
2313         break;
2314       }
2315       tp = tp->next;
2316     }
2317   }
2318
2319   g_strlcpy(tp->name, name, MAXNAMELEN);
2320   if (new_one) {
2321       tp->addr = addr;
2322       tp->next = NULL;
2323   }
2324   tp->is_dummy_entry = FALSE;
2325
2326 } /* add_ipv4_name */
2327
2328 extern void add_ipv6_name(struct e_in6_addr *addrp, const gchar *name)
2329 {
2330   int hash_idx;
2331   hashipv6_t *tp;
2332   int new_one = TRUE;
2333
2334   hash_idx = HASH_IPV6_ADDRESS(*addrp);
2335
2336   tp = ipv6_table[hash_idx];
2337
2338   if( tp == NULL ) {
2339     tp = ipv6_table[hash_idx] = (hashipv6_t *)g_malloc(sizeof(hashipv6_t));
2340   } else {
2341     while(1) {
2342       if (memcmp(&tp->addr, addrp, sizeof (struct e_in6_addr)) == 0) {
2343         /* address already known */
2344         if (!tp->is_dummy_entry) {
2345           return;
2346         } else {
2347           /* replace this dummy entry with the new one */
2348           new_one = FALSE;
2349           break;
2350         }
2351       }
2352       if (tp->next == NULL) {
2353         tp->next = (hashipv6_t *)g_malloc(sizeof(hashipv6_t));
2354         tp = tp->next;
2355         break;
2356       }
2357       tp = tp->next;
2358     }
2359   }
2360
2361   g_strlcpy(tp->name, name, MAXNAMELEN);
2362   if (new_one) {
2363       tp->addr = *addrp;
2364       tp->next = NULL;
2365   }
2366   tp->is_dummy_entry = FALSE;
2367
2368 } /* add_ipv6_name */
2369
2370 /* -----------------
2371  * unsigned integer to ascii
2372 */
2373 static gchar *ep_utoa(guint port)
2374 {
2375   gchar *bp = ep_alloc(MAXNAMELEN);
2376
2377   bp = &bp[MAXNAMELEN -1];
2378
2379   *bp = 0;
2380   do {
2381       *--bp = (port % 10) +'0';
2382   } while ((port /= 10) != 0);
2383   return bp;
2384 }
2385
2386
2387 extern gchar *get_udp_port(guint port)
2388 {
2389
2390   if (!(g_resolv_flags & RESOLV_TRANSPORT)) {
2391     return ep_utoa(port);
2392   }
2393
2394   return serv_name_lookup(port, PT_UDP);
2395
2396 } /* get_udp_port */
2397
2398 extern gchar *get_dccp_port(guint port)
2399 {
2400
2401   if (!(g_resolv_flags & RESOLV_TRANSPORT)) {
2402     return ep_utoa(port);
2403   }
2404
2405   return serv_name_lookup(port, PT_DCCP);
2406
2407 } /* get_dccp_port */
2408
2409
2410 extern gchar *get_tcp_port(guint port)
2411 {
2412
2413   if (!(g_resolv_flags & RESOLV_TRANSPORT)) {
2414     return ep_utoa(port);
2415   }
2416
2417   return serv_name_lookup(port, PT_TCP);
2418
2419 } /* get_tcp_port */
2420
2421 extern gchar *get_sctp_port(guint port)
2422 {
2423
2424   if (!(g_resolv_flags & RESOLV_TRANSPORT)) {
2425     return ep_utoa(port);
2426   }
2427
2428   return serv_name_lookup(port, PT_SCTP);
2429
2430 } /* get_sctp_port */
2431
2432
2433 const gchar *get_addr_name(address *addr)
2434 {
2435   const gchar *result;
2436
2437   result = solve_address_to_name(addr);
2438
2439   if (result!=NULL){
2440           return result;
2441   }
2442
2443   /* if it gets here, either it is of type AT_NONE, */
2444   /* or it should be solvable in address_to_str -unless addr->type is wrongly defined- */
2445
2446   if (addr->type == AT_NONE){
2447           return "NONE";
2448   }
2449
2450   return(address_to_str(addr));
2451 } /* get_addr_name */
2452
2453
2454 void get_addr_name_buf(address *addr, gchar *buf, guint size)
2455 {
2456   const gchar *result = get_addr_name(addr);
2457
2458   g_snprintf(buf, size, "%s", result);
2459 } /* get_addr_name_buf */
2460
2461
2462 extern gchar *get_ether_name(const guint8 *addr)
2463 {
2464   if (!(g_resolv_flags & RESOLV_MAC))
2465     return ether_to_str(addr);
2466
2467   if (!eth_resolution_initialized) {
2468     initialize_ethers();
2469     eth_resolution_initialized = 1;
2470   }
2471
2472   return eth_name_lookup(addr);
2473
2474 } /* get_ether_name */
2475
2476 /* Look for an ether name in the hash, and return it if found.
2477  * If it's not found, simply return NULL. We DO NOT make a new
2478  * hash entry for it with the hex digits turned into a string.
2479  */
2480 gchar *get_ether_name_if_known(const guint8 *addr)
2481 {
2482   int hash_idx;
2483   hashether_t *tp;
2484
2485   /* Initialize ether structs if we're the first
2486    * ether-related function called */
2487   if (!(g_resolv_flags & RESOLV_MAC))
2488     return NULL;
2489
2490   if (!eth_resolution_initialized) {
2491     initialize_ethers();
2492     eth_resolution_initialized = 1;
2493   }
2494
2495   hash_idx = HASH_ETH_ADDRESS(addr);
2496
2497   tp = eth_table[hash_idx];
2498
2499   if( tp == NULL ) {
2500           /* Hash key not found in table.
2501            * Force a lookup (and a hash entry) for addr, then call
2502            * myself. I plan on not getting into an infinite loop because
2503            * eth_name_lookup() is guaranteed to make a hashtable entry,
2504            * so when I call myself again, I can never get into this
2505            * block of code again. Knock on wood...
2506            */
2507           (void) eth_name_lookup(addr);
2508           return get_ether_name_if_known(addr); /* a well-placed goto would suffice */
2509   }
2510   else {
2511     while(1) {
2512       if (memcmp(tp->addr, addr, sizeof(tp->addr)) == 0) {
2513               if (!tp->is_dummy_entry) {
2514                 /* A name was found, and its origin is an ethers file */
2515                 return tp->name;
2516               }
2517               else {
2518                 /* A name was found, but it was created, not found in a file */
2519                 return NULL;
2520               }
2521       }
2522       if (tp->next == NULL) {
2523           /* Read my reason above for why I'm sure I can't get into an infinite loop */
2524           (void) eth_name_lookup(addr);
2525           return get_ether_name_if_known(addr); /* a well-placed goto would suffice */
2526       }
2527       tp = tp->next;
2528     }
2529   }
2530   g_assert_not_reached();
2531   return NULL;
2532 }
2533
2534
2535 extern guint8 *get_ether_addr(const gchar *name)
2536 {
2537
2538   /* force resolution (do not check g_resolv_flags) */
2539
2540   if (!eth_resolution_initialized) {
2541     initialize_ethers();
2542     eth_resolution_initialized = 1;
2543   }
2544
2545   return eth_addr_lookup(name);
2546
2547 } /* get_ether_addr */
2548
2549 extern void add_ether_byip(guint ip, const guint8 *eth)
2550 {
2551
2552   gchar *host;
2553   gboolean found;
2554
2555   /* first check that IP address can be resolved */
2556
2557   if (!(g_resolv_flags & RESOLV_NETWORK) || ((host = host_name_lookup(ip, &found)) == NULL))
2558     return;
2559
2560   /* ok, we can add this entry in the ethers hashtable */
2561
2562   if (found)
2563     add_eth_name(eth, host);
2564
2565 } /* add_ether_byip */
2566
2567 extern const gchar *get_ipxnet_name(const guint32 addr)
2568 {
2569
2570   if (!(g_resolv_flags & RESOLV_NETWORK)) {
2571           return ipxnet_to_str_punct(addr, '\0');
2572   }
2573
2574   if (!ipxnet_resolution_initialized) {
2575     initialize_ipxnets();
2576     ipxnet_resolution_initialized = 1;
2577   }
2578
2579   return ipxnet_name_lookup(addr);
2580
2581 } /* get_ipxnet_name */
2582
2583 extern guint32 get_ipxnet_addr(const gchar *name, gboolean *known)
2584 {
2585   guint32 addr;
2586   gboolean success;
2587
2588   /* force resolution (do not check g_resolv_flags) */
2589
2590   if (!ipxnet_resolution_initialized) {
2591     initialize_ipxnets();
2592     ipxnet_resolution_initialized = 1;
2593   }
2594
2595   addr =  ipxnet_addr_lookup(name, &success);
2596
2597   *known = success;
2598   return addr;
2599
2600 } /* get_ipxnet_addr */
2601
2602 extern const gchar *get_manuf_name(const guint8 *addr)
2603 {
2604   gchar *cur;
2605   hashmanuf_t  *manufp;
2606
2607   if ((g_resolv_flags & RESOLV_MAC) && !eth_resolution_initialized) {
2608     initialize_ethers();
2609     eth_resolution_initialized = 1;
2610   }
2611
2612   if (!(g_resolv_flags & RESOLV_MAC) || ((manufp = manuf_name_lookup(addr)) == NULL)) {
2613     cur=ep_alloc(MAXMANUFLEN);
2614     g_snprintf(cur, MAXMANUFLEN, "%02x:%02x:%02x", addr[0], addr[1], addr[2]);
2615     return cur;
2616   }
2617
2618   return manufp->name;
2619
2620 } /* get_manuf_name */
2621
2622
2623 const gchar *get_manuf_name_if_known(const guint8 *addr)
2624 {
2625   hashmanuf_t  *manufp;
2626
2627   if (!eth_resolution_initialized) {
2628     initialize_ethers();
2629     eth_resolution_initialized = 1;
2630   }
2631
2632   if ((manufp = manuf_name_lookup(addr)) == NULL) {
2633     return NULL;
2634   }
2635
2636   return manufp->name;
2637
2638 } /* get_manuf_name_if_known */
2639
2640
2641 /* Translate a string, assumed either to be a dotted-quad IP address or
2642  * a host name, to a numeric IP address.  Return TRUE if we succeed and
2643  * set "*addrp" to that numeric IP address; return FALSE if we fail.
2644  * Used more in the dfilter parser rather than in packet dissectors */
2645 gboolean get_host_ipaddr(const char *host, guint32 *addrp)
2646 {
2647         struct in_addr          ipaddr;
2648         struct hostent          *hp;
2649
2650         /*
2651          * don't change it to inet_pton(AF_INET), they are not 100% compatible.
2652          * inet_pton(AF_INET) does not support hexadecimal notation nor
2653          * less-than-4 octet notation.
2654          */
2655         if (!inet_aton(host, &ipaddr)) {
2656                 /* It's not a valid dotted-quad IP address; is it a valid
2657                  * host name? */
2658                 hp = gethostbyname(host);
2659                 if (hp == NULL) {
2660                         /* No. */
2661                         return FALSE;
2662                         /* Apparently, some versions of gethostbyaddr can
2663                          * return IPv6 addresses. */
2664                 } else if (hp->h_length <= (int) sizeof (struct in_addr)) {
2665                         memcpy(&ipaddr, hp->h_addr, hp->h_length);
2666                 } else {
2667                         return FALSE;
2668                 }
2669         } else {
2670                 /* Does the string really contain dotted-quad IP?
2671                  * Check against inet_atons that accept strings such as
2672                  * "130.230" as valid addresses and try to convert them
2673                  * to some form of a classful (host.net) notation.
2674                  */
2675                 unsigned int a0, a1, a2, a3;
2676                 if (sscanf(host, "%u.%u.%u.%u", &a0, &a1, &a2, &a3) != 4)
2677                         return FALSE;
2678         }
2679
2680         *addrp = g_ntohl(ipaddr.s_addr);
2681         return TRUE;
2682 }
2683
2684 /*
2685  * Translate IPv6 numeric address or FQDN hostname, into binary IPv6 address.
2686  * Return TRUE if we succeed and set "*addrp" to that numeric IP address;
2687  * return FALSE if we fail.
2688  */
2689 gboolean get_host_ipaddr6(const char *host, struct e_in6_addr *addrp)
2690 {
2691         struct hostent *hp;
2692
2693         if (inet_pton(AF_INET6, host, addrp) == 1)
2694                 return TRUE;
2695
2696         /* try FQDN */
2697 #ifdef HAVE_GETHOSTBYNAME2
2698         hp = gethostbyname2(host, AF_INET6);
2699 #else
2700         hp = NULL;
2701 #endif
2702         if (hp != NULL && hp->h_length == sizeof(struct e_in6_addr)) {
2703                 memcpy(addrp, hp->h_addr, hp->h_length);
2704                 return TRUE;
2705         }
2706
2707         return FALSE;
2708 }
2709
2710 /*
2711  * Find out whether a hostname resolves to an ip or ipv6 address
2712  * Return "ip6" if it is IPv6, "ip" otherwise (including the case
2713  * that we don't know)
2714  */
2715 const char* host_ip_af(const char *host
2716 #ifndef HAVE_GETHOSTBYNAME2
2717 _U_
2718 #endif
2719 )
2720 {
2721 #ifdef HAVE_GETHOSTBYNAME2
2722         struct hostent *h;
2723         return (h = gethostbyname2(host, AF_INET6)) && h->h_addrtype == AF_INET6 ? "ip6" : "ip";
2724 #else
2725         return "ip";
2726 #endif
2727 }