s3-ads-dns: Break dependency on lp_parm
[sfrench/samba-autobuild/.git] / source3 / libads / dns.c
1 /*
2    Unix SMB/CIFS implementation.
3    DNS utility library
4    Copyright (C) Gerald (Jerry) Carter           2006.
5    Copyright (C) Jeremy Allison                  2007.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "includes.h"
22 #include "libads/dns.h"
23 #include "../librpc/ndr/libndr.h"
24
25 /* AIX resolv.h uses 'class' in struct ns_rr */
26
27 #if defined(AIX)
28 #  if defined(class)
29 #    undef class
30 #  endif
31 #endif  /* AIX */
32
33 /* resolver headers */
34
35 #include <sys/types.h>
36 #include <netinet/in.h>
37 #include <arpa/nameser.h>
38 #include <resolv.h>
39 #include <netdb.h>
40
41 #define MAX_DNS_PACKET_SIZE 0xffff
42
43 #ifdef NS_HFIXEDSZ      /* Bind 8/9 interface */
44 #if !defined(C_IN)      /* AIX 5.3 already defines C_IN */
45 #  define C_IN          ns_c_in
46 #endif
47 #if !defined(T_A)       /* AIX 5.3 already defines T_A */
48 #  define T_A           ns_t_a
49 #endif
50
51 #if defined(HAVE_IPV6)
52 #if !defined(T_AAAA)
53 #  define T_AAAA        ns_t_aaaa
54 #endif
55 #endif
56
57 #  define T_SRV         ns_t_srv
58 #if !defined(T_NS)      /* AIX 5.3 already defines T_NS */
59 #  define T_NS          ns_t_ns
60 #endif
61 #else
62 #  ifdef HFIXEDSZ
63 #    define NS_HFIXEDSZ HFIXEDSZ
64 #  else
65 #    define NS_HFIXEDSZ sizeof(HEADER)
66 #  endif        /* HFIXEDSZ */
67 #  ifdef PACKETSZ
68 #    define NS_PACKETSZ PACKETSZ
69 #  else /* 512 is usually the default */
70 #    define NS_PACKETSZ 512
71 #  endif        /* PACKETSZ */
72 #  define T_SRV         33
73 #endif
74
75 /*********************************************************************
76 *********************************************************************/
77
78 static bool ads_dns_parse_query( TALLOC_CTX *ctx, uint8_t *start, uint8_t *end,
79                           uint8_t **ptr, struct dns_query *q )
80 {
81         uint8_t *p = *ptr;
82         char hostname[MAX_DNS_NAME_LENGTH];
83         int namelen;
84
85         ZERO_STRUCTP( q );
86
87         if ( !start || !end || !q || !*ptr)
88                 return false;
89
90         /* See RFC 1035 for details. If this fails, then return. */
91
92         namelen = dn_expand( start, end, p, hostname, sizeof(hostname) );
93         if ( namelen < 0 ) {
94                 return false;
95         }
96         p += namelen;
97         q->hostname = talloc_strdup( ctx, hostname );
98
99         /* check that we have space remaining */
100
101         if ( PTR_DIFF(p+4, end) > 0 )
102                 return false;
103
104         q->type     = RSVAL( p, 0 );
105         q->in_class = RSVAL( p, 2 );
106         p += 4;
107
108         *ptr = p;
109
110         return true;
111 }
112
113 /*********************************************************************
114 *********************************************************************/
115
116 static bool ads_dns_parse_rr( TALLOC_CTX *ctx, uint8_t *start, uint8_t *end,
117                        uint8_t **ptr, struct dns_rr *rr )
118 {
119         uint8_t *p = *ptr;
120         char hostname[MAX_DNS_NAME_LENGTH];
121         int namelen;
122
123         if ( !start || !end || !rr || !*ptr)
124                 return -1;
125
126         ZERO_STRUCTP( rr );
127         /* pull the name from the answer */
128
129         namelen = dn_expand( start, end, p, hostname, sizeof(hostname) );
130         if ( namelen < 0 ) {
131                 return -1;
132         }
133         p += namelen;
134         rr->hostname = talloc_strdup( ctx, hostname );
135
136         /* check that we have space remaining */
137
138         if ( PTR_DIFF(p+10, end) > 0 )
139                 return false;
140
141         /* pull some values and then skip onto the string */
142
143         rr->type     = RSVAL(p, 0);
144         rr->in_class = RSVAL(p, 2);
145         rr->ttl      = RIVAL(p, 4);
146         rr->rdatalen = RSVAL(p, 8);
147
148         p += 10;
149
150         /* sanity check the available space */
151
152         if ( PTR_DIFF(p+rr->rdatalen, end ) > 0 ) {
153                 return false;
154
155         }
156
157         /* save a point to the rdata for this section */
158
159         rr->rdata = p;
160         p += rr->rdatalen;
161
162         *ptr = p;
163
164         return true;
165 }
166
167 /*********************************************************************
168 *********************************************************************/
169
170 static bool ads_dns_parse_rr_srv( TALLOC_CTX *ctx, uint8_t *start, uint8_t *end,
171                        uint8_t **ptr, struct dns_rr_srv *srv )
172 {
173         struct dns_rr rr;
174         uint8_t *p;
175         char dcname[MAX_DNS_NAME_LENGTH];
176         int namelen;
177
178         if ( !start || !end || !srv || !*ptr)
179                 return -1;
180
181         /* Parse the RR entry.  Coming out of the this, ptr is at the beginning
182            of the next record */
183
184         if ( !ads_dns_parse_rr( ctx, start, end, ptr, &rr ) ) {
185                 DEBUG(1,("ads_dns_parse_rr_srv: Failed to parse RR record\n"));
186                 return false;
187         }
188
189         if ( rr.type != T_SRV ) {
190                 DEBUG(1,("ads_dns_parse_rr_srv: Bad answer type (%d)\n",
191                                         rr.type));
192                 return false;
193         }
194
195         p = rr.rdata;
196
197         srv->priority = RSVAL(p, 0);
198         srv->weight   = RSVAL(p, 2);
199         srv->port     = RSVAL(p, 4);
200
201         p += 6;
202
203         namelen = dn_expand( start, end, p, dcname, sizeof(dcname) );
204         if ( namelen < 0 ) {
205                 DEBUG(1,("ads_dns_parse_rr_srv: Failed to uncompress name!\n"));
206                 return false;
207         }
208
209         srv->hostname = talloc_strdup( ctx, dcname );
210
211         DEBUG(10,("ads_dns_parse_rr_srv: Parsed %s [%u, %u, %u]\n", 
212                   srv->hostname, 
213                   srv->priority,
214                   srv->weight,
215                   srv->port));
216
217         return true;
218 }
219
220 /*********************************************************************
221 *********************************************************************/
222
223 static bool ads_dns_parse_rr_ns( TALLOC_CTX *ctx, uint8_t *start, uint8_t *end,
224                        uint8_t **ptr, struct dns_rr_ns *nsrec )
225 {
226         struct dns_rr rr;
227         uint8_t *p;
228         char nsname[MAX_DNS_NAME_LENGTH];
229         int namelen;
230
231         if ( !start || !end || !nsrec || !*ptr)
232                 return -1;
233
234         /* Parse the RR entry.  Coming out of the this, ptr is at the beginning
235            of the next record */
236
237         if ( !ads_dns_parse_rr( ctx, start, end, ptr, &rr ) ) {
238                 DEBUG(1,("ads_dns_parse_rr_ns: Failed to parse RR record\n"));
239                 return false;
240         }
241
242         if ( rr.type != T_NS ) {
243                 DEBUG(1,("ads_dns_parse_rr_ns: Bad answer type (%d)\n",
244                                         rr.type));
245                 return false;
246         }
247
248         p = rr.rdata;
249
250         /* ame server hostname */
251
252         namelen = dn_expand( start, end, p, nsname, sizeof(nsname) );
253         if ( namelen < 0 ) {
254                 DEBUG(1,("ads_dns_parse_rr_ns: Failed to uncompress name!\n"));
255                 return false;
256         }
257         nsrec->hostname = talloc_strdup( ctx, nsname );
258
259         return true;
260 }
261
262 /*********************************************************************
263  Sort SRV record list based on weight and priority.  See RFC 2782.
264 *********************************************************************/
265
266 static int dnssrvcmp( struct dns_rr_srv *a, struct dns_rr_srv *b )
267 {
268         if ( a->priority == b->priority ) {
269
270                 /* randomize entries with an equal weight and priority */
271                 if ( a->weight == b->weight )
272                         return 0;
273
274                 /* higher weights should be sorted lower */
275                 if ( a->weight > b->weight )
276                         return -1;
277                 else
278                         return 1;
279         }
280
281         if ( a->priority < b->priority )
282                 return -1;
283
284         return 1;
285 }
286
287 /*********************************************************************
288  Simple wrapper for a DNS query
289 *********************************************************************/
290
291 #define DNS_FAILED_WAITTIME          30
292
293 static NTSTATUS dns_send_req( TALLOC_CTX *ctx, const char *name, int q_type,
294                               uint8_t **buf, int *resp_length )
295 {
296         uint8_t *buffer = NULL;
297         size_t buf_len = 0;
298         int resp_len = NS_PACKETSZ;
299         static time_t last_dns_check = 0;
300         static NTSTATUS last_dns_status = NT_STATUS_OK;
301         time_t now = time_mono(NULL);
302
303         /* Try to prevent bursts of DNS lookups if the server is down */
304
305         /* Protect against large clock changes */
306
307         if ( last_dns_check > now )
308                 last_dns_check = 0;
309
310         /* IF we had a DNS timeout or a bad server and we are still
311            in the 30 second cache window, just return the previous
312            status and save the network timeout. */
313
314         if ( (NT_STATUS_EQUAL(last_dns_status,NT_STATUS_IO_TIMEOUT) ||
315               NT_STATUS_EQUAL(last_dns_status,NT_STATUS_CONNECTION_REFUSED)) &&
316              (last_dns_check+DNS_FAILED_WAITTIME) > now )
317         {
318                 DEBUG(10,("last_dns_check: Returning cached status (%s)\n",
319                           nt_errstr(last_dns_status) ));
320                 return last_dns_status;
321         }
322
323         /* Send the Query */
324         do {
325                 if ( buffer )
326                         TALLOC_FREE( buffer );
327
328                 buf_len = resp_len * sizeof(uint8_t);
329
330                 if (buf_len) {
331                         if ((buffer = talloc_array(ctx, uint8_t, buf_len))
332                                         == NULL ) {
333                                 DEBUG(0,("ads_dns_lookup_srv: "
334                                         "talloc() failed!\n"));
335                                 last_dns_status = NT_STATUS_NO_MEMORY;
336                                 last_dns_check = time_mono(NULL);
337                                 return last_dns_status;
338                         }
339                 }
340
341                 if ((resp_len = res_query(name, C_IN, q_type, buffer, buf_len))
342                                 < 0 ) {
343                         DEBUG(3,("ads_dns_lookup_srv: "
344                                 "Failed to resolve %s (%s)\n",
345                                 name, strerror(errno)));
346                         TALLOC_FREE( buffer );
347                         last_dns_status = NT_STATUS_UNSUCCESSFUL;
348
349                         if (errno == ETIMEDOUT) {
350                                 last_dns_status = NT_STATUS_IO_TIMEOUT;
351                         }
352                         if (errno == ECONNREFUSED) {
353                                 last_dns_status = NT_STATUS_CONNECTION_REFUSED;
354                         }
355                         last_dns_check = time_mono(NULL);
356                         return last_dns_status;
357                 }
358
359                 /* On AIX, Solaris, and possibly some older glibc systems (e.g. SLES8)
360                    truncated replies never give back a resp_len > buflen
361                    which ends up causing DNS resolve failures on large tcp DNS replies */
362
363                 if (buf_len == resp_len) {
364                         if (resp_len == MAX_DNS_PACKET_SIZE) {
365                                 DEBUG(1,("dns_send_req: DNS reply too large when resolving %s\n",
366                                         name));
367                                 TALLOC_FREE( buffer );
368                                 last_dns_status = NT_STATUS_BUFFER_TOO_SMALL;
369                                 last_dns_check = time_mono(NULL);
370                                 return last_dns_status;
371                         }
372
373                         resp_len = MIN(resp_len*2, MAX_DNS_PACKET_SIZE);
374                 }
375
376
377         } while ( buf_len < resp_len && resp_len <= MAX_DNS_PACKET_SIZE );
378
379         *buf = buffer;
380         *resp_length = resp_len;
381
382         last_dns_check = time_mono(NULL);
383         last_dns_status = NT_STATUS_OK;
384         return last_dns_status;
385 }
386
387 /*********************************************************************
388  Simple wrapper for a DNS SRV query
389 *********************************************************************/
390
391 static NTSTATUS ads_dns_lookup_srv( TALLOC_CTX *ctx,
392                                 const char *dns_hosts_file,
393                                 const char *name,
394                                 struct dns_rr_srv **dclist,
395                                 int *numdcs)
396 {
397         uint8_t *buffer = NULL;
398         int resp_len = 0;
399         struct dns_rr_srv *dcs = NULL;
400         int query_count, answer_count, auth_count, additional_count;
401         uint8_t *p = buffer;
402         int rrnum;
403         int idx = 0;
404         NTSTATUS status;
405
406         if ( !ctx || !name || !dclist ) {
407                 return NT_STATUS_INVALID_PARAMETER;
408         }
409
410         if (dns_hosts_file) {
411                 return resolve_dns_hosts_file_as_dns_rr(dns_hosts_file,
412                                                         name, true, ctx,
413                                                         dclist, numdcs);
414         }
415
416         /* Send the request.  May have to loop several times in case
417            of large replies */
418
419         status = dns_send_req( ctx, name, T_SRV, &buffer, &resp_len );
420         if ( !NT_STATUS_IS_OK(status) ) {
421                 DEBUG(3,("ads_dns_lookup_srv: Failed to send DNS query (%s)\n",
422                         nt_errstr(status)));
423                 return status;
424         }
425         p = buffer;
426
427         /* For some insane reason, the ns_initparse() et. al. routines are only
428            available in libresolv.a, and not the shared lib.  Who knows why....
429            So we have to parse the DNS reply ourselves */
430
431         /* Pull the answer RR's count from the header.
432          * Use the NMB ordering macros */
433
434         query_count      = RSVAL( p, 4 );
435         answer_count     = RSVAL( p, 6 );
436         auth_count       = RSVAL( p, 8 );
437         additional_count = RSVAL( p, 10 );
438
439         DEBUG(4,("ads_dns_lookup_srv: "
440                 "%d records returned in the answer section.\n",
441                 answer_count));
442
443         if (answer_count) {
444                 if ((dcs = talloc_zero_array(ctx, struct dns_rr_srv,
445                                                 answer_count)) == NULL ) {
446                         DEBUG(0,("ads_dns_lookup_srv: "
447                                 "talloc() failure for %d char*'s\n",
448                                 answer_count));
449                         return NT_STATUS_NO_MEMORY;
450                 }
451         } else {
452                 dcs = NULL;
453         }
454
455         /* now skip the header */
456
457         p += NS_HFIXEDSZ;
458
459         /* parse the query section */
460
461         for ( rrnum=0; rrnum<query_count; rrnum++ ) {
462                 struct dns_query q;
463
464                 if (!ads_dns_parse_query(ctx, buffer,
465                                         buffer+resp_len, &p, &q)) {
466                         DEBUG(1,("ads_dns_lookup_srv: "
467                                  "Failed to parse query record [%d]!\n", rrnum));
468                         return NT_STATUS_UNSUCCESSFUL;
469                 }
470         }
471
472         /* now we are at the answer section */
473
474         for ( rrnum=0; rrnum<answer_count; rrnum++ ) {
475                 if (!ads_dns_parse_rr_srv(ctx, buffer, buffer+resp_len,
476                                         &p, &dcs[rrnum])) {
477                         DEBUG(1,("ads_dns_lookup_srv: "
478                                  "Failed to parse answer recordi [%d]!\n", rrnum));
479                         return NT_STATUS_UNSUCCESSFUL;
480                 }
481         }
482         idx = rrnum;
483
484         /* Parse the authority section */
485         /* just skip these for now */
486
487         for ( rrnum=0; rrnum<auth_count; rrnum++ ) {
488                 struct dns_rr rr;
489
490                 if (!ads_dns_parse_rr( ctx, buffer,
491                                         buffer+resp_len, &p, &rr)) {
492                         DEBUG(1,("ads_dns_lookup_srv: "
493                                  "Failed to parse authority record! [%d]\n", rrnum));
494                         return NT_STATUS_UNSUCCESSFUL;
495                 }
496         }
497
498         /* Parse the additional records section */
499
500         for ( rrnum=0; rrnum<additional_count; rrnum++ ) {
501                 struct dns_rr rr;
502                 int i;
503
504                 if (!ads_dns_parse_rr(ctx, buffer, buffer+resp_len,
505                                         &p, &rr)) {
506                         DEBUG(1,("ads_dns_lookup_srv: Failed "
507                                  "to parse additional records section! [%d]\n", rrnum));
508                         return NT_STATUS_UNSUCCESSFUL;
509                 }
510
511                 /* Only interested in A or AAAA records as a shortcut for having
512                  * to come back later and lookup the name. For multi-homed
513                  * hosts, the number of additional records and exceed the
514                  * number of answer records. */
515
516                 if (rr.type != T_A || rr.rdatalen != 4) {
517 #if defined(HAVE_IPV6)
518                         /* RFC2874 defines A6 records. This
519                          * requires recusive and horribly complex lookups.
520                          * Bastards. Ignore this for now.... JRA.
521                          * Luckily RFC3363 reprecates A6 records.
522                          */
523                         if (rr.type != T_AAAA || rr.rdatalen != 16)
524 #endif
525                                 continue;
526                 }
527
528                 for ( i=0; i<idx; i++ ) {
529                         if ( strcmp( rr.hostname, dcs[i].hostname ) == 0 ) {
530                                 int num_ips = dcs[i].num_ips;
531                                 struct sockaddr_storage *tmp_ss_s;
532
533                                 /* allocate new memory */
534
535                                 if (dcs[i].num_ips == 0) {
536                                         if ((dcs[i].ss_s = talloc_array(dcs,
537                                                 struct sockaddr_storage, 1 ))
538                                                         == NULL ) {
539                                                 return NT_STATUS_NO_MEMORY;
540                                         }
541                                 } else {
542                                         if ((tmp_ss_s = talloc_realloc(dcs,
543                                                         dcs[i].ss_s,
544                                                         struct sockaddr_storage,
545                                                         dcs[i].num_ips+1))
546                                                                 == NULL ) {
547                                                 return NT_STATUS_NO_MEMORY;
548                                         }
549
550                                         dcs[i].ss_s = tmp_ss_s;
551                                 }
552                                 dcs[i].num_ips++;
553
554                                 /* copy the new IP address */
555                                 if (rr.type == T_A) {
556                                         struct in_addr ip;
557                                         memcpy(&ip, rr.rdata, 4);
558                                         in_addr_to_sockaddr_storage(
559                                                         &dcs[i].ss_s[num_ips],
560                                                         ip);
561                                 }
562 #if defined(HAVE_IPV6)
563                                 if (rr.type == T_AAAA) {
564                                         struct in6_addr ip6;
565                                         memcpy(&ip6, rr.rdata, rr.rdatalen);
566                                         in6_addr_to_sockaddr_storage(
567                                                         &dcs[i].ss_s[num_ips],
568                                                         ip6);
569                                 }
570 #endif
571                         }
572                 }
573         }
574
575         TYPESAFE_QSORT(dcs, idx, dnssrvcmp );
576
577         *dclist = dcs;
578         *numdcs = idx;
579
580         return NT_STATUS_OK;
581 }
582
583 /*********************************************************************
584  Simple wrapper for a DNS NS query
585 *********************************************************************/
586
587 NTSTATUS ads_dns_lookup_ns(TALLOC_CTX *ctx,
588                                 const char *dns_hosts_file,
589                                 const char *dnsdomain,
590                                 struct dns_rr_ns **nslist,
591                                 int *numns)
592 {
593         uint8_t *buffer = NULL;
594         int resp_len = 0;
595         struct dns_rr_ns *nsarray = NULL;
596         int query_count, answer_count, auth_count, additional_count;
597         uint8_t *p;
598         int rrnum;
599         int idx = 0;
600         NTSTATUS status;
601
602         if ( !ctx || !dnsdomain || !nslist ) {
603                 return NT_STATUS_INVALID_PARAMETER;
604         }
605
606         if (dns_hosts_file) {
607                 DEBUG(1, ("NO 'NS' lookup available when using resolv:host file"));
608                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
609         }
610
611         /* Send the request.  May have to loop several times in case
612            of large replies */
613
614         status = dns_send_req( ctx, dnsdomain, T_NS, &buffer, &resp_len );
615         if ( !NT_STATUS_IS_OK(status) ) {
616                 DEBUG(3,("ads_dns_lookup_ns: Failed to send DNS query (%s)\n",
617                         nt_errstr(status)));
618                 return status;
619         }
620         p = buffer;
621
622         /* For some insane reason, the ns_initparse() et. al. routines are only
623            available in libresolv.a, and not the shared lib.  Who knows why....
624            So we have to parse the DNS reply ourselves */
625
626         /* Pull the answer RR's count from the header.
627          * Use the NMB ordering macros */
628
629         query_count      = RSVAL( p, 4 );
630         answer_count     = RSVAL( p, 6 );
631         auth_count       = RSVAL( p, 8 );
632         additional_count = RSVAL( p, 10 );
633
634         DEBUG(4,("ads_dns_lookup_ns: "
635                 "%d records returned in the answer section.\n",
636                 answer_count));
637
638         if (answer_count) {
639                 if ((nsarray = talloc_array(ctx, struct dns_rr_ns,
640                                                 answer_count)) == NULL ) {
641                         DEBUG(0,("ads_dns_lookup_ns: "
642                                 "talloc() failure for %d char*'s\n",
643                                 answer_count));
644                         return NT_STATUS_NO_MEMORY;
645                 }
646         } else {
647                 nsarray = NULL;
648         }
649
650         /* now skip the header */
651
652         p += NS_HFIXEDSZ;
653
654         /* parse the query section */
655
656         for ( rrnum=0; rrnum<query_count; rrnum++ ) {
657                 struct dns_query q;
658
659                 if (!ads_dns_parse_query(ctx, buffer, buffer+resp_len,
660                                         &p, &q)) {
661                         DEBUG(1,("ads_dns_lookup_ns: "
662                                 " Failed to parse query record!\n"));
663                         return NT_STATUS_UNSUCCESSFUL;
664                 }
665         }
666
667         /* now we are at the answer section */
668
669         for ( rrnum=0; rrnum<answer_count; rrnum++ ) {
670                 if (!ads_dns_parse_rr_ns(ctx, buffer, buffer+resp_len,
671                                         &p, &nsarray[rrnum])) {
672                         DEBUG(1,("ads_dns_lookup_ns: "
673                                 "Failed to parse answer record!\n"));
674                         return NT_STATUS_UNSUCCESSFUL;
675                 }
676         }
677         idx = rrnum;
678
679         /* Parse the authority section */
680         /* just skip these for now */
681
682         for ( rrnum=0; rrnum<auth_count; rrnum++ ) {
683                 struct dns_rr rr;
684
685                 if ( !ads_dns_parse_rr(ctx, buffer, buffer+resp_len,
686                                         &p, &rr)) {
687                         DEBUG(1,("ads_dns_lookup_ns: "
688                                 "Failed to parse authority record!\n"));
689                         return NT_STATUS_UNSUCCESSFUL;
690                 }
691         }
692
693         /* Parse the additional records section */
694
695         for ( rrnum=0; rrnum<additional_count; rrnum++ ) {
696                 struct dns_rr rr;
697                 int i;
698
699                 if (!ads_dns_parse_rr(ctx, buffer, buffer+resp_len,
700                                         &p, &rr)) {
701                         DEBUG(1,("ads_dns_lookup_ns: Failed "
702                                 "to parse additional records section!\n"));
703                         return NT_STATUS_UNSUCCESSFUL;
704                 }
705
706                 /* only interested in A records as a shortcut for having to come
707                    back later and lookup the name */
708
709                 if (rr.type != T_A || rr.rdatalen != 4) {
710 #if defined(HAVE_IPV6)
711                         if (rr.type != T_AAAA || rr.rdatalen != 16)
712 #endif
713                                 continue;
714                 }
715
716                 for ( i=0; i<idx; i++ ) {
717                         if (strcmp(rr.hostname, nsarray[i].hostname) == 0) {
718                                 if (rr.type == T_A) {
719                                         struct in_addr ip;
720                                         memcpy(&ip, rr.rdata, 4);
721                                         in_addr_to_sockaddr_storage(
722                                                         &nsarray[i].ss,
723                                                         ip);
724                                 }
725 #if defined(HAVE_IPV6)
726                                 if (rr.type == T_AAAA) {
727                                         struct in6_addr ip6;
728                                         memcpy(&ip6, rr.rdata, rr.rdatalen);
729                                         in6_addr_to_sockaddr_storage(
730                                                         &nsarray[i].ss,
731                                                         ip6);
732                                 }
733 #endif
734                         }
735                 }
736         }
737
738         *nslist = nsarray;
739         *numns = idx;
740
741         return NT_STATUS_OK;
742 }
743
744 /********************************************************************
745  Query with optional sitename.
746 ********************************************************************/
747
748 static NTSTATUS ads_dns_query_internal(TALLOC_CTX *ctx,
749                                        const char *dns_hosts_file,
750                                        const char *servicename,
751                                        const char *dc_pdc_gc_domains,
752                                        const char *realm,
753                                        const char *sitename,
754                                        struct dns_rr_srv **dclist,
755                                        int *numdcs )
756 {
757         char *name;
758         if (sitename && strlen(sitename)) {
759                 name = talloc_asprintf(ctx, "%s._tcp.%s._sites.%s._msdcs.%s",
760                                        servicename, sitename,
761                                        dc_pdc_gc_domains, realm);
762         } else {
763                 name = talloc_asprintf(ctx, "%s._tcp.%s._msdcs.%s",
764                                 servicename, dc_pdc_gc_domains, realm);
765         }
766         if (!name) {
767                 return NT_STATUS_NO_MEMORY;
768         }
769         return ads_dns_lookup_srv(ctx, dns_hosts_file, name, dclist, numdcs);
770 }
771
772 /********************************************************************
773  Query for AD DC's.
774 ********************************************************************/
775
776 NTSTATUS ads_dns_query_dcs(TALLOC_CTX *ctx,
777                            const char *dns_hosts_file,
778                            const char *realm,
779                            const char *sitename,
780                            struct dns_rr_srv **dclist,
781                            int *numdcs )
782 {
783         NTSTATUS status;
784
785         status = ads_dns_query_internal(ctx, dns_hosts_file, "_ldap", "dc",
786                                         realm, sitename, dclist, numdcs);
787
788         if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) ||
789             NT_STATUS_EQUAL(status, NT_STATUS_CONNECTION_REFUSED)) {
790                 return status;
791         }
792
793         if (sitename &&
794             ((!NT_STATUS_IS_OK(status)) ||
795              (NT_STATUS_IS_OK(status) && (numdcs == 0)))) {
796                 /* Sitename DNS query may have failed. Try without. */
797                 status = ads_dns_query_internal(ctx, dns_hosts_file,
798                                                 "_ldap", "dc", realm,
799                                                 NULL, dclist, numdcs);
800         }
801         return status;
802 }
803
804 /********************************************************************
805  Query for AD GC's.
806 ********************************************************************/
807
808 NTSTATUS ads_dns_query_gcs(TALLOC_CTX *ctx,
809                            const char *dns_hosts_file,
810                            const char *realm,
811                            const char *sitename,
812                            struct dns_rr_srv **dclist,
813                            int *numdcs )
814 {
815         NTSTATUS status;
816
817         status = ads_dns_query_internal(ctx, dns_hosts_file, "_ldap", "gc",
818                                         realm, sitename, dclist, numdcs);
819
820         if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) ||
821             NT_STATUS_EQUAL(status, NT_STATUS_CONNECTION_REFUSED)) {
822                 return status;
823         }
824
825         if (sitename &&
826             ((!NT_STATUS_IS_OK(status)) ||
827              (NT_STATUS_IS_OK(status) && (numdcs == 0)))) {
828                 /* Sitename DNS query may have failed. Try without. */
829                 status = ads_dns_query_internal(ctx, dns_hosts_file,
830                                                 "_ldap", "gc", realm,
831                                                 NULL, dclist, numdcs);
832         }
833         return status;
834 }
835
836 /********************************************************************
837  Query for AD KDC's.
838  Even if our underlying kerberos libraries are UDP only, this
839  is pretty safe as it's unlikely that a KDC supports TCP and not UDP.
840 ********************************************************************/
841
842 NTSTATUS ads_dns_query_kdcs(TALLOC_CTX *ctx,
843                             const char *dns_hosts_file,
844                             const char *dns_forest_name,
845                             const char *sitename,
846                             struct dns_rr_srv **dclist,
847                             int *numdcs )
848 {
849         NTSTATUS status;
850
851         status = ads_dns_query_internal(ctx, dns_hosts_file, "_kerberos", "dc",
852                                         dns_forest_name, sitename, dclist,
853                                         numdcs);
854
855         if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) ||
856             NT_STATUS_EQUAL(status, NT_STATUS_CONNECTION_REFUSED)) {
857                 return status;
858         }
859
860         if (sitename &&
861             ((!NT_STATUS_IS_OK(status)) ||
862              (NT_STATUS_IS_OK(status) && (numdcs == 0)))) {
863                 /* Sitename DNS query may have failed. Try without. */
864                 status = ads_dns_query_internal(ctx, dns_hosts_file,
865                                                 "_kerberos", "dc",
866                                                 dns_forest_name, NULL,
867                                                 dclist, numdcs);
868         }
869         return status;
870 }
871
872 /********************************************************************
873  Query for AD PDC. Sitename is obsolete here.
874 ********************************************************************/
875
876 NTSTATUS ads_dns_query_pdc(TALLOC_CTX *ctx,
877                            const char *dns_hosts_file,
878                            const char *dns_domain_name,
879                            struct dns_rr_srv **dclist,
880                            int *numdcs )
881 {
882         return ads_dns_query_internal(ctx, dns_hosts_file, "_ldap", "pdc",
883                                       dns_domain_name, NULL, dclist, numdcs);
884 }
885
886 /********************************************************************
887  Query for AD DC by guid. Sitename is obsolete here.
888 ********************************************************************/
889
890 NTSTATUS ads_dns_query_dcs_guid(TALLOC_CTX *ctx,
891                                 const char *dns_hosts_file,
892                                 const char *dns_forest_name,
893                                 const struct GUID *domain_guid,
894                                 struct dns_rr_srv **dclist,
895                                 int *numdcs )
896 {
897         /*_ldap._tcp.DomainGuid.domains._msdcs.DnsForestName */
898
899         const char *domains;
900         char *guid_string;
901
902         guid_string = GUID_string(ctx, domain_guid);
903         if (!guid_string) {
904                 return NT_STATUS_NO_MEMORY;
905         }
906
907         /* little hack */
908         domains = talloc_asprintf(ctx, "%s.domains", guid_string);
909         if (!domains) {
910                 return NT_STATUS_NO_MEMORY;
911         }
912         TALLOC_FREE(guid_string);
913
914         return ads_dns_query_internal(ctx, dns_hosts_file, "_ldap", domains,
915                                       dns_forest_name, NULL, dclist, numdcs);
916 }