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