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