Can we reassure Microsoft's static analyzer that 0 <= mask <= 48?
[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)) != NULL) && 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)) != NULL) && 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)) != NULL) && 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)) != NULL) && 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   /*
1336    * XXX - can we use Standard Annotation Language annotations to
1337    * note that mask, as returned by parse_ether_address() (and thus
1338    * by the routines that call it, and thus passed to us) cannot be > 48,
1339    * or is SAL too weak to express that?
1340    */
1341   if (mask >= 48) {
1342     /* This is a well-known MAC address; just add this to the Ethernet
1343        hash table */
1344     add_eth_name(addr, name);
1345     return;
1346   }
1347
1348   if (mask == 0) {
1349     /* This is a manufacturer ID; add it to the manufacturer ID hash table */
1350
1351     hash_idx = HASH_ETH_MANUF(addr);
1352     mtp = manuf_table[hash_idx];
1353
1354     if( mtp == NULL ) {
1355       manuf_table[hash_idx] = manuf_hash_new_entry(addr, name);
1356       return;
1357     } else {
1358       while(TRUE) {
1359         if (mtp->next == NULL) {
1360           mtp->next = manuf_hash_new_entry(addr, name);
1361           return;
1362         }
1363         mtp = mtp->next;
1364       }
1365     }
1366   } /* mask == 0 */
1367
1368   /* This is a range of well-known addresses; add it to the appropriate
1369      well-known-address table, creating that table if necessary. */
1370   wka_tp = wka_table[mask];
1371   if (wka_tp == NULL)
1372     wka_tp = wka_table[mask] = g_malloc0(sizeof *wka_table[mask]);
1373
1374   hash_idx = hash_eth_wka(addr, mask);
1375
1376   wtp = (*wka_tp)[hash_idx];
1377
1378   if( wtp == NULL ) {
1379     (*wka_tp)[hash_idx] = wka_hash_new_entry(addr, name);
1380     return;
1381   } else {
1382     while(TRUE) {
1383       if (memcmp(wtp->addr, addr, sizeof(wtp->addr)) == 0) {
1384         /* address already known */
1385         return;
1386       }
1387       if (wtp->next == NULL) {
1388         wtp->next = wka_hash_new_entry(addr, name);
1389         return;
1390       }
1391       wtp = wtp->next;
1392     }
1393   }
1394 } /* add_manuf_name */
1395
1396 static hashmanuf_t *
1397 manuf_name_lookup(const guint8 *addr)
1398 {
1399   gint         hash_idx;
1400   hashmanuf_t *mtp;
1401   guint8       stripped_addr[3];
1402
1403   hash_idx = HASH_ETH_MANUF(addr);
1404
1405   /* first try to find a "perfect match" */
1406   mtp = manuf_table[hash_idx];
1407   while(mtp != NULL) {
1408     if (memcmp(mtp->addr, addr, sizeof(mtp->addr)) == 0) {
1409       return mtp;
1410     }
1411     mtp = mtp->next;
1412   }
1413
1414   /* Mask out the broadcast/multicast flag but not the locally
1415    * administered flag as localy administered means: not assigend
1416    * by the IEEE but the local administrator instead.
1417    * 0x01 multicast / broadcast bit
1418    * 0x02 locally administered bit */
1419   memcpy(stripped_addr, addr, 3);
1420   stripped_addr[0] &= 0xFE;
1421
1422   mtp = manuf_table[hash_idx];
1423   while(mtp != NULL) {
1424     if (memcmp(mtp->addr, stripped_addr, sizeof(mtp->addr)) == 0) {
1425       return mtp;
1426     }
1427     mtp = mtp->next;
1428   }
1429
1430   return NULL;
1431
1432 } /* manuf_name_lookup */
1433
1434 static hashwka_t *
1435 wka_name_lookup(const guint8 *addr, const unsigned int mask)
1436 {
1437   gint       hash_idx;
1438   hashwka_t *(*wka_tp)[HASHETHSIZE];
1439   hashwka_t *wtp;
1440   guint8     masked_addr[6];
1441   guint      num;
1442   gint       i;
1443
1444   wka_tp = wka_table[mask];
1445   if (wka_tp == NULL) {
1446     /* There are no entries in the table for that mask value, as there is
1447        no table for that mask value. */
1448     return NULL;
1449   }
1450
1451   /* Get the part of the address covered by the mask. */
1452   for (i = 0, num = mask; num >= 8; i++, num -= 8)
1453     masked_addr[i] = addr[i];   /* copy octets entirely covered by the mask */
1454   /* Mask out the first masked octet */
1455   masked_addr[i] = addr[i] & (0xFF << (8 - num));
1456   i++;
1457   /* Zero out completely-masked-out octets */
1458   for (; i < 6; i++)
1459     masked_addr[i] = 0;
1460
1461   hash_idx = hash_eth_wka(masked_addr, mask);
1462
1463   wtp = (*wka_tp)[hash_idx];
1464
1465   while(wtp != NULL) {
1466     if (memcmp(wtp->addr, masked_addr, sizeof(wtp->addr)) == 0) {
1467       return wtp;
1468     }
1469     wtp = wtp->next;
1470   }
1471
1472   return NULL;
1473
1474 } /* wka_name_lookup */
1475
1476 static void
1477 initialize_ethers(void)
1478 {
1479   ether_t *eth;
1480   char    *manuf_path;
1481   guint    mask;
1482
1483   /* Compute the pathname of the ethers file. */
1484   if (g_ethers_path == NULL) {
1485     g_ethers_path = g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s",
1486                                     get_systemfile_dir(), ENAME_ETHERS);
1487   }
1488
1489   /* Set g_pethers_path here, but don't actually do anything
1490    * with it. It's used in get_ethbyname() and get_ethbyaddr()
1491    */
1492   if (g_pethers_path == NULL)
1493     g_pethers_path = get_persconffile_path(ENAME_ETHERS, FALSE, FALSE);
1494
1495   /* manuf hash table initialization */
1496
1497   /* Compute the pathname of the manuf file */
1498   manuf_path = get_datafile_path(ENAME_MANUF);
1499
1500   /* Read it and initialize the hash table */
1501   set_ethent(manuf_path);
1502
1503   while ((eth = get_ethent(&mask, TRUE))) {
1504     add_manuf_name(eth->addr, mask, eth->name);
1505   }
1506
1507   end_ethent();
1508
1509   g_free(manuf_path);
1510
1511 } /* initialize_ethers */
1512
1513 /* Resolve ethernet address */
1514 static hashether_t *
1515 eth_addr_resolve(hashether_t *tp) {
1516   ether_t      *eth;
1517   const guint8 *addr = tp->addr;
1518
1519   if ( (eth = get_ethbyaddr(addr)) != NULL) {
1520     g_strlcpy(tp->resolved_name, eth->name, MAXNAMELEN);
1521     tp->status = HASHETHER_STATUS_RESOLVED_NAME;
1522     return tp;
1523   } else {
1524     hashwka_t    *wtp;
1525     hashmanuf_t  *mtp;
1526     guint         mask;
1527
1528     /* Unknown name.  Try looking for it in the well-known-address
1529        tables for well-known address ranges smaller than 2^24. */
1530     mask = 7;
1531     for (;;) {
1532       /* Only the topmost 5 bytes participate fully */
1533       if ((wtp = wka_name_lookup(addr, mask+40)) != NULL) {
1534         g_snprintf(tp->resolved_name, MAXNAMELEN, "%s_%02x",
1535                    wtp->name, addr[5] & (0xFF >> mask));
1536         tp->status = HASHETHER_STATUS_RESOLVED_DUMMY;
1537         return tp;
1538       }
1539       if (mask == 0)
1540         break;
1541       mask--;
1542     }
1543
1544     mask = 7;
1545     for (;;) {
1546       /* Only the topmost 4 bytes participate fully */
1547       if ((wtp = wka_name_lookup(addr, mask+32)) != NULL) {
1548         g_snprintf(tp->resolved_name, MAXNAMELEN, "%s_%02x:%02x",
1549                    wtp->name, addr[4] & (0xFF >> mask), addr[5]);
1550         tp->status = HASHETHER_STATUS_RESOLVED_DUMMY;
1551         return tp;
1552       }
1553       if (mask == 0)
1554         break;
1555       mask--;
1556     }
1557
1558     mask = 7;
1559     for (;;) {
1560       /* Only the topmost 3 bytes participate fully */
1561       if ((wtp = wka_name_lookup(addr, mask+24)) != NULL) {
1562         g_snprintf(tp->resolved_name, MAXNAMELEN, "%s_%02x:%02x:%02x",
1563                    wtp->name, addr[3] & (0xFF >> mask), addr[4], addr[5]);
1564         tp->status = HASHETHER_STATUS_RESOLVED_DUMMY;
1565         return tp;
1566       }
1567       if (mask == 0)
1568         break;
1569       mask--;
1570     }
1571
1572     /* Now try looking in the manufacturer table. */
1573     if ((mtp = manuf_name_lookup(addr)) != NULL) {
1574       g_snprintf(tp->resolved_name, MAXNAMELEN, "%s_%02x:%02x:%02x",
1575                  mtp->name, addr[3], addr[4], addr[5]);
1576       tp->status = HASHETHER_STATUS_RESOLVED_DUMMY;
1577       return tp;
1578     }
1579
1580     /* Now try looking for it in the well-known-address
1581        tables for well-known address ranges larger than 2^24. */
1582     mask = 7;
1583     for (;;) {
1584       /* Only the topmost 2 bytes participate fully */
1585       if ((wtp = wka_name_lookup(addr, mask+16)) != NULL) {
1586         g_snprintf(tp->resolved_name, MAXNAMELEN, "%s_%02x:%02x:%02x:%02x",
1587                    wtp->name, addr[2] & (0xFF >> mask), addr[3], addr[4],
1588                    addr[5]);
1589         tp->status = HASHETHER_STATUS_RESOLVED_DUMMY;
1590         return tp;
1591       }
1592       if (mask == 0)
1593         break;
1594       mask--;
1595     }
1596
1597     mask = 7;
1598     for (;;) {
1599       /* Only the topmost byte participates fully */
1600       if ((wtp = wka_name_lookup(addr, mask+8)) != NULL) {
1601         g_snprintf(tp->resolved_name, MAXNAMELEN, "%s_%02x:%02x:%02x:%02x:%02x",
1602                    wtp->name, addr[1] & (0xFF >> mask), addr[2], addr[3],
1603                    addr[4], addr[5]);
1604         tp->status = HASHETHER_STATUS_RESOLVED_DUMMY;
1605         return tp;
1606       }
1607       if (mask == 0)
1608         break;
1609       mask--;
1610     }
1611
1612     for (mask = 7; mask > 0; mask--) {
1613       /* Not even the topmost byte participates fully */
1614       if ((wtp = wka_name_lookup(addr, mask)) != NULL) {
1615         g_snprintf(tp->resolved_name, MAXNAMELEN, "%s_%02x:%02x:%02x:%02x:%02x:%02x",
1616                    wtp->name, addr[0] & (0xFF >> mask), addr[1], addr[2],
1617                    addr[3], addr[4], addr[5]);
1618         tp->status = HASHETHER_STATUS_RESOLVED_DUMMY;
1619         return tp;
1620       }
1621     }
1622
1623     /* No match whatsoever. */
1624     g_snprintf(tp->resolved_name, MAXNAMELEN, "%s", ether_to_str(addr));
1625     tp->status = HASHETHER_STATUS_RESOLVED_DUMMY;
1626     return tp;
1627   }
1628   g_assert_not_reached();
1629 } /* eth_addr_resolve */
1630
1631 static hashether_t *
1632 eth_hash_new_entry(const guint8 *addr, const gboolean resolve) {
1633   hashether_t *tp;
1634
1635   tp = (hashether_t *)g_malloc(sizeof(hashether_t));
1636   memcpy(tp->addr, addr, sizeof(tp->addr));
1637   tp->status = HASHETHER_STATUS_UNRESOLVED;
1638   g_strlcpy(tp->hexaddr, bytestring_to_str(addr, sizeof(tp->addr), ':'), sizeof(tp->hexaddr));
1639   tp->resolved_name[0] = '\0';
1640   tp->next = NULL;
1641
1642   if (resolve)
1643     eth_addr_resolve(tp);
1644
1645   return tp;
1646 } /* eth_hash_new_entry */
1647
1648 static hashether_t *
1649 add_eth_name(const guint8 *addr, const gchar *name)
1650 {
1651   gint         hash_idx;
1652   hashether_t *tp;
1653
1654   hash_idx = HASH_ETH_ADDRESS(addr);
1655
1656   tp = eth_table[hash_idx];
1657   if( tp == NULL ) {
1658     tp = eth_table[hash_idx] = eth_hash_new_entry(addr, FALSE);
1659   } else {
1660     while(TRUE) {
1661       if (memcmp(tp->addr, addr, sizeof(tp->addr)) == 0) {
1662         /* address already known */
1663         if (tp->status == HASHETHER_STATUS_RESOLVED_NAME)
1664           return tp; /* Entry with a name already in table; ignore attempted replacement */
1665         break;       /* Update name of existing entry */
1666         }
1667       if (tp->next == NULL) {
1668         tp = tp->next = eth_hash_new_entry(addr, FALSE);
1669         break;
1670       }
1671       tp = tp->next;
1672     }
1673   }
1674
1675   g_strlcpy(tp->resolved_name, name, MAXNAMELEN);
1676   tp->status = HASHETHER_STATUS_RESOLVED_NAME;
1677   new_resolved_objects = TRUE;
1678
1679   return tp;
1680 } /* add_eth_name */
1681
1682 static hashether_t *
1683 eth_name_lookup(const guint8 *addr, const gboolean resolve) {
1684   gint          hash_idx;
1685   hashether_t  *tp;
1686
1687   hash_idx = HASH_ETH_ADDRESS(addr);
1688
1689   tp = eth_table[hash_idx];
1690   if( tp == NULL ) {
1691     tp = eth_table[hash_idx] = eth_hash_new_entry(addr, resolve);
1692     return tp;
1693   } else {
1694     while(TRUE) {
1695       if (memcmp(tp->addr, addr, sizeof(tp->addr)) == 0) {
1696         if (resolve && (tp->status == HASHETHER_STATUS_UNRESOLVED))
1697           eth_addr_resolve(tp); /* Found but needs to be resolved */
1698         return tp;
1699       }
1700       if (tp->next == NULL) {
1701         tp->next = eth_hash_new_entry(addr, resolve);
1702         return tp->next;
1703       }
1704       tp = tp->next;
1705     }
1706   }
1707 } /* eth_name_lookup */
1708
1709 static guint8 *
1710 eth_addr_lookup(const gchar *name)
1711 {
1712   ether_t      *eth;
1713   hashether_t  *tp;
1714   hashether_t **table = eth_table;
1715   gint          i;
1716
1717   /* to be optimized (hash table from name to addr) */
1718   for (i = 0; i < HASHETHSIZE; i++) {
1719     tp = table[i];
1720     while (tp) {
1721       if (strcmp(tp->resolved_name, name) == 0)
1722         return tp->addr;
1723       tp = tp->next;
1724     }
1725   }
1726
1727   /* not in hash table : performs a file lookup */
1728
1729   if ((eth = get_ethbyname(name)) == NULL)
1730     return NULL;
1731
1732   /* add new entry in hash table */
1733
1734   tp = add_eth_name(eth->addr, name);
1735
1736   return tp->addr;
1737
1738 } /* eth_addr_lookup */
1739
1740
1741 /* IPXNETS */
1742 static int
1743 parse_ipxnets_line(char *line, ipxnet_t *ipxnet)
1744 {
1745   /*
1746    *  We allow three address separators (':', '-', and '.'),
1747    *  as well as no separators
1748    */
1749
1750   gchar     *cp;
1751   guint32   a, a0, a1, a2, a3;
1752   gboolean  found_single_number = FALSE;
1753
1754   if ((cp = strchr(line, '#')))
1755     *cp = '\0';
1756
1757   if ((cp = strtok(line, " \t\n")) == NULL)
1758     return -1;
1759
1760   /* Either fill a0,a1,a2,a3 and found_single_number is FALSE,
1761    * fill a and found_single_number is TRUE,
1762    * or return -1
1763    */
1764   if (sscanf(cp, "%x:%x:%x:%x", &a0, &a1, &a2, &a3) != 4) {
1765     if (sscanf(cp, "%x-%x-%x-%x", &a0, &a1, &a2, &a3) != 4) {
1766       if (sscanf(cp, "%x.%x.%x.%x", &a0, &a1, &a2, &a3) != 4) {
1767         if (sscanf(cp, "%x", &a) == 1) {
1768           found_single_number = TRUE;
1769         }
1770         else {
1771           return -1;
1772         }
1773       }
1774     }
1775   }
1776
1777   if ((cp = strtok(NULL, " \t\n")) == NULL)
1778     return -1;
1779
1780   if (found_single_number) {
1781     ipxnet->addr = a;
1782   }
1783   else {
1784     ipxnet->addr = (a0 << 24) | (a1 << 16) | (a2 << 8) | a3;
1785   }
1786
1787   g_strlcpy(ipxnet->name, cp, MAXNAMELEN);
1788
1789   return 0;
1790
1791 } /* parse_ipxnets_line */
1792
1793 static FILE *ipxnet_p = NULL;
1794
1795 static void
1796 set_ipxnetent(char *path)
1797 {
1798   if (ipxnet_p)
1799     rewind(ipxnet_p);
1800   else
1801     ipxnet_p = ws_fopen(path, "r");
1802 }
1803
1804 static void
1805 end_ipxnetent(void)
1806 {
1807   if (ipxnet_p) {
1808     fclose(ipxnet_p);
1809     ipxnet_p = NULL;
1810   }
1811 }
1812
1813 static ipxnet_t *
1814 get_ipxnetent(void)
1815 {
1816
1817   static ipxnet_t ipxnet;
1818   static int     size = 0;
1819   static char   *buf = NULL;
1820
1821   if (ipxnet_p == NULL)
1822     return NULL;
1823
1824   while (fgetline(&buf, &size, ipxnet_p) >= 0) {
1825     if (parse_ipxnets_line(buf, &ipxnet) == 0) {
1826       return &ipxnet;
1827     }
1828   }
1829
1830   return NULL;
1831
1832 } /* get_ipxnetent */
1833
1834 static ipxnet_t *
1835 get_ipxnetbyname(const gchar *name)
1836 {
1837   ipxnet_t *ipxnet;
1838
1839   set_ipxnetent(g_ipxnets_path);
1840
1841   while (((ipxnet = get_ipxnetent()) != NULL) && strncmp(name, ipxnet->name, MAXNAMELEN) != 0)
1842     ;
1843
1844   if (ipxnet == NULL) {
1845     end_ipxnetent();
1846
1847     set_ipxnetent(g_pipxnets_path);
1848
1849     while (((ipxnet = get_ipxnetent()) != NULL) && strncmp(name, ipxnet->name, MAXNAMELEN) != 0)
1850       ;
1851
1852     end_ipxnetent();
1853   }
1854
1855   return ipxnet;
1856
1857 } /* get_ipxnetbyname */
1858
1859 static ipxnet_t *
1860 get_ipxnetbyaddr(guint32 addr)
1861 {
1862   ipxnet_t *ipxnet;
1863
1864   set_ipxnetent(g_ipxnets_path);
1865
1866   while (((ipxnet = get_ipxnetent()) != NULL) && (addr != ipxnet->addr) ) ;
1867
1868   if (ipxnet == NULL) {
1869     end_ipxnetent();
1870
1871     set_ipxnetent(g_pipxnets_path);
1872
1873     while (((ipxnet = get_ipxnetent()) != NULL) && (addr != ipxnet->addr) )
1874       ;
1875
1876     end_ipxnetent();
1877   }
1878
1879   return ipxnet;
1880
1881 } /* get_ipxnetbyaddr */
1882
1883 static void
1884 initialize_ipxnets(void)
1885 {
1886   /* Compute the pathname of the ipxnets file.
1887    *
1888    * XXX - is there a notion of an "ipxnets file" in any flavor of
1889    * UNIX, or with any add-on Netware package for UNIX?  If not,
1890    * should the UNIX version of the ipxnets file be in the datafile
1891    * directory as well?
1892    */
1893   if (g_ipxnets_path == NULL) {
1894     g_ipxnets_path = g_strdup_printf("%s" G_DIR_SEPARATOR_S "%s",
1895                                      get_systemfile_dir(), ENAME_IPXNETS);
1896   }
1897
1898   /* Set g_pipxnets_path here, but don't actually do anything
1899    * with it. It's used in get_ipxnetbyname() and get_ipxnetbyaddr()
1900    */
1901   if (g_pipxnets_path == NULL)
1902     g_pipxnets_path = get_persconffile_path(ENAME_IPXNETS, FALSE, FALSE);
1903
1904 } /* initialize_ipxnets */
1905
1906 static hashipxnet_t *
1907 add_ipxnet_name(guint addr, const gchar *name)
1908 {
1909   int hash_idx;
1910   hashipxnet_t *tp;
1911
1912   hash_idx = HASH_IPX_NET(addr);
1913
1914   tp = ipxnet_table[hash_idx];
1915
1916   if( tp == NULL ) {
1917     tp = ipxnet_table[hash_idx] = (hashipxnet_t *)g_malloc(sizeof(hashipxnet_t));
1918   } else {
1919     while(1) {
1920       if (tp->next == NULL) {
1921         tp->next = (hashipxnet_t *)g_malloc(sizeof(hashipxnet_t));
1922         tp = tp->next;
1923         break;
1924       }
1925       tp = tp->next;
1926     }
1927   }
1928
1929   tp->addr = addr;
1930   g_strlcpy(tp->name, name, MAXNAMELEN);
1931   tp->next = NULL;
1932   new_resolved_objects = TRUE;
1933
1934   return tp;
1935
1936 } /* add_ipxnet_name */
1937
1938 static gchar *
1939 ipxnet_name_lookup(const guint addr)
1940 {
1941   int hash_idx;
1942   hashipxnet_t *tp;
1943   ipxnet_t *ipxnet;
1944
1945   hash_idx = HASH_IPX_NET(addr);
1946
1947   tp = ipxnet_table[hash_idx];
1948
1949   if( tp == NULL ) {
1950     tp = ipxnet_table[hash_idx] = (hashipxnet_t *)g_malloc(sizeof(hashipxnet_t));
1951   } else {
1952     while(1) {
1953       if (tp->addr == addr) {
1954         return tp->name;
1955       }
1956       if (tp->next == NULL) {
1957         tp->next = (hashipxnet_t *)g_malloc(sizeof(hashipxnet_t));
1958         tp = tp->next;
1959         break;
1960       }
1961       tp = tp->next;
1962     }
1963   }
1964
1965   /* fill in a new entry */
1966
1967   tp->addr = addr;
1968   tp->next = NULL;
1969
1970   if ( (ipxnet = get_ipxnetbyaddr(addr)) == NULL) {
1971     /* unknown name */
1972     g_snprintf(tp->name, MAXNAMELEN, "%X", addr);
1973
1974   } else {
1975     g_strlcpy(tp->name, ipxnet->name, MAXNAMELEN);
1976   }
1977
1978   return (tp->name);
1979
1980 } /* ipxnet_name_lookup */
1981
1982 static guint
1983 ipxnet_addr_lookup(const gchar *name, gboolean *success)
1984 {
1985   ipxnet_t *ipxnet;
1986   hashipxnet_t *tp;
1987   hashipxnet_t **table = ipxnet_table;
1988   int i;
1989
1990   /* to be optimized (hash table from name to addr) */
1991   for (i = 0; i < HASHIPXNETSIZE; i++) {
1992     tp = table[i];
1993     while (tp) {
1994       if (strcmp(tp->name, name) == 0) {
1995         *success = TRUE;
1996         return tp->addr;
1997       }
1998       tp = tp->next;
1999     }
2000   }
2001
2002   /* not in hash table : performs a file lookup */
2003
2004   if ((ipxnet = get_ipxnetbyname(name)) == NULL) {
2005     *success = FALSE;
2006     return 0;
2007   }
2008
2009   /* add new entry in hash table */
2010
2011   tp = add_ipxnet_name(ipxnet->addr, name);
2012
2013   *success = TRUE;
2014   return tp->addr;
2015
2016 } /* ipxnet_addr_lookup */
2017
2018 static gboolean
2019 read_hosts_file (const char *hostspath)
2020 {
2021   FILE *hf;
2022   char *line = NULL;
2023   int size = 0;
2024   gchar *cp;
2025   guint32 host_addr[4]; /* IPv4 or IPv6 */
2026   struct e_in6_addr ip6_addr;
2027   gboolean is_ipv6;
2028   int ret;
2029
2030   /*
2031    *  See the hosts(4) or hosts(5) man page for hosts file format
2032    *  (not available on all systems).
2033    */
2034   if ((hf = ws_fopen(hostspath, "r")) == NULL)
2035     return FALSE;
2036
2037   while (fgetline(&line, &size, hf) >= 0) {
2038     if ((cp = strchr(line, '#')))
2039       *cp = '\0';
2040
2041     if ((cp = strtok(line, " \t")) == NULL)
2042       continue; /* no tokens in the line */
2043
2044     ret = inet_pton(AF_INET6, cp, &host_addr);
2045     if (ret == -1)
2046       continue; /* error parsing */
2047     if (ret == 1) {
2048       /* Valid IPv6 */
2049       is_ipv6 = TRUE;
2050     } else {
2051       /* Not valid IPv6 - valid IPv4? */
2052       if (inet_pton(AF_INET, cp, &host_addr) != 1)
2053         continue; /* no */
2054       is_ipv6 = FALSE;
2055     }
2056
2057     if ((cp = strtok(NULL, " \t")) == NULL)
2058       continue; /* no host name */
2059
2060     if (is_ipv6) {
2061       memcpy(&ip6_addr, host_addr, sizeof ip6_addr);
2062       add_ipv6_name(&ip6_addr, cp);
2063     } else
2064       add_ipv4_name(host_addr[0], cp);
2065
2066     /*
2067      * Add the aliases, too, if there are any.
2068      */
2069     while ((cp = strtok(NULL, " \t")) != NULL) {
2070       if (is_ipv6) {
2071         memcpy(&ip6_addr, host_addr, sizeof ip6_addr);
2072         add_ipv6_name(&ip6_addr, cp);
2073       } else
2074         add_ipv4_name(host_addr[0], cp);
2075     }
2076   }
2077   g_free(line);
2078
2079   fclose(hf);
2080   return TRUE;
2081 } /* read_hosts_file */
2082
2083 gboolean
2084 add_ip_name_from_string (const char *addr, const char *name)
2085 {
2086   guint32 host_addr[4]; /* IPv4 */
2087   struct e_in6_addr ip6_addr; /* IPv6 */
2088   gboolean is_ipv6;
2089   int ret;
2090
2091   ret = inet_pton(AF_INET6, addr, &ip6_addr);
2092   if (ret == -1)
2093     /* Error parsing address */
2094     return FALSE;
2095
2096   if (ret == 1) {
2097     /* Valid IPv6 */
2098     is_ipv6 = TRUE;
2099   } else {
2100     /* Not valid IPv6 - valid IPv4? */
2101     if (inet_pton(AF_INET, addr, &host_addr) != 1)
2102       return FALSE; /* no */
2103     is_ipv6 = FALSE;
2104   }
2105
2106   if (is_ipv6) {
2107     add_ipv6_name(&ip6_addr, name);
2108   } else {
2109     add_ipv4_name(host_addr[0], name);
2110   }
2111
2112   return TRUE;
2113 } /* add_ip_name_from_string */
2114
2115
2116 /* Read in a list of subnet definition - name pairs.
2117  * <line> = <comment> | <entry> | <whitespace>
2118  * <comment> = <whitespace>#<any>
2119  * <entry> = <subnet_definition> <whitespace> <subnet_name> [<comment>|<whitespace><any>]
2120  * <subnet_definition> = <ipv4_address> / <subnet_mask_length>
2121  * <ipv4_address> is a full address; it will be masked to get the subnet-ID.
2122  * <subnet_mask_length> is a decimal 1-31
2123  * <subnet_name> is a string containing no whitespace.
2124  * <whitespace> = (space | tab)+
2125  * Any malformed entries are ignored.
2126  * Any trailing data after the subnet_name is ignored.
2127  *
2128  * XXX Support IPv6
2129  */
2130 static gboolean
2131 read_subnets_file (const char *subnetspath)
2132 {
2133   FILE *hf;
2134   char *line = NULL;
2135   int size = 0;
2136   gchar *cp, *cp2;
2137   guint32 host_addr; /* IPv4 ONLY */
2138   int mask_length;
2139
2140   if ((hf = ws_fopen(subnetspath, "r")) == NULL)
2141     return FALSE;
2142
2143   while (fgetline(&line, &size, hf) >= 0) {
2144     if ((cp = strchr(line, '#')))
2145       *cp = '\0';
2146
2147     if ((cp = strtok(line, " \t")) == NULL)
2148       continue; /* no tokens in the line */
2149
2150
2151     /* Expected format is <IP4 address>/<subnet length> */
2152     cp2 = strchr(cp, '/');
2153     if(NULL == cp2) {
2154         /* No length */
2155         continue;
2156     }
2157     *cp2 = '\0'; /* Cut token */
2158     ++cp2    ;
2159
2160     /* Check if this is a valid IPv4 address */
2161     if (inet_pton(AF_INET, cp, &host_addr) != 1) {
2162         continue; /* no */
2163     }
2164
2165     mask_length = atoi(cp2);
2166     if(0 >= mask_length || mask_length > 31) {
2167         continue; /* invalid mask length */
2168     }
2169
2170     if ((cp = strtok(NULL, " \t")) == NULL)
2171       continue; /* no subnet name */
2172
2173     subnet_entry_set(host_addr, (guint32)mask_length, cp);
2174   }
2175   g_free(line);
2176
2177   fclose(hf);
2178   return TRUE;
2179 } /* read_subnets_file */
2180
2181 static subnet_entry_t
2182 subnet_lookup(const guint32 addr)
2183 {
2184   subnet_entry_t subnet_entry;
2185   guint32 i;
2186
2187   /* Search mask lengths linearly, longest first */
2188
2189   i = SUBNETLENGTHSIZE;
2190   while(have_subnet_entry && i > 0) {
2191     guint32 masked_addr;
2192     subnet_length_entry_t* length_entry;
2193
2194     /* Note that we run from 31 (length 32)  to 0 (length 1)  */
2195     --i;
2196     g_assert(i < SUBNETLENGTHSIZE);
2197
2198
2199     length_entry = &subnet_length_entries[i];
2200
2201     if(NULL != length_entry->subnet_addresses) {
2202       hashipv4_t * tp;
2203       guint32 hash_idx;
2204
2205       masked_addr = addr & length_entry->mask;
2206       hash_idx = HASH_IPV4_ADDRESS(masked_addr);
2207
2208       tp = length_entry->subnet_addresses[hash_idx];
2209       while(tp != NULL && tp->addr != masked_addr) {
2210         tp = tp->next;
2211       }
2212
2213       if(NULL != tp) {
2214         subnet_entry.mask = length_entry->mask;
2215         subnet_entry.mask_length = i + 1; /* Length is offset + 1 */
2216         subnet_entry.name = tp->name;
2217         return subnet_entry;
2218       }
2219     }
2220   }
2221
2222   subnet_entry.mask = 0;
2223   subnet_entry.mask_length = 0;
2224   subnet_entry.name = NULL;
2225
2226   return subnet_entry;
2227 }
2228
2229 /* Add a subnet-definition - name pair to the set.
2230  * The definition is taken by masking the address passed in with the mask of the
2231  * given length.
2232  */
2233 static void
2234 subnet_entry_set(guint32 subnet_addr, const guint32 mask_length, const gchar* name)
2235 {
2236   subnet_length_entry_t* entry;
2237   hashipv4_t * tp;
2238   gsize hash_idx;
2239
2240   g_assert(mask_length > 0 && mask_length <= 32);
2241
2242   entry = &subnet_length_entries[mask_length - 1];
2243
2244   subnet_addr &= entry->mask;
2245
2246   hash_idx = HASH_IPV4_ADDRESS(subnet_addr);
2247
2248   if(NULL == entry->subnet_addresses) {
2249     entry->subnet_addresses = g_new0(hashipv4_t*,HASHHOSTSIZE);
2250   }
2251
2252   if(NULL != (tp = entry->subnet_addresses[hash_idx])) {
2253     if(tp->addr == subnet_addr) {
2254       return;    /* XXX provide warning that an address was repeated? */
2255     } else {
2256       hashipv4_t * new_tp = g_new(hashipv4_t,1);
2257       tp->next = new_tp;
2258       tp = new_tp;
2259     }
2260   } else {
2261     tp = entry->subnet_addresses[hash_idx] = g_new(hashipv4_t,1);
2262   }
2263
2264   tp->next = NULL;
2265   tp->addr = subnet_addr;
2266   tp->is_dummy_entry = FALSE; /*Never used again...*/
2267   g_strlcpy(tp->name, name, MAXNAMELEN); /* This is longer than subnet names can actually be */
2268   have_subnet_entry = TRUE;
2269 }
2270
2271 static guint32
2272 get_subnet_mask(const guint32 mask_length) {
2273
2274   static guint32 masks[SUBNETLENGTHSIZE];
2275   static gboolean initialised = FALSE;
2276
2277   if(!initialised) {
2278     memset(masks, 0, sizeof(masks));
2279
2280     initialised = TRUE;
2281
2282     /* XXX There must be a better way to do this than
2283      * hand-coding the values, but I can't seem to
2284      * come up with one!
2285      */
2286
2287     inet_pton(AF_INET, "128.0.0.0", &masks[0]);
2288     inet_pton(AF_INET, "192.0.0.0", &masks[1]);
2289     inet_pton(AF_INET, "224.0.0.0", &masks[2]);
2290     inet_pton(AF_INET, "240.0.0.0", &masks[3]);
2291     inet_pton(AF_INET, "248.0.0.0", &masks[4]);
2292     inet_pton(AF_INET, "252.0.0.0", &masks[5]);
2293     inet_pton(AF_INET, "254.0.0.0", &masks[6]);
2294     inet_pton(AF_INET, "255.0.0.0", &masks[7]);
2295
2296     inet_pton(AF_INET, "255.128.0.0", &masks[8]);
2297     inet_pton(AF_INET, "255.192.0.0", &masks[9]);
2298     inet_pton(AF_INET, "255.224.0.0", &masks[10]);
2299     inet_pton(AF_INET, "255.240.0.0", &masks[11]);
2300     inet_pton(AF_INET, "255.248.0.0", &masks[12]);
2301     inet_pton(AF_INET, "255.252.0.0", &masks[13]);
2302     inet_pton(AF_INET, "255.254.0.0", &masks[14]);
2303     inet_pton(AF_INET, "255.255.0.0", &masks[15]);
2304
2305     inet_pton(AF_INET, "255.255.128.0", &masks[16]);
2306     inet_pton(AF_INET, "255.255.192.0", &masks[17]);
2307     inet_pton(AF_INET, "255.255.224.0", &masks[18]);
2308     inet_pton(AF_INET, "255.255.240.0", &masks[19]);
2309     inet_pton(AF_INET, "255.255.248.0", &masks[20]);
2310     inet_pton(AF_INET, "255.255.252.0", &masks[21]);
2311     inet_pton(AF_INET, "255.255.254.0", &masks[22]);
2312     inet_pton(AF_INET, "255.255.255.0", &masks[23]);
2313
2314     inet_pton(AF_INET, "255.255.255.128", &masks[24]);
2315     inet_pton(AF_INET, "255.255.255.192", &masks[25]);
2316     inet_pton(AF_INET, "255.255.255.224", &masks[26]);
2317     inet_pton(AF_INET, "255.255.255.240", &masks[27]);
2318     inet_pton(AF_INET, "255.255.255.248", &masks[28]);
2319     inet_pton(AF_INET, "255.255.255.252", &masks[29]);
2320     inet_pton(AF_INET, "255.255.255.254", &masks[30]);
2321     inet_pton(AF_INET, "255.255.255.255", &masks[31]);
2322   }
2323
2324   if(mask_length == 0 || mask_length > SUBNETLENGTHSIZE) {
2325     g_assert_not_reached();
2326     return 0;
2327   } else {
2328     return masks[mask_length - 1];
2329   }
2330 }
2331
2332 static void
2333 subnet_name_lookup_init(void)
2334 {
2335   gchar* subnetspath;
2336   guint32 i;
2337
2338   for(i = 0; i < SUBNETLENGTHSIZE; ++i) {
2339     guint32 length = i + 1;
2340
2341     subnet_length_entries[i].subnet_addresses  = NULL;
2342     subnet_length_entries[i].mask_length  = length;
2343     subnet_length_entries[i].mask = get_subnet_mask(length);
2344   }
2345
2346   subnetspath = get_persconffile_path(ENAME_SUBNETS, FALSE, FALSE);
2347   if (!read_subnets_file(subnetspath) && errno != ENOENT) {
2348     report_open_failure(subnetspath, errno, FALSE);
2349   }
2350   g_free(subnetspath);
2351
2352   /*
2353    * Load the global subnets file, if we have one.
2354    */
2355   subnetspath = get_datafile_path(ENAME_SUBNETS);
2356   if (!read_subnets_file(subnetspath) && errno != ENOENT) {
2357     report_open_failure(subnetspath, errno, FALSE);
2358   }
2359   g_free(subnetspath);
2360 }
2361
2362 /*
2363  *  External Functions
2364  */
2365
2366 void
2367 host_name_lookup_init(void) {
2368   char *hostspath;
2369
2370 #ifdef HAVE_GNU_ADNS
2371 #ifdef _WIN32
2372   char *sysroot;
2373   static char rootpath_nt[] = "\\system32\\drivers\\etc\\hosts";
2374   static char rootpath_ot[] = "\\hosts";
2375 #endif /* _WIN32 */
2376 #endif /*GNU_ADNS */
2377
2378   /*
2379    * Load the user's hosts file, if they have one.
2380    */
2381   hostspath = get_persconffile_path(ENAME_HOSTS, FALSE, FALSE);
2382   if (!read_hosts_file(hostspath) && errno != ENOENT) {
2383     report_open_failure(hostspath, errno, FALSE);
2384   }
2385   g_free(hostspath);
2386
2387   /*
2388    * Load the global hosts file, if we have one.
2389    */
2390   hostspath = get_datafile_path(ENAME_HOSTS);
2391   if (!read_hosts_file(hostspath) && errno != ENOENT) {
2392     report_open_failure(hostspath, errno, FALSE);
2393   }
2394   g_free(hostspath);
2395
2396 #ifdef HAVE_C_ARES
2397 #ifdef CARES_HAVE_ARES_LIBRARY_INIT
2398   if (ares_library_init(ARES_LIB_INIT_ALL) == ARES_SUCCESS) {
2399 #endif
2400   if (ares_init(&ghba_chan) == ARES_SUCCESS && ares_init(&ghbn_chan) == ARES_SUCCESS) {
2401     async_dns_initialized = TRUE;
2402   }
2403 #ifdef CARES_HAVE_ARES_LIBRARY_INIT
2404   }
2405 #endif
2406 #else
2407 #ifdef HAVE_GNU_ADNS
2408   /*
2409    * We're using GNU ADNS, which doesn't check the system hosts file;
2410    * we load that file ourselves.
2411    */
2412 #ifdef _WIN32
2413
2414   sysroot = getenv_utf8("WINDIR");
2415   if (sysroot != NULL) {
2416     /*
2417      * The file should be under WINDIR.
2418      * If this is Windows NT (NT 4.0,2K,XP,Server2K3), it's in
2419      * %WINDIR%\system32\drivers\etc\hosts.
2420      * If this is Windows OT (95,98,Me), it's in %WINDIR%\hosts.
2421      * Try both.
2422      * XXX - should we base it on the dwPlatformId value from
2423      * GetVersionEx()?
2424      */
2425     hostspath = g_strconcat(sysroot, rootpath_nt, NULL);
2426     if (!read_hosts_file(hostspath)) {
2427       g_free(hostspath);
2428       hostspath = g_strconcat(sysroot, rootpath_ot, NULL);
2429       read_hosts_file(hostspath);
2430     }
2431     g_free(hostspath);
2432   }
2433 #else /* _WIN32 */
2434   read_hosts_file("/etc/hosts");
2435 #endif /* _WIN32 */
2436
2437   /* XXX - Any flags we should be using? */
2438   /* XXX - We could provide config settings for DNS servers, and
2439            pass them to ADNS with adns_init_strcfg */
2440   if (adns_init(&ads, 0, 0 /*0=>stderr*/) != 0) {
2441     /*
2442      * XXX - should we report the error?  I'm assuming that some crashes
2443      * reported on a Windows machine with TCP/IP not configured are due
2444      * to "adns_init()" failing (due to the lack of TCP/IP) and leaving
2445      * ADNS in a state where it crashes due to that.  We'll still try
2446      * doing name resolution anyway.
2447      */
2448     return;
2449   }
2450   async_dns_initialized = TRUE;
2451   async_dns_in_flight = 0;
2452 #endif /* HAVE_GNU_ADNS */
2453 #endif /* HAVE_C_ARES */
2454
2455   subnet_name_lookup_init();
2456 }
2457
2458 #ifdef HAVE_C_ARES
2459 gboolean
2460 host_name_lookup_process(gpointer data _U_) {
2461   async_dns_queue_msg_t *caqm;
2462   struct timeval tv = { 0, 0 };
2463   int nfds;
2464   fd_set rfds, wfds;
2465   gboolean nro = new_resolved_objects;
2466
2467   new_resolved_objects = FALSE;
2468
2469   if (!async_dns_initialized)
2470     /* c-ares not initialized. Bail out and cancel timers. */
2471     return nro;
2472
2473   async_dns_queue_head = g_list_first(async_dns_queue_head);
2474
2475   while (async_dns_queue_head != NULL && async_dns_in_flight <= prefs.name_resolve_concurrency) {
2476     caqm = (async_dns_queue_msg_t *) async_dns_queue_head->data;
2477     async_dns_queue_head = g_list_remove(async_dns_queue_head, (void *) caqm);
2478     if (caqm->family == AF_INET) {
2479       ares_gethostbyaddr(ghba_chan, &caqm->addr.ip4, sizeof(guint32), AF_INET,
2480                          c_ares_ghba_cb, caqm);
2481       async_dns_in_flight++;
2482     } else if (caqm->family == AF_INET6) {
2483       ares_gethostbyaddr(ghba_chan, &caqm->addr.ip6, sizeof(struct e_in6_addr),
2484                          AF_INET6, c_ares_ghba_cb, caqm);
2485       async_dns_in_flight++;
2486     }
2487   }
2488
2489   FD_ZERO(&rfds);
2490   FD_ZERO(&wfds);
2491   nfds = ares_fds(ghba_chan, &rfds, &wfds);
2492   if (nfds > 0) {
2493     select(nfds, &rfds, &wfds, NULL, &tv);
2494     ares_process(ghba_chan, &rfds, &wfds);
2495   }
2496
2497   /* Any new entries? */
2498   return nro;
2499 }
2500
2501 void
2502 host_name_lookup_cleanup(void) {
2503   GList *cur;
2504
2505   cur = g_list_first(async_dns_queue_head);
2506   while (cur) {
2507     g_free(cur->data);
2508     cur = g_list_next (cur);
2509   }
2510
2511   g_list_free(async_dns_queue_head);
2512
2513   if (async_dns_initialized) {
2514     ares_destroy(ghba_chan);
2515     ares_destroy(ghbn_chan);
2516   }
2517 #ifdef CARES_HAVE_ARES_LIBRARY_INIT
2518   ares_library_cleanup();
2519 #endif
2520   async_dns_initialized = FALSE;
2521 }
2522
2523 #elif defined(HAVE_GNU_ADNS)
2524
2525 /* XXX - The ADNS "documentation" isn't very clear:
2526  * - Do we need to keep our query structures around?
2527  */
2528 gboolean
2529 host_name_lookup_process(gpointer data _U_) {
2530   async_dns_queue_msg_t *almsg;
2531   GList *cur;
2532   char addr_str[] = "111.222.333.444.in-addr.arpa.";
2533   guint8 *addr_bytes;
2534   adns_answer *ans;
2535   int ret;
2536   gboolean dequeue;
2537   gboolean nro = new_resolved_objects;
2538
2539   new_resolved_objects = FALSE;
2540   async_dns_queue_head = g_list_first(async_dns_queue_head);
2541
2542   cur = async_dns_queue_head;
2543   while (cur &&  async_dns_in_flight <= prefs.name_resolve_concurrency) {
2544     almsg = (async_dns_queue_msg_t *) cur->data;
2545     if (! almsg->submitted && almsg->type == AF_INET) {
2546       addr_bytes = (guint8 *) &almsg->ip4_addr;
2547       g_snprintf(addr_str, sizeof addr_str, "%u.%u.%u.%u.in-addr.arpa.", addr_bytes[3],
2548                  addr_bytes[2], addr_bytes[1], addr_bytes[0]);
2549       /* XXX - what if it fails? */
2550       adns_submit (ads, addr_str, adns_r_ptr, 0, NULL, &almsg->query);
2551       almsg->submitted = TRUE;
2552       async_dns_in_flight++;
2553     }
2554     cur = cur->next;
2555   }
2556
2557   cur = async_dns_queue_head;
2558   while (cur) {
2559     dequeue = FALSE;
2560     almsg = (async_dns_queue_msg_t *) cur->data;
2561     if (almsg->submitted) {
2562       ret = adns_check(ads, &almsg->query, &ans, NULL);
2563       if (ret == 0) {
2564         if (ans->status == adns_s_ok) {
2565           add_ipv4_name(almsg->ip4_addr, *ans->rrs.str);
2566         }
2567         dequeue = TRUE;
2568       }
2569     }
2570     cur = cur->next;
2571     if (dequeue) {
2572       async_dns_queue_head = g_list_remove(async_dns_queue_head, (void *) almsg);
2573       g_free(almsg);
2574       async_dns_in_flight--;
2575     }
2576   }
2577
2578   /* Keep the timeout in place */
2579   return nro;
2580 }
2581
2582 void
2583 host_name_lookup_cleanup(void) {
2584   void *qdata;
2585
2586   async_dns_queue_head = g_list_first(async_dns_queue_head);
2587   while (async_dns_queue_head) {
2588     qdata = async_dns_queue_head->data;
2589     async_dns_queue_head = g_list_remove(async_dns_queue_head, qdata);
2590     g_free(qdata);
2591   }
2592
2593   if (async_dns_initialized)
2594     adns_finish(ads);
2595   async_dns_initialized = FALSE;
2596 }
2597
2598 #else /* HAVE_GNU_ADNS */
2599
2600 gboolean
2601 host_name_lookup_process(gpointer data _U_) {
2602   gboolean nro = new_resolved_objects;
2603
2604   new_resolved_objects = FALSE;
2605
2606   return nro;
2607 }
2608
2609 void
2610 host_name_lookup_cleanup(void) {
2611 }
2612
2613 #endif /* HAVE_C_ARES */
2614
2615 extern const gchar *
2616 get_hostname(const guint addr)
2617 {
2618   gboolean found;
2619   gboolean resolve = gbl_resolv_flags & RESOLV_NETWORK;
2620   hashipv4_t *tp = host_lookup(addr, resolve, &found);
2621
2622   if (!resolve)
2623     return tp->ip;
2624
2625   return tp->name;
2626 }
2627
2628 /* -------------------------- */
2629
2630 extern const gchar *
2631 get_hostname6(const struct e_in6_addr *addr)
2632 {
2633   gboolean found;
2634   gboolean resolve = gbl_resolv_flags & RESOLV_NETWORK;
2635   hashipv6_t *tp = host_lookup6(addr, resolve, &found);
2636
2637   if (!resolve)
2638     return tp->ip6;
2639
2640   return tp->name;
2641 }
2642
2643 /* -------------------------- */
2644 extern void
2645 add_ipv4_name(const guint addr, const gchar *name)
2646 {
2647   int hash_idx;
2648   hashipv4_t *tp;
2649
2650   hash_idx = HASH_IPV4_ADDRESS(addr);
2651
2652   tp = ipv4_table[hash_idx];
2653
2654   if( tp == NULL ) {
2655     tp = ipv4_table[hash_idx] = new_ipv4(addr);
2656   } else {
2657     while(1) {
2658       if (tp->addr == addr) {
2659         /* address already known */
2660         if (!tp->is_dummy_entry) {
2661           return;
2662         } else {
2663           /* replace this dummy entry with the new one */
2664           break;
2665         }
2666       }
2667       if (tp->next == NULL) {
2668         tp->next = new_ipv4(addr);
2669         tp = tp->next;
2670         break;
2671       }
2672       tp = tp->next;
2673     }
2674   }
2675   g_strlcpy(tp->name, name, MAXNAMELEN);
2676   tp->resolve = TRUE;
2677   new_resolved_objects = TRUE;
2678 } /* add_ipv4_name */
2679
2680 /* -------------------------- */
2681 extern void
2682 add_ipv6_name(const struct e_in6_addr *addrp, const gchar *name)
2683 {
2684   int hash_idx;
2685   hashipv6_t *tp;
2686
2687   hash_idx = HASH_IPV6_ADDRESS(*addrp);
2688
2689   tp = ipv6_table[hash_idx];
2690
2691   if( tp == NULL ) {
2692     tp = ipv6_table[hash_idx] = new_ipv6(addrp);
2693   } else {
2694     while(1) {
2695       if (memcmp(&tp->addr, addrp, sizeof (struct e_in6_addr)) == 0) {
2696         /* address already known */
2697         if (!tp->is_dummy_entry) {
2698           return;
2699         } else {
2700           /* replace this dummy entry with the new one */
2701           break;
2702         }
2703       }
2704       if (tp->next == NULL) {
2705         tp->next = new_ipv6(addrp);
2706         tp = tp->next;
2707         break;
2708       }
2709       tp = tp->next;
2710     }
2711   }
2712
2713   g_strlcpy(tp->name, name, MAXNAMELEN);
2714   tp->resolve = TRUE;
2715   new_resolved_objects = TRUE;
2716
2717 } /* add_ipv6_name */
2718
2719 /* -----------------
2720  * unsigned integer to ascii
2721 */
2722 static gchar *
2723 ep_utoa(guint port)
2724 {
2725   gchar *bp = ep_alloc(MAXNAMELEN);
2726
2727   /* XXX, guint32_to_str() ? */
2728   guint32_to_str_buf(port, bp, MAXNAMELEN);
2729   return bp;
2730 }
2731
2732
2733 extern gchar *
2734 get_udp_port(guint port)
2735 {
2736
2737   if (!(gbl_resolv_flags & RESOLV_TRANSPORT)) {
2738     return ep_utoa(port);
2739   }
2740
2741   return serv_name_lookup(port, PT_UDP);
2742
2743 } /* get_udp_port */
2744
2745 extern gchar *
2746 get_dccp_port(guint port)
2747 {
2748
2749   if (!(gbl_resolv_flags & RESOLV_TRANSPORT)) {
2750     return ep_utoa(port);
2751   }
2752
2753   return serv_name_lookup(port, PT_DCCP);
2754
2755 } /* get_dccp_port */
2756
2757
2758 extern gchar *
2759 get_tcp_port(guint port)
2760 {
2761
2762   if (!(gbl_resolv_flags & RESOLV_TRANSPORT)) {
2763     return ep_utoa(port);
2764   }
2765
2766   return serv_name_lookup(port, PT_TCP);
2767
2768 } /* get_tcp_port */
2769
2770 extern gchar *
2771 get_sctp_port(guint port)
2772 {
2773
2774   if (!(gbl_resolv_flags & RESOLV_TRANSPORT)) {
2775     return ep_utoa(port);
2776   }
2777
2778   return serv_name_lookup(port, PT_SCTP);
2779
2780 } /* get_sctp_port */
2781
2782 const gchar *
2783 get_addr_name(const address *addr)
2784 {
2785   const gchar *result;
2786
2787   result = solve_address_to_name(addr);
2788
2789   if (result != NULL)
2790     return result;
2791
2792   /* if it gets here, either it is of type AT_NONE, */
2793   /* or it should be solvable in address_to_str -unless addr->type is wrongly defined */
2794
2795   if (addr->type == AT_NONE){
2796     return "NONE";
2797   }
2798
2799   /* We need an ephemeral allocated string */
2800   return ep_address_to_str(addr);
2801 }
2802
2803 const gchar *
2804 se_get_addr_name(const address *addr)
2805 {
2806   const gchar *result;
2807
2808   result = se_solve_address_to_name(addr);
2809
2810   if (result != NULL)
2811     return result;
2812
2813   /* if it gets here, either it is of type AT_NONE, */
2814   /* or it should be solvable in se_address_to_str -unless addr->type is wrongly defined */
2815
2816   if (addr->type == AT_NONE){
2817     return "NONE";
2818   }
2819
2820   /* We need a "permanently" allocated string */
2821   return se_address_to_str(addr);
2822 }
2823
2824 void
2825 get_addr_name_buf(const address *addr, gchar *buf, gsize size)
2826 {
2827   const gchar *result = get_addr_name(addr);
2828
2829   g_strlcpy(buf, result, size);
2830 } /* get_addr_name_buf */
2831
2832
2833 gchar *
2834 get_ether_name(const guint8 *addr)
2835 {
2836   hashether_t *tp;
2837   gboolean resolve = (gbl_resolv_flags & RESOLV_MAC) != 0;
2838
2839   if (resolve && !eth_resolution_initialized) {
2840     initialize_ethers();
2841     eth_resolution_initialized = TRUE;
2842   }
2843
2844   tp = eth_name_lookup(addr, resolve);
2845
2846   return resolve ? tp->resolved_name : tp->hexaddr;
2847
2848 } /* get_ether_name */
2849
2850 /* Look for a (non-dummy) ether name in the hash, and return it if found.
2851  * If it's not found, simply return NULL.
2852  */
2853 gchar *
2854 get_ether_name_if_known(const guint8 *addr)
2855 {
2856   hashether_t *tp;
2857
2858   /* Initialize ether structs if we're the first
2859    * ether-related function called */
2860   if (!(gbl_resolv_flags & RESOLV_MAC))
2861     return NULL;
2862
2863   if (!eth_resolution_initialized) {
2864     initialize_ethers();
2865     eth_resolution_initialized = TRUE;
2866   }
2867
2868   /* eth_name_lookup will create a (resolved) hash entry if it doesn't exist */
2869   tp = eth_name_lookup(addr, TRUE);
2870   g_assert(tp != NULL);
2871
2872   if (tp->status == HASHETHER_STATUS_RESOLVED_NAME) {
2873     /* Name is from an ethers file (or is a "well-known" MAC address name from the manuf file) */
2874     return tp->resolved_name;
2875   }
2876   else {
2877     /* Name was created */
2878     return NULL;
2879   }
2880 }
2881
2882 extern guint8 *
2883 get_ether_addr(const gchar *name)
2884 {
2885
2886   /* force resolution (do not check gbl_resolv_flags) */
2887
2888   if (!eth_resolution_initialized) {
2889     initialize_ethers();
2890     eth_resolution_initialized = TRUE;
2891   }
2892
2893   return eth_addr_lookup(name);
2894
2895 } /* get_ether_addr */
2896
2897 extern void
2898 add_ether_byip(const guint ip, const guint8 *eth)
2899 {
2900
2901   gchar *host;
2902   gboolean found;
2903
2904   /* first check that IP address can be resolved */
2905   if (!(gbl_resolv_flags & RESOLV_NETWORK))
2906     return;
2907
2908   if ((host = host_name_lookup(ip, &found)) == NULL)
2909     return;
2910
2911   /* ok, we can add this entry in the ethers hashtable */
2912
2913   if (found)
2914     add_eth_name(eth, host);
2915
2916 } /* add_ether_byip */
2917
2918 extern const gchar *
2919 get_ipxnet_name(const guint32 addr)
2920 {
2921
2922   if (!(gbl_resolv_flags & RESOLV_NETWORK)) {
2923     return ipxnet_to_str_punct(addr, '\0');
2924   }
2925
2926   if (!ipxnet_resolution_initialized) {
2927     initialize_ipxnets();
2928     ipxnet_resolution_initialized = 1;
2929   }
2930
2931   return ipxnet_name_lookup(addr);
2932
2933 } /* get_ipxnet_name */
2934
2935 extern guint32
2936 get_ipxnet_addr(const gchar *name, gboolean *known)
2937 {
2938   guint32 addr;
2939   gboolean success;
2940
2941   /* force resolution (do not check gbl_resolv_flags) */
2942
2943   if (!ipxnet_resolution_initialized) {
2944     initialize_ipxnets();
2945     ipxnet_resolution_initialized = 1;
2946   }
2947
2948   addr =  ipxnet_addr_lookup(name, &success);
2949
2950   *known = success;
2951   return addr;
2952
2953 } /* get_ipxnet_addr */
2954
2955 extern const gchar *
2956 get_manuf_name(const guint8 *addr)
2957 {
2958   gchar *cur;
2959   hashmanuf_t  *mtp;
2960
2961   if ((gbl_resolv_flags & RESOLV_MAC) && !eth_resolution_initialized) {
2962     initialize_ethers();
2963     eth_resolution_initialized = TRUE;
2964   }
2965
2966   if (!(gbl_resolv_flags & RESOLV_MAC) || ((mtp = manuf_name_lookup(addr)) == NULL)) {
2967     cur=ep_strdup_printf("%02x:%02x:%02x", addr[0], addr[1], addr[2]);
2968     return cur;
2969   }
2970
2971   return mtp->name;
2972
2973 } /* get_manuf_name */
2974
2975
2976 const gchar *
2977 get_manuf_name_if_known(const guint8 *addr)
2978 {
2979   hashmanuf_t  *mtp;
2980
2981   if (!eth_resolution_initialized) {
2982     initialize_ethers();
2983     eth_resolution_initialized = TRUE;
2984   }
2985
2986   if ((mtp = manuf_name_lookup(addr)) == NULL) {
2987     return NULL;
2988   }
2989
2990   return mtp->name;
2991
2992 } /* get_manuf_name_if_known */
2993
2994
2995 #ifdef HAVE_C_ARES
2996 #define GHI_TIMEOUT (250 * 1000)
2997 static void
2998 #if ( ( ARES_VERSION_MAJOR < 1 )                                     \
2999  || ( 1 == ARES_VERSION_MAJOR && ARES_VERSION_MINOR < 5 ) )
3000 c_ares_ghi_cb(void *arg, int status, struct hostent *hp) {
3001 #else
3002 c_ares_ghi_cb(void *arg, int status, int timeouts _U_, struct hostent *hp) {
3003 #endif
3004   /*
3005    * XXX - If we wanted to be really fancy we could cache results here and
3006    * look them up in get_host_ipaddr* below.
3007    */
3008   async_hostent_t *ahp = arg;
3009   if (status == ARES_SUCCESS && hp && ahp && hp->h_length == ahp->addr_size) {
3010     memcpy(ahp->addrp, hp->h_addr, hp->h_length);
3011     ahp->copied = hp->h_length;
3012   }
3013 }
3014 #endif /* HAVE_C_ARES */
3015
3016 /* Translate a string, assumed either to be a dotted-quad IP address or
3017  * a host name, to a numeric IP address.  Return TRUE if we succeed and
3018  * set "*addrp" to that numeric IP address; return FALSE if we fail.
3019  * Used more in the dfilter parser rather than in packet dissectors */
3020 gboolean
3021 get_host_ipaddr(const char *host, guint32 *addrp)
3022 {
3023   struct in_addr      ipaddr;
3024 #ifdef HAVE_C_ARES
3025   struct timeval tv = { 0, GHI_TIMEOUT }, *tvp;
3026   int nfds;
3027   fd_set rfds, wfds;
3028   async_hostent_t ahe;
3029 #else /* HAVE_C_ARES */
3030   struct hostent      *hp;
3031 #endif /* HAVE_C_ARES */
3032
3033   /*
3034    * don't change it to inet_pton(AF_INET), they are not 100% compatible.
3035    * inet_pton(AF_INET) does not support hexadecimal notation nor
3036    * less-than-4 octet notation.
3037    */
3038   if (!inet_aton(host, &ipaddr)) {
3039     if (! (gbl_resolv_flags & RESOLV_NETWORK)) {
3040       return FALSE;
3041     }
3042     /* It's not a valid dotted-quad IP address; is it a valid
3043      * host name? */
3044 #ifdef HAVE_C_ARES
3045     if (! (gbl_resolv_flags & RESOLV_CONCURRENT) ||
3046         prefs.name_resolve_concurrency < 1 ||
3047         ! async_dns_initialized) {
3048       return FALSE;
3049     }
3050     ahe.addr_size = (int) sizeof (struct in_addr);
3051     ahe.copied = 0;
3052     ahe.addrp = addrp;
3053     ares_gethostbyname(ghbn_chan, host, AF_INET, c_ares_ghi_cb, &ahe);
3054     FD_ZERO(&rfds);
3055     FD_ZERO(&wfds);
3056     nfds = ares_fds(ghbn_chan, &rfds, &wfds);
3057     if (nfds > 0) {
3058       tvp = ares_timeout(ghbn_chan, &tv, &tv);
3059       select(nfds, &rfds, &wfds, NULL, tvp);
3060       ares_process(ghbn_chan, &rfds, &wfds);
3061     }
3062     ares_cancel(ghbn_chan);
3063     if (ahe.addr_size == ahe.copied) {
3064       return TRUE;
3065     }
3066     return FALSE;
3067 #else /* ! HAVE_C_ARES */
3068     hp = gethostbyname(host);
3069     if (hp == NULL) {
3070       /* No. */
3071       return FALSE;
3072       /* Apparently, some versions of gethostbyaddr can
3073        * return IPv6 addresses. */
3074     } else if (hp->h_length <= (int) sizeof (struct in_addr)) {
3075       memcpy(&ipaddr, hp->h_addr, hp->h_length);
3076     } else {
3077       return FALSE;
3078     }
3079 #endif /* HAVE_C_ARES */
3080   } else {
3081     /* Does the string really contain dotted-quad IP?
3082      * Check against inet_atons that accept strings such as
3083      * "130.230" as valid addresses and try to convert them
3084      * to some form of a classful (host.net) notation.
3085      */
3086     unsigned int a0, a1, a2, a3;
3087     if (sscanf(host, "%u.%u.%u.%u", &a0, &a1, &a2, &a3) != 4)
3088       return FALSE;
3089   }
3090
3091   *addrp = g_ntohl(ipaddr.s_addr);
3092   return TRUE;
3093 }
3094
3095 /*
3096  * Translate IPv6 numeric address or FQDN hostname, into binary IPv6 address.
3097  * Return TRUE if we succeed and set "*addrp" to that numeric IP address;
3098  * return FALSE if we fail.
3099  */
3100 gboolean
3101 get_host_ipaddr6(const char *host, struct e_in6_addr *addrp)
3102 {
3103 #ifdef HAVE_C_ARES
3104   struct timeval tv = { 0, GHI_TIMEOUT }, *tvp;
3105   int nfds;
3106   fd_set rfds, wfds;
3107   async_hostent_t ahe;
3108 #elif defined(HAVE_GETHOSTBYNAME2)
3109   struct hostent *hp;
3110 #endif /* HAVE_C_ARES */
3111
3112   if (inet_pton(AF_INET6, host, addrp) == 1)
3113     return TRUE;
3114
3115   if (! (gbl_resolv_flags & RESOLV_NETWORK)) {
3116     return FALSE;
3117   }
3118
3119   /* try FQDN */
3120 #ifdef HAVE_C_ARES
3121   if (! (gbl_resolv_flags & RESOLV_CONCURRENT) ||
3122       prefs.name_resolve_concurrency < 1 ||
3123       ! async_dns_initialized) {
3124     return FALSE;
3125   }
3126   ahe.addr_size = (int) sizeof (struct e_in6_addr);
3127   ahe.copied = 0;
3128   ahe.addrp = addrp;
3129   ares_gethostbyname(ghbn_chan, host, AF_INET6, c_ares_ghi_cb, &ahe);
3130   FD_ZERO(&rfds);
3131   FD_ZERO(&wfds);
3132   nfds = ares_fds(ghbn_chan, &rfds, &wfds);
3133   if (nfds > 0) {
3134     tvp = ares_timeout(ghbn_chan, &tv, &tv);
3135     select(nfds, &rfds, &wfds, NULL, tvp);
3136     ares_process(ghbn_chan, &rfds, &wfds);
3137   }
3138   ares_cancel(ghbn_chan);
3139   if (ahe.addr_size == ahe.copied) {
3140     return TRUE;
3141   }
3142 #elif defined(HAVE_GETHOSTBYNAME2)
3143   hp = gethostbyname2(host, AF_INET6);
3144   if (hp != NULL && hp->h_length == sizeof(struct e_in6_addr)) {
3145     memcpy(addrp, hp->h_addr, hp->h_length);
3146     return TRUE;
3147   }
3148 #endif
3149
3150   return FALSE;
3151 }
3152
3153 /*
3154  * Find out whether a hostname resolves to an ip or ipv6 address
3155  * Return "ip6" if it is IPv6, "ip" otherwise (including the case
3156  * that we don't know)
3157  */
3158 const char* host_ip_af(const char *host
3159 #ifndef HAVE_GETHOSTBYNAME2
3160 _U_
3161 #endif
3162 )
3163 {
3164 #ifdef HAVE_GETHOSTBYNAME2
3165   struct hostent *h;
3166   return (h = gethostbyname2(host, AF_INET6)) && h->h_addrtype == AF_INET6 ? "ip6" : "ip";
3167 #else
3168   return "ip";
3169 #endif
3170 }