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