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