s3-talloc Change TALLOC_ARRAY() to talloc_array()
[samba.git] / source3 / libads / dns.c
index b67d802bdc739070dd537dd4188f869de3234986..c1332849bff6bc5988327b844c1880cf87acea60 100644 (file)
@@ -1,24 +1,26 @@
-/* 
+/*
    Unix SMB/CIFS implementation.
    DNS utility library
    Copyright (C) Gerald (Jerry) Carter           2006.
+   Copyright (C) Jeremy Allison                  2007.
 
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
-   the Free Software Foundation; either version 2 of the License, or
+   the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.
-   
+
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
-   
+
    You should have received a copy of the GNU General Public License
-   along with this program; if not, write to the Free Software
-   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
 
 #include "includes.h"
+#include "libads/dns.h"
+#include "../librpc/ndr/libndr.h"
 
 /* AIX resolv.h uses 'class' in struct ns_rr */
 
 #if !defined(T_A)      /* AIX 5.3 already defines T_A */
 #  define T_A          ns_t_a
 #endif
+
+#if defined(HAVE_IPV6)
+#if !defined(T_AAAA)
+#  define T_AAAA       ns_t_aaaa
+#endif
+#endif
+
 #  define T_SRV        ns_t_srv
 #if !defined(T_NS)     /* AIX 5.3 already defines T_NS */
 #  define T_NS                 ns_t_ns
 /*********************************************************************
 *********************************************************************/
 
-static BOOL ads_dns_parse_query( TALLOC_CTX *ctx, uint8 *start, uint8 *end,
+static bool ads_dns_parse_query( TALLOC_CTX *ctx, uint8 *start, uint8 *end,
                           uint8 **ptr, struct dns_query *q )
 {
        uint8 *p = *ptr;
-       pstring hostname;
+       char hostname[MAX_DNS_NAME_LENGTH];
        int namelen;
 
        ZERO_STRUCTP( q );
-       
+
        if ( !start || !end || !q || !*ptr)
                return False;
 
@@ -104,11 +113,11 @@ static BOOL ads_dns_parse_query( TALLOC_CTX *ctx, uint8 *start, uint8 *end,
 /*********************************************************************
 *********************************************************************/
 
-static BOOL ads_dns_parse_rr( TALLOC_CTX *ctx, uint8 *start, uint8 *end,
+static bool ads_dns_parse_rr( TALLOC_CTX *ctx, uint8 *start, uint8 *end,
                        uint8 **ptr, struct dns_rr *rr )
 {
        uint8 *p = *ptr;
-       pstring hostname;
+       char hostname[MAX_DNS_NAME_LENGTH];
        int namelen;
 
        if ( !start || !end || !rr || !*ptr)
@@ -135,7 +144,7 @@ static BOOL ads_dns_parse_rr( TALLOC_CTX *ctx, uint8 *start, uint8 *end,
        rr->in_class = RSVAL(p, 2);
        rr->ttl      = RIVAL(p, 4);
        rr->rdatalen = RSVAL(p, 8);
-       
+
        p += 10;
 
        /* sanity check the available space */
@@ -158,18 +167,18 @@ static BOOL ads_dns_parse_rr( TALLOC_CTX *ctx, uint8 *start, uint8 *end,
 /*********************************************************************
 *********************************************************************/
 
-static BOOL ads_dns_parse_rr_srv( TALLOC_CTX *ctx, uint8 *start, uint8 *end,
+static bool ads_dns_parse_rr_srv( TALLOC_CTX *ctx, uint8 *start, uint8 *end,
                        uint8 **ptr, struct dns_rr_srv *srv )
 {
        struct dns_rr rr;
        uint8 *p;
-       pstring dcname;
+       char dcname[MAX_DNS_NAME_LENGTH];
        int namelen;
 
        if ( !start || !end || !srv || !*ptr)
                return -1;
 
-       /* Parse the RR entry.  Coming out of the this, ptr is at the beginning 
+       /* Parse the RR entry.  Coming out of the this, ptr is at the beginning
           of the next record */
 
        if ( !ads_dns_parse_rr( ctx, start, end, ptr, &rr ) ) {
@@ -178,7 +187,8 @@ static BOOL ads_dns_parse_rr_srv( TALLOC_CTX *ctx, uint8 *start, uint8 *end,
        }
 
        if ( rr.type != T_SRV ) {
-               DEBUG(1,("ads_dns_parse_rr_srv: Bad answer type (%d)\n", rr.type));
+               DEBUG(1,("ads_dns_parse_rr_srv: Bad answer type (%d)\n",
+                                       rr.type));
                return False;
        }
 
@@ -195,26 +205,33 @@ static BOOL ads_dns_parse_rr_srv( TALLOC_CTX *ctx, uint8 *start, uint8 *end,
                DEBUG(1,("ads_dns_parse_rr_srv: Failed to uncompress name!\n"));
                return False;
        }
+
        srv->hostname = talloc_strdup( ctx, dcname );
 
+       DEBUG(10,("ads_dns_parse_rr_srv: Parsed %s [%u, %u, %u]\n", 
+                 srv->hostname, 
+                 srv->priority,
+                 srv->weight,
+                 srv->port));
+
        return True;
 }
 
 /*********************************************************************
 *********************************************************************/
 
-static BOOL ads_dns_parse_rr_ns( TALLOC_CTX *ctx, uint8 *start, uint8 *end,
+static bool ads_dns_parse_rr_ns( TALLOC_CTX *ctx, uint8 *start, uint8 *end,
                        uint8 **ptr, struct dns_rr_ns *nsrec )
 {
        struct dns_rr rr;
        uint8 *p;
-       pstring nsname;
+       char nsname[MAX_DNS_NAME_LENGTH];
        int namelen;
 
        if ( !start || !end || !nsrec || !*ptr)
                return -1;
 
-       /* Parse the RR entry.  Coming out of the this, ptr is at the beginning 
+       /* Parse the RR entry.  Coming out of the this, ptr is at the beginning
           of the next record */
 
        if ( !ads_dns_parse_rr( ctx, start, end, ptr, &rr ) ) {
@@ -223,14 +240,15 @@ static BOOL ads_dns_parse_rr_ns( TALLOC_CTX *ctx, uint8 *start, uint8 *end,
        }
 
        if ( rr.type != T_NS ) {
-               DEBUG(1,("ads_dns_parse_rr_ns: Bad answer type (%d)\n", rr.type));
+               DEBUG(1,("ads_dns_parse_rr_ns: Bad answer type (%d)\n",
+                                       rr.type));
                return False;
        }
 
        p = rr.rdata;
 
        /* ame server hostname */
-       
+
        namelen = dn_expand( start, end, p, nsname, sizeof(nsname) );
        if ( namelen < 0 ) {
                DEBUG(1,("ads_dns_parse_rr_ns: Failed to uncompress name!\n"));
@@ -250,16 +268,16 @@ static int dnssrvcmp( struct dns_rr_srv *a, struct dns_rr_srv *b )
        if ( a->priority == b->priority ) {
 
                /* randomize entries with an equal weight and priority */
-               if ( a->weight == b->weight ) 
+               if ( a->weight == b->weight )
                        return 0;
 
-               /* higher weights should be sorted lower */ 
+               /* higher weights should be sorted lower */
                if ( a->weight > b->weight )
                        return -1;
                else
                        return 1;
        }
-               
+
        if ( a->priority < b->priority )
                return -1;
 
@@ -270,42 +288,110 @@ static int dnssrvcmp( struct dns_rr_srv *a, struct dns_rr_srv *b )
  Simple wrapper for a DNS query
 *********************************************************************/
 
-static NTSTATUS dns_send_req( TALLOC_CTX *ctx, const char *name, int q_type, 
+#define DNS_FAILED_WAITTIME          30
+
+static NTSTATUS dns_send_req( TALLOC_CTX *ctx, const char *name, int q_type,
                               uint8 **buf, int *resp_length )
 {
        uint8 *buffer = NULL;
-       size_t buf_len;
-       int resp_len = NS_PACKETSZ;     
-       
+       size_t buf_len = 0;
+       int resp_len = NS_PACKETSZ;
+       static time_t last_dns_check = 0;
+       static NTSTATUS last_dns_status = NT_STATUS_OK;
+       time_t now = time_mono(NULL);
+
+       /* Try to prevent bursts of DNS lookups if the server is down */
+
+       /* Protect against large clock changes */
+
+       if ( last_dns_check > now )
+               last_dns_check = 0;
+
+       /* IF we had a DNS timeout or a bad server and we are still
+          in the 30 second cache window, just return the previous
+          status and save the network timeout. */
+
+       if ( (NT_STATUS_EQUAL(last_dns_status,NT_STATUS_IO_TIMEOUT) ||
+             NT_STATUS_EQUAL(last_dns_status,NT_STATUS_CONNECTION_REFUSED)) &&
+            (last_dns_check+DNS_FAILED_WAITTIME) > now )
+       {
+               DEBUG(10,("last_dns_check: Returning cached status (%s)\n",
+                         nt_errstr(last_dns_status) ));
+               return last_dns_status;
+       }
+
+       /* Send the Query */
        do {
                if ( buffer )
                        TALLOC_FREE( buffer );
-               
+
                buf_len = resp_len * sizeof(uint8);
 
-               if ( (buffer = TALLOC_ARRAY(ctx, uint8, buf_len)) == NULL ) {
-                       DEBUG(0,("ads_dns_lookup_srv: talloc() failed!\n"));
-                       return NT_STATUS_NO_MEMORY;
+               if (buf_len) {
+                       if ((buffer = talloc_array(ctx, uint8, buf_len))
+                                       == NULL ) {
+                               DEBUG(0,("ads_dns_lookup_srv: "
+                                       "talloc() failed!\n"));
+                               last_dns_status = NT_STATUS_NO_MEMORY;
+                               last_dns_check = time_mono(NULL);
+                               return last_dns_status;
+                       }
                }
 
-               if ( (resp_len = res_query(name, C_IN, q_type, buffer, buf_len)) < 0 ) {
-                       DEBUG(3,("ads_dns_lookup_srv: Failed to resolve %s (%s)\n", name, strerror(errno)));
+               if ((resp_len = res_query(name, C_IN, q_type, buffer, buf_len))
+                               < 0 ) {
+                       DEBUG(3,("ads_dns_lookup_srv: "
+                               "Failed to resolve %s (%s)\n",
+                               name, strerror(errno)));
                        TALLOC_FREE( buffer );
-                       return NT_STATUS_UNSUCCESSFUL;
+                       last_dns_status = NT_STATUS_UNSUCCESSFUL;
+
+                       if (errno == ETIMEDOUT) {
+                               last_dns_status = NT_STATUS_IO_TIMEOUT;
+                       }
+                       if (errno == ECONNREFUSED) {
+                               last_dns_status = NT_STATUS_CONNECTION_REFUSED;
+                       }
+                       last_dns_check = time_mono(NULL);
+                       return last_dns_status;
                }
-       } while ( buf_len < resp_len && resp_len < MAX_DNS_PACKET_SIZE );
-       
+
+               /* On AIX, Solaris, and possibly some older glibc systems (e.g. SLES8)
+                  truncated replies never give back a resp_len > buflen
+                  which ends up causing DNS resolve failures on large tcp DNS replies */
+
+               if (buf_len == resp_len) {
+                       if (resp_len == MAX_DNS_PACKET_SIZE) {
+                               DEBUG(1,("dns_send_req: DNS reply too large when resolving %s\n",
+                                       name));
+                               TALLOC_FREE( buffer );
+                               last_dns_status = NT_STATUS_BUFFER_TOO_SMALL;
+                               last_dns_check = time_mono(NULL);
+                               return last_dns_status;
+                       }
+
+                       resp_len = MIN(resp_len*2, MAX_DNS_PACKET_SIZE);
+               }
+
+
+       } while ( buf_len < resp_len && resp_len <= MAX_DNS_PACKET_SIZE );
+
        *buf = buffer;
        *resp_length = resp_len;
 
-       return NT_STATUS_OK;
+       last_dns_check = time_mono(NULL);
+       last_dns_status = NT_STATUS_OK;
+       return last_dns_status;
 }
 
 /*********************************************************************
  Simple wrapper for a DNS SRV query
 *********************************************************************/
 
-static NTSTATUS ads_dns_lookup_srv( TALLOC_CTX *ctx, const char *name, struct dns_rr_srv **dclist, int *numdcs )
+static NTSTATUS ads_dns_lookup_srv( TALLOC_CTX *ctx,
+                               const char *name,
+                               struct dns_rr_srv **dclist,
+                               int *numdcs)
 {
        uint8 *buffer = NULL;
        int resp_len = 0;
@@ -315,12 +401,20 @@ static NTSTATUS ads_dns_lookup_srv( TALLOC_CTX *ctx, const char *name, struct dn
        int rrnum;
        int idx = 0;
        NTSTATUS status;
+       const char *dns_hosts_file;
 
        if ( !ctx || !name || !dclist ) {
                return NT_STATUS_INVALID_PARAMETER;
        }
-       
-       /* Send the request.  May have to loop several times in case 
+
+       dns_hosts_file = lp_parm_const_string(-1, "resolv", "host file", NULL);
+       if (dns_hosts_file) {
+               return resolve_dns_hosts_file_as_dns_rr(dns_hosts_file,
+                                                       name, true, ctx,
+                                                       dclist, numdcs);
+       }
+
+       /* Send the request.  May have to loop several times in case
           of large replies */
 
        status = dns_send_req( ctx, name, T_SRV, &buffer, &resp_len );
@@ -335,20 +429,28 @@ static NTSTATUS ads_dns_lookup_srv( TALLOC_CTX *ctx, const char *name, struct dn
           available in libresolv.a, and not the shared lib.  Who knows why....
           So we have to parse the DNS reply ourselves */
 
-       /* Pull the answer RR's count from the header.  Use the NMB ordering macros */
+       /* Pull the answer RR's count from the header.
+        * Use the NMB ordering macros */
 
        query_count      = RSVAL( p, 4 );
        answer_count     = RSVAL( p, 6 );
        auth_count       = RSVAL( p, 8 );
        additional_count = RSVAL( p, 10 );
 
-       DEBUG(4,("ads_dns_lookup_srv: %d records returned in the answer section.\n", 
+       DEBUG(4,("ads_dns_lookup_srv: "
+               "%d records returned in the answer section.\n",
                answer_count));
-               
-       if ( (dcs = TALLOC_ZERO_ARRAY(ctx, struct dns_rr_srv, answer_count)) == NULL ) {
-               DEBUG(0,("ads_dns_lookup_srv: talloc() failure for %d char*'s\n", 
-                       answer_count));
-               return NT_STATUS_NO_MEMORY;
+
+       if (answer_count) {
+               if ((dcs = TALLOC_ZERO_ARRAY(ctx, struct dns_rr_srv,
+                                               answer_count)) == NULL ) {
+                       DEBUG(0,("ads_dns_lookup_srv: "
+                               "talloc() failure for %d char*'s\n",
+                               answer_count));
+                       return NT_STATUS_NO_MEMORY;
+               }
+       } else {
+               dcs = NULL;
        }
 
        /* now skip the header */
@@ -360,8 +462,10 @@ static NTSTATUS ads_dns_lookup_srv( TALLOC_CTX *ctx, const char *name, struct dn
        for ( rrnum=0; rrnum<query_count; rrnum++ ) {
                struct dns_query q;
 
-               if ( !ads_dns_parse_query( ctx, buffer, buffer+resp_len, &p, &q ) ) {
-                       DEBUG(1,("ads_dns_lookup_srv: Failed to parse query record!\n"));
+               if (!ads_dns_parse_query(ctx, buffer,
+                                       buffer+resp_len, &p, &q)) {
+                       DEBUG(1,("ads_dns_lookup_srv: "
+                                "Failed to parse query record [%d]!\n", rrnum));
                        return NT_STATUS_UNSUCCESSFUL;
                }
        }
@@ -369,10 +473,12 @@ static NTSTATUS ads_dns_lookup_srv( TALLOC_CTX *ctx, const char *name, struct dn
        /* now we are at the answer section */
 
        for ( rrnum=0; rrnum<answer_count; rrnum++ ) {
-               if ( !ads_dns_parse_rr_srv( ctx, buffer, buffer+resp_len, &p, &dcs[rrnum] ) ) {
-                       DEBUG(1,("ads_dns_lookup_srv: Failed to parse answer record!\n"));
+               if (!ads_dns_parse_rr_srv(ctx, buffer, buffer+resp_len,
+                                       &p, &dcs[rrnum])) {
+                       DEBUG(1,("ads_dns_lookup_srv: "
+                                "Failed to parse answer recordi [%d]!\n", rrnum));
                        return NT_STATUS_UNSUCCESSFUL;
-               }               
+               }
        }
        idx = rrnum;
 
@@ -382,8 +488,10 @@ static NTSTATUS ads_dns_lookup_srv( TALLOC_CTX *ctx, const char *name, struct dn
        for ( rrnum=0; rrnum<auth_count; rrnum++ ) {
                struct dns_rr rr;
 
-               if ( !ads_dns_parse_rr( ctx, buffer, buffer+resp_len, &p, &rr ) ) {
-                       DEBUG(1,("ads_dns_lookup_srv: Failed to parse authority record!\n"));
+               if (!ads_dns_parse_rr( ctx, buffer,
+                                       buffer+resp_len, &p, &rr)) {
+                       DEBUG(1,("ads_dns_lookup_srv: "
+                                "Failed to parse authority record! [%d]\n", rrnum));
                        return NT_STATUS_UNSUCCESSFUL;
                }
        }
@@ -394,58 +502,82 @@ static NTSTATUS ads_dns_lookup_srv( TALLOC_CTX *ctx, const char *name, struct dn
                struct dns_rr rr;
                int i;
 
-               if ( !ads_dns_parse_rr( ctx, buffer, buffer+resp_len, &p, &rr ) ) {
-                       DEBUG(1,("ads_dns_lookup_srv: Failed to parse additional records section!\n"));
+               if (!ads_dns_parse_rr(ctx, buffer, buffer+resp_len,
+                                       &p, &rr)) {
+                       DEBUG(1,("ads_dns_lookup_srv: Failed "
+                                "to parse additional records section! [%d]\n", rrnum));
                        return NT_STATUS_UNSUCCESSFUL;
                }
 
-               /* only interested in A records as a shortcut for having to come 
-                  back later and lookup the name.  For multi-homed hosts, the 
-                  number of additional records and exceed the number of answer 
-                  records. */
-                 
-
-               if ( (rr.type != T_A) || (rr.rdatalen != 4) ) 
-                       continue;
+               /* Only interested in A or AAAA records as a shortcut for having
+                * to come back later and lookup the name. For multi-homed
+                * hosts, the number of additional records and exceed the
+                * number of answer records. */
+
+               if (rr.type != T_A || rr.rdatalen != 4) {
+#if defined(HAVE_IPV6)
+                       /* RFC2874 defines A6 records. This
+                        * requires recusive and horribly complex lookups.
+                        * Bastards. Ignore this for now.... JRA.
+                        * Luckily RFC3363 reprecates A6 records.
+                        */
+                       if (rr.type != T_AAAA || rr.rdatalen != 16)
+#endif
+                               continue;
+               }
 
                for ( i=0; i<idx; i++ ) {
                        if ( strcmp( rr.hostname, dcs[i].hostname ) == 0 ) {
                                int num_ips = dcs[i].num_ips;
-                               uint8 *buf;
-                               struct in_addr *tmp_ips;
+                               struct sockaddr_storage *tmp_ss_s;
 
                                /* allocate new memory */
-                               
-                               if ( dcs[i].num_ips == 0 ) {
-                                       if ( (dcs[i].ips = TALLOC_ARRAY( dcs, 
-                                               struct in_addr, 1 )) == NULL ) 
-                                       {
+
+                               if (dcs[i].num_ips == 0) {
+                                       if ((dcs[i].ss_s = talloc_array(dcs,
+                                               struct sockaddr_storage, 1 ))
+                                                       == NULL ) {
                                                return NT_STATUS_NO_MEMORY;
                                        }
                                } else {
-                                       if ( (tmp_ips = TALLOC_REALLOC_ARRAY( dcs, dcs[i].ips,
-                                               struct in_addr, dcs[i].num_ips+1)) == NULL ) 
-                                       {
+                                       if ((tmp_ss_s = talloc_realloc(dcs,
+                                                       dcs[i].ss_s,
+                                                       struct sockaddr_storage,
+                                                       dcs[i].num_ips+1))
+                                                               == NULL ) {
                                                return NT_STATUS_NO_MEMORY;
                                        }
-                                       
-                                       dcs[i].ips = tmp_ips;
+
+                                       dcs[i].ss_s = tmp_ss_s;
                                }
                                dcs[i].num_ips++;
-                               
+
                                /* copy the new IP address */
-                               
-                               buf = (uint8*)&dcs[i].ips[num_ips].s_addr;
-                               memcpy( buf, rr.rdata, 4 );
+                               if (rr.type == T_A) {
+                                       struct in_addr ip;
+                                       memcpy(&ip, rr.rdata, 4);
+                                       in_addr_to_sockaddr_storage(
+                                                       &dcs[i].ss_s[num_ips],
+                                                       ip);
+                               }
+#if defined(HAVE_IPV6)
+                               if (rr.type == T_AAAA) {
+                                       struct in6_addr ip6;
+                                       memcpy(&ip6, rr.rdata, rr.rdatalen);
+                                       in6_addr_to_sockaddr_storage(
+                                                       &dcs[i].ss_s[num_ips],
+                                                       ip6);
+                               }
+#endif
                        }
                }
        }
 
-       qsort( dcs, idx, sizeof(struct dns_rr_srv), QSORT_CAST dnssrvcmp );
-       
+       TYPESAFE_QSORT(dcs, idx, dnssrvcmp );
+
        *dclist = dcs;
        *numdcs = idx;
-       
+
        return NT_STATUS_OK;
 }
 
@@ -453,7 +585,10 @@ static NTSTATUS ads_dns_lookup_srv( TALLOC_CTX *ctx, const char *name, struct dn
  Simple wrapper for a DNS NS query
 *********************************************************************/
 
-NTSTATUS ads_dns_lookup_ns( TALLOC_CTX *ctx, const char *dnsdomain, struct dns_rr_ns **nslist, int *numns )
+NTSTATUS ads_dns_lookup_ns(TALLOC_CTX *ctx,
+                               const char *dnsdomain,
+                               struct dns_rr_ns **nslist,
+                               int *numns)
 {
        uint8 *buffer = NULL;
        int resp_len = 0;
@@ -463,14 +598,21 @@ NTSTATUS ads_dns_lookup_ns( TALLOC_CTX *ctx, const char *dnsdomain, struct dns_r
        int rrnum;
        int idx = 0;
        NTSTATUS status;
+       const char *dns_hosts_file;
 
        if ( !ctx || !dnsdomain || !nslist ) {
                return NT_STATUS_INVALID_PARAMETER;
        }
-       
-       /* Send the request.  May have to loop several times in case 
+
+       dns_hosts_file = lp_parm_const_string(-1, "resolv", "host file", NULL);
+       if (dns_hosts_file) {
+               DEBUG(1, ("NO 'NS' lookup available when using resolv:host file"));
+               return NT_STATUS_OBJECT_NAME_NOT_FOUND;
+       }
+
+       /* Send the request.  May have to loop several times in case
           of large replies */
-          
+
        status = dns_send_req( ctx, dnsdomain, T_NS, &buffer, &resp_len );
        if ( !NT_STATUS_IS_OK(status) ) {
                DEBUG(3,("ads_dns_lookup_ns: Failed to send DNS query (%s)\n",
@@ -483,20 +625,28 @@ NTSTATUS ads_dns_lookup_ns( TALLOC_CTX *ctx, const char *dnsdomain, struct dns_r
           available in libresolv.a, and not the shared lib.  Who knows why....
           So we have to parse the DNS reply ourselves */
 
-       /* Pull the answer RR's count from the header.  Use the NMB ordering macros */
+       /* Pull the answer RR's count from the header.
+        * Use the NMB ordering macros */
 
        query_count      = RSVAL( p, 4 );
        answer_count     = RSVAL( p, 6 );
        auth_count       = RSVAL( p, 8 );
        additional_count = RSVAL( p, 10 );
 
-       DEBUG(4,("ads_dns_lookup_ns: %d records returned in the answer section.\n", 
+       DEBUG(4,("ads_dns_lookup_ns: "
+               "%d records returned in the answer section.\n",
                answer_count));
-               
-       if ( (nsarray = TALLOC_ARRAY(ctx, struct dns_rr_ns, answer_count)) == NULL ) {
-               DEBUG(0,("ads_dns_lookup_ns: talloc() failure for %d char*'s\n", 
-                       answer_count));
-               return NT_STATUS_NO_MEMORY;
+
+       if (answer_count) {
+               if ((nsarray = talloc_array(ctx, struct dns_rr_ns,
+                                               answer_count)) == NULL ) {
+                       DEBUG(0,("ads_dns_lookup_ns: "
+                               "talloc() failure for %d char*'s\n",
+                               answer_count));
+                       return NT_STATUS_NO_MEMORY;
+               }
+       } else {
+               nsarray = NULL;
        }
 
        /* now skip the header */
@@ -508,8 +658,10 @@ NTSTATUS ads_dns_lookup_ns( TALLOC_CTX *ctx, const char *dnsdomain, struct dns_r
        for ( rrnum=0; rrnum<query_count; rrnum++ ) {
                struct dns_query q;
 
-               if ( !ads_dns_parse_query( ctx, buffer, buffer+resp_len, &p, &q ) ) {
-                       DEBUG(1,("ads_dns_lookup_ns: Failed to parse query record!\n"));
+               if (!ads_dns_parse_query(ctx, buffer, buffer+resp_len,
+                                       &p, &q)) {
+                       DEBUG(1,("ads_dns_lookup_ns: "
+                               " Failed to parse query record!\n"));
                        return NT_STATUS_UNSUCCESSFUL;
                }
        }
@@ -517,10 +669,12 @@ NTSTATUS ads_dns_lookup_ns( TALLOC_CTX *ctx, const char *dnsdomain, struct dns_r
        /* now we are at the answer section */
 
        for ( rrnum=0; rrnum<answer_count; rrnum++ ) {
-               if ( !ads_dns_parse_rr_ns( ctx, buffer, buffer+resp_len, &p, &nsarray[rrnum] ) ) {
-                       DEBUG(1,("ads_dns_lookup_ns: Failed to parse answer record!\n"));
+               if (!ads_dns_parse_rr_ns(ctx, buffer, buffer+resp_len,
+                                       &p, &nsarray[rrnum])) {
+                       DEBUG(1,("ads_dns_lookup_ns: "
+                               "Failed to parse answer record!\n"));
                        return NT_STATUS_UNSUCCESSFUL;
-               }               
+               }
        }
        idx = rrnum;
 
@@ -530,8 +684,10 @@ NTSTATUS ads_dns_lookup_ns( TALLOC_CTX *ctx, const char *dnsdomain, struct dns_r
        for ( rrnum=0; rrnum<auth_count; rrnum++ ) {
                struct dns_rr rr;
 
-               if ( !ads_dns_parse_rr( ctx, buffer, buffer+resp_len, &p, &rr ) ) {
-                       DEBUG(1,("ads_dns_lookup_ns: Failed to parse authority record!\n"));
+               if ( !ads_dns_parse_rr(ctx, buffer, buffer+resp_len,
+                                       &p, &rr)) {
+                       DEBUG(1,("ads_dns_lookup_ns: "
+                               "Failed to parse authority record!\n"));
                        return NT_STATUS_UNSUCCESSFUL;
                }
        }
@@ -542,130 +698,72 @@ NTSTATUS ads_dns_lookup_ns( TALLOC_CTX *ctx, const char *dnsdomain, struct dns_r
                struct dns_rr rr;
                int i;
 
-               if ( !ads_dns_parse_rr( ctx, buffer, buffer+resp_len, &p, &rr ) ) {
-                       DEBUG(1,("ads_dns_lookup_ns: Failed to parse additional records section!\n"));
+               if (!ads_dns_parse_rr(ctx, buffer, buffer+resp_len,
+                                       &p, &rr)) {
+                       DEBUG(1,("ads_dns_lookup_ns: Failed "
+                               "to parse additional records section!\n"));
                        return NT_STATUS_UNSUCCESSFUL;
                }
 
-               /* only interested in A records as a shortcut for having to come 
+               /* only interested in A records as a shortcut for having to come
                   back later and lookup the name */
 
-               if ( (rr.type != T_A) || (rr.rdatalen != 4) ) 
-                       continue;
+               if (rr.type != T_A || rr.rdatalen != 4) {
+#if defined(HAVE_IPV6)
+                       if (rr.type != T_AAAA || rr.rdatalen != 16)
+#endif
+                               continue;
+               }
 
                for ( i=0; i<idx; i++ ) {
-                       if ( strcmp( rr.hostname, nsarray[i].hostname ) == 0 ) {
-                               uint8 *buf = (uint8*)&nsarray[i].ip.s_addr;
-                               memcpy( buf, rr.rdata, 4 );
+                       if (strcmp(rr.hostname, nsarray[i].hostname) == 0) {
+                               if (rr.type == T_A) {
+                                       struct in_addr ip;
+                                       memcpy(&ip, rr.rdata, 4);
+                                       in_addr_to_sockaddr_storage(
+                                                       &nsarray[i].ss,
+                                                       ip);
+                               }
+#if defined(HAVE_IPV6)
+                               if (rr.type == T_AAAA) {
+                                       struct in6_addr ip6;
+                                       memcpy(&ip6, rr.rdata, rr.rdatalen);
+                                       in6_addr_to_sockaddr_storage(
+                                                       &nsarray[i].ss,
+                                                       ip6);
+                               }
+#endif
                        }
                }
        }
-       
+
        *nslist = nsarray;
        *numns = idx;
-       
-       return NT_STATUS_OK;
-}
-
-/****************************************************************************
- Store and fetch the AD client sitename.
-****************************************************************************/
-
-#define SITENAME_KEY   "AD_SITENAME"
 
-/****************************************************************************
- Store the AD client sitename.
- We store indefinately as every new CLDAP query will re-write this.
- If the sitename is "Default-First-Site-Name" we don't store it
- as this isn't a valid DNS name.
-****************************************************************************/
-
-BOOL sitename_store(const char *sitename)
-{
-       time_t expire;
-       BOOL ret = False;
-
-       if (!gencache_init()) {
-               return False;
-       }
-       
-       if (!sitename || (sitename && !*sitename)) {
-               DEBUG(5,("sitename_store: deleting empty sitename!\n"));
-               return gencache_del(SITENAME_KEY);
-       }
-
-       expire = get_time_t_max(); /* Store indefinately. */
-       
-       DEBUG(10,("sitename_store: sitename = [%s], expire = [%u]\n",
-               sitename, (unsigned int)expire ));
-
-       ret = gencache_set( SITENAME_KEY, sitename, expire );
-       return ret;
-}
-
-/****************************************************************************
- Fetch the AD client sitename.
- Caller must free.
-****************************************************************************/
-
-char *sitename_fetch(void)
-{
-       char *sitename = NULL;
-       time_t timeout;
-       BOOL ret = False;
-       
-       if (!gencache_init()) {
-               return False;
-       }
-       
-       ret = gencache_get( SITENAME_KEY, &sitename, &timeout );
-       if ( !ret ) {
-               DEBUG(5,("sitename_fetch: No stored sitename\n"));
-       } else {
-               DEBUG(5,("sitename_fetch: Returning sitename \"%s\"\n",
-                       sitename ));
-       }
-       return sitename;
-}
-
-/****************************************************************************
- Did the sitename change ?
-****************************************************************************/
-
-BOOL stored_sitename_changed(const char *sitename)
-{
-       BOOL ret = False;
-       char *new_sitename = sitename_fetch();
-
-       if (sitename && new_sitename && !strequal(sitename, new_sitename)) {
-               ret = True;
-       } else if ((sitename && !new_sitename) ||
-                       (!sitename && new_sitename)) {
-               ret = True;
-       }
-       SAFE_FREE(new_sitename);
-       return ret;
+       return NT_STATUS_OK;
 }
 
 /********************************************************************
  Query with optional sitename.
 ********************************************************************/
 
-NTSTATUS ads_dns_query_internal(TALLOC_CTX *ctx,
-                               const char *servicename,
-                               const char *realm,
-                               const char *sitename,
-                               struct dns_rr_srv **dclist,
-                               int *numdcs )
+static NTSTATUS ads_dns_query_internal(TALLOC_CTX *ctx,
+                                      const char *servicename,
+                                      const char *dc_pdc_gc_domains,
+                                      const char *realm,
+                                      const char *sitename,
+                                      struct dns_rr_srv **dclist,
+                                      int *numdcs )
 {
        char *name;
        if (sitename) {
-               name = talloc_asprintf(ctx, "%s._tcp.%s._sites.dc._msdcs.%s",
-                               servicename, sitename, realm );
-       } else {
-               name = talloc_asprintf(ctx, "%s._tcp.dc._msdcs.%s",
-                               servicename, realm );
-       }
+               name = talloc_asprintf(ctx, "%s._tcp.%s._sites.%s._msdcs.%s",
+                                      servicename, sitename,
+                                      dc_pdc_gc_domains, realm);
+       } else {
+               name = talloc_asprintf(ctx, "%s._tcp.%s._msdcs.%s",
+                               servicename, dc_pdc_gc_domains, realm);
+       }
        if (!name) {
                return NT_STATUS_NO_MEMORY;
        }
@@ -677,19 +775,57 @@ NTSTATUS ads_dns_query_internal(TALLOC_CTX *ctx,
 ********************************************************************/
 
 NTSTATUS ads_dns_query_dcs(TALLOC_CTX *ctx,
-                       const char *realm,
-                       const char *sitename,
-                       struct dns_rr_srv **dclist,
-                       int *numdcs )
+                          const char *realm,
+                          const char *sitename,
+                          struct dns_rr_srv **dclist,
+                          int *numdcs )
 {
        NTSTATUS status;
 
-       status = ads_dns_query_internal(ctx, "_ldap", realm, sitename,
+       status = ads_dns_query_internal(ctx, "_ldap", "dc", realm, sitename,
                                        dclist, numdcs);
-       if (sitename && !NT_STATUS_IS_OK(status)) {
+
+       if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) ||
+           NT_STATUS_EQUAL(status, NT_STATUS_CONNECTION_REFUSED)) {
+               return status;
+       }
+
+       if (sitename &&
+           ((!NT_STATUS_IS_OK(status)) ||
+            (NT_STATUS_IS_OK(status) && (numdcs == 0)))) {
                /* Sitename DNS query may have failed. Try without. */
-               status = ads_dns_query_internal(ctx, "_ldap", realm, NULL,
-                                               dclist, numdcs);
+               status = ads_dns_query_internal(ctx, "_ldap", "dc", realm,
+                                               NULL, dclist, numdcs);
+       }
+       return status;
+}
+
+/********************************************************************
+ Query for AD GC's.
+********************************************************************/
+
+NTSTATUS ads_dns_query_gcs(TALLOC_CTX *ctx,
+                          const char *realm,
+                          const char *sitename,
+                          struct dns_rr_srv **dclist,
+                          int *numdcs )
+{
+       NTSTATUS status;
+
+       status = ads_dns_query_internal(ctx, "_ldap", "gc", realm, sitename,
+                                       dclist, numdcs);
+
+       if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) ||
+           NT_STATUS_EQUAL(status, NT_STATUS_CONNECTION_REFUSED)) {
+               return status;
+       }
+
+       if (sitename &&
+           ((!NT_STATUS_IS_OK(status)) ||
+            (NT_STATUS_IS_OK(status) && (numdcs == 0)))) {
+               /* Sitename DNS query may have failed. Try without. */
+               status = ads_dns_query_internal(ctx, "_ldap", "gc", realm,
+                                               NULL, dclist, numdcs);
        }
        return status;
 }
@@ -701,19 +837,73 @@ NTSTATUS ads_dns_query_dcs(TALLOC_CTX *ctx,
 ********************************************************************/
 
 NTSTATUS ads_dns_query_kdcs(TALLOC_CTX *ctx,
-                       const char *realm,
-                       const char *sitename,
-                       struct dns_rr_srv **dclist,
-                       int *numdcs )
+                           const char *dns_forest_name,
+                           const char *sitename,
+                           struct dns_rr_srv **dclist,
+                           int *numdcs )
 {
        NTSTATUS status;
 
-       status = ads_dns_query_internal(ctx, "_kerberos", realm, sitename,
-                                       dclist, numdcs);
-       if (sitename && !NT_STATUS_IS_OK(status)) {
+       status = ads_dns_query_internal(ctx, "_kerberos", "dc",
+                                       dns_forest_name, sitename, dclist,
+                                       numdcs);
+
+       if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) ||
+           NT_STATUS_EQUAL(status, NT_STATUS_CONNECTION_REFUSED)) {
+               return status;
+       }
+
+       if (sitename &&
+           ((!NT_STATUS_IS_OK(status)) ||
+            (NT_STATUS_IS_OK(status) && (numdcs == 0)))) {
                /* Sitename DNS query may have failed. Try without. */
-               status = ads_dns_query_internal(ctx, "_kerberos", realm, NULL,
+               status = ads_dns_query_internal(ctx, "_kerberos", "dc",
+                                               dns_forest_name, NULL,
                                                dclist, numdcs);
        }
        return status;
 }
+
+/********************************************************************
+ Query for AD PDC. Sitename is obsolete here.
+********************************************************************/
+
+NTSTATUS ads_dns_query_pdc(TALLOC_CTX *ctx,
+                          const char *dns_domain_name,
+                          struct dns_rr_srv **dclist,
+                          int *numdcs )
+{
+       return ads_dns_query_internal(ctx, "_ldap", "pdc", dns_domain_name,
+                                     NULL, dclist, numdcs);
+}
+
+/********************************************************************
+ Query for AD DC by guid. Sitename is obsolete here.
+********************************************************************/
+
+NTSTATUS ads_dns_query_dcs_guid(TALLOC_CTX *ctx,
+                               const char *dns_forest_name,
+                               const struct GUID *domain_guid,
+                               struct dns_rr_srv **dclist,
+                               int *numdcs )
+{
+       /*_ldap._tcp.DomainGuid.domains._msdcs.DnsForestName */
+
+       const char *domains;
+       char *guid_string;
+
+       guid_string = GUID_string(ctx, domain_guid);
+       if (!guid_string) {
+               return NT_STATUS_NO_MEMORY;
+       }
+
+       /* little hack */
+       domains = talloc_asprintf(ctx, "%s.domains", guid_string);
+       if (!domains) {
+               return NT_STATUS_NO_MEMORY;
+       }
+       TALLOC_FREE(guid_string);
+
+       return ads_dns_query_internal(ctx, "_ldap", domains, dns_forest_name,
+                                     NULL, dclist, numdcs);
+}