993ef43caabbf94d0fe7ff88e5452789eb5b8fe9
[ddiss/samba.git] / source4 / libcli / resolve / dns_ex.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    async getaddrinfo()/dns_lookup() name resolution module
5
6    Copyright (C) Andrew Tridgell 2005
7    Copyright (C) Stefan Metzmacher 2008
8    Copyright (C) Matthieu Patou 2011
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 */
23
24 /*
25   this module uses a fork() per getaddrinfo() or dns_looup() call.
26   At first that might seem crazy, but it is actually very fast,
27   and solves many of the tricky problems of keeping a child
28   hanging around in a librar (like what happens when the parent forks).
29   We use a talloc destructor to ensure that the child is cleaned up
30   when we have finished with this name resolution.
31 */
32
33 #include "includes.h"
34 #include "lib/events/events.h"
35 #include "system/network.h"
36 #include "system/filesys.h"
37 #include "lib/socket/socket.h"
38 #include "libcli/composite/composite.h"
39 #include "librpc/gen_ndr/ndr_nbt.h"
40 #include "libcli/resolve/resolve.h"
41 #include "lib/util/util_net.h"
42
43 #ifdef class
44 #undef class
45 #endif
46
47 #include "heimdal/lib/roken/resolve.h"
48
49 struct dns_ex_state {
50         bool do_fallback;
51         uint32_t flags;
52         uint16_t port;
53         struct nbt_name name;
54         struct socket_address **addrs;
55         char **names;
56         pid_t child;
57         int child_fd;
58         struct tevent_fd *fde;
59         struct tevent_context *event_ctx;
60 };
61
62 /*
63   kill off a wayward child if needed. This allows us to stop an async
64   name resolution without leaving a potentially blocking call running
65   in a child
66 */
67 static int dns_ex_destructor(struct dns_ex_state *state)
68 {
69         int status;
70
71         kill(state->child, SIGTERM);
72         if (waitpid(state->child, &status, WNOHANG) == 0) {
73                 kill(state->child, SIGKILL);
74                 waitpid(state->child, &status, 0);
75         }
76
77         return 0;
78 }
79
80 static uint32_t count_dns_rr(struct rk_resource_record *head, unsigned record_type)
81 {
82         uint32_t count = 0;
83         struct rk_resource_record *rr;
84
85         for (rr=head; rr; rr=rr->next) {
86
87                 /* we are only interested in the IN class */
88                 if (rr->class != rk_ns_c_in) {
89                         continue;
90                 }
91
92                 /* we are only interested by requested record */
93                 if (rr->type != record_type) {
94                         continue;
95                 }
96
97                 switch(record_type) {
98                         case rk_ns_t_srv:
99
100                                 /* verify we actually have a SRV record here */
101                                 if (!rr->u.srv) {
102                                         continue;
103                                 }
104
105                                 /* Verify we got a port */
106                                 if (rr->u.srv->port == 0) {
107                                         continue;
108                                 }
109                                 count++;
110                                 break;
111                         case rk_ns_t_a:
112                         case rk_ns_t_aaaa:
113                                 /* verify we actually have a record here */
114                                 if (!rr->u.data) {
115                                         continue;
116                                 }
117                                 count++;
118                                 break;
119                         default:
120                                 count++;
121                                 break;
122                 }
123         }
124
125         return count;
126 }
127
128 struct dns_records_container {
129         char **list;
130         uint32_t count;
131 };
132
133 static char* rr_to_string(TALLOC_CTX *mem_ctx,
134                                         struct rk_resource_record *rr,
135                                         uint16_t port)
136 {
137         char addrstr[INET6_ADDRSTRLEN];
138         char *addr;
139
140         switch (rr->type) {
141                 case rk_ns_t_a:
142                         if (inet_ntop(AF_INET, rr->u.a,
143                                       addrstr, sizeof(addrstr)) == NULL) {
144                                 return NULL;
145                         }
146                         break;
147 #ifdef HAVE_IPV6
148                 case rk_ns_t_aaaa:
149                         if (inet_ntop(AF_INET6, (struct in6_addr *)rr->u.data,
150                                       addrstr, sizeof(addrstr)) == NULL) {
151                                 return NULL;
152                         }
153                         break;
154 #endif
155                 default:
156                         return NULL;
157         }
158
159         addr = talloc_asprintf(mem_ctx, "%s@%u/%s", addrstr,
160                                          port, rr->domain);
161
162         return addr;
163 }
164
165 static struct dns_records_container get_a_aaaa_records(TALLOC_CTX *mem_ctx,
166                                                         const char* name,
167                                                         int port)
168 {
169         struct rk_dns_reply *reply, *reply2, *rep, *tmp[3];
170         struct rk_resource_record *rr;
171         struct dns_records_container ret;
172         char **addrs = NULL;
173         uint32_t count, count2, total;
174         uint32_t i;
175
176         memset(&ret, 0, sizeof(struct dns_records_container));
177         /* this is the blocking call we are going to lots of trouble
178            to avoid them in the parent */
179         reply = rk_dns_lookup(name, "AAAA");
180
181         count = count2 = 0;
182
183         if (reply) {
184
185                 count = count_dns_rr(reply->head, rk_ns_t_aaaa);
186                 count2 = count_dns_rr(reply->head, rk_ns_t_a);
187
188                 if (!count2) {
189                         /*
190                         * DNS server didn't returned A when asked for AAAA records.
191                         * Most of the server do it, let's ask for A specificaly.
192                         */
193                         reply2 = rk_dns_lookup(name, "A");
194
195                         if (!reply2) {
196                                 return ret;
197                         }
198
199                         count2 = count_dns_rr(reply2->head, rk_ns_t_a);
200                 } else {
201                         reply2 = NULL;
202                 }
203         } else {
204
205                 reply = rk_dns_lookup(name, "A");
206                 if (!reply) {
207                         return ret;
208                 }
209
210                 reply2 = NULL;
211                 count = count_dns_rr(reply->head, rk_ns_t_a);
212         }
213         count += count2;
214
215         if (count == 0) {
216                 goto done;
217         }
218
219         addrs = talloc_zero_array(mem_ctx, char*, count);
220         total = 0;
221
222         tmp[0] = reply;
223         tmp[1] = reply2;
224         tmp[2] = NULL;
225
226         /* Loop over all returned records and pick the records */
227         for (i=0; tmp[i] != NULL; i++) {
228                 rep = tmp[i];
229                 for (rr=rep->head; rr; rr=rr->next) {
230                         /* we are only interested in the IN class */
231                         if (rr->class != rk_ns_c_in) {
232                                 continue;
233                         }
234
235                         /* we are only interested in A and AAAA records */
236                         if (rr->type != rk_ns_t_a && rr->type != rk_ns_t_aaaa) {
237                                 continue;
238                         }
239
240                         /* verify we actually have a record here */
241                         if (!rr->u.data) {
242                                 continue;
243                         }
244                         rr_to_string(mem_ctx, rr, port);
245                         addrs[total] = rr_to_string(mem_ctx, rr, port);
246                         if (addrs[total]) {
247                                 total++;
248                         }
249                 }
250         }
251         if (total) {
252                 ret.count = total;
253                 ret.list = addrs;
254         }
255
256 done:
257         if (reply != NULL)
258                 rk_dns_free_data(reply);
259
260         if (reply2 != NULL)
261                 rk_dns_free_data(reply2);
262
263         return ret;
264 }
265
266 static struct dns_records_container get_srv_records(TALLOC_CTX *mem_ctx,
267                                                         const char* name)
268 {
269         struct rk_dns_reply *reply;
270         struct rk_resource_record *rr;
271         struct dns_records_container ret;
272         char **addrs = NULL;
273         uint32_t count, total;
274
275         memset(&ret, 0, sizeof(struct dns_records_container));
276         /* this is the blocking call we are going to lots of trouble
277            to avoid them in the parent */
278         reply = rk_dns_lookup(name, "SRV");
279
280         if (!reply) {
281                 return ret;
282         }
283
284         rk_dns_srv_order(reply);
285         count = count_dns_rr(reply->head, rk_ns_t_srv);
286
287         total = 0;
288         if (count == 0) {
289                 goto done;
290         }
291
292         /* Loop over all returned records and pick the records */
293         for (rr=reply->head; rr; rr=rr->next) {
294                 struct dns_records_container c;
295                 char* tmp_str;
296                 /* we are only interested in the IN class */
297                 if (rr->class != rk_ns_c_in) {
298                         continue;
299                 }
300
301                 /* we are only interested in SRV records */
302                 if (rr->type != rk_ns_t_srv) {
303                         continue;
304                 }
305
306                 /* verify we actually have a srv record here */
307                 if (!rr->u.srv) {
308                         continue;
309                 }
310
311                 /* Verify we got a port */
312                 if (rr->u.srv->port == 0) {
313                         continue;
314                 }
315
316                 tmp_str = rr->u.srv->target;
317                 if (strchr(tmp_str, '.') && tmp_str[strlen(tmp_str)-1] != '.') {
318                         /* we are asking for a fully qualified name, but the
319                         name doesn't end in a '.'. We need to prevent the
320                         DNS library trying the search domains configured in
321                         resolv.conf */
322                         tmp_str = talloc_asprintf(mem_ctx, "%s.", tmp_str);
323                 }
324
325                 c = get_a_aaaa_records(mem_ctx, tmp_str, rr->u.srv->port);
326                 total += c.count;
327                 if (addrs == NULL) {
328                         addrs = c.list;
329                 } else {
330                         unsigned j;
331
332                         addrs = talloc_realloc(mem_ctx, addrs, char*, total);
333                         for (j=0; j < c.count; j++) {
334                                 addrs[total - j - 1] = talloc_steal(addrs, c.list[j]);
335                         }
336                 }
337         }
338
339         if (total) {
340                 ret.count = total;
341                 ret.list = addrs;
342         }
343
344
345 done:
346         if (reply != NULL)
347                 rk_dns_free_data(reply);
348
349         return ret;
350 }
351 /*
352   the blocking child
353 */
354 static void run_child_dns_lookup(struct dns_ex_state *state, int fd)
355 {
356         bool first;
357         bool do_srv = (state->flags & RESOLVE_NAME_FLAG_DNS_SRV);
358         struct dns_records_container c;
359         char* addrs = NULL;
360         unsigned int i;
361
362         if (strchr(state->name.name, '.') && state->name.name[strlen(state->name.name)-1] != '.') {
363                 /* we are asking for a fully qualified name, but the
364                    name doesn't end in a '.'. We need to prevent the
365                    DNS library trying the search domains configured in
366                    resolv.conf */
367                 state->name.name = talloc_strdup_append(discard_const_p(char, state->name.name),
368                                                         ".");
369         }
370
371
372         if (do_srv) {
373                 c = get_srv_records(state, state->name.name);
374         } else {
375                 c = get_a_aaaa_records(state, state->name.name, state->port);
376         }
377
378         addrs = talloc_strdup(state, "");
379         if (!addrs) {
380                 goto done;
381         }
382         first = true;
383
384         for (i=0; i < c.count; i++) {
385                 addrs = talloc_asprintf_append_buffer(addrs, "%s%s",
386                                                         first?"":",",
387                                                         c.list[i]);
388                 first = false;
389         }
390
391         if (addrs) {
392                 DEBUG(11, ("Addrs = %s\n", addrs));
393                 write(fd, addrs, talloc_get_size(addrs));
394         }
395
396 done:
397         close(fd);
398 }
399
400 /*
401   the blocking child
402 */
403 static void run_child_getaddrinfo(struct dns_ex_state *state, int fd)
404 {
405         int ret;
406         struct addrinfo hints;
407         struct addrinfo *res;
408         struct addrinfo *res_list = NULL;
409         char *addrs;
410         bool first;
411
412         ZERO_STRUCT(hints);
413         hints.ai_socktype = SOCK_STREAM;
414         hints.ai_flags = AI_ADDRCONFIG | AI_NUMERICSERV;
415
416         ret = getaddrinfo(state->name.name, "0", &hints, &res_list);
417         /* try to fallback in case of error */
418         if (state->do_fallback) {
419                 switch (ret) {
420 #ifdef EAI_NODATA
421                 case EAI_NODATA:
422 #endif
423                 case EAI_NONAME:
424                         /* getaddrinfo() doesn't handle CNAME records */
425                         run_child_dns_lookup(state, fd);
426                         return;
427                 default:
428                         break;
429                 }
430         }
431         if (ret != 0) {
432                 goto done;
433         }
434
435         addrs = talloc_strdup(state, "");
436         if (!addrs) {
437                 goto done;
438         }
439         first = true;
440         for (res = res_list; res; res = res->ai_next) {
441                 char addrstr[INET6_ADDRSTRLEN];
442                 if (!print_sockaddr_len(addrstr, sizeof(addrstr), (struct sockaddr *)res->ai_addr, res->ai_addrlen)) {
443                         continue;
444                 }
445                 addrs = talloc_asprintf_append_buffer(addrs, "%s%s@%u/%s",
446                                                       first?"":",",
447                                                       addrstr,
448                                                       state->port,
449                                                       state->name.name);
450                 if (!addrs) {
451                         goto done;
452                 }
453                 first = false;
454         }
455
456         if (addrs) {
457                 write(fd, addrs, talloc_get_size(addrs));
458         }
459 done:
460         if (res_list) {
461                 freeaddrinfo(res_list);
462         }
463         close(fd);
464 }
465
466 /*
467   handle a read event on the pipe
468 */
469 static void pipe_handler(struct tevent_context *ev, struct tevent_fd *fde, 
470                          uint16_t flags, void *private_data)
471 {
472         struct composite_context *c = talloc_get_type(private_data, struct composite_context);
473         struct dns_ex_state *state = talloc_get_type(c->private_data,
474                                      struct dns_ex_state);
475         char *address;
476         uint32_t num_addrs, i;
477         char **addrs;
478         int ret;
479         int status;
480         int value = 0;
481
482         /* if we get any event from the child then we know that we
483            won't need to kill it off */
484         talloc_set_destructor(state, NULL);
485
486         if (ioctl(state->child_fd, FIONREAD, &value) != 0) {
487                 value = 8192;
488         }
489
490         address = talloc_array(state, char, value+1);
491         if (address) {
492                 /* yes, we don't care about EAGAIN or other niceities
493                    here. They just can't happen with this parent/child
494                    relationship, and even if they did then giving an error is
495                    the right thing to do */
496                 ret = read(state->child_fd, address, value);
497         } else {
498                 ret = -1;
499         }
500         if (waitpid(state->child, &status, WNOHANG) == 0) {
501                 kill(state->child, SIGKILL);
502                 waitpid(state->child, &status, 0);
503         }
504
505         if (ret <= 0) {
506                 DEBUG(3,("dns child failed to find name '%s' of type %s\n",
507                          state->name.name, (state->flags & RESOLVE_NAME_FLAG_DNS_SRV)?"SRV":"A"));
508                 composite_error(c, NT_STATUS_OBJECT_NAME_NOT_FOUND);
509                 return;
510         }
511
512         /* enusre the address looks good */
513         address[ret] = 0;
514
515         addrs = str_list_make(state, address, ",");
516         if (composite_nomem(addrs, c)) return;
517
518         num_addrs = str_list_length((const char * const *)addrs);
519
520         state->addrs = talloc_array(state, struct socket_address *,
521                                     num_addrs+1);
522         if (composite_nomem(state->addrs, c)) return;
523
524         state->names = talloc_array(state, char *, num_addrs+1);
525         if (composite_nomem(state->names, c)) return;
526
527         for (i=0; i < num_addrs; i++) {
528                 uint32_t port = 0;
529                 char *p = strrchr(addrs[i], '@');
530                 char *n;
531
532                 if (!p) {
533                         composite_error(c, NT_STATUS_OBJECT_NAME_NOT_FOUND);
534                         return;
535                 }
536
537                 *p = '\0';
538                 p++;
539
540                 n = strrchr(p, '/');
541                 if (!n) {
542                         composite_error(c, NT_STATUS_OBJECT_NAME_NOT_FOUND);
543                         return;
544                 }
545
546                 *n = '\0';
547                 n++;
548
549                 if (strcmp(addrs[i], "0.0.0.0") == 0) {
550                         composite_error(c, NT_STATUS_OBJECT_NAME_NOT_FOUND);
551                         return;
552                 }
553                 port = strtoul(p, NULL, 10);
554                 if (port > UINT16_MAX) {
555                         composite_error(c, NT_STATUS_OBJECT_NAME_NOT_FOUND);
556                         return;
557                 }
558                 state->addrs[i] = socket_address_from_strings(state->addrs,
559                                                               "ip",
560                                                               addrs[i],
561                                                               port);
562                 if (composite_nomem(state->addrs[i], c)) return;
563
564                 state->names[i] = talloc_strdup(state->names, n);
565                 if (composite_nomem(state->names[i], c)) return;
566         }
567         state->addrs[i] = NULL;
568         state->names[i] = NULL;
569
570         composite_done(c);
571 }
572
573 /*
574   getaddrinfo() or dns_lookup() name resolution method - async send
575  */
576 struct composite_context *resolve_name_dns_ex_send(TALLOC_CTX *mem_ctx,
577                                                    struct tevent_context *event_ctx,
578                                                    void *privdata,
579                                                    uint32_t flags,
580                                                    uint16_t port,
581                                                    struct nbt_name *name,
582                                                    bool do_fallback)
583 {
584         struct composite_context *c;
585         struct dns_ex_state *state;
586         int fd[2] = { -1, -1 };
587         int ret;
588
589         c = composite_create(mem_ctx, event_ctx);
590         if (c == NULL) return NULL;
591
592         if (flags & RESOLVE_NAME_FLAG_FORCE_NBT) {
593                 composite_error(c, NT_STATUS_OBJECT_NAME_NOT_FOUND);
594                 return c;
595         }
596
597         state = talloc_zero(c, struct dns_ex_state);
598         if (composite_nomem(state, c)) return c;
599         c->private_data = state;
600
601         c->status = nbt_name_dup(state, name, &state->name);
602         if (!composite_is_ok(c)) return c;
603
604         /* setup a pipe to chat to our child */
605         ret = pipe(fd);
606         if (ret == -1) {
607                 composite_error(c, map_nt_error_from_unix_common(errno));
608                 return c;
609         }
610
611         state->do_fallback = do_fallback;
612         state->flags = flags;
613         state->port = port;
614
615         state->child_fd = fd[0];
616         state->event_ctx = c->event_ctx;
617
618         /* we need to put the child in our event context so
619            we know when the dns_lookup() has finished */
620         state->fde = tevent_add_fd(c->event_ctx, c, state->child_fd, TEVENT_FD_READ,
621                                   pipe_handler, c);
622         if (composite_nomem(state->fde, c)) {
623                 close(fd[0]);
624                 close(fd[1]);
625                 return c;
626         }
627         tevent_fd_set_auto_close(state->fde);
628
629         state->child = fork();
630         if (state->child == (pid_t)-1) {
631                 composite_error(c, map_nt_error_from_unix_common(errno));
632                 return c;
633         }
634
635         if (state->child == 0) {
636                 close(fd[0]);
637                 if (state->flags & RESOLVE_NAME_FLAG_FORCE_DNS) {
638                         run_child_dns_lookup(state, fd[1]);
639                 } else {
640                         run_child_getaddrinfo(state, fd[1]);
641                 }
642                 _exit(0);
643         }
644         close(fd[1]);
645
646         /* cleanup wayward children */
647         talloc_set_destructor(state, dns_ex_destructor);
648
649         return c;
650 }
651
652 /*
653   getaddrinfo() or dns_lookup() name resolution method - recv side
654 */
655 NTSTATUS resolve_name_dns_ex_recv(struct composite_context *c, 
656                                   TALLOC_CTX *mem_ctx,
657                                   struct socket_address ***addrs,
658                                   char ***names)
659 {
660         NTSTATUS status;
661
662         status = composite_wait(c);
663
664         if (NT_STATUS_IS_OK(status)) {
665                 struct dns_ex_state *state = talloc_get_type(c->private_data,
666                                              struct dns_ex_state);
667                 *addrs = talloc_steal(mem_ctx, state->addrs);
668                 if (names) {
669                         *names = talloc_steal(mem_ctx, state->names);
670                 }
671         }
672
673         talloc_free(c);
674         return status;
675 }