[GLUE] Rsync SAMBA_3_0 SVN r25598 in order to create the v3-0-test branch.
[Samba.git] / source / libads / dns.c
blobbf51625797a556f3095ed13b667219fa90919f69
1 /*
2 Unix SMB/CIFS implementation.
3 DNS utility library
4 Copyright (C) Gerald (Jerry) Carter 2006.
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 #include "includes.h"
23 /* AIX resolv.h uses 'class' in struct ns_rr */
25 #if defined(AIX)
26 # if defined(class)
27 # undef class
28 # endif
29 #endif /* AIX */
31 /* resolver headers */
33 #include <sys/types.h>
34 #include <netinet/in.h>
35 #include <arpa/nameser.h>
36 #include <resolv.h>
37 #include <netdb.h>
39 #define MAX_DNS_PACKET_SIZE 0xffff
41 #ifdef NS_HFIXEDSZ /* Bind 8/9 interface */
42 #if !defined(C_IN) /* AIX 5.3 already defines C_IN */
43 # define C_IN ns_c_in
44 #endif
45 #if !defined(T_A) /* AIX 5.3 already defines T_A */
46 # define T_A ns_t_a
47 #endif
48 # define T_SRV ns_t_srv
49 #if !defined(T_NS) /* AIX 5.3 already defines T_NS */
50 # define T_NS ns_t_ns
51 #endif
52 #else
53 # ifdef HFIXEDSZ
54 # define NS_HFIXEDSZ HFIXEDSZ
55 # else
56 # define NS_HFIXEDSZ sizeof(HEADER)
57 # endif /* HFIXEDSZ */
58 # ifdef PACKETSZ
59 # define NS_PACKETSZ PACKETSZ
60 # else /* 512 is usually the default */
61 # define NS_PACKETSZ 512
62 # endif /* PACKETSZ */
63 # define T_SRV 33
64 #endif
66 /*********************************************************************
67 *********************************************************************/
69 static BOOL ads_dns_parse_query( TALLOC_CTX *ctx, uint8 *start, uint8 *end,
70 uint8 **ptr, struct dns_query *q )
72 uint8 *p = *ptr;
73 pstring hostname;
74 int namelen;
76 ZERO_STRUCTP( q );
78 if ( !start || !end || !q || !*ptr)
79 return False;
81 /* See RFC 1035 for details. If this fails, then return. */
83 namelen = dn_expand( start, end, p, hostname, sizeof(hostname) );
84 if ( namelen < 0 ) {
85 return False;
87 p += namelen;
88 q->hostname = talloc_strdup( ctx, hostname );
90 /* check that we have space remaining */
92 if ( PTR_DIFF(p+4, end) > 0 )
93 return False;
95 q->type = RSVAL( p, 0 );
96 q->in_class = RSVAL( p, 2 );
97 p += 4;
99 *ptr = p;
101 return True;
104 /*********************************************************************
105 *********************************************************************/
107 static BOOL ads_dns_parse_rr( TALLOC_CTX *ctx, uint8 *start, uint8 *end,
108 uint8 **ptr, struct dns_rr *rr )
110 uint8 *p = *ptr;
111 pstring hostname;
112 int namelen;
114 if ( !start || !end || !rr || !*ptr)
115 return -1;
117 ZERO_STRUCTP( rr );
118 /* pull the name from the answer */
120 namelen = dn_expand( start, end, p, hostname, sizeof(hostname) );
121 if ( namelen < 0 ) {
122 return -1;
124 p += namelen;
125 rr->hostname = talloc_strdup( ctx, hostname );
127 /* check that we have space remaining */
129 if ( PTR_DIFF(p+10, end) > 0 )
130 return False;
132 /* pull some values and then skip onto the string */
134 rr->type = RSVAL(p, 0);
135 rr->in_class = RSVAL(p, 2);
136 rr->ttl = RIVAL(p, 4);
137 rr->rdatalen = RSVAL(p, 8);
139 p += 10;
141 /* sanity check the available space */
143 if ( PTR_DIFF(p+rr->rdatalen, end ) > 0 ) {
144 return False;
148 /* save a point to the rdata for this section */
150 rr->rdata = p;
151 p += rr->rdatalen;
153 *ptr = p;
155 return True;
158 /*********************************************************************
159 *********************************************************************/
161 static BOOL ads_dns_parse_rr_srv( TALLOC_CTX *ctx, uint8 *start, uint8 *end,
162 uint8 **ptr, struct dns_rr_srv *srv )
164 struct dns_rr rr;
165 uint8 *p;
166 pstring dcname;
167 int namelen;
169 if ( !start || !end || !srv || !*ptr)
170 return -1;
172 /* Parse the RR entry. Coming out of the this, ptr is at the beginning
173 of the next record */
175 if ( !ads_dns_parse_rr( ctx, start, end, ptr, &rr ) ) {
176 DEBUG(1,("ads_dns_parse_rr_srv: Failed to parse RR record\n"));
177 return False;
180 if ( rr.type != T_SRV ) {
181 DEBUG(1,("ads_dns_parse_rr_srv: Bad answer type (%d)\n", rr.type));
182 return False;
185 p = rr.rdata;
187 srv->priority = RSVAL(p, 0);
188 srv->weight = RSVAL(p, 2);
189 srv->port = RSVAL(p, 4);
191 p += 6;
193 namelen = dn_expand( start, end, p, dcname, sizeof(dcname) );
194 if ( namelen < 0 ) {
195 DEBUG(1,("ads_dns_parse_rr_srv: Failed to uncompress name!\n"));
196 return False;
198 srv->hostname = talloc_strdup( ctx, dcname );
200 return True;
203 /*********************************************************************
204 *********************************************************************/
206 static BOOL ads_dns_parse_rr_ns( TALLOC_CTX *ctx, uint8 *start, uint8 *end,
207 uint8 **ptr, struct dns_rr_ns *nsrec )
209 struct dns_rr rr;
210 uint8 *p;
211 pstring nsname;
212 int namelen;
214 if ( !start || !end || !nsrec || !*ptr)
215 return -1;
217 /* Parse the RR entry. Coming out of the this, ptr is at the beginning
218 of the next record */
220 if ( !ads_dns_parse_rr( ctx, start, end, ptr, &rr ) ) {
221 DEBUG(1,("ads_dns_parse_rr_ns: Failed to parse RR record\n"));
222 return False;
225 if ( rr.type != T_NS ) {
226 DEBUG(1,("ads_dns_parse_rr_ns: Bad answer type (%d)\n", rr.type));
227 return False;
230 p = rr.rdata;
232 /* ame server hostname */
234 namelen = dn_expand( start, end, p, nsname, sizeof(nsname) );
235 if ( namelen < 0 ) {
236 DEBUG(1,("ads_dns_parse_rr_ns: Failed to uncompress name!\n"));
237 return False;
239 nsrec->hostname = talloc_strdup( ctx, nsname );
241 return True;
244 /*********************************************************************
245 Sort SRV record list based on weight and priority. See RFC 2782.
246 *********************************************************************/
248 static int dnssrvcmp( struct dns_rr_srv *a, struct dns_rr_srv *b )
250 if ( a->priority == b->priority ) {
252 /* randomize entries with an equal weight and priority */
253 if ( a->weight == b->weight )
254 return 0;
256 /* higher weights should be sorted lower */
257 if ( a->weight > b->weight )
258 return -1;
259 else
260 return 1;
263 if ( a->priority < b->priority )
264 return -1;
266 return 1;
269 /*********************************************************************
270 Simple wrapper for a DNS query
271 *********************************************************************/
273 static NTSTATUS dns_send_req( TALLOC_CTX *ctx, const char *name, int q_type,
274 uint8 **buf, int *resp_length )
276 uint8 *buffer = NULL;
277 size_t buf_len;
278 int resp_len = NS_PACKETSZ;
280 do {
281 if ( buffer )
282 TALLOC_FREE( buffer );
284 buf_len = resp_len * sizeof(uint8);
286 if (buf_len) {
287 if ( (buffer = TALLOC_ARRAY(ctx, uint8, buf_len)) == NULL ) {
288 DEBUG(0,("ads_dns_lookup_srv: talloc() failed!\n"));
289 return NT_STATUS_NO_MEMORY;
291 } else {
292 buffer = NULL;
295 if ( (resp_len = res_query(name, C_IN, q_type, buffer, buf_len)) < 0 ) {
296 DEBUG(3,("ads_dns_lookup_srv: Failed to resolve %s (%s)\n", name, strerror(errno)));
297 TALLOC_FREE( buffer );
298 if (errno == ETIMEDOUT) {
299 return NT_STATUS_IO_TIMEOUT;
301 if (errno == ECONNREFUSED) {
302 return NT_STATUS_CONNECTION_REFUSED;
304 return NT_STATUS_UNSUCCESSFUL;
306 } while ( buf_len < resp_len && resp_len < MAX_DNS_PACKET_SIZE );
308 *buf = buffer;
309 *resp_length = resp_len;
311 return NT_STATUS_OK;
314 /*********************************************************************
315 Simple wrapper for a DNS SRV query
316 *********************************************************************/
318 static NTSTATUS ads_dns_lookup_srv( TALLOC_CTX *ctx, const char *name, struct dns_rr_srv **dclist, int *numdcs )
320 uint8 *buffer = NULL;
321 int resp_len = 0;
322 struct dns_rr_srv *dcs = NULL;
323 int query_count, answer_count, auth_count, additional_count;
324 uint8 *p = buffer;
325 int rrnum;
326 int idx = 0;
327 NTSTATUS status;
329 if ( !ctx || !name || !dclist ) {
330 return NT_STATUS_INVALID_PARAMETER;
333 /* Send the request. May have to loop several times in case
334 of large replies */
336 status = dns_send_req( ctx, name, T_SRV, &buffer, &resp_len );
337 if ( !NT_STATUS_IS_OK(status) ) {
338 DEBUG(3,("ads_dns_lookup_srv: Failed to send DNS query (%s)\n",
339 nt_errstr(status)));
340 return status;
342 p = buffer;
344 /* For some insane reason, the ns_initparse() et. al. routines are only
345 available in libresolv.a, and not the shared lib. Who knows why....
346 So we have to parse the DNS reply ourselves */
348 /* Pull the answer RR's count from the header. Use the NMB ordering macros */
350 query_count = RSVAL( p, 4 );
351 answer_count = RSVAL( p, 6 );
352 auth_count = RSVAL( p, 8 );
353 additional_count = RSVAL( p, 10 );
355 DEBUG(4,("ads_dns_lookup_srv: %d records returned in the answer section.\n",
356 answer_count));
358 if (answer_count) {
359 if ( (dcs = TALLOC_ZERO_ARRAY(ctx, struct dns_rr_srv, answer_count)) == NULL ) {
360 DEBUG(0,("ads_dns_lookup_srv: talloc() failure for %d char*'s\n",
361 answer_count));
362 return NT_STATUS_NO_MEMORY;
364 } else {
365 dcs = NULL;
368 /* now skip the header */
370 p += NS_HFIXEDSZ;
372 /* parse the query section */
374 for ( rrnum=0; rrnum<query_count; rrnum++ ) {
375 struct dns_query q;
377 if ( !ads_dns_parse_query( ctx, buffer, buffer+resp_len, &p, &q ) ) {
378 DEBUG(1,("ads_dns_lookup_srv: Failed to parse query record!\n"));
379 return NT_STATUS_UNSUCCESSFUL;
383 /* now we are at the answer section */
385 for ( rrnum=0; rrnum<answer_count; rrnum++ ) {
386 if ( !ads_dns_parse_rr_srv( ctx, buffer, buffer+resp_len, &p, &dcs[rrnum] ) ) {
387 DEBUG(1,("ads_dns_lookup_srv: Failed to parse answer record!\n"));
388 return NT_STATUS_UNSUCCESSFUL;
391 idx = rrnum;
393 /* Parse the authority section */
394 /* just skip these for now */
396 for ( rrnum=0; rrnum<auth_count; rrnum++ ) {
397 struct dns_rr rr;
399 if ( !ads_dns_parse_rr( ctx, buffer, buffer+resp_len, &p, &rr ) ) {
400 DEBUG(1,("ads_dns_lookup_srv: Failed to parse authority record!\n"));
401 return NT_STATUS_UNSUCCESSFUL;
405 /* Parse the additional records section */
407 for ( rrnum=0; rrnum<additional_count; rrnum++ ) {
408 struct dns_rr rr;
409 int i;
411 if ( !ads_dns_parse_rr( ctx, buffer, buffer+resp_len, &p, &rr ) ) {
412 DEBUG(1,("ads_dns_lookup_srv: Failed to parse additional records section!\n"));
413 return NT_STATUS_UNSUCCESSFUL;
416 /* only interested in A records as a shortcut for having to come
417 back later and lookup the name. For multi-homed hosts, the
418 number of additional records and exceed the number of answer
419 records. */
422 if ( (rr.type != T_A) || (rr.rdatalen != 4) )
423 continue;
425 for ( i=0; i<idx; i++ ) {
426 if ( strcmp( rr.hostname, dcs[i].hostname ) == 0 ) {
427 int num_ips = dcs[i].num_ips;
428 uint8 *buf;
429 struct in_addr *tmp_ips;
431 /* allocate new memory */
433 if ( dcs[i].num_ips == 0 ) {
434 if ( (dcs[i].ips = TALLOC_ARRAY( dcs,
435 struct in_addr, 1 )) == NULL )
437 return NT_STATUS_NO_MEMORY;
439 } else {
440 if ( (tmp_ips = TALLOC_REALLOC_ARRAY( dcs, dcs[i].ips,
441 struct in_addr, dcs[i].num_ips+1)) == NULL )
443 return NT_STATUS_NO_MEMORY;
446 dcs[i].ips = tmp_ips;
448 dcs[i].num_ips++;
450 /* copy the new IP address */
452 buf = (uint8*)&dcs[i].ips[num_ips].s_addr;
453 memcpy( buf, rr.rdata, 4 );
458 qsort( dcs, idx, sizeof(struct dns_rr_srv), QSORT_CAST dnssrvcmp );
460 *dclist = dcs;
461 *numdcs = idx;
463 return NT_STATUS_OK;
466 /*********************************************************************
467 Simple wrapper for a DNS NS query
468 *********************************************************************/
470 NTSTATUS ads_dns_lookup_ns( TALLOC_CTX *ctx, const char *dnsdomain, struct dns_rr_ns **nslist, int *numns )
472 uint8 *buffer = NULL;
473 int resp_len = 0;
474 struct dns_rr_ns *nsarray = NULL;
475 int query_count, answer_count, auth_count, additional_count;
476 uint8 *p;
477 int rrnum;
478 int idx = 0;
479 NTSTATUS status;
481 if ( !ctx || !dnsdomain || !nslist ) {
482 return NT_STATUS_INVALID_PARAMETER;
485 /* Send the request. May have to loop several times in case
486 of large replies */
488 status = dns_send_req( ctx, dnsdomain, T_NS, &buffer, &resp_len );
489 if ( !NT_STATUS_IS_OK(status) ) {
490 DEBUG(3,("ads_dns_lookup_ns: Failed to send DNS query (%s)\n",
491 nt_errstr(status)));
492 return status;
494 p = buffer;
496 /* For some insane reason, the ns_initparse() et. al. routines are only
497 available in libresolv.a, and not the shared lib. Who knows why....
498 So we have to parse the DNS reply ourselves */
500 /* Pull the answer RR's count from the header. Use the NMB ordering macros */
502 query_count = RSVAL( p, 4 );
503 answer_count = RSVAL( p, 6 );
504 auth_count = RSVAL( p, 8 );
505 additional_count = RSVAL( p, 10 );
507 DEBUG(4,("ads_dns_lookup_ns: %d records returned in the answer section.\n",
508 answer_count));
510 if (answer_count) {
511 if ( (nsarray = TALLOC_ARRAY(ctx, struct dns_rr_ns, answer_count)) == NULL ) {
512 DEBUG(0,("ads_dns_lookup_ns: talloc() failure for %d char*'s\n",
513 answer_count));
514 return NT_STATUS_NO_MEMORY;
516 } else {
517 nsarray = NULL;
520 /* now skip the header */
522 p += NS_HFIXEDSZ;
524 /* parse the query section */
526 for ( rrnum=0; rrnum<query_count; rrnum++ ) {
527 struct dns_query q;
529 if ( !ads_dns_parse_query( ctx, buffer, buffer+resp_len, &p, &q ) ) {
530 DEBUG(1,("ads_dns_lookup_ns: Failed to parse query record!\n"));
531 return NT_STATUS_UNSUCCESSFUL;
535 /* now we are at the answer section */
537 for ( rrnum=0; rrnum<answer_count; rrnum++ ) {
538 if ( !ads_dns_parse_rr_ns( ctx, buffer, buffer+resp_len, &p, &nsarray[rrnum] ) ) {
539 DEBUG(1,("ads_dns_lookup_ns: Failed to parse answer record!\n"));
540 return NT_STATUS_UNSUCCESSFUL;
543 idx = rrnum;
545 /* Parse the authority section */
546 /* just skip these for now */
548 for ( rrnum=0; rrnum<auth_count; rrnum++ ) {
549 struct dns_rr rr;
551 if ( !ads_dns_parse_rr( ctx, buffer, buffer+resp_len, &p, &rr ) ) {
552 DEBUG(1,("ads_dns_lookup_ns: Failed to parse authority record!\n"));
553 return NT_STATUS_UNSUCCESSFUL;
557 /* Parse the additional records section */
559 for ( rrnum=0; rrnum<additional_count; rrnum++ ) {
560 struct dns_rr rr;
561 int i;
563 if ( !ads_dns_parse_rr( ctx, buffer, buffer+resp_len, &p, &rr ) ) {
564 DEBUG(1,("ads_dns_lookup_ns: Failed to parse additional records section!\n"));
565 return NT_STATUS_UNSUCCESSFUL;
568 /* only interested in A records as a shortcut for having to come
569 back later and lookup the name */
571 if ( (rr.type != T_A) || (rr.rdatalen != 4) )
572 continue;
574 for ( i=0; i<idx; i++ ) {
575 if ( strcmp( rr.hostname, nsarray[i].hostname ) == 0 ) {
576 uint8 *buf = (uint8*)&nsarray[i].ip.s_addr;
577 memcpy( buf, rr.rdata, 4 );
582 *nslist = nsarray;
583 *numns = idx;
585 return NT_STATUS_OK;
588 /****************************************************************************
589 Store and fetch the AD client sitename.
590 ****************************************************************************/
592 #define SITENAME_KEY "AD_SITENAME/DOMAIN/%s"
594 static char *sitename_key(const char *realm)
596 char *keystr;
598 if (asprintf(&keystr, SITENAME_KEY, strupper_static(realm)) == -1) {
599 return NULL;
602 return keystr;
606 /****************************************************************************
607 Store the AD client sitename.
608 We store indefinately as every new CLDAP query will re-write this.
609 ****************************************************************************/
611 BOOL sitename_store(const char *realm, const char *sitename)
613 time_t expire;
614 BOOL ret = False;
615 char *key;
617 if (!gencache_init()) {
618 return False;
621 if (!realm || (strlen(realm) == 0)) {
622 DEBUG(0,("sitename_store: no realm\n"));
623 return False;
626 key = sitename_key(realm);
628 if (!sitename || (sitename && !*sitename)) {
629 DEBUG(5,("sitename_store: deleting empty sitename!\n"));
630 ret = gencache_del(key);
631 SAFE_FREE(key);
632 return ret;
635 expire = get_time_t_max(); /* Store indefinately. */
637 DEBUG(10,("sitename_store: realm = [%s], sitename = [%s], expire = [%u]\n",
638 realm, sitename, (unsigned int)expire ));
640 ret = gencache_set( key, sitename, expire );
641 SAFE_FREE(key);
642 return ret;
645 /****************************************************************************
646 Fetch the AD client sitename.
647 Caller must free.
648 ****************************************************************************/
650 char *sitename_fetch(const char *realm)
652 char *sitename = NULL;
653 time_t timeout;
654 BOOL ret = False;
655 const char *query_realm;
656 char *key;
658 if (!gencache_init()) {
659 return False;
662 if (!realm || (strlen(realm) == 0)) {
663 query_realm = lp_realm();
664 } else {
665 query_realm = realm;
668 key = sitename_key(query_realm);
670 ret = gencache_get( key, &sitename, &timeout );
671 SAFE_FREE(key);
672 if ( !ret ) {
673 DEBUG(5,("sitename_fetch: No stored sitename for %s\n",
674 query_realm));
675 } else {
676 DEBUG(5,("sitename_fetch: Returning sitename for %s: \"%s\"\n",
677 query_realm, sitename ));
679 return sitename;
682 /****************************************************************************
683 Did the sitename change ?
684 ****************************************************************************/
686 BOOL stored_sitename_changed(const char *realm, const char *sitename)
688 BOOL ret = False;
690 char *new_sitename;
692 if (!realm || (strlen(realm) == 0)) {
693 DEBUG(0,("stored_sitename_changed: no realm\n"));
694 return False;
697 new_sitename = sitename_fetch(realm);
699 if (sitename && new_sitename && !strequal(sitename, new_sitename)) {
700 ret = True;
701 } else if ((sitename && !new_sitename) ||
702 (!sitename && new_sitename)) {
703 ret = True;
705 SAFE_FREE(new_sitename);
706 return ret;
709 /********************************************************************
710 Query with optional sitename.
711 ********************************************************************/
713 NTSTATUS ads_dns_query_internal(TALLOC_CTX *ctx,
714 const char *servicename,
715 const char *realm,
716 const char *sitename,
717 struct dns_rr_srv **dclist,
718 int *numdcs )
720 char *name;
721 if (sitename) {
722 name = talloc_asprintf(ctx, "%s._tcp.%s._sites.dc._msdcs.%s",
723 servicename, sitename, realm );
724 } else {
725 name = talloc_asprintf(ctx, "%s._tcp.dc._msdcs.%s",
726 servicename, realm );
728 if (!name) {
729 return NT_STATUS_NO_MEMORY;
731 return ads_dns_lookup_srv( ctx, name, dclist, numdcs );
734 /********************************************************************
735 Query for AD DC's.
736 ********************************************************************/
738 NTSTATUS ads_dns_query_dcs(TALLOC_CTX *ctx,
739 const char *realm,
740 const char *sitename,
741 struct dns_rr_srv **dclist,
742 int *numdcs )
744 NTSTATUS status;
746 status = ads_dns_query_internal(ctx, "_ldap", realm, sitename,
747 dclist, numdcs);
749 if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) ||
750 NT_STATUS_EQUAL(status, NT_STATUS_CONNECTION_REFUSED)) {
751 return status;
754 if (sitename && !NT_STATUS_IS_OK(status)) {
755 /* Sitename DNS query may have failed. Try without. */
756 status = ads_dns_query_internal(ctx, "_ldap", realm, NULL,
757 dclist, numdcs);
759 return status;
762 /********************************************************************
763 Query for AD KDC's.
764 Even if our underlying kerberos libraries are UDP only, this
765 is pretty safe as it's unlikely that a KDC supports TCP and not UDP.
766 ********************************************************************/
768 NTSTATUS ads_dns_query_kdcs(TALLOC_CTX *ctx,
769 const char *realm,
770 const char *sitename,
771 struct dns_rr_srv **dclist,
772 int *numdcs )
774 NTSTATUS status;
776 status = ads_dns_query_internal(ctx, "_kerberos", realm, sitename,
777 dclist, numdcs);
779 if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT) ||
780 NT_STATUS_EQUAL(status, NT_STATUS_CONNECTION_REFUSED)) {
781 return status;
784 if (sitename && !NT_STATUS_IS_OK(status)) {
785 /* Sitename DNS query may have failed. Try without. */
786 status = ads_dns_query_internal(ctx, "_kerberos", realm, NULL,
787 dclist, numdcs);
789 return status;