r15462: replace the use of OpenLDAP's ldap_domain2hostlist() for
[samba.git] / source3 / libads / dns.c
1 /* 
2    Unix SMB/CIFS implementation.
3    DNS utility library
4    Copyright (C) Gerald (Jerry) Carter           2006.
5
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.
10    
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.
15    
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.
19 */
20
21 #include "includes.h"
22
23 /* AIX resolv.h uses 'class' in struct ns_rr */
24
25 #if defined(AIX)
26 #  if defined(class)
27 #    undef class
28 #  endif
29 #endif  /* AIX */
30
31 /* resolver headers */
32
33 #include <sys/types.h>
34 #include <netinet/in.h>
35 #include <arpa/nameser.h>
36 #include <resolv.h>
37 #include <netdb.h>
38
39 #define MAX_DNS_PACKET_SIZE 0xffff
40
41 /*********************************************************************
42 *********************************************************************/
43
44 static BOOL ads_dns_parse_query( TALLOC_CTX *ctx, uint8 *start, uint8 *end,
45                           uint8 **ptr, struct dns_query *q )
46 {
47         uint8 *p = *ptr;
48         pstring hostname;
49         int namelen;
50
51         ZERO_STRUCTP( q );
52         
53         if ( !start || !end || !q || !*ptr)
54                 return False;
55
56         /* See RFC 1035 for details. If this fails, then return. */
57
58         namelen = dn_expand( start, end, p, hostname, sizeof(hostname) );
59         if ( namelen < 0 ) {
60                 return False;
61         }
62         p += namelen;
63         q->hostname = talloc_strdup( ctx, hostname );
64
65         /* check that we have space remaining */
66
67         if ( PTR_DIFF(p+4, end) > 0 )
68                 return False;
69
70         q->type     = RSVAL( p, 0 );
71         q->in_class = RSVAL( p, 2 );
72         p += 4;
73
74         *ptr = p;
75
76         return True;
77 }
78
79 /*********************************************************************
80 *********************************************************************/
81
82 static BOOL ads_dns_parse_rr( TALLOC_CTX *ctx, uint8 *start, uint8 *end,
83                        uint8 **ptr, struct dns_rr *rr )
84 {
85         uint8 *p = *ptr;
86         pstring hostname;
87         int namelen;
88
89         if ( !start || !end || !rr || !*ptr)
90                 return -1;
91
92         ZERO_STRUCTP( rr );
93         /* pull the name from the answer */
94
95         namelen = dn_expand( start, end, p, hostname, sizeof(hostname) );
96         if ( namelen < 0 ) {
97                 return -1;
98         }
99         p += namelen;
100         rr->hostname = talloc_strdup( ctx, hostname );
101
102         /* check that we have space remaining */
103
104         if ( PTR_DIFF(p+10, end) > 0 )
105                 return False;
106
107         /* pull some values and then skip onto the string */
108
109         rr->type     = RSVAL(p, 0);
110         rr->in_class = RSVAL(p, 2);
111         rr->ttl      = RIVAL(p, 4);
112         rr->rdatalen = RSVAL(p, 8);
113         
114         p += 10;
115
116         /* sanity check the available space */
117
118         if ( PTR_DIFF(p+rr->rdatalen, end ) > 0 ) {
119                 return False;
120
121         }
122
123         /* save a point to the rdata for this section */
124
125         rr->rdata = p;
126         p += rr->rdatalen;
127
128         *ptr = p;
129
130         return True;
131 }
132
133 /*********************************************************************
134 *********************************************************************/
135
136 static BOOL ads_dns_parse_rr_srv( TALLOC_CTX *ctx, uint8 *start, uint8 *end,
137                        uint8 **ptr, struct dns_rr_srv *srv )
138 {
139         struct dns_rr rr;
140         uint8 *p;
141         pstring dcname;
142         int namelen;
143
144         if ( !start || !end || !srv || !*ptr)
145                 return -1;
146
147         /* Parse the RR entry.  Coming out of the this, ptr is at the beginning 
148            of the next record */
149
150         if ( !ads_dns_parse_rr( ctx, start, end, ptr, &rr ) ) {
151                 DEBUG(1,("ads_dns_parse_rr_srv: Failed to parse RR record\n"));
152                 return False;
153         }
154
155         if ( rr.type != ns_t_srv ) {
156                 DEBUG(1,("ads_dns_parse_rr_srv: Bad answer type (%d)\n", rr.type));
157                 return False;
158         }
159
160         p = rr.rdata;
161
162         srv->priority = RSVAL(p, 0);
163         srv->weight   = RSVAL(p, 2);
164         srv->port     = RSVAL(p, 4);
165
166         p += 6;
167
168         namelen = dn_expand( start, end, p, dcname, sizeof(dcname) );
169         if ( namelen < 0 ) {
170                 DEBUG(1,("ads_dns_parse_rr_srv: Failed to uncompress name!\n"));
171                 return False;
172         }
173         srv->hostname = talloc_strdup( ctx, dcname );
174
175         return True;
176 }
177
178
179 /*********************************************************************
180  Sort SRV record list based on weight and priority.  See RFC 2782.
181 *********************************************************************/
182
183 static int dnssrvcmp( struct dns_rr_srv *a, struct dns_rr_srv *b )
184 {
185         BOOL init = False;
186
187         if ( !init ) {
188                 srand( (uint32)time(NULL) );
189         }
190
191         if ( a->priority == b->priority ) {
192
193                 /* randomize entries with an equal weight and priority */
194                 if ( a->weight == b->weight ) 
195                         return rand() % 2 ? -1 : 1;
196
197                 /* higher weights should be sorted lower */ 
198                 if ( a->weight > b->weight )
199                         return -1;
200                 else
201                         return 1;
202         }
203                 
204         if ( a->priority < b->priority )
205                 return -1;
206
207         return 1;
208 }
209
210 /*********************************************************************
211  Simple wrapper for a DNS SRV query
212 *********************************************************************/
213
214 NTSTATUS ads_dns_lookup_srv( TALLOC_CTX *ctx, const char *name, struct dns_rr_srv **dclist, int *numdcs )
215 {
216         uint8 *buffer = NULL;
217         size_t buf_len;
218         int resp_len = NS_PACKETSZ;
219         struct dns_rr_srv *dcs = NULL;
220         int query_count, answer_count, auth_count, additional_count;
221         uint8 *p = buffer;
222         int rrnum;
223         int idx = 0;
224
225         if ( !ctx || !name || !dclist ) {
226                 return NT_STATUS_INVALID_PARAMETER;
227         }
228         
229         /* Send the request.  May have to loop several times in case 
230            of large replies */
231
232         do {
233                 if ( buffer )
234                         TALLOC_FREE( buffer );
235                 
236                 buf_len = resp_len * sizeof(uint8);
237
238                 if ( (buffer = TALLOC_ARRAY(ctx, uint8, buf_len)) == NULL ) {
239                         DEBUG(0,("ads_dns_lookup_srv: talloc() failed!\n"));
240                         return NT_STATUS_NO_MEMORY;
241                 }
242
243                 if ( (resp_len = res_query(name, ns_c_in, ns_t_srv, buffer, buf_len)) < 0 ) {
244                         DEBUG(1,("ads_dns_lookup_srv: Failed to resolve %s (%s)\n", name, strerror(errno)));
245                         TALLOC_FREE( buffer );
246                         return NT_STATUS_UNSUCCESSFUL;
247                 }
248         } while ( buf_len < resp_len && resp_len < MAX_DNS_PACKET_SIZE );
249
250         p = buffer;
251
252         /* For some insane reason, the ns_initparse() et. al. routines are only
253            available in libresolv.a, and not the shared lib.  Who knows why....
254            So we have to parse the DNS reply ourselves */
255
256         /* Pull the answer RR's count from the header.  Use the NMB ordering macros */
257
258         query_count      = RSVAL( p, 4 );
259         answer_count     = RSVAL( p, 6 );
260         auth_count       = RSVAL( p, 8 );
261         additional_count = RSVAL( p, 10 );
262
263         DEBUG(4,("ads_dns_lookup_srv: %d records returned in the answer section.\n", 
264                 answer_count));
265                 
266         if ( (dcs = TALLOC_ARRAY(ctx, struct dns_rr_srv, answer_count)) == NULL ) {
267                 DEBUG(0,("ads_dns_lookup_srv: talloc() failure for %d char*'s\n", 
268                         answer_count));
269                 return NT_STATUS_NO_MEMORY;
270         }
271
272         /* now skip the header */
273
274         p += NS_HFIXEDSZ;
275
276         /* parse the query section */
277
278         for ( rrnum=0; rrnum<query_count; rrnum++ ) {
279                 struct dns_query q;
280
281                 if ( !ads_dns_parse_query( ctx, buffer, buffer+resp_len, &p, &q ) ) {
282                         DEBUG(1,("ads_dns_lookup_srv: Failed to parse query record!\n"));
283                         return NT_STATUS_UNSUCCESSFUL;
284                 }
285         }
286
287         /* now we are at the answer section */
288
289         for ( rrnum=0; rrnum<answer_count; rrnum++ ) {
290                 if ( !ads_dns_parse_rr_srv( ctx, buffer, buffer+resp_len, &p, &dcs[rrnum] ) ) {
291                         DEBUG(1,("ads_dns_lookup_srv: Failed to parse answer record!\n"));
292                         return NT_STATUS_UNSUCCESSFUL;
293                 }               
294         }
295         idx = rrnum;
296
297         /* Parse the authority section */
298         /* just skip these for now */
299
300         for ( rrnum=0; rrnum<auth_count; rrnum++ ) {
301                 struct dns_rr rr;
302
303                 if ( !ads_dns_parse_rr( ctx, buffer, buffer+resp_len, &p, &rr ) ) {
304                         DEBUG(1,("ads_dns_lookup_srv: Failed to parse authority record!\n"));
305                         return NT_STATUS_UNSUCCESSFUL;
306                 }
307         }
308
309         /* Parse the additional records section */
310
311         for ( rrnum=0; rrnum<additional_count; rrnum++ ) {
312                 struct dns_rr rr;
313                 int i;
314
315                 if ( !ads_dns_parse_rr( ctx, buffer, buffer+resp_len, &p, &rr ) ) {
316                         DEBUG(1,("ads_dns_lookup_srv: Failed to parse additional records section!\n"));
317                         return NT_STATUS_UNSUCCESSFUL;
318                 }
319
320                 /* only interested in A records as a shortcut for having to come 
321                    back later and lookup the name */
322
323                 if ( (rr.type != ns_t_a) || (rr.rdatalen != 4) ) 
324                         continue;
325
326                 for ( i=0; i<idx; i++ ) {
327                         if ( strcmp( rr.hostname, dcs[i].hostname ) == 0 ) {
328                                 uint8 *buf = (uint8*)&dcs[i].ip.s_addr;
329                                 memcpy( buf, rr.rdata, 4 );
330                         }
331                 }
332         }
333
334         qsort( dcs, idx, sizeof(struct dns_rr_srv), QSORT_CAST dnssrvcmp );
335         
336         *dclist = dcs;
337         *numdcs = idx;
338         
339         return NT_STATUS_OK;
340 }
341
342 /********************************************************************
343 ********************************************************************/
344
345 NTSTATUS ads_dns_query_dcs( TALLOC_CTX *ctx, const char *domain, struct dns_rr_srv **dclist, int *numdcs )
346 {
347         pstring name;
348
349         snprintf( name, sizeof(name), "_ldap._tcp.dc._msdcs.%s", domain );
350
351         return ads_dns_lookup_srv( ctx, name, dclist, numdcs );
352 }
353