ares_parse_txt_reply: return a ares_txt_reply node for each sub-string
[platform/upstream/c-ares.git] / ares_init.c
index 2781813..d23c1b0 100644 (file)
@@ -1,7 +1,6 @@
-/* $Id$ */
 
 /* Copyright 1998 by the Massachusetts Institute of Technology.
- * Copyright (C) 2007-2008 by Daniel Stenberg
+ * Copyright (C) 2007-2013 by Daniel Stenberg
  *
  * Permission to use, copy, modify, and distribute this
  * software and its documentation for any purpose and without
  * without express or implied warranty.
  */
 
-#include "setup.h"
+#include "ares_setup.h"
 
-#if defined(WIN32) && !defined(WATT32)
-#include "nameser.h"
-#include <iphlpapi.h>
-#include <malloc.h>
-
-#else
 #ifdef HAVE_SYS_PARAM_H
 #include <sys/param.h>
 #endif
 
-#ifdef HAVE_SYS_TIME_H
-#include <sys/time.h>
+#ifdef HAVE_NETINET_IN_H
+#include <netinet/in.h>
 #endif
 
-#ifdef HAVE_SYS_SOCKET_H
-#include <sys/socket.h>
+#ifdef HAVE_NETDB_H
+#include <netdb.h>
 #endif
 
-#include <netinet/in.h>
+#ifdef HAVE_ARPA_INET_H
 #include <arpa/inet.h>
-#include <netdb.h>
-#include <arpa/nameser.h>
-#ifdef HAVE_ARPA_NAMESER_COMPAT_H
-#include <arpa/nameser_compat.h>
 #endif
-#ifdef HAVE_UNISTD_H
-#include <unistd.h>
+
+#ifdef HAVE_ARPA_NAMESER_H
+#  include <arpa/nameser.h>
+#else
+#  include "nameser.h"
 #endif
-#ifdef HAVE_PROCESS_H
-#include <process.h>  /* Some have getpid() here */
+#ifdef HAVE_ARPA_NAMESER_COMPAT_H
+#  include <arpa/nameser_compat.h>
 #endif
+
+#if defined(ANDROID) || defined(__ANDROID__)
+#include <sys/system_properties.h>
+/* From the Bionic sources */
+#define DNS_PROP_NAME_PREFIX  "net.dns"
+#define MAX_DNS_PROPERTIES    8
 #endif
 
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <ctype.h>
-#include <time.h>
-#include <errno.h>
 #include "ares.h"
+#include "ares_inet_net_pton.h"
+#include "ares_library_init.h"
+#include "ares_nowarn.h"
+#include "ares_platform.h"
 #include "ares_private.h"
-#include "inet_net_pton.h"
 
 #ifdef WATT32
 #undef WIN32  /* Redefined in MingW/MSVC headers */
 #endif
 
-static int init_by_options(ares_channel channel, const struct ares_options *options,
+static int init_by_options(ares_channel channel,
+                           const struct ares_options *options,
                            int optmask);
 static int init_by_environment(ares_channel channel);
 static int init_by_resolv_conf(ares_channel channel);
 static int init_by_defaults(ares_channel channel);
 
+#ifndef WATT32
 static int config_nameserver(struct server_state **servers, int *nservers,
                              char *str);
+#endif
 static int set_search(ares_channel channel, const char *str);
 static int set_options(ares_channel channel, const char *str);
 static const char *try_option(const char *p, const char *q, const char *opt);
 static int init_id_key(rc4_key* key,int key_data_len);
 
-#ifndef WIN32
-static int sortlist_alloc(struct apattern **sortlist, int *nsort, struct apattern *pat);
-static int ip_addr(const char *s, int len, struct in_addr *addr);
+#if !defined(WIN32) && !defined(WATT32) && \
+    !defined(ANDROID) && !defined(__ANDROID__)
+static int sortlist_alloc(struct apattern **sortlist, int *nsort,
+                          struct apattern *pat);
+static int ip_addr(const char *s, ssize_t len, struct in_addr *addr);
 static void natural_mask(struct apattern *pat);
 static int config_domain(ares_channel channel, char *str);
 static int config_lookup(ares_channel channel, const char *str,
                          const char *bindch, const char *filech);
 static int config_sortlist(struct apattern **sortlist, int *nsort,
                            const char *str);
-static char *try_config(char *s, const char *opt);
+static char *try_config(char *s, const char *opt, char scc);
 #endif
 
 #define ARES_CONFIG_CHECK(x) (x->lookups && x->nsort > -1 && \
@@ -107,7 +107,7 @@ int ares_init_options(ares_channel *channelptr, struct ares_options *options,
   ares_channel channel;
   int i;
   int status = ARES_SUCCESS;
-  struct server_state *server;
+  struct timeval now;
 
 #ifdef CURLDEBUG
   const char *env = getenv("CARES_MEMDEBUG");
@@ -115,16 +115,25 @@ int ares_init_options(ares_channel *channelptr, struct ares_options *options,
   if (env)
     curl_memdebug(env);
   env = getenv("CARES_MEMLIMIT");
-  if (env)
-    curl_memlimit(atoi(env));
+  if (env) {
+    char *endptr;
+    long num = strtol(env, &endptr, 10);
+    if((endptr != env) && (endptr == env + strlen(env)) && (num > 0))
+      curl_memlimit(num);
+  }
 #endif
 
+  if (ares_library_initialized() != ARES_SUCCESS)
+    return ARES_ENOTINITIALIZED;
+
   channel = malloc(sizeof(struct ares_channeldata));
   if (!channel) {
     *channelptr = NULL;
     return ARES_ENOMEM;
   }
 
+  now = ares__tvnow();
+
   /* Set everything to distinguished values so we know they haven't
    * been set yet.
    */
@@ -132,8 +141,10 @@ int ares_init_options(ares_channel *channelptr, struct ares_options *options,
   channel->timeout = -1;
   channel->tries = -1;
   channel->ndots = -1;
+  channel->rotate = -1;
   channel->udp_port = -1;
   channel->tcp_port = -1;
+  channel->ednspsz = -1;
   channel->socket_send_buffer_size = -1;
   channel->socket_receive_buffer_size = -1;
   channel->nservers = -1;
@@ -146,8 +157,15 @@ int ares_init_options(ares_channel *channelptr, struct ares_options *options,
   channel->servers = NULL;
   channel->sock_state_cb = NULL;
   channel->sock_state_cb_data = NULL;
+  channel->sock_create_cb = NULL;
+  channel->sock_create_cb_data = NULL;
+
+  channel->last_server = 0;
+  channel->last_timeout_processed = (time_t)now.tv_sec;
 
-  channel->last_timeout_processed = (long)time(NULL);
+  memset(&channel->local_dev_name, 0, sizeof(channel->local_dev_name));
+  channel->local_ip4 = 0;
+  memset(&channel->local_ip6, 0, sizeof(channel->local_ip6));
 
   /* Initialize our lists of queries */
   ares__init_list_head(&(channel->all_queries));
@@ -165,7 +183,7 @@ int ares_init_options(ares_channel *channelptr, struct ares_options *options,
    */
 
   if (status == ARES_SUCCESS) {
-  status = init_by_options(channel, options, optmask);
+    status = init_by_options(channel, options, optmask);
     if (status != ARES_SUCCESS)
       DEBUGF(fprintf(stderr, "Error: init_by_options failed: %s\n",
                      ares_strerror(status)));
@@ -182,12 +200,15 @@ int ares_init_options(ares_channel *channelptr, struct ares_options *options,
       DEBUGF(fprintf(stderr, "Error: init_by_resolv_conf failed: %s\n",
                      ares_strerror(status)));
   }
-  if (status == ARES_SUCCESS) {
-    status = init_by_defaults(channel);
-    if (status != ARES_SUCCESS)
-      DEBUGF(fprintf(stderr, "Error: init_by_defaults failed: %s\n",
-                     ares_strerror(status)));
-  }
+
+  /*
+   * No matter what failed or succeeded, seed defaults to provide
+   * useful behavior for things that we missed.
+   */
+  status = init_by_defaults(channel);
+  if (status != ARES_SUCCESS)
+    DEBUGF(fprintf(stderr, "Error: init_by_defaults failed: %s\n",
+                   ares_strerror(status)));
 
   /* Generate random key */
 
@@ -223,31 +244,75 @@ int ares_init_options(ares_channel *channelptr, struct ares_options *options,
   if ((channel->flags & ARES_FLAG_PRIMARY) && channel->nservers > 1)
     channel->nservers = 1;
 
-  /* Initialize server states. */
-  for (i = 0; i < channel->nservers; i++)
-    {
-      server = &channel->servers[i];
-      server->udp_socket = ARES_SOCKET_BAD;
-      server->tcp_socket = ARES_SOCKET_BAD;
-      server->tcp_connection_generation = ++channel->tcp_connection_generation;
-      server->tcp_lenbuf_pos = 0;
-      server->tcp_buffer = NULL;
-      server->qhead = NULL;
-      server->qtail = NULL;
-      ares__init_list_head(&(server->queries_to_server));
-      server->channel = channel;
-      server->is_broken = 0;
-    }
+  ares__init_servers_state(channel);
 
   *channelptr = channel;
   return ARES_SUCCESS;
 }
 
+/* ares_dup() duplicates a channel handle with all its options and returns a
+   new channel handle */
+int ares_dup(ares_channel *dest, ares_channel src)
+{
+  struct ares_options opts;
+  struct ares_addr_node *servers;
+  int ipv6_nservers = 0;
+  int i, rc;
+  int optmask;
+
+  *dest = NULL; /* in case of failure return NULL explicitly */
+
+  /* First get the options supported by the old ares_save_options() function,
+     which is most of them */
+  rc = ares_save_options(src, &opts, &optmask);
+  if(rc)
+    return rc;
+
+  /* Then create the new channel with those options */
+  rc = ares_init_options(dest, &opts, optmask);
+
+  /* destroy the options copy to not leak any memory */
+  ares_destroy_options(&opts);
+
+  if(rc)
+    return rc;
+
+  /* Now clone the options that ares_save_options() doesn't support. */
+  (*dest)->sock_create_cb      = src->sock_create_cb;
+  (*dest)->sock_create_cb_data = src->sock_create_cb_data;
+
+  strncpy((*dest)->local_dev_name, src->local_dev_name,
+          sizeof(src->local_dev_name));
+  (*dest)->local_ip4 = src->local_ip4;
+  memcpy((*dest)->local_ip6, src->local_ip6, sizeof(src->local_ip6));
+
+  /* Full name server cloning required when not all are IPv4 */
+  for (i = 0; i < src->nservers; i++)
+    {
+      if (src->servers[i].addr.family != AF_INET) {
+        ipv6_nservers++;
+        break;
+      }
+    }
+  if (ipv6_nservers) {
+    rc = ares_get_servers(src, &servers);
+    if (rc != ARES_SUCCESS)
+      return rc;
+    rc = ares_set_servers(*dest, servers);
+    ares_free_data(servers);
+    if (rc != ARES_SUCCESS)
+      return rc;
+  }
+
+  return ARES_SUCCESS; /* everything went fine */
+}
+
 /* Save options from initialized channel */
 int ares_save_options(ares_channel channel, struct ares_options *options,
                       int *optmask)
 {
-  int i;
+  int i, j;
+  int ipv4_nservers = 0;
 
   /* Zero everything out */
   memset(options, 0, sizeof(struct ares_options));
@@ -255,10 +320,14 @@ int ares_save_options(ares_channel channel, struct ares_options *options,
   if (!ARES_CONFIG_CHECK(channel))
     return ARES_ENODATA;
 
+  /* Traditionally the optmask wasn't saved in the channel struct so it was
+     recreated here. ROTATE is the first option that has no struct field of
+     its own in the public config struct */
   (*optmask) = (ARES_OPT_FLAGS|ARES_OPT_TRIES|ARES_OPT_NDOTS|
                 ARES_OPT_UDP_PORT|ARES_OPT_TCP_PORT|ARES_OPT_SOCK_STATE_CB|
                 ARES_OPT_SERVERS|ARES_OPT_DOMAINS|ARES_OPT_LOOKUPS|
-                ARES_OPT_SORTLIST|ARES_OPT_TIMEOUTMS);
+                ARES_OPT_SORTLIST|ARES_OPT_TIMEOUTMS) |
+    (channel->optmask & ARES_OPT_ROTATE);
 
   /* Copy easy stuff */
   options->flags   = channel->flags;
@@ -268,21 +337,32 @@ int ares_save_options(ares_channel channel, struct ares_options *options,
   options->timeout = channel->timeout;
   options->tries   = channel->tries;
   options->ndots   = channel->ndots;
-  options->udp_port = (unsigned short)channel->udp_port;
-  options->tcp_port = (unsigned short)channel->tcp_port;
+  options->udp_port = ntohs(aresx_sitous(channel->udp_port));
+  options->tcp_port = ntohs(aresx_sitous(channel->tcp_port));
   options->sock_state_cb     = channel->sock_state_cb;
   options->sock_state_cb_data = channel->sock_state_cb_data;
 
-  /* Copy servers */
+  /* Copy IPv4 servers */
   if (channel->nservers) {
-    options->servers =
-      malloc(channel->nservers * sizeof(struct server_state));
-    if (!options->servers && channel->nservers != 0)
-      return ARES_ENOMEM;
     for (i = 0; i < channel->nservers; i++)
-      options->servers[i] = channel->servers[i].addr;
+    {
+      if (channel->servers[i].addr.family == AF_INET)
+        ipv4_nservers++;
+    }
+    if (ipv4_nservers) {
+      options->servers = malloc(ipv4_nservers * sizeof(struct in_addr));
+      if (!options->servers)
+        return ARES_ENOMEM;
+      for (i = j = 0; i < channel->nservers; i++)
+      {
+        if (channel->servers[i].addr.family == AF_INET)
+          memcpy(&options->servers[j++],
+                 &channel->servers[i].addr.addrV4,
+                 sizeof(channel->servers[i].addr.addrV4));
+      }
+    }
   }
-  options->nservers = channel->nservers;
+  options->nservers = ipv4_nservers;
 
   /* copy domains */
   if (channel->ndomains) {
@@ -313,10 +393,7 @@ int ares_save_options(ares_channel channel, struct ares_options *options,
     if (!options->sortlist)
       return ARES_ENOMEM;
     for (i = 0; i < channel->nsort; i++)
-    {
-      memcpy(&(options->sortlist[i]), &(channel->sortlist[i]),
-             sizeof(struct apattern));
-    }
+      options->sortlist[i] = channel->sortlist[i];
   }
   options->nsort = channel->nsort;
 
@@ -340,10 +417,12 @@ static int init_by_options(ares_channel channel,
     channel->tries = options->tries;
   if ((optmask & ARES_OPT_NDOTS) && channel->ndots == -1)
     channel->ndots = options->ndots;
+  if ((optmask & ARES_OPT_ROTATE) && channel->rotate == -1)
+    channel->rotate = 1;
   if ((optmask & ARES_OPT_UDP_PORT) && channel->udp_port == -1)
-    channel->udp_port = options->udp_port;
+    channel->udp_port = htons(options->udp_port);
   if ((optmask & ARES_OPT_TCP_PORT) && channel->tcp_port == -1)
-    channel->tcp_port = options->tcp_port;
+    channel->tcp_port = htons(options->tcp_port);
   if ((optmask & ARES_OPT_SOCK_STATE_CB) && channel->sock_state_cb == NULL)
     {
       channel->sock_state_cb = options->sock_state_cb;
@@ -356,7 +435,10 @@ static int init_by_options(ares_channel channel,
       && channel->socket_receive_buffer_size == -1)
     channel->socket_receive_buffer_size = options->socket_receive_buffer_size;
 
-  /* Copy the servers, if given. */
+  if ((optmask & ARES_OPT_EDNSPSZ) && channel->ednspsz == -1)
+    channel->ednspsz = options->ednspsz;
+
+  /* Copy the IPv4 servers, if given. */
   if ((optmask & ARES_OPT_SERVERS) && channel->nservers == -1)
     {
       /* Avoid zero size allocations at any cost */
@@ -367,7 +449,12 @@ static int init_by_options(ares_channel channel,
           if (!channel->servers)
             return ARES_ENOMEM;
           for (i = 0; i < options->nservers; i++)
-            channel->servers[i].addr = options->servers[i];
+            {
+              channel->servers[i].addr.family = AF_INET;
+              memcpy(&channel->servers[i].addr.addrV4,
+                     &options->servers[i],
+                     sizeof(channel->servers[i].addr.addrV4));
+            }
         }
       channel->nservers = options->nservers;
     }
@@ -403,17 +490,17 @@ static int init_by_options(ares_channel channel,
     }
 
   /* copy sortlist */
-  if ((optmask & ARES_OPT_SORTLIST) && channel->nsort == -1)
-    {
-      channel->sortlist = malloc(options->nsort * sizeof(struct apattern));
-      if (!channel->sortlist)
-        return ARES_ENOMEM;
-      for (i = 0; i < options->nsort; i++)
-        {
-          memcpy(&(channel->sortlist[i]), &(options->sortlist[i]), sizeof(struct apattern));
-        }
-      channel->nsort = options->nsort;
-    }
+  if ((optmask & ARES_OPT_SORTLIST) && (channel->nsort == -1) &&
+      (options->nsort>0)) {
+    channel->sortlist = malloc(options->nsort * sizeof(struct apattern));
+    if (!channel->sortlist)
+      return ARES_ENOMEM;
+    for (i = 0; i < options->nsort; i++)
+      channel->sortlist[i] = options->sortlist[i];
+    channel->nsort = options->nsort;
+  }
+
+  channel->optmask = optmask;
 
   return ARES_SUCCESS;
 }
@@ -444,246 +531,546 @@ static int init_by_environment(ares_channel channel)
 
 #ifdef WIN32
 /*
- * Warning: returns a dynamically allocated buffer, the user MUST
- * use free() if the function returns 1
+ * get_REG_SZ()
+ *
+ * Given a 'hKey' handle to an open registry key and a 'leafKeyName' pointer
+ * to the name of the registry leaf key to be queried, fetch it's string
+ * value and return a pointer in *outptr to a newly allocated memory area
+ * holding it as a null-terminated string.
+ *
+ * Returns 0 and nullifies *outptr upon inability to return a string value.
+ *
+ * Returns 1 and sets *outptr when returning a dynamically allocated string.
+ *
+ * Supported on Windows NT 3.5 and newer.
  */
-static int get_res_nt(HKEY hKey, const char *subkey, char **obuf)
+static int get_REG_SZ(HKEY hKey, const char *leafKeyName, char **outptr)
 {
-  /* Test for the size we need */
   DWORD size = 0;
-  int result;
+  int   res;
+
+  *outptr = NULL;
 
-  result = RegQueryValueEx(hKey, subkey, 0, NULL, NULL, &size);
-  if ((result != ERROR_SUCCESS && result != ERROR_MORE_DATA) || !size)
+  /* Find out size of string stored in registry */
+  res = RegQueryValueEx(hKey, leafKeyName, 0, NULL, NULL, &size);
+  if ((res != ERROR_SUCCESS && res != ERROR_MORE_DATA) || !size)
     return 0;
-  *obuf = malloc(size+1);
-  if (!*obuf)
+
+  /* Allocate buffer of indicated size plus one given that string
+     might have been stored without null termination */
+  *outptr = malloc(size+1);
+  if (!*outptr)
     return 0;
 
-  if (RegQueryValueEx(hKey, subkey, 0, NULL,
-                      (LPBYTE)*obuf, &size) != ERROR_SUCCESS)
+  /* Get the value for real */
+  res = RegQueryValueEx(hKey, leafKeyName, 0, NULL,
+                        (unsigned char *)*outptr, &size);
+  if ((res != ERROR_SUCCESS) || (size == 1))
   {
-    free(*obuf);
+    free(*outptr);
+    *outptr = NULL;
     return 0;
   }
-  if (size == 1)
+
+  /* Null terminate buffer allways */
+  *(*outptr + size) = '\0';
+
+  return 1;
+}
+
+/*
+ * get_REG_SZ_9X()
+ *
+ * Functionally identical to get_REG_SZ()
+ *
+ * Supported on Windows 95, 98 and ME.
+ */
+static int get_REG_SZ_9X(HKEY hKey, const char *leafKeyName, char **outptr)
+{
+  DWORD dataType = 0;
+  DWORD size = 0;
+  int   res;
+
+  *outptr = NULL;
+
+  /* Find out size of string stored in registry */
+  res = RegQueryValueEx(hKey, leafKeyName, 0, &dataType, NULL, &size);
+  if ((res != ERROR_SUCCESS && res != ERROR_MORE_DATA) || !size)
+    return 0;
+
+  /* Allocate buffer of indicated size plus one given that string
+     might have been stored without null termination */
+  *outptr = malloc(size+1);
+  if (!*outptr)
+    return 0;
+
+  /* Get the value for real */
+  res = RegQueryValueEx(hKey, leafKeyName, 0, &dataType,
+                        (unsigned char *)*outptr, &size);
+  if ((res != ERROR_SUCCESS) || (size == 1))
   {
-    free(*obuf);
+    free(*outptr);
+    *outptr = NULL;
     return 0;
   }
+
+  /* Null terminate buffer allways */
+  *(*outptr + size) = '\0';
+
   return 1;
 }
 
-static int get_res_interfaces_nt(HKEY hKey, const char *subkey, char **obuf)
+/*
+ * get_enum_REG_SZ()
+ *
+ * Given a 'hKeyParent' handle to an open registry key and a 'leafKeyName'
+ * pointer to the name of the registry leaf key to be queried, parent key
+ * is enumerated searching in child keys for given leaf key name and its
+ * associated string value. When located, this returns a pointer in *outptr
+ * to a newly allocated memory area holding it as a null-terminated string.
+ *
+ * Returns 0 and nullifies *outptr upon inability to return a string value.
+ *
+ * Returns 1 and sets *outptr when returning a dynamically allocated string.
+ *
+ * Supported on Windows NT 3.5 and newer.
+ */
+static int get_enum_REG_SZ(HKEY hKeyParent, const char *leafKeyName,
+                           char **outptr)
 {
-  char enumbuf[39]; /* GUIDs are 38 chars + 1 for NULL */
-  DWORD enum_size = 39;
-  int idx = 0;
-  HKEY hVal;
+  char  enumKeyName[256];
+  DWORD enumKeyNameBuffSize;
+  DWORD enumKeyIdx = 0;
+  HKEY  hKeyEnum;
+  int   gotString;
+  int   res;
 
-  while (RegEnumKeyEx(hKey, idx++, enumbuf, &enum_size, 0,
-                      NULL, NULL, NULL) != ERROR_NO_MORE_ITEMS)
-  {
-    int rc;
+  *outptr = NULL;
 
-    enum_size = 39;
-    if (RegOpenKeyEx(hKey, enumbuf, 0, KEY_QUERY_VALUE, &hVal) !=
-        ERROR_SUCCESS)
+  for(;;)
+  {
+    enumKeyNameBuffSize = sizeof(enumKeyName);
+    res = RegEnumKeyEx(hKeyParent, enumKeyIdx++, enumKeyName,
+                       &enumKeyNameBuffSize, 0, NULL, NULL, NULL);
+    if (res != ERROR_SUCCESS)
+      break;
+    res = RegOpenKeyEx(hKeyParent, enumKeyName, 0, KEY_QUERY_VALUE,
+                       &hKeyEnum);
+    if (res != ERROR_SUCCESS)
       continue;
-    rc = get_res_nt(hVal, subkey, obuf);
-      RegCloseKey(hVal);
-    if (rc)
-      return 1;
-    }
-  return 0;
+    gotString = get_REG_SZ(hKeyEnum, leafKeyName, outptr);
+    RegCloseKey(hKeyEnum);
+    if (gotString)
+      break;
+  }
+
+  if (!*outptr)
+    return 0;
+
+  return 1;
 }
 
-static int get_iphlpapi_dns_info (char *ret_buf, size_t ret_size)
+/*
+ * get_DNS_Registry_9X()
+ *
+ * Functionally identical to get_DNS_Registry()
+ *
+ * Implementation supports Windows 95, 98 and ME.
+ */
+static int get_DNS_Registry_9X(char **outptr)
 {
-  FIXED_INFO    *fi   = alloca (sizeof(*fi));
-  DWORD          size = sizeof (*fi);
-  typedef DWORD (WINAPI* get_net_param_func) (FIXED_INFO*, DWORD*);
-  get_net_param_func fpGetNetworkParams;  /* available only on Win-98/2000+ */
-  HMODULE        handle;
-  IP_ADDR_STRING *ipAddr;
-  int            i, count = 0;
-  int            debug  = 0;
-  size_t         ip_size = sizeof("255.255.255.255,")-1;
-  size_t         left = ret_size;
-  char          *ret = ret_buf;
-  HRESULT        res;
+  HKEY hKey_VxD_MStcp;
+  int  gotString;
+  int  res;
 
-  if (!fi)
-     return (0);
+  *outptr = NULL;
 
-  handle = LoadLibrary ("iphlpapi.dll");
-  if (!handle)
-     return (0);
+  res = RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_9X, 0, KEY_READ,
+                     &hKey_VxD_MStcp);
+  if (res != ERROR_SUCCESS)
+    return 0;
 
-  fpGetNetworkParams = (get_net_param_func) GetProcAddress (handle, "GetNetworkParams");
-  if (!fpGetNetworkParams)
-     goto quit;
+  gotString = get_REG_SZ_9X(hKey_VxD_MStcp, NAMESERVER, outptr);
+  RegCloseKey(hKey_VxD_MStcp);
 
-  res = (*fpGetNetworkParams) (fi, &size);
-  if ((res != ERROR_BUFFER_OVERFLOW) && (res != ERROR_SUCCESS))
-     goto quit;
+  if (!gotString || !*outptr)
+    return 0;
 
-  fi = alloca (size);
-  if (!fi || (*fpGetNetworkParams) (fi, &size) != ERROR_SUCCESS)
-     goto quit;
+  return 1;
+}
 
-  if (debug)
+/*
+ * get_DNS_Registry_NT()
+ *
+ * Functionally identical to get_DNS_Registry()
+ *
+ * Refs: Microsoft Knowledge Base articles KB120642 and KB314053.
+ *
+ * Implementation supports Windows NT 3.5 and newer.
+ */
+static int get_DNS_Registry_NT(char **outptr)
+{
+  HKEY hKey_Interfaces = NULL;
+  HKEY hKey_Tcpip_Parameters;
+  int  gotString;
+  int  res;
+
+  *outptr = NULL;
+
+  res = RegOpenKeyEx(HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0, KEY_READ,
+                     &hKey_Tcpip_Parameters);
+  if (res != ERROR_SUCCESS)
+    return 0;
+
+  /*
+  ** Global DNS settings override adapter specific parameters when both
+  ** are set. Additionally static DNS settings override DHCP-configured
+  ** parameters when both are set.
+  */
+
+  /* Global DNS static parameters */
+  gotString = get_REG_SZ(hKey_Tcpip_Parameters, NAMESERVER, outptr);
+  if (gotString)
+    goto done;
+
+  /* Global DNS DHCP-configured parameters */
+  gotString = get_REG_SZ(hKey_Tcpip_Parameters, DHCPNAMESERVER, outptr);
+  if (gotString)
+    goto done;
+
+  /* Try adapter specific parameters */
+  res = RegOpenKeyEx(hKey_Tcpip_Parameters, "Interfaces", 0,
+                     KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS,
+                     &hKey_Interfaces);
+  if (res != ERROR_SUCCESS)
   {
-    printf ("Host Name: %s\n", fi->HostName);
-    printf ("Domain Name: %s\n", fi->DomainName);
-    printf ("DNS Servers:\n"
-            "    %s (primary)\n", fi->DnsServerList.IpAddress.String);
+    hKey_Interfaces = NULL;
+    goto done;
   }
-  if (strlen(fi->DnsServerList.IpAddress.String) > 0 &&
-      inet_addr(fi->DnsServerList.IpAddress.String) != INADDR_NONE &&
-      left > ip_size)
+
+  /* Adapter specific DNS static parameters */
+  gotString = get_enum_REG_SZ(hKey_Interfaces, NAMESERVER, outptr);
+  if (gotString)
+    goto done;
+
+  /* Adapter specific DNS DHCP-configured parameters */
+  gotString = get_enum_REG_SZ(hKey_Interfaces, DHCPNAMESERVER, outptr);
+
+done:
+  if (hKey_Interfaces)
+    RegCloseKey(hKey_Interfaces);
+
+  RegCloseKey(hKey_Tcpip_Parameters);
+
+  if (!gotString || !*outptr)
+    return 0;
+
+  return 1;
+}
+
+/*
+ * get_DNS_Registry()
+ *
+ * Locates DNS info in the registry. When located, this returns a pointer
+ * in *outptr to a newly allocated memory area holding a null-terminated
+ * string with a space or comma seperated list of DNS IP addresses.
+ *
+ * Returns 0 and nullifies *outptr upon inability to return DNSes string.
+ *
+ * Returns 1 and sets *outptr when returning a dynamically allocated string.
+ */
+static int get_DNS_Registry(char **outptr)
+{
+  win_platform platform;
+  int gotString = 0;
+
+  *outptr = NULL;
+
+  platform = ares__getplatform();
+
+  if (platform == WIN_NT)
+    gotString = get_DNS_Registry_NT(outptr);
+  else if (platform == WIN_9X)
+    gotString = get_DNS_Registry_9X(outptr);
+
+  if (!gotString)
+    return 0;
+
+  return 1;
+}
+
+/*
+ * commajoin()
+ *
+ * RTF code.
+ */
+static void commajoin(char **dst, const char *src)
+{
+  char *tmp;
+
+  if (*dst)
+  {
+    tmp = malloc(strlen(*dst) + strlen(src) + 2);
+    if (!tmp)
+      return;
+    sprintf(tmp, "%s,%s", *dst, src);
+    free(*dst);
+    *dst = tmp;
+  }
+  else
   {
-    ret += sprintf (ret, "%s,", fi->DnsServerList.IpAddress.String);
-    left -= ret - ret_buf;
-    count++;
+    *dst = malloc(strlen(src) + 1);
+    if (!*dst)
+      return;
+    strcpy(*dst, src);
   }
+}
+
+/*
+ * get_DNS_NetworkParams()
+ *
+ * Locates DNS info using GetNetworkParams() function from the Internet
+ * Protocol Helper (IP Helper) API. When located, this returns a pointer
+ * in *outptr to a newly allocated memory area holding a null-terminated
+ * string with a space or comma seperated list of DNS IP addresses.
+ *
+ * Returns 0 and nullifies *outptr upon inability to return DNSes string.
+ *
+ * Returns 1 and sets *outptr when returning a dynamically allocated string.
+ *
+ * Implementation supports Windows 98 and newer.
+ *
+ * Note: Ancient PSDK required in order to build a W98 target.
+ */
+static int get_DNS_NetworkParams(char **outptr)
+{
+  FIXED_INFO       *fi, *newfi;
+  struct ares_addr namesrvr;
+  char             *txtaddr;
+  IP_ADDR_STRING   *ipAddr;
+  int              res;
+  DWORD            size = sizeof (*fi);
+
+  *outptr = NULL;
 
-  for (i = 0, ipAddr = fi->DnsServerList.Next; ipAddr && left > ip_size;
-       ipAddr = ipAddr->Next, i++)
+  /* Verify run-time availability of GetNetworkParams() */
+  if (ares_fpGetNetworkParams == ZERO_NULL)
+    return 0;
+
+  fi = malloc(size);
+  if (!fi)
+    return 0;
+
+  res = (*ares_fpGetNetworkParams) (fi, &size);
+  if ((res != ERROR_BUFFER_OVERFLOW) && (res != ERROR_SUCCESS))
+    goto done;
+
+  newfi = realloc(fi, size);
+  if (!newfi)
+    goto done;
+
+  fi = newfi;
+  res = (*ares_fpGetNetworkParams) (fi, &size);
+  if (res != ERROR_SUCCESS)
+    goto done;
+
+  for (ipAddr = &fi->DnsServerList; ipAddr; ipAddr = ipAddr->Next)
   {
-    if (inet_addr(ipAddr->IpAddress.String) != INADDR_NONE)
+    txtaddr = &ipAddr->IpAddress.String[0];
+
+    /* Validate converting textual address to binary format. */
+    if (ares_inet_pton(AF_INET, txtaddr, &namesrvr.addrV4) == 1)
     {
-       ret += sprintf (ret, "%s,", ipAddr->IpAddress.String);
-       left -= ret - ret_buf;
-       count++;
+      if ((namesrvr.addrV4.S_un.S_addr == INADDR_ANY) ||
+          (namesrvr.addrV4.S_un.S_addr == INADDR_NONE))
+        continue;
     }
-    if (debug)
-       printf ("    %s (secondary %d)\n", ipAddr->IpAddress.String, i+1);
+    else if (ares_inet_pton(AF_INET6, txtaddr, &namesrvr.addrV6) == 1)
+    {
+      if (memcmp(&namesrvr.addrV6, &ares_in6addr_any,
+                 sizeof(namesrvr.addrV6)) == 0)
+        continue;
+    }
+    else
+      continue;
+
+    commajoin(outptr, txtaddr);
+
+    if (!*outptr)
+      break;
   }
 
-quit:
-  if (handle)
-     FreeLibrary (handle);
+done:
+  if (fi)
+    free(fi);
 
-  if (debug && left <= ip_size)
-     printf ("Too many nameservers. Truncating to %d addressess", count);
-  if (ret > ret_buf)
-     ret[-1] = '\0';
-  return (count);
+  if (!*outptr)
+    return 0;
+
+  return 1;
 }
-#endif
 
-static int init_by_resolv_conf(ares_channel channel)
+/*
+ * get_DNS_AdaptersAddresses()
+ *
+ * Locates DNS info using GetAdaptersAddresses() function from the Internet
+ * Protocol Helper (IP Helper) API. When located, this returns a pointer
+ * in *outptr to a newly allocated memory area holding a null-terminated
+ * string with a space or comma seperated list of DNS IP addresses.
+ *
+ * Returns 0 and nullifies *outptr upon inability to return DNSes string.
+ *
+ * Returns 1 and sets *outptr when returning a dynamically allocated string.
+ *
+ * Implementation supports Windows XP and newer.
+ */
+#define IPAA_INITIAL_BUF_SZ 15 * 1024
+#define IPAA_MAX_TRIES 3
+static int get_DNS_AdaptersAddresses(char **outptr)
 {
-  char *line = NULL;
-  int status = -1, nservers = 0, nsort = 0;
-  struct server_state *servers = NULL;
-  struct apattern *sortlist = NULL;
-
-#ifdef WIN32
-
-    /*
-  NameServer info via IPHLPAPI (IP helper API):
-    GetNetworkParams() should be the trusted source for this.
-    Available in Win-98/2000 and later. If that fail, fall-back to
-    registry information.
-
-  NameServer Registry:
-
-   On Windows 9X, the DNS server can be found in:
-HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\VxD\MSTCP\NameServer
-
-        On Windows NT/2000/XP/2003:
-HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\NameServer
-        or
-HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\DhcpNameServer
-        or
-HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
-NameServer
-        or
-HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\{AdapterID}\
-DhcpNameServer
-   */
+  IP_ADAPTER_DNS_SERVER_ADDRESS *ipaDNSAddr;
+  IP_ADAPTER_ADDRESSES *ipaa, *newipaa, *ipaaEntry;
+  ULONG ReqBufsz = IPAA_INITIAL_BUF_SZ;
+  ULONG Bufsz = IPAA_INITIAL_BUF_SZ;
+  ULONG AddrFlags = 0;
+  int trying = IPAA_MAX_TRIES;
+  int res;
+
+  union {
+    struct sockaddr     *sa;
+    struct sockaddr_in  *sa4;
+    struct sockaddr_in6 *sa6;
+  } namesrvr;
+
+  char txtaddr[sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255")];
+
+  *outptr = NULL;
+
+  /* Verify run-time availability of GetAdaptersAddresses() */
+  if (ares_fpGetAdaptersAddresses == ZERO_NULL)
+    return 0;
 
-  HKEY mykey;
-  HKEY subkey;
-  DWORD data_type;
-  DWORD bytes;
-  DWORD result;
-  char  buf[256];
+  ipaa = malloc(Bufsz);
+  if (!ipaa)
+    return 0;
 
-  if (channel->nservers > -1)  /* don't override ARES_OPT_SERVER */
-     return ARES_SUCCESS;
+  /* Usually this call suceeds with initial buffer size */
+  res = (*ares_fpGetAdaptersAddresses) (AF_UNSPEC, AddrFlags, NULL,
+                                        ipaa, &ReqBufsz);
+  if ((res != ERROR_BUFFER_OVERFLOW) && (res != ERROR_SUCCESS))
+    goto done;
 
-  if (get_iphlpapi_dns_info(buf,sizeof(buf)) > 0)
+  while ((res == ERROR_BUFFER_OVERFLOW) && (--trying))
   {
-    status = config_nameserver(&servers, &nservers, buf);
-    if (status == ARES_SUCCESS)
-      goto okay;
+    if (Bufsz < ReqBufsz)
+    {
+      newipaa = realloc(ipaa, ReqBufsz);
+      if (!newipaa)
+        goto done;
+      Bufsz = ReqBufsz;
+      ipaa = newipaa;
+    }
+    res = (*ares_fpGetAdaptersAddresses) (AF_UNSPEC, AddrFlags, NULL,
+                                          ipaa, &ReqBufsz);
+    if (res == ERROR_SUCCESS)
+      break;
   }
+  if (res != ERROR_SUCCESS)
+    goto done;
 
-  if (IS_NT())
+  for (ipaaEntry = ipaa; ipaaEntry; ipaaEntry = ipaaEntry->Next)
   {
-    if (RegOpenKeyEx(
-          HKEY_LOCAL_MACHINE, WIN_NS_NT_KEY, 0,
-          KEY_READ, &mykey
-          ) == ERROR_SUCCESS)
+    for (ipaDNSAddr = ipaaEntry->FirstDnsServerAddress;
+         ipaDNSAddr;
+         ipaDNSAddr = ipaDNSAddr->Next)
     {
-      RegOpenKeyEx(mykey, "Interfaces", 0,
-                   KEY_QUERY_VALUE|KEY_ENUMERATE_SUB_KEYS, &subkey);
-      if (get_res_nt(mykey, NAMESERVER, &line))
-      {
-        status = config_nameserver(&servers, &nservers, line);
-        free(line);
-      }
-      else if (get_res_nt(mykey, DHCPNAMESERVER, &line))
-      {
-        status = config_nameserver(&servers, &nservers, line);
-        free(line);
-      }
-      /* Try the interfaces */
-      else if (get_res_interfaces_nt(subkey, NAMESERVER, &line))
+      namesrvr.sa = ipaDNSAddr->Address.lpSockaddr;
+
+      if (namesrvr.sa->sa_family == AF_INET)
       {
-        status = config_nameserver(&servers, &nservers, line);
-        free(line);
+        if ((namesrvr.sa4->sin_addr.S_un.S_addr == INADDR_ANY) ||
+            (namesrvr.sa4->sin_addr.S_un.S_addr == INADDR_NONE))
+          continue;
+        if (! ares_inet_ntop(AF_INET, &namesrvr.sa4->sin_addr,
+                             txtaddr, sizeof(txtaddr)))
+          continue;
       }
-      else if (get_res_interfaces_nt(subkey, DHCPNAMESERVER, &line))
+      else if (namesrvr.sa->sa_family == AF_INET6)
       {
-        status = config_nameserver(&servers, &nservers, line);
-        free(line);
+        if (memcmp(&namesrvr.sa6->sin6_addr, &ares_in6addr_any,
+                   sizeof(namesrvr.sa6->sin6_addr)) == 0)
+          continue;
+        if (! ares_inet_ntop(AF_INET6, &namesrvr.sa6->sin6_addr,
+                             txtaddr, sizeof(txtaddr)))
+          continue;
       }
-      RegCloseKey(subkey);
-      RegCloseKey(mykey);
+      else
+        continue;
+
+      commajoin(outptr, txtaddr);
+
+      if (!*outptr)
+        goto done;
     }
   }
-  else
+
+done:
+  if (ipaa)
+    free(ipaa);
+
+  if (!*outptr)
+    return 0;
+
+  return 1;
+}
+
+/*
+ * get_DNS_Windows()
+ *
+ * Locates DNS info from Windows employing most suitable methods available at
+ * run-time no matter which Windows version it is. When located, this returns
+ * a pointer in *outptr to a newly allocated memory area holding a string with
+ * a space or comma seperated list of DNS IP addresses, null-terminated.
+ *
+ * Returns 0 and nullifies *outptr upon inability to return DNSes string.
+ *
+ * Returns 1 and sets *outptr when returning a dynamically allocated string.
+ *
+ * Implementation supports Windows 95 and newer.
+ */
+static int get_DNS_Windows(char **outptr)
+{
+  /* Try using IP helper API GetAdaptersAddresses() */
+  if (get_DNS_AdaptersAddresses(outptr))
+    return 1;
+
+  /* Try using IP helper API GetNetworkParams() */
+  if (get_DNS_NetworkParams(outptr))
+    return 1;
+
+  /* Fall-back to registry information */
+  return get_DNS_Registry(outptr);
+}
+#endif
+
+static int init_by_resolv_conf(ares_channel channel)
+{
+#if !defined(ANDROID) && !defined(__ANDROID__) && !defined(WATT32)
+  char *line = NULL;
+#endif
+  int status = -1, nservers = 0, nsort = 0;
+  struct server_state *servers = NULL;
+  struct apattern *sortlist = NULL;
+
+#ifdef WIN32
+
+  if (channel->nservers > -1)  /* don't override ARES_OPT_SERVER */
+     return ARES_SUCCESS;
+
+  if (get_DNS_Windows(&line))
   {
-    if (RegOpenKeyEx(
-          HKEY_LOCAL_MACHINE, WIN_NS_9X, 0,
-          KEY_READ, &mykey
-          ) == ERROR_SUCCESS)
-    {
-      if ((result = RegQueryValueEx(
-             mykey, NAMESERVER, NULL, &data_type,
-             NULL, &bytes
-             )
-            ) == ERROR_SUCCESS ||
-          result == ERROR_MORE_DATA)
-      {
-        if (bytes)
-        {
-          line = (char *)malloc(bytes+1);
-          if (RegQueryValueEx(mykey, NAMESERVER, NULL, &data_type,
-                              (unsigned char *)line, &bytes) ==
-              ERROR_SUCCESS)
-          {
-            status = config_nameserver(&servers, &nservers, line);
-          }
-          free(line);
-        }
-      }
-    }
-    RegCloseKey(mykey);
+    status = config_nameserver(&servers, &nservers, line);
+    free(line);
   }
 
   if (status == ARES_SUCCESS)
@@ -733,19 +1120,38 @@ DhcpNameServer
     return ARES_SUCCESS; /* use localhost DNS server */
 
   nservers = i;
-  servers = calloc(sizeof(*servers), i);
+  servers = calloc(i, sizeof(struct server_state));
   if (!servers)
      return ARES_ENOMEM;
 
   for (i = 0; def_nameservers[i]; i++)
-      servers[i].addr.s_addr = htonl(def_nameservers[i]);
+  {
+    servers[i].addr.addrV4.s_addr = htonl(def_nameservers[i]);
+    servers[i].addr.family = AF_INET;
+  }
   status = ARES_EOF;
 
+#elif defined(ANDROID) || defined(__ANDROID__)
+  unsigned int i;
+  char propname[PROP_NAME_MAX];
+  char propvalue[PROP_VALUE_MAX]="";
+
+  for (i = 1; i <= MAX_DNS_PROPERTIES; i++) {
+    snprintf(propname, sizeof(propname), "%s%u", DNS_PROP_NAME_PREFIX, i);
+    if (__system_property_get(propname, propvalue) < 1) {
+      status = ARES_EOF;
+      break;
+    }
+    status = config_nameserver(&servers, &nservers, propvalue);
+    if (status != ARES_SUCCESS)
+      break;
+    status = ARES_EOF;
+  }
 #else
   {
     char *p;
     FILE *fp;
-    int linesize;
+    size_t linesize;
     int error;
 
     /* Don't read resolv.conf and friends if we don't have to */
@@ -756,17 +1162,19 @@ DhcpNameServer
     if (fp) {
       while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
       {
-        if ((p = try_config(line, "domain")) && channel->ndomains == -1)
+        if ((p = try_config(line, "domain", ';')))
           status = config_domain(channel, p);
-        else if ((p = try_config(line, "lookup")) && !channel->lookups)
+        else if ((p = try_config(line, "lookup", ';')) && !channel->lookups)
           status = config_lookup(channel, p, "bind", "file");
-        else if ((p = try_config(line, "search")) && channel->ndomains == -1)
+        else if ((p = try_config(line, "search", ';')))
           status = set_search(channel, p);
-        else if ((p = try_config(line, "nameserver")) && channel->nservers == -1)
+        else if ((p = try_config(line, "nameserver", ';')) &&
+                 channel->nservers == -1)
           status = config_nameserver(&servers, &nservers, p);
-        else if ((p = try_config(line, "sortlist")) && channel->nsort == -1)
+        else if ((p = try_config(line, "sortlist", ';')) &&
+                 channel->nsort == -1)
           status = config_sortlist(&sortlist, &nsort, p);
-        else if ((p = try_config(line, "options")))
+        else if ((p = try_config(line, "options", ';')))
           status = set_options(channel, p);
         else
           status = ARES_SUCCESS;
@@ -794,10 +1202,12 @@ DhcpNameServer
       /* Many systems (Solaris, Linux, BSD's) use nsswitch.conf */
       fp = fopen("/etc/nsswitch.conf", "r");
       if (fp) {
-        while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
+        while ((status = ares__read_line(fp, &line, &linesize)) ==
+               ARES_SUCCESS)
         {
-          if ((p = try_config(line, "hosts:")) && !channel->lookups)
-            status = config_lookup(channel, p, "dns", "files");
+          if ((p = try_config(line, "hosts:", '\0')) && !channel->lookups)
+            /* ignore errors */
+            (void)config_lookup(channel, p, "dns", "files");
         }
         fclose(fp);
       }
@@ -811,7 +1221,8 @@ DhcpNameServer
         default:
           DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
                          error, strerror(error)));
-          DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/nsswitch.conf"));
+          DEBUGF(fprintf(stderr, "Error opening file: %s\n",
+                         "/etc/nsswitch.conf"));
           status = ARES_EFILE;
         }
       }
@@ -821,10 +1232,12 @@ DhcpNameServer
       /* Linux / GNU libc 2.x and possibly others have host.conf */
       fp = fopen("/etc/host.conf", "r");
       if (fp) {
-        while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
+        while ((status = ares__read_line(fp, &line, &linesize)) ==
+               ARES_SUCCESS)
         {
-          if ((p = try_config(line, "order")) && !channel->lookups)
-            status = config_lookup(channel, p, "bind", "hosts");
+          if ((p = try_config(line, "order", '\0')) && !channel->lookups)
+            /* ignore errors */
+            (void)config_lookup(channel, p, "bind", "hosts");
         }
         fclose(fp);
       }
@@ -838,7 +1251,8 @@ DhcpNameServer
         default:
           DEBUGF(fprintf(stderr, "fopen() failed with error: %d %s\n",
                          error, strerror(error)));
-          DEBUGF(fprintf(stderr, "Error opening file: %s\n", "/etc/host.conf"));
+          DEBUGF(fprintf(stderr, "Error opening file: %s\n",
+                         "/etc/host.conf"));
           status = ARES_EFILE;
         }
       }
@@ -848,10 +1262,12 @@ DhcpNameServer
       /* Tru64 uses /etc/svc.conf */
       fp = fopen("/etc/svc.conf", "r");
       if (fp) {
-        while ((status = ares__read_line(fp, &line, &linesize)) == ARES_SUCCESS)
+        while ((status = ares__read_line(fp, &line, &linesize)) ==
+               ARES_SUCCESS)
         {
-          if ((p = try_config(line, "hosts=")) && !channel->lookups)
-            status = config_lookup(channel, p, "bind", "local");
+          if ((p = try_config(line, "hosts=", '\0')) && !channel->lookups)
+            /* ignore errors */
+            (void)config_lookup(channel, p, "bind", "local");
         }
         fclose(fp);
       }
@@ -888,9 +1304,6 @@ DhcpNameServer
     }
 
   /* If we got any name server entries, fill them in. */
-#ifdef WIN32
-okay:
-#endif
   if (servers)
     {
       channel->servers = servers;
@@ -909,7 +1322,11 @@ okay:
 
 static int init_by_defaults(ares_channel channel)
 {
-  char hostname[MAXHOSTNAMELEN + 1];
+  char *hostname = NULL;
+  int rc = ARES_SUCCESS;
+#ifdef HAVE_GETHOSTNAME
+  char *dot;
+#endif
 
   if (channel->flags == -1)
     channel->flags = 0;
@@ -919,61 +1336,134 @@ static int init_by_defaults(ares_channel channel)
     channel->tries = DEFAULT_TRIES;
   if (channel->ndots == -1)
     channel->ndots = 1;
+  if (channel->rotate == -1)
+    channel->rotate = 0;
   if (channel->udp_port == -1)
     channel->udp_port = htons(NAMESERVER_PORT);
   if (channel->tcp_port == -1)
     channel->tcp_port = htons(NAMESERVER_PORT);
 
-  if (channel->nservers == -1)
-    {
-      /* If nobody specified servers, try a local named. */
-      channel->servers = malloc(sizeof(struct server_state));
-      if (!channel->servers)
-        return ARES_ENOMEM;
-      channel->servers[0].addr.s_addr = htonl(INADDR_LOOPBACK);
-      channel->nservers = 1;
+  if (channel->ednspsz == -1)
+    channel->ednspsz = EDNSPACKETSZ;
+
+  if (channel->nservers == -1) {
+    /* If nobody specified servers, try a local named. */
+    channel->servers = malloc(sizeof(struct server_state));
+    if (!channel->servers) {
+      rc = ARES_ENOMEM;
+      goto error;
     }
+    channel->servers[0].addr.family = AF_INET;
+    channel->servers[0].addr.addrV4.s_addr = htonl(INADDR_LOOPBACK);
+    channel->nservers = 1;
+  }
 
-  if (channel->ndomains == -1)
-    {
-      /* Derive a default domain search list from the kernel hostname,
-       * or set it to empty if the hostname isn't helpful.
-       */
-      if (gethostname(hostname, sizeof(hostname)) == -1
-          || !strchr(hostname, '.'))
-        {
-          channel->ndomains = 0;
-        }
-      else
-        {
-          channel->domains = malloc(sizeof(char *));
-          if (!channel->domains)
-            return ARES_ENOMEM;
-          channel->ndomains = 0;
-          channel->domains[0] = strdup(strchr(hostname, '.') + 1);
-          if (!channel->domains[0])
-            return ARES_ENOMEM;
-          channel->ndomains = 1;
+#if defined(USE_WINSOCK)
+#define toolong(x) (x == -1) &&  (SOCKERRNO == WSAEFAULT)
+#elif defined(ENAMETOOLONG)
+#define toolong(x) (x == -1) && ((SOCKERRNO == ENAMETOOLONG) || \
+                                 (SOCKERRNO == EINVAL))
+#else
+#define toolong(x) (x == -1) &&  (SOCKERRNO == EINVAL)
+#endif
+
+  if (channel->ndomains == -1) {
+    /* Derive a default domain search list from the kernel hostname,
+     * or set it to empty if the hostname isn't helpful.
+     */
+#ifndef HAVE_GETHOSTNAME
+    channel->ndomains = 0; /* default to none */
+#else
+    GETHOSTNAME_TYPE_ARG2 lenv = 64;
+    size_t len = 64;
+    int res;
+    channel->ndomains = 0; /* default to none */
+
+    hostname = malloc(len);
+    if(!hostname) {
+      rc = ARES_ENOMEM;
+      goto error;
+    }
+
+    do {
+      res = gethostname(hostname, lenv);
+
+      if(toolong(res)) {
+        char *p;
+        len *= 2;
+        lenv *= 2;
+        p = realloc(hostname, len);
+        if(!p) {
+          rc = ARES_ENOMEM;
+          goto error;
         }
+        hostname = p;
+        continue;
+      }
+      else if(res) {
+        rc = ARES_EBADNAME;
+        goto error;
+      }
+
+    } WHILE_FALSE;
+
+    dot = strchr(hostname, '.');
+    if (dot) {
+      /* a dot was found */
+      channel->domains = malloc(sizeof(char *));
+      if (!channel->domains) {
+        rc = ARES_ENOMEM;
+        goto error;
+      }
+      channel->domains[0] = strdup(dot + 1);
+      if (!channel->domains[0]) {
+        rc = ARES_ENOMEM;
+        goto error;
+      }
+      channel->ndomains = 1;
     }
+#endif
+  }
 
-  if (channel->nsort == -1)
-    {
-      channel->sortlist = NULL;
-      channel->nsort = 0;
+  if (channel->nsort == -1) {
+    channel->sortlist = NULL;
+    channel->nsort = 0;
+  }
+
+  if (!channel->lookups) {
+    channel->lookups = strdup("fb");
+    if (!channel->lookups)
+      rc = ARES_ENOMEM;
+  }
+
+  error:
+  if(rc) {
+    if(channel->servers) {
+      free(channel->servers);
+      channel->servers = NULL;
     }
 
-  if (!channel->lookups)
-    {
-      channel->lookups = strdup("fb");
-      if (!channel->lookups)
-        return ARES_ENOMEM;
+    if(channel->domains && channel->domains[0])
+      free(channel->domains[0]);
+    if(channel->domains) {
+      free(channel->domains);
+      channel->domains = NULL;
     }
 
-  return ARES_SUCCESS;
+    if(channel->lookups) {
+      free(channel->lookups);
+      channel->lookups = NULL;
+    }
+  }
+
+  if(hostname)
+    free(hostname);
+
+  return rc;
 }
 
-#ifndef WIN32
+#if !defined(WIN32) && !defined(WATT32) && \
+    !defined(ANDROID) && !defined(__ANDROID__)
 static int config_domain(ares_channel channel, char *str)
 {
   char *q;
@@ -986,11 +1476,19 @@ static int config_domain(ares_channel channel, char *str)
   return set_search(channel, str);
 }
 
+#if defined(__INTEL_COMPILER) && (__INTEL_COMPILER == 910) && \
+    defined(__OPTIMIZE__) && defined(__unix__) &&  defined(__i386__)
+  /* workaround icc 9.1 optimizer issue */
+# define vqualifier volatile
+#else
+# define vqualifier
+#endif
+
 static int config_lookup(ares_channel channel, const char *str,
                          const char *bindch, const char *filech)
 {
   char lookups[3], *l;
-  const char *p;
+  const char *vqualifier p;
 
   /* Set the lookup order.  Only the first letter of each work
    * is relevant, and it has to be "b" for DNS or "f" for the
@@ -1013,71 +1511,72 @@ static int config_lookup(ares_channel channel, const char *str,
   channel->lookups = strdup(lookups);
   return (channel->lookups) ? ARES_SUCCESS : ARES_ENOMEM;
 }
+#endif  /* !WIN32 & !WATT32 & !ANDROID & !__ANDROID__ */
 
-#endif
-
+#ifndef WATT32
 static int config_nameserver(struct server_state **servers, int *nservers,
                              char *str)
 {
-  struct in_addr addr;
+  struct ares_addr host;
   struct server_state *newserv;
+  char *p, *txtaddr;
   /* On Windows, there may be more than one nameserver specified in the same
-   * registry key, so we parse it as a space or comma seperated list.
+   * registry key, so we parse input as a space or comma seperated list.
    */
-#ifdef WIN32
-  char *p = str;
-  char *begin = str;
-  int more = 1;
-  while (more)
-  {
-    more = 0;
-    while (*p && !ISSPACE(*p) && *p != ',')
-      p++;
-
-    if (*p)
+  for (p = str; p;)
     {
-      *p = '\0';
-      more = 1;
-    }
+      /* Skip whitespace and commas. */
+      while (*p && (ISSPACE(*p) || (*p == ',')))
+        p++;
+      if (!*p)
+        /* No more input, done. */
+        break;
 
-    /* Skip multiple spaces or trailing spaces */
-    if (!*begin)
-    {
-      begin = ++p;
-      continue;
-    }
+      /* Pointer to start of IPv4 or IPv6 address part. */
+      txtaddr = p;
 
-    /* This is the part that actually sets the nameserver */
-    addr.s_addr = inet_addr(begin);
-    if (addr.s_addr == INADDR_NONE)
-      continue;
-    newserv = realloc(*servers, (*nservers + 1) * sizeof(struct server_state));
-    if (!newserv)
-      return ARES_ENOMEM;
-    newserv[*nservers].addr = addr;
-    *servers = newserv;
-    (*nservers)++;
+      /* Advance past this address. */
+      while (*p && !ISSPACE(*p) && (*p != ','))
+        p++;
+      if (*p)
+        /* Null terminate this address. */
+        *p++ = '\0';
+      else
+        /* Reached end of input, done when this address is processed. */
+        p = NULL;
+
+      /* Convert textual address to binary format. */
+      if (ares_inet_pton(AF_INET, txtaddr, &host.addrV4) == 1)
+        host.family = AF_INET;
+      else if (ares_inet_pton(AF_INET6, txtaddr, &host.addrV6) == 1)
+        host.family = AF_INET6;
+      else
+        continue;
+
+      /* Resize servers state array. */
+      newserv = realloc(*servers, (*nservers + 1) *
+                        sizeof(struct server_state));
+      if (!newserv)
+        return ARES_ENOMEM;
+
+      /* Store address data. */
+      newserv[*nservers].addr.family = host.family;
+      if (host.family == AF_INET)
+        memcpy(&newserv[*nservers].addr.addrV4, &host.addrV4,
+               sizeof(host.addrV4));
+      else
+        memcpy(&newserv[*nservers].addr.addrV6, &host.addrV6,
+               sizeof(host.addrV6));
+
+      /* Update arguments. */
+      *servers = newserv;
+      *nservers += 1;
+    }
 
-    if (!more)
-      break;
-    begin = ++p;
-  }
-#else
-  /* Add a nameserver entry, if this is a valid address. */
-  addr.s_addr = inet_addr(str);
-  if (addr.s_addr == INADDR_NONE)
-    return ARES_SUCCESS;
-  newserv = realloc(*servers, (*nservers + 1) * sizeof(struct server_state));
-  if (!newserv)
-    return ARES_ENOMEM;
-  newserv[*nservers].addr = addr;
-  *servers = newserv;
-  (*nservers)++;
-#endif
   return ARES_SUCCESS;
 }
 
-#ifndef WIN32
+#if !defined(WIN32) && !defined(ANDROID) && !defined(__ANDROID__)
 static int config_sortlist(struct apattern **sortlist, int *nsort,
                            const char *str)
 {
@@ -1093,16 +1592,16 @@ static int config_sortlist(struct apattern **sortlist, int *nsort,
       q = str;
       while (*q && *q != '/' && *q != ';' && !ISSPACE(*q))
         q++;
-      memcpy(ipbuf, str, (int)(q-str));
-      ipbuf[(int)(q-str)] = '\0';
+      memcpy(ipbuf, str, q-str);
+      ipbuf[q-str] = '\0';
       /* Find the prefix */
       if (*q == '/')
         {
           const char *str2 = q+1;
           while (*q && *q != ';' && !ISSPACE(*q))
             q++;
-          memcpy(ipbufpfx, str, (int)(q-str));
-          ipbufpfx[(int)(q-str)] = '\0';
+          memcpy(ipbufpfx, str, q-str);
+          ipbufpfx[q-str] = '\0';
           str = str2;
         }
       else
@@ -1110,8 +1609,8 @@ static int config_sortlist(struct apattern **sortlist, int *nsort,
       /* Lets see if it is CIDR */
       /* First we'll try IPv6 */
       if ((bits = ares_inet_net_pton(AF_INET6, ipbufpfx[0] ? ipbufpfx : ipbuf,
-                                     &pat.addr.addr6,
-                                     sizeof(pat.addr.addr6))) > 0)
+                                     &pat.addrV6,
+                                     sizeof(pat.addrV6))) > 0)
         {
           pat.type = PATTERN_CIDR;
           pat.mask.bits = (unsigned short)bits;
@@ -1119,9 +1618,9 @@ static int config_sortlist(struct apattern **sortlist, int *nsort,
           if (!sortlist_alloc(sortlist, nsort, &pat))
             return ARES_ENOMEM;
         }
-      if (ipbufpfx[0] &&
-          (bits = ares_inet_net_pton(AF_INET, ipbufpfx, &pat.addr.addr4,
-                                     sizeof(pat.addr.addr4))) > 0)
+      else if (ipbufpfx[0] &&
+               (bits = ares_inet_net_pton(AF_INET, ipbufpfx, &pat.addrV4,
+                                          sizeof(pat.addrV4))) > 0)
         {
           pat.type = PATTERN_CIDR;
           pat.mask.bits = (unsigned short)bits;
@@ -1130,13 +1629,13 @@ static int config_sortlist(struct apattern **sortlist, int *nsort,
             return ARES_ENOMEM;
         }
       /* See if it is just a regular IP */
-      else if (ip_addr(ipbuf, (int)(q-str), &pat.addr.addr4) == 0)
+      else if (ip_addr(ipbuf, q-str, &pat.addrV4) == 0)
         {
           if (ipbufpfx[0])
             {
-              memcpy(ipbuf, str, (int)(q-str));
-              ipbuf[(int)(q-str)] = '\0';
-              if (ip_addr(ipbuf, (int)(q - str), &pat.mask.addr.addr4) != 0)
+              memcpy(ipbuf, str, q-str);
+              ipbuf[q-str] = '\0';
+              if (ip_addr(ipbuf, q-str, &pat.mask.addr4) != 0)
                 natural_mask(&pat);
             }
           else
@@ -1158,7 +1657,8 @@ static int config_sortlist(struct apattern **sortlist, int *nsort,
 
   return ARES_SUCCESS;
 }
-#endif
+#endif  /* !WIN32 & !ANDROID & !__ANDROID__ */
+#endif  /* !WATT32 */
 
 static int set_search(ares_channel channel, const char *str)
 {
@@ -1232,13 +1732,16 @@ static int set_options(ares_channel channel, const char *str)
         q++;
       val = try_option(p, q, "ndots:");
       if (val && channel->ndots == -1)
-        channel->ndots = atoi(val);
+        channel->ndots = aresx_sltosi(strtol(val, NULL, 10));
       val = try_option(p, q, "retrans:");
       if (val && channel->timeout == -1)
-        channel->timeout = atoi(val);
+        channel->timeout = aresx_sltosi(strtol(val, NULL, 10));
       val = try_option(p, q, "retry:");
       if (val && channel->tries == -1)
-        channel->tries = atoi(val);
+        channel->tries = aresx_sltosi(strtol(val, NULL, 10));
+      val = try_option(p, q, "rotate");
+      if (val && channel->rotate == -1)
+        channel->rotate = 1;
       p = q;
       while (ISSPACE(*p))
         p++;
@@ -1247,29 +1750,47 @@ static int set_options(ares_channel channel, const char *str)
   return ARES_SUCCESS;
 }
 
-#ifndef WIN32
-static char *try_config(char *s, const char *opt)
+static const char *try_option(const char *p, const char *q, const char *opt)
+{
+  size_t len = strlen(opt);
+  return ((size_t)(q - p) >= len && !strncmp(p, opt, len)) ? &p[len] : NULL;
+}
+
+#if !defined(WIN32) && !defined(WATT32) && \
+    !defined(ANDROID) && !defined(__ANDROID__)
+static char *try_config(char *s, const char *opt, char scc)
 {
   size_t len;
-  ssize_t i;
-  ssize_t j;
   char *p;
+  char *q;
 
   if (!s || !opt)
     /* no line or no option */
     return NULL;
 
+  /* Hash '#' character is always used as primary comment char, additionally
+     a not-NUL secondary comment char will be considered when specified. */
+
   /* trim line comment */
-  for (i = 0; s[i] && s[i] != '#'; ++i);
-  s[i] = '\0';
+  p = s;
+  if(scc)
+    while (*p && (*p != '#') && (*p != scc))
+      p++;
+  else
+    while (*p && (*p != '#'))
+      p++;
+  *p = '\0';
 
   /* trim trailing whitespace */
-  for (j = i-1; j >= 0 && ISSPACE(s[j]); --j);
-  s[++j] = '\0';
+  q = p - 1;
+  while ((q >= s) && ISSPACE(*q))
+    q--;
+  *++q = '\0';
 
   /* skip leading whitespace */
-  for (i = 0; s[i] && ISSPACE(s[i]); ++i);
-  p = &s[i];
+  p = s;
+  while (*p && ISSPACE(*p))
+    p++;
 
   if (!*p)
     /* empty line */
@@ -1306,15 +1827,7 @@ static char *try_config(char *s, const char *opt)
   /* return pointer to option value */
   return p;
 }
-#endif
-
-static const char *try_option(const char *p, const char *q, const char *opt)
-{
-  size_t len = strlen(opt);
-  return ((size_t)(q - p) > len && !strncmp(p, opt, len)) ? &p[len] : NULL;
-}
 
-#ifndef WIN32
 static int sortlist_alloc(struct apattern **sortlist, int *nsort,
                           struct apattern *pat)
 {
@@ -1328,7 +1841,7 @@ static int sortlist_alloc(struct apattern **sortlist, int *nsort,
   return 1;
 }
 
-static int ip_addr(const char *ipbuf, int len, struct in_addr *addr)
+static int ip_addr(const char *ipbuf, ssize_t len, struct in_addr *addr)
 {
 
   /* Four octets and three periods yields at most 15 characters. */
@@ -1348,19 +1861,20 @@ static void natural_mask(struct apattern *pat)
   /* Store a host-byte-order copy of pat in a struct in_addr.  Icky,
    * but portable.
    */
-  addr.s_addr = ntohl(pat->addr.addr4.s_addr);
+  addr.s_addr = ntohl(pat->addrV4.s_addr);
 
   /* This is out of date in the CIDR world, but some people might
    * still rely on it.
    */
   if (IN_CLASSA(addr.s_addr))
-    pat->mask.addr.addr4.s_addr = htonl(IN_CLASSA_NET);
+    pat->mask.addr4.s_addr = htonl(IN_CLASSA_NET);
   else if (IN_CLASSB(addr.s_addr))
-    pat->mask.addr.addr4.s_addr = htonl(IN_CLASSB_NET);
+    pat->mask.addr4.s_addr = htonl(IN_CLASSB_NET);
   else
-    pat->mask.addr.addr4.s_addr = htonl(IN_CLASSC_NET);
+    pat->mask.addr4.s_addr = htonl(IN_CLASSC_NET);
 }
-#endif
+#endif  /* !WIN32 & !WATT32 & !ANDROID & !__ANDROID__ */
+
 /* initialize an rc4 key. If possible a cryptographically secure random key
    is generated using a suitable function (for example win32's RtlGenRandom as
    described in
@@ -1373,26 +1887,24 @@ static void randomize_key(unsigned char* key,int key_data_len)
   int randomized = 0;
   int counter=0;
 #ifdef WIN32
-  HMODULE lib=LoadLibrary("ADVAPI32.DLL");
-  if (lib) {
-    BOOLEAN (APIENTRY *pfn)(void*, ULONG) =
-      (BOOLEAN (APIENTRY *)(void*,ULONG))GetProcAddress(lib,"SystemFunction036");
-    if (pfn && pfn(key,key_data_len) )
-      randomized = 1;
-
-    FreeLibrary(lib);
-  }
+  BOOLEAN res;
+  if (ares_fpSystemFunction036)
+    {
+      res = (*ares_fpSystemFunction036) (key, key_data_len);
+      if (res)
+        randomized = 1;
+    }
 #else /* !WIN32 */
 #ifdef RANDOM_FILE
   FILE *f = fopen(RANDOM_FILE, "rb");
   if(f) {
-    counter = fread(key, 1, key_data_len, f);
+    counter = aresx_uztosi(fread(key, 1, key_data_len, f));
     fclose(f);
   }
 #endif
 #endif /* WIN32 */
 
-  if ( !randomized ) {
+  if (!randomized) {
     for (;counter<key_data_len;counter++)
       key[counter]=(unsigned char)(rand() % 256);
   }
@@ -1410,11 +1922,11 @@ static int init_id_key(rc4_key* key,int key_data_len)
   if (!key_data_ptr)
     return ARES_ENOMEM;
 
-  randomize_key(key->state,key_data_len);
   state = &key->state[0];
   for(counter = 0; counter < 256; counter++)
     /* unnecessary AND but it keeps some compilers happier */
     state[counter] = (unsigned char)(counter & 0xff);
+  randomize_key(key->state,key_data_len);
   key->x = 0;
   key->y = 0;
   index1 = 0;
@@ -1431,9 +1943,55 @@ static int init_id_key(rc4_key* key,int key_data_len)
   return ARES_SUCCESS;
 }
 
-short ares__generate_new_id(rc4_key* key)
+void ares_set_local_ip4(ares_channel channel, unsigned int local_ip)
+{
+  channel->local_ip4 = local_ip;
+}
+
+/* local_ip6 should be 16 bytes in length */
+void ares_set_local_ip6(ares_channel channel,
+                        const unsigned char* local_ip6)
 {
-  short r=0;
-  ares__rc4(key, (unsigned char *)&r, sizeof(r));
-  return r;
+  memcpy(&channel->local_ip6, local_ip6, sizeof(channel->local_ip6));
+}
+
+/* local_dev_name should be null terminated. */
+void ares_set_local_dev(ares_channel channel,
+                        const char* local_dev_name)
+{
+  strncpy(channel->local_dev_name, local_dev_name,
+          sizeof(channel->local_dev_name));
+  channel->local_dev_name[sizeof(channel->local_dev_name) - 1] = 0;
+}
+
+
+void ares_set_socket_callback(ares_channel channel,
+                              ares_sock_create_callback cb,
+                              void *data)
+{
+  channel->sock_create_cb = cb;
+  channel->sock_create_cb_data = data;
+}
+
+void ares__init_servers_state(ares_channel channel)
+{
+  struct server_state *server;
+  int i;
+
+  for (i = 0; i < channel->nservers; i++)
+    {
+      server = &channel->servers[i];
+      server->udp_socket = ARES_SOCKET_BAD;
+      server->tcp_socket = ARES_SOCKET_BAD;
+      server->tcp_connection_generation = ++channel->tcp_connection_generation;
+      server->tcp_lenbuf_pos = 0;
+      server->tcp_buffer_pos = 0;
+      server->tcp_buffer = NULL;
+      server->tcp_length = 0;
+      server->qhead = NULL;
+      server->qtail = NULL;
+      ares__init_list_head(&server->queries_to_server);
+      server->channel = channel;
+      server->is_broken = 0;
+    }
 }