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