r17239: BUG 3959: patch from William Charles <william@charles.name> to fix a segv...
[ira/wip.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 #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 #  define T_NS          ns_t_ns
50 #else
51 #  ifdef HFIXEDSZ
52 #    define NS_HFIXEDSZ HFIXEDSZ
53 #  else
54 #    define NS_HFIXEDSZ sizeof(HEADER)
55 #  endif        /* HFIXEDSZ */
56 #  ifdef PACKETSZ
57 #    define NS_PACKETSZ PACKETSZ
58 #  else /* 512 is usually the default */
59 #    define NS_PACKETSZ 512
60 #  endif        /* PACKETSZ */
61 #  define T_SRV         33
62 #endif
63
64 /*********************************************************************
65 *********************************************************************/
66
67 static BOOL ads_dns_parse_query( TALLOC_CTX *ctx, uint8 *start, uint8 *end,
68                           uint8 **ptr, struct dns_query *q )
69 {
70         uint8 *p = *ptr;
71         pstring hostname;
72         int namelen;
73
74         ZERO_STRUCTP( q );
75         
76         if ( !start || !end || !q || !*ptr)
77                 return False;
78
79         /* See RFC 1035 for details. If this fails, then return. */
80
81         namelen = dn_expand( start, end, p, hostname, sizeof(hostname) );
82         if ( namelen < 0 ) {
83                 return False;
84         }
85         p += namelen;
86         q->hostname = talloc_strdup( ctx, hostname );
87
88         /* check that we have space remaining */
89
90         if ( PTR_DIFF(p+4, end) > 0 )
91                 return False;
92
93         q->type     = RSVAL( p, 0 );
94         q->in_class = RSVAL( p, 2 );
95         p += 4;
96
97         *ptr = p;
98
99         return True;
100 }
101
102 /*********************************************************************
103 *********************************************************************/
104
105 static BOOL ads_dns_parse_rr( TALLOC_CTX *ctx, uint8 *start, uint8 *end,
106                        uint8 **ptr, struct dns_rr *rr )
107 {
108         uint8 *p = *ptr;
109         pstring hostname;
110         int namelen;
111
112         if ( !start || !end || !rr || !*ptr)
113                 return -1;
114
115         ZERO_STRUCTP( rr );
116         /* pull the name from the answer */
117
118         namelen = dn_expand( start, end, p, hostname, sizeof(hostname) );
119         if ( namelen < 0 ) {
120                 return -1;
121         }
122         p += namelen;
123         rr->hostname = talloc_strdup( ctx, hostname );
124
125         /* check that we have space remaining */
126
127         if ( PTR_DIFF(p+10, end) > 0 )
128                 return False;
129
130         /* pull some values and then skip onto the string */
131
132         rr->type     = RSVAL(p, 0);
133         rr->in_class = RSVAL(p, 2);
134         rr->ttl      = RIVAL(p, 4);
135         rr->rdatalen = RSVAL(p, 8);
136         
137         p += 10;
138
139         /* sanity check the available space */
140
141         if ( PTR_DIFF(p+rr->rdatalen, end ) > 0 ) {
142                 return False;
143
144         }
145
146         /* save a point to the rdata for this section */
147
148         rr->rdata = p;
149         p += rr->rdatalen;
150
151         *ptr = p;
152
153         return True;
154 }
155
156 /*********************************************************************
157 *********************************************************************/
158
159 static BOOL ads_dns_parse_rr_srv( TALLOC_CTX *ctx, uint8 *start, uint8 *end,
160                        uint8 **ptr, struct dns_rr_srv *srv )
161 {
162         struct dns_rr rr;
163         uint8 *p;
164         pstring dcname;
165         int namelen;
166
167         if ( !start || !end || !srv || !*ptr)
168                 return -1;
169
170         /* Parse the RR entry.  Coming out of the this, ptr is at the beginning 
171            of the next record */
172
173         if ( !ads_dns_parse_rr( ctx, start, end, ptr, &rr ) ) {
174                 DEBUG(1,("ads_dns_parse_rr_srv: Failed to parse RR record\n"));
175                 return False;
176         }
177
178         if ( rr.type != T_SRV ) {
179                 DEBUG(1,("ads_dns_parse_rr_srv: Bad answer type (%d)\n", rr.type));
180                 return False;
181         }
182
183         p = rr.rdata;
184
185         srv->priority = RSVAL(p, 0);
186         srv->weight   = RSVAL(p, 2);
187         srv->port     = RSVAL(p, 4);
188
189         p += 6;
190
191         namelen = dn_expand( start, end, p, dcname, sizeof(dcname) );
192         if ( namelen < 0 ) {
193                 DEBUG(1,("ads_dns_parse_rr_srv: Failed to uncompress name!\n"));
194                 return False;
195         }
196         srv->hostname = talloc_strdup( ctx, dcname );
197
198         return True;
199 }
200
201 /*********************************************************************
202 *********************************************************************/
203
204 static BOOL ads_dns_parse_rr_ns( TALLOC_CTX *ctx, uint8 *start, uint8 *end,
205                        uint8 **ptr, struct dns_rr_ns *nsrec )
206 {
207         struct dns_rr rr;
208         uint8 *p;
209         pstring nsname;
210         int namelen;
211
212         if ( !start || !end || !nsrec || !*ptr)
213                 return -1;
214
215         /* Parse the RR entry.  Coming out of the this, ptr is at the beginning 
216            of the next record */
217
218         if ( !ads_dns_parse_rr( ctx, start, end, ptr, &rr ) ) {
219                 DEBUG(1,("ads_dns_parse_rr_ns: Failed to parse RR record\n"));
220                 return False;
221         }
222
223         if ( rr.type != T_NS ) {
224                 DEBUG(1,("ads_dns_parse_rr_ns: Bad answer type (%d)\n", rr.type));
225                 return False;
226         }
227
228         p = rr.rdata;
229
230         /* ame server hostname */
231         
232         namelen = dn_expand( start, end, p, nsname, sizeof(nsname) );
233         if ( namelen < 0 ) {
234                 DEBUG(1,("ads_dns_parse_rr_ns: Failed to uncompress name!\n"));
235                 return False;
236         }
237         nsrec->hostname = talloc_strdup( ctx, nsname );
238
239         return True;
240 }
241
242 /*********************************************************************
243  Sort SRV record list based on weight and priority.  See RFC 2782.
244 *********************************************************************/
245
246 static int dnssrvcmp( struct dns_rr_srv *a, struct dns_rr_srv *b )
247 {
248         if ( a->priority == b->priority ) {
249
250                 /* randomize entries with an equal weight and priority */
251                 if ( a->weight == b->weight ) 
252                         return 0;
253
254                 /* higher weights should be sorted lower */ 
255                 if ( a->weight > b->weight )
256                         return -1;
257                 else
258                         return 1;
259         }
260                 
261         if ( a->priority < b->priority )
262                 return -1;
263
264         return 1;
265 }
266
267 /*********************************************************************
268  Simple wrapper for a DNS query
269 *********************************************************************/
270
271 static NTSTATUS dns_send_req( TALLOC_CTX *ctx, const char *name, int q_type, 
272                               uint8 **buf, int *resp_length )
273 {
274         uint8 *buffer = NULL;
275         size_t buf_len;
276         int resp_len = NS_PACKETSZ;     
277         
278         do {
279                 if ( buffer )
280                         TALLOC_FREE( buffer );
281                 
282                 buf_len = resp_len * sizeof(uint8);
283
284                 if ( (buffer = TALLOC_ARRAY(ctx, uint8, buf_len)) == NULL ) {
285                         DEBUG(0,("ads_dns_lookup_srv: talloc() failed!\n"));
286                         return NT_STATUS_NO_MEMORY;
287                 }
288
289                 if ( (resp_len = res_query(name, C_IN, q_type, buffer, buf_len)) < 0 ) {
290                         DEBUG(1,("ads_dns_lookup_srv: Failed to resolve %s (%s)\n", name, strerror(errno)));
291                         TALLOC_FREE( buffer );
292                         return NT_STATUS_UNSUCCESSFUL;
293                 }
294         } while ( buf_len < resp_len && resp_len < MAX_DNS_PACKET_SIZE );
295         
296         *buf = buffer;
297         *resp_length = resp_len;
298
299         return NT_STATUS_OK;
300 }
301
302 /*********************************************************************
303  Simple wrapper for a DNS SRV query
304 *********************************************************************/
305
306 static NTSTATUS ads_dns_lookup_srv( TALLOC_CTX *ctx, const char *name, struct dns_rr_srv **dclist, int *numdcs )
307 {
308         uint8 *buffer = NULL;
309         int resp_len = 0;
310         struct dns_rr_srv *dcs = NULL;
311         int query_count, answer_count, auth_count, additional_count;
312         uint8 *p = buffer;
313         int rrnum;
314         int idx = 0;
315         NTSTATUS status;
316
317         if ( !ctx || !name || !dclist ) {
318                 return NT_STATUS_INVALID_PARAMETER;
319         }
320         
321         /* Send the request.  May have to loop several times in case 
322            of large replies */
323
324         status = dns_send_req( ctx, name, T_SRV, &buffer, &resp_len );
325         if ( !NT_STATUS_IS_OK(status) ) {
326                 DEBUG(0,("ads_dns_lookup_srv: Failed to send DNS query (%s)\n",
327                         nt_errstr(status)));
328                 return status;
329         }
330         p = buffer;
331
332         /* For some insane reason, the ns_initparse() et. al. routines are only
333            available in libresolv.a, and not the shared lib.  Who knows why....
334            So we have to parse the DNS reply ourselves */
335
336         /* Pull the answer RR's count from the header.  Use the NMB ordering macros */
337
338         query_count      = RSVAL( p, 4 );
339         answer_count     = RSVAL( p, 6 );
340         auth_count       = RSVAL( p, 8 );
341         additional_count = RSVAL( p, 10 );
342
343         DEBUG(4,("ads_dns_lookup_srv: %d records returned in the answer section.\n", 
344                 answer_count));
345                 
346         if ( (dcs = TALLOC_ARRAY(ctx, struct dns_rr_srv, answer_count)) == NULL ) {
347                 DEBUG(0,("ads_dns_lookup_srv: talloc() failure for %d char*'s\n", 
348                         answer_count));
349                 return NT_STATUS_NO_MEMORY;
350         }
351
352         /* now skip the header */
353
354         p += NS_HFIXEDSZ;
355
356         /* parse the query section */
357
358         for ( rrnum=0; rrnum<query_count; rrnum++ ) {
359                 struct dns_query q;
360
361                 if ( !ads_dns_parse_query( ctx, buffer, buffer+resp_len, &p, &q ) ) {
362                         DEBUG(1,("ads_dns_lookup_srv: Failed to parse query record!\n"));
363                         return NT_STATUS_UNSUCCESSFUL;
364                 }
365         }
366
367         /* now we are at the answer section */
368
369         for ( rrnum=0; rrnum<answer_count; rrnum++ ) {
370                 if ( !ads_dns_parse_rr_srv( ctx, buffer, buffer+resp_len, &p, &dcs[rrnum] ) ) {
371                         DEBUG(1,("ads_dns_lookup_srv: Failed to parse answer record!\n"));
372                         return NT_STATUS_UNSUCCESSFUL;
373                 }               
374         }
375         idx = rrnum;
376
377         /* Parse the authority section */
378         /* just skip these for now */
379
380         for ( rrnum=0; rrnum<auth_count; rrnum++ ) {
381                 struct dns_rr rr;
382
383                 if ( !ads_dns_parse_rr( ctx, buffer, buffer+resp_len, &p, &rr ) ) {
384                         DEBUG(1,("ads_dns_lookup_srv: Failed to parse authority record!\n"));
385                         return NT_STATUS_UNSUCCESSFUL;
386                 }
387         }
388
389         /* Parse the additional records section */
390
391         for ( rrnum=0; rrnum<additional_count; rrnum++ ) {
392                 struct dns_rr rr;
393                 int i;
394
395                 if ( !ads_dns_parse_rr( ctx, buffer, buffer+resp_len, &p, &rr ) ) {
396                         DEBUG(1,("ads_dns_lookup_srv: Failed to parse additional records section!\n"));
397                         return NT_STATUS_UNSUCCESSFUL;
398                 }
399
400                 /* only interested in A records as a shortcut for having to come 
401                    back later and lookup the name */
402
403                 if ( (rr.type != T_A) || (rr.rdatalen != 4) ) 
404                         continue;
405
406                 for ( i=0; i<idx; i++ ) {
407                         if ( strcmp( rr.hostname, dcs[i].hostname ) == 0 ) {
408                                 uint8 *buf = (uint8*)&dcs[i].ip.s_addr;
409                                 memcpy( buf, rr.rdata, 4 );
410                         }
411                 }
412         }
413
414         qsort( dcs, idx, sizeof(struct dns_rr_srv), QSORT_CAST dnssrvcmp );
415         
416         *dclist = dcs;
417         *numdcs = idx;
418         
419         return NT_STATUS_OK;
420 }
421
422 /*********************************************************************
423  Simple wrapper for a DNS NS query
424 *********************************************************************/
425
426 NTSTATUS ads_dns_lookup_ns( TALLOC_CTX *ctx, const char *dnsdomain, struct dns_rr_ns **nslist, int *numns )
427 {
428         uint8 *buffer = NULL;
429         int resp_len = 0;
430         struct dns_rr_ns *nsarray = NULL;
431         int query_count, answer_count, auth_count, additional_count;
432         uint8 *p;
433         int rrnum;
434         int idx = 0;
435         NTSTATUS status;
436
437         if ( !ctx || !dnsdomain || !nslist ) {
438                 return NT_STATUS_INVALID_PARAMETER;
439         }
440         
441         /* Send the request.  May have to loop several times in case 
442            of large replies */
443            
444         status = dns_send_req( ctx, dnsdomain, T_NS, &buffer, &resp_len );
445         if ( !NT_STATUS_IS_OK(status) ) {
446                 DEBUG(0,("ads_dns_lookup_ns: Failed to send DNS query (%s)\n",
447                         nt_errstr(status)));
448                 return status;
449         }
450         p = buffer;
451
452         /* For some insane reason, the ns_initparse() et. al. routines are only
453            available in libresolv.a, and not the shared lib.  Who knows why....
454            So we have to parse the DNS reply ourselves */
455
456         /* Pull the answer RR's count from the header.  Use the NMB ordering macros */
457
458         query_count      = RSVAL( p, 4 );
459         answer_count     = RSVAL( p, 6 );
460         auth_count       = RSVAL( p, 8 );
461         additional_count = RSVAL( p, 10 );
462
463         DEBUG(4,("ads_dns_lookup_ns: %d records returned in the answer section.\n", 
464                 answer_count));
465                 
466         if ( (nsarray = TALLOC_ARRAY(ctx, struct dns_rr_ns, answer_count)) == NULL ) {
467                 DEBUG(0,("ads_dns_lookup_ns: talloc() failure for %d char*'s\n", 
468                         answer_count));
469                 return NT_STATUS_NO_MEMORY;
470         }
471
472         /* now skip the header */
473
474         p += NS_HFIXEDSZ;
475
476         /* parse the query section */
477
478         for ( rrnum=0; rrnum<query_count; rrnum++ ) {
479                 struct dns_query q;
480
481                 if ( !ads_dns_parse_query( ctx, buffer, buffer+resp_len, &p, &q ) ) {
482                         DEBUG(1,("ads_dns_lookup_ns: Failed to parse query record!\n"));
483                         return NT_STATUS_UNSUCCESSFUL;
484                 }
485         }
486
487         /* now we are at the answer section */
488
489         for ( rrnum=0; rrnum<answer_count; rrnum++ ) {
490                 if ( !ads_dns_parse_rr_ns( ctx, buffer, buffer+resp_len, &p, &nsarray[rrnum] ) ) {
491                         DEBUG(1,("ads_dns_lookup_ns: Failed to parse answer record!\n"));
492                         return NT_STATUS_UNSUCCESSFUL;
493                 }               
494         }
495         idx = rrnum;
496
497         /* Parse the authority section */
498         /* just skip these for now */
499
500         for ( rrnum=0; rrnum<auth_count; rrnum++ ) {
501                 struct dns_rr rr;
502
503                 if ( !ads_dns_parse_rr( ctx, buffer, buffer+resp_len, &p, &rr ) ) {
504                         DEBUG(1,("ads_dns_lookup_ns: Failed to parse authority record!\n"));
505                         return NT_STATUS_UNSUCCESSFUL;
506                 }
507         }
508
509         /* Parse the additional records section */
510
511         for ( rrnum=0; rrnum<additional_count; rrnum++ ) {
512                 struct dns_rr rr;
513                 int i;
514
515                 if ( !ads_dns_parse_rr( ctx, buffer, buffer+resp_len, &p, &rr ) ) {
516                         DEBUG(1,("ads_dns_lookup_ns: Failed to parse additional records section!\n"));
517                         return NT_STATUS_UNSUCCESSFUL;
518                 }
519
520                 /* only interested in A records as a shortcut for having to come 
521                    back later and lookup the name */
522
523                 if ( (rr.type != T_A) || (rr.rdatalen != 4) ) 
524                         continue;
525
526                 for ( i=0; i<idx; i++ ) {
527                         if ( strcmp( rr.hostname, nsarray[i].hostname ) == 0 ) {
528                                 uint8 *buf = (uint8*)&nsarray[i].ip.s_addr;
529                                 memcpy( buf, rr.rdata, 4 );
530                         }
531                 }
532         }
533         
534         *nslist = nsarray;
535         *numns = idx;
536         
537         return NT_STATUS_OK;
538 }
539
540
541 /********************************************************************
542 ********************************************************************/
543
544 NTSTATUS ads_dns_query_dcs( TALLOC_CTX *ctx, const char *domain, struct dns_rr_srv **dclist, int *numdcs )
545 {
546         pstring name;
547
548         snprintf( name, sizeof(name), "_ldap._tcp.dc._msdcs.%s", domain );
549
550         return ads_dns_lookup_srv( ctx, name, dclist, numdcs );
551 }
552