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