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