4f46235a9ff57ae885ba020d75e1c94c00e4ac37
[sfrench/samba-autobuild/.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                 if (rr->type == rk_ns_t_ns) {
93                         /*
94                          * Record that will follow will be related to the NS
95                          * not what we are really interested with.
96                          * It's a good idea not to count them
97                          */
98                         break;
99                 }
100                 /* we are only interested by requested record */
101                 if (rr->type != record_type) {
102                         continue;
103                 }
104
105                 switch(record_type) {
106                         case rk_ns_t_srv:
107
108                                 /* verify we actually have a SRV record here */
109                                 if (!rr->u.srv) {
110                                         continue;
111                                 }
112
113                                 /* Verify we got a port */
114                                 if (rr->u.srv->port == 0) {
115                                         continue;
116                                 }
117                                 count++;
118                                 break;
119                         case rk_ns_t_a:
120                         case rk_ns_t_aaaa:
121                                 /* verify we actually have a record here */
122                                 if (!rr->u.data) {
123                                         continue;
124                                 }
125                                 count++;
126                                 break;
127                         default:
128                                 count++;
129                                 break;
130                 }
131         }
132
133         return count;
134 }
135
136 struct dns_records_container {
137         char **list;
138         uint32_t count;
139 };
140
141 static char* rr_to_string(TALLOC_CTX *mem_ctx,
142                                         struct rk_resource_record *rr,
143                                         uint16_t port)
144 {
145         char addrstr[INET6_ADDRSTRLEN];
146         char *addr;
147
148         switch (rr->type) {
149                 case rk_ns_t_a:
150                         if (inet_ntop(AF_INET, rr->u.a,
151                                       addrstr, sizeof(addrstr)) == NULL) {
152                                 return NULL;
153                         }
154                         break;
155 #ifdef HAVE_IPV6
156                 case rk_ns_t_aaaa:
157                         if (inet_ntop(AF_INET6, (struct in6_addr *)rr->u.data,
158                                       addrstr, sizeof(addrstr)) == NULL) {
159                                 return NULL;
160                         }
161                         break;
162 #endif
163                 default:
164                         return NULL;
165         }
166
167         addr = talloc_asprintf(mem_ctx, "%s@%u/%s", addrstr,
168                                          port, rr->domain);
169
170         return addr;
171 }
172
173 static struct dns_records_container get_a_aaaa_records(TALLOC_CTX *mem_ctx,
174                                                         const char* name,
175                                                         int port)
176 {
177         struct rk_dns_reply *reply, *reply2, *rep, *tmp[3];
178         struct rk_resource_record *rr;
179         struct dns_records_container ret;
180         char **addrs = NULL;
181         uint32_t count, count2, total;
182         uint32_t i;
183
184         memset(&ret, 0, sizeof(struct dns_records_container));
185         /* this is the blocking call we are going to lots of trouble
186            to avoid them in the parent */
187         reply = rk_dns_lookup(name, "AAAA");
188
189         count = count2 = 0;
190
191         if (reply) {
192
193                 count = count_dns_rr(reply->head, rk_ns_t_aaaa);
194                 count2 = count_dns_rr(reply->head, rk_ns_t_a);
195
196                 if (!count2) {
197                         /*
198                         * DNS server didn't returned A when asked for AAAA records.
199                         * Most of the server do it, let's ask for A specificaly.
200                         */
201                         reply2 = rk_dns_lookup(name, "A");
202
203                         if (!reply2) {
204                                 return ret;
205                         }
206
207                         /* Some servers (Microsoft at least return here AAAA records .... */
208                         count += count_dns_rr(reply2->head, rk_ns_t_aaaa);
209                         count2 = count_dns_rr(reply2->head, rk_ns_t_a);
210                 } else {
211                         reply2 = NULL;
212                 }
213         } else {
214
215                 reply = rk_dns_lookup(name, "A");
216                 if (!reply) {
217                         return ret;
218                 }
219
220                 reply2 = NULL;
221                 count = count_dns_rr(reply->head, rk_ns_t_a);
222         }
223         count += count2;
224
225         if (count == 0) {
226                 goto done;
227         }
228
229         addrs = talloc_zero_array(mem_ctx, char*, count);
230         total = 0;
231
232         tmp[0] = reply;
233         tmp[1] = reply2;
234         tmp[2] = NULL;
235
236         /* Loop over all returned records and pick the records */
237         for (i=0; tmp[i] != NULL; i++) {
238                 rep = tmp[i];
239                 for (rr=rep->head; rr; rr=rr->next) {
240                         /* we are only interested in the IN class */
241                         if (rr->class != rk_ns_c_in) {
242                                 continue;
243                         }
244
245                         if (rr->type == rk_ns_t_ns) {
246                                 /*
247                                  * After the record for NS will come the A or AAAA
248                                  * record of the NS.
249                                  */
250                                 break;
251                         }
252
253                         /* we are only interested in A and AAAA records */
254                         if (rr->type != rk_ns_t_a && rr->type != rk_ns_t_aaaa) {
255                                 continue;
256                         }
257
258                         /* verify we actually have a record here */
259                         if (!rr->u.data) {
260                                 continue;
261                         }
262
263                         addrs[total] = rr_to_string(addrs, rr, port);
264                         if (addrs[total]) {
265                                 total++;
266                         }
267                 }
268         }
269         if (total) {
270                 ret.count = total;
271                 ret.list = addrs;
272         }
273
274 done:
275         if (reply != NULL)
276                 rk_dns_free_data(reply);
277
278         if (reply2 != NULL)
279                 rk_dns_free_data(reply2);
280
281         return ret;
282 }
283
284 static struct dns_records_container get_srv_records(TALLOC_CTX *mem_ctx,
285                                                         const char* name)
286 {
287         struct rk_dns_reply *reply;
288         struct rk_resource_record *rr;
289         struct dns_records_container ret;
290         char **addrs = NULL;
291         uint32_t count, total;
292
293         memset(&ret, 0, sizeof(struct dns_records_container));
294         /* this is the blocking call we are going to lots of trouble
295            to avoid them in the parent */
296         reply = rk_dns_lookup(name, "SRV");
297
298         if (!reply) {
299                 return ret;
300         }
301
302         rk_dns_srv_order(reply);
303         count = count_dns_rr(reply->head, rk_ns_t_srv);
304
305         total = 0;
306         if (count == 0) {
307                 goto done;
308         }
309
310         /* Loop over all returned records and pick the records */
311         for (rr=reply->head; rr; rr=rr->next) {
312                 struct dns_records_container c;
313                 char* tmp_str;
314                 /* we are only interested in the IN class */
315                 if (rr->class != rk_ns_c_in) {
316                         continue;
317                 }
318
319                 /* we are only interested in SRV records */
320                 if (rr->type != rk_ns_t_srv) {
321                         continue;
322                 }
323
324                 /* verify we actually have a srv record here */
325                 if (!rr->u.srv) {
326                         continue;
327                 }
328
329                 /* Verify we got a port */
330                 if (rr->u.srv->port == 0) {
331                         continue;
332                 }
333
334                 tmp_str = rr->u.srv->target;
335                 if (strchr(tmp_str, '.') && tmp_str[strlen(tmp_str)-1] != '.') {
336                         /* we are asking for a fully qualified name, but the
337                         name doesn't end in a '.'. We need to prevent the
338                         DNS library trying the search domains configured in
339                         resolv.conf */
340                         tmp_str = talloc_asprintf(mem_ctx, "%s.", tmp_str);
341                 }
342
343                 c = get_a_aaaa_records(mem_ctx, tmp_str, rr->u.srv->port);
344                 total += c.count;
345                 if (addrs == NULL) {
346                         addrs = c.list;
347                 } else {
348                         unsigned j;
349
350                         addrs = talloc_realloc(mem_ctx, addrs, char*, total);
351                         for (j=0; j < c.count; j++) {
352                                 addrs[total - j - 1] = talloc_steal(addrs, c.list[j]);
353                         }
354                 }
355         }
356
357         if (total) {
358                 ret.count = total;
359                 ret.list = addrs;
360         }
361
362
363 done:
364         if (reply != NULL)
365                 rk_dns_free_data(reply);
366
367         return ret;
368 }
369 /*
370   the blocking child
371 */
372 static void run_child_dns_lookup(struct dns_ex_state *state, int fd)
373 {
374         bool first;
375         bool do_srv = (state->flags & RESOLVE_NAME_FLAG_DNS_SRV);
376         struct dns_records_container c;
377         char* addrs = NULL;
378         unsigned int i;
379
380         if (strchr(state->name.name, '.') && state->name.name[strlen(state->name.name)-1] != '.') {
381                 /* we are asking for a fully qualified name, but the
382                    name doesn't end in a '.'. We need to prevent the
383                    DNS library trying the search domains configured in
384                    resolv.conf */
385                 state->name.name = talloc_strdup_append(discard_const_p(char, state->name.name),
386                                                         ".");
387         }
388
389
390         if (do_srv) {
391                 c = get_srv_records(state, state->name.name);
392         } else {
393                 c = get_a_aaaa_records(state, state->name.name, state->port);
394         }
395
396         /* This line in critical - if we return without writing to the
397          * pipe, this is the signal that the name did not exist */
398         if (c.count == 0) {
399                 goto done;
400         }
401
402         addrs = talloc_strdup(state, "");
403         if (!addrs) {
404                 goto done;
405         }
406         first = true;
407
408         for (i=0; i < c.count; i++) {
409                 addrs = talloc_asprintf_append_buffer(addrs, "%s%s",
410                                                         first?"":",",
411                                                         c.list[i]);
412                 first = false;
413         }
414
415         if (addrs) {
416                 DEBUG(11, ("Addrs = %s\n", addrs));
417                 write(fd, addrs, talloc_get_size(addrs));
418         }
419
420 done:
421         close(fd);
422 }
423
424 /*
425   the blocking child
426 */
427 static void run_child_getaddrinfo(struct dns_ex_state *state, int fd)
428 {
429         int ret;
430         struct addrinfo hints;
431         struct addrinfo *res;
432         struct addrinfo *res_list = NULL;
433         char *addrs;
434         bool first;
435
436         ZERO_STRUCT(hints);
437         hints.ai_socktype = SOCK_STREAM;
438         hints.ai_flags = AI_ADDRCONFIG | AI_NUMERICSERV;
439
440         ret = getaddrinfo(state->name.name, "0", &hints, &res_list);
441         /* try to fallback in case of error */
442         if (state->do_fallback) {
443                 switch (ret) {
444 #ifdef EAI_NODATA
445                 case EAI_NODATA:
446 #endif
447                 case EAI_NONAME:
448                         /* getaddrinfo() doesn't handle CNAME records */
449                         run_child_dns_lookup(state, fd);
450                         return;
451                 default:
452                         break;
453                 }
454         }
455         if (ret != 0) {
456                 goto done;
457         }
458
459         addrs = talloc_strdup(state, "");
460         if (!addrs) {
461                 goto done;
462         }
463         first = true;
464         for (res = res_list; res; res = res->ai_next) {
465                 char addrstr[INET6_ADDRSTRLEN];
466                 if (!print_sockaddr_len(addrstr, sizeof(addrstr), (struct sockaddr *)res->ai_addr, res->ai_addrlen)) {
467                         continue;
468                 }
469                 addrs = talloc_asprintf_append_buffer(addrs, "%s%s@%u/%s",
470                                                       first?"":",",
471                                                       addrstr,
472                                                       state->port,
473                                                       state->name.name);
474                 if (!addrs) {
475                         goto done;
476                 }
477                 first = false;
478         }
479
480         if (addrs) {
481                 write(fd, addrs, talloc_get_size(addrs));
482         }
483 done:
484         if (res_list) {
485                 freeaddrinfo(res_list);
486         }
487         close(fd);
488 }
489
490 /*
491   handle a read event on the pipe
492 */
493 static void pipe_handler(struct tevent_context *ev, struct tevent_fd *fde, 
494                          uint16_t flags, void *private_data)
495 {
496         struct composite_context *c = talloc_get_type(private_data, struct composite_context);
497         struct dns_ex_state *state = talloc_get_type(c->private_data,
498                                      struct dns_ex_state);
499         char *address;
500         uint32_t num_addrs, i;
501         char **addrs;
502         int ret;
503         int status;
504         int value = 0;
505
506         /* if we get any event from the child then we know that we
507            won't need to kill it off */
508         talloc_set_destructor(state, NULL);
509
510         if (ioctl(state->child_fd, FIONREAD, &value) != 0) {
511                 value = 8192;
512         }
513
514         address = talloc_array(state, char, value+1);
515         if (address) {
516                 /* yes, we don't care about EAGAIN or other niceities
517                    here. They just can't happen with this parent/child
518                    relationship, and even if they did then giving an error is
519                    the right thing to do */
520                 ret = read(state->child_fd, address, value);
521         } else {
522                 ret = -1;
523         }
524         if (waitpid(state->child, &status, WNOHANG) == 0) {
525                 kill(state->child, SIGKILL);
526                 waitpid(state->child, &status, 0);
527         }
528
529         if (ret <= 0) {
530                 /* The check for ret == 0 here is important, if the
531                  * name does not exist, then no bytes are written to
532                  * the pipe */
533                 DEBUG(3,("dns child failed to find name '%s' of type %s\n",
534                          state->name.name, (state->flags & RESOLVE_NAME_FLAG_DNS_SRV)?"SRV":"A"));
535                 composite_error(c, NT_STATUS_OBJECT_NAME_NOT_FOUND);
536                 return;
537         }
538
539         /* enusre the address looks good */
540         address[ret] = 0;
541
542         addrs = str_list_make(state, address, ",");
543         if (composite_nomem(addrs, c)) return;
544
545         num_addrs = str_list_length((const char * const *)addrs);
546
547         state->addrs = talloc_array(state, struct socket_address *,
548                                     num_addrs+1);
549         if (composite_nomem(state->addrs, c)) return;
550
551         state->names = talloc_array(state, char *, num_addrs+1);
552         if (composite_nomem(state->names, c)) return;
553
554         for (i=0; i < num_addrs; i++) {
555                 uint32_t port = 0;
556                 char *p = strrchr(addrs[i], '@');
557                 char *n;
558
559                 if (!p) {
560                         composite_error(c, NT_STATUS_OBJECT_NAME_NOT_FOUND);
561                         return;
562                 }
563
564                 *p = '\0';
565                 p++;
566
567                 n = strrchr(p, '/');
568                 if (!n) {
569                         composite_error(c, NT_STATUS_OBJECT_NAME_NOT_FOUND);
570                         return;
571                 }
572
573                 *n = '\0';
574                 n++;
575
576                 if (strcmp(addrs[i], "0.0.0.0") == 0) {
577                         composite_error(c, NT_STATUS_OBJECT_NAME_NOT_FOUND);
578                         return;
579                 }
580                 port = strtoul(p, NULL, 10);
581                 if (port > UINT16_MAX) {
582                         composite_error(c, NT_STATUS_OBJECT_NAME_NOT_FOUND);
583                         return;
584                 }
585                 state->addrs[i] = socket_address_from_strings(state->addrs,
586                                                               "ip",
587                                                               addrs[i],
588                                                               port);
589                 if (composite_nomem(state->addrs[i], c)) return;
590
591                 state->names[i] = talloc_strdup(state->names, n);
592                 if (composite_nomem(state->names[i], c)) return;
593         }
594         state->addrs[i] = NULL;
595         state->names[i] = NULL;
596
597         composite_done(c);
598 }
599
600 /*
601   getaddrinfo() or dns_lookup() name resolution method - async send
602  */
603 struct composite_context *resolve_name_dns_ex_send(TALLOC_CTX *mem_ctx,
604                                                    struct tevent_context *event_ctx,
605                                                    void *privdata,
606                                                    uint32_t flags,
607                                                    uint16_t port,
608                                                    struct nbt_name *name,
609                                                    bool do_fallback)
610 {
611         struct composite_context *c;
612         struct dns_ex_state *state;
613         int fd[2] = { -1, -1 };
614         int ret;
615
616         c = composite_create(mem_ctx, event_ctx);
617         if (c == NULL) return NULL;
618
619         if (flags & RESOLVE_NAME_FLAG_FORCE_NBT) {
620                 composite_error(c, NT_STATUS_OBJECT_NAME_NOT_FOUND);
621                 return c;
622         }
623
624         state = talloc_zero(c, struct dns_ex_state);
625         if (composite_nomem(state, c)) return c;
626         c->private_data = state;
627
628         c->status = nbt_name_dup(state, name, &state->name);
629         if (!composite_is_ok(c)) return c;
630
631         /* setup a pipe to chat to our child */
632         ret = pipe(fd);
633         if (ret == -1) {
634                 composite_error(c, map_nt_error_from_unix_common(errno));
635                 return c;
636         }
637
638         state->do_fallback = do_fallback;
639         state->flags = flags;
640         state->port = port;
641
642         state->child_fd = fd[0];
643         state->event_ctx = c->event_ctx;
644
645         /* we need to put the child in our event context so
646            we know when the dns_lookup() has finished */
647         state->fde = tevent_add_fd(c->event_ctx, c, state->child_fd, TEVENT_FD_READ,
648                                   pipe_handler, c);
649         if (composite_nomem(state->fde, c)) {
650                 close(fd[0]);
651                 close(fd[1]);
652                 return c;
653         }
654         tevent_fd_set_auto_close(state->fde);
655
656         state->child = fork();
657         if (state->child == (pid_t)-1) {
658                 composite_error(c, map_nt_error_from_unix_common(errno));
659                 return c;
660         }
661
662         if (state->child == 0) {
663                 close(fd[0]);
664                 if (state->flags & RESOLVE_NAME_FLAG_FORCE_DNS) {
665                         run_child_dns_lookup(state, fd[1]);
666                 } else {
667                         run_child_getaddrinfo(state, fd[1]);
668                 }
669                 _exit(0);
670         }
671         close(fd[1]);
672
673         /* cleanup wayward children */
674         talloc_set_destructor(state, dns_ex_destructor);
675
676         return c;
677 }
678
679 /*
680   getaddrinfo() or dns_lookup() name resolution method - recv side
681 */
682 NTSTATUS resolve_name_dns_ex_recv(struct composite_context *c, 
683                                   TALLOC_CTX *mem_ctx,
684                                   struct socket_address ***addrs,
685                                   char ***names)
686 {
687         NTSTATUS status;
688
689         status = composite_wait(c);
690
691         if (NT_STATUS_IS_OK(status)) {
692                 struct dns_ex_state *state = talloc_get_type(c->private_data,
693                                              struct dns_ex_state);
694                 *addrs = talloc_steal(mem_ctx, state->addrs);
695                 if (names) {
696                         *names = talloc_steal(mem_ctx, state->names);
697                 }
698         }
699
700         talloc_free(c);
701         return status;
702 }