]> arthur.barton.de Git - netatalk.git/blob - libevent/test/regress_dns.c
Update libevent to 2.0.12
[netatalk.git] / libevent / test / regress_dns.c
1 /*
2  * Copyright (c) 2003-2007 Niels Provos <provos@citi.umich.edu>
3  * Copyright (c) 2007-2010 Niels Provos and Nick Mathewson
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. The name of the author may not be used to endorse or promote products
14  *    derived from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27
28 #ifdef WIN32
29 #include <winsock2.h>
30 #include <windows.h>
31 #include <ws2tcpip.h>
32 #endif
33
34 #include "event2/event-config.h"
35
36 #include <sys/types.h>
37 #include <sys/stat.h>
38 #ifdef _EVENT_HAVE_SYS_TIME_H
39 #include <sys/time.h>
40 #endif
41 #include <sys/queue.h>
42 #ifndef WIN32
43 #include <sys/socket.h>
44 #include <signal.h>
45 #include <netinet/in.h>
46 #include <arpa/inet.h>
47 #include <unistd.h>
48 #endif
49 #ifdef _EVENT_HAVE_NETINET_IN6_H
50 #include <netinet/in6.h>
51 #endif
52 #ifdef HAVE_NETDB_H
53 #include <netdb.h>
54 #endif
55 #include <fcntl.h>
56 #include <stdlib.h>
57 #include <stdio.h>
58 #include <string.h>
59 #include <errno.h>
60
61 #include "event2/dns.h"
62 #include "event2/dns_compat.h"
63 #include "event2/dns_struct.h"
64 #include "event2/event.h"
65 #include "event2/event_compat.h"
66 #include "event2/event_struct.h"
67 #include "event2/util.h"
68 #include "event2/listener.h"
69 #include "event2/bufferevent.h"
70 #include "log-internal.h"
71 #include "regress.h"
72 #include "regress_testutils.h"
73
74 #include "../util-internal.h"
75
76 static int dns_ok = 0;
77 static int dns_got_cancel = 0;
78 static int dns_err = 0;
79
80
81 static void
82 dns_gethostbyname_cb(int result, char type, int count, int ttl,
83     void *addresses, void *arg)
84 {
85         dns_ok = dns_err = 0;
86
87         if (result == DNS_ERR_TIMEOUT) {
88                 printf("[Timed out] ");
89                 dns_err = result;
90                 goto out;
91         }
92
93         if (result != DNS_ERR_NONE) {
94                 printf("[Error code %d] ", result);
95                 goto out;
96         }
97
98         TT_BLATHER(("type: %d, count: %d, ttl: %d: ", type, count, ttl));
99
100         switch (type) {
101         case DNS_IPv6_AAAA: {
102 #if defined(_EVENT_HAVE_STRUCT_IN6_ADDR) && defined(_EVENT_HAVE_INET_NTOP) && defined(INET6_ADDRSTRLEN)
103                 struct in6_addr *in6_addrs = addresses;
104                 char buf[INET6_ADDRSTRLEN+1];
105                 int i;
106                 /* a resolution that's not valid does not help */
107                 if (ttl < 0)
108                         goto out;
109                 for (i = 0; i < count; ++i) {
110                         const char *b = inet_ntop(AF_INET6, &in6_addrs[i], buf,sizeof(buf));
111                         if (b)
112                                 TT_BLATHER(("%s ", b));
113                         else
114                                 TT_BLATHER(("%s ", strerror(errno)));
115                 }
116 #endif
117                 break;
118         }
119         case DNS_IPv4_A: {
120                 struct in_addr *in_addrs = addresses;
121                 int i;
122                 /* a resolution that's not valid does not help */
123                 if (ttl < 0)
124                         goto out;
125                 for (i = 0; i < count; ++i)
126                         TT_BLATHER(("%s ", inet_ntoa(in_addrs[i])));
127                 break;
128         }
129         case DNS_PTR:
130                 /* may get at most one PTR */
131                 if (count != 1)
132                         goto out;
133
134                 TT_BLATHER(("%s ", *(char **)addresses));
135                 break;
136         default:
137                 goto out;
138         }
139
140         dns_ok = type;
141
142 out:
143         if (arg == NULL)
144                 event_loopexit(NULL);
145         else
146                 event_base_loopexit((struct event_base *)arg, NULL);
147 }
148
149 static void
150 dns_gethostbyname(void)
151 {
152         dns_ok = 0;
153         evdns_resolve_ipv4("www.monkey.org", 0, dns_gethostbyname_cb, NULL);
154         event_dispatch();
155
156         tt_int_op(dns_ok, ==, DNS_IPv4_A);
157         test_ok = dns_ok;
158 end:
159         ;
160 }
161
162 static void
163 dns_gethostbyname6(void)
164 {
165         dns_ok = 0;
166         evdns_resolve_ipv6("www.ietf.org", 0, dns_gethostbyname_cb, NULL);
167         event_dispatch();
168
169         if (!dns_ok && dns_err == DNS_ERR_TIMEOUT) {
170                 tt_skip();
171         }
172
173         tt_int_op(dns_ok, ==, DNS_IPv6_AAAA);
174         test_ok = 1;
175 end:
176         ;
177 }
178
179 static void
180 dns_gethostbyaddr(void)
181 {
182         struct in_addr in;
183         in.s_addr = htonl(0x7f000001ul); /* 127.0.0.1 */
184         dns_ok = 0;
185         evdns_resolve_reverse(&in, 0, dns_gethostbyname_cb, NULL);
186         event_dispatch();
187
188         tt_int_op(dns_ok, ==, DNS_PTR);
189         test_ok = dns_ok;
190 end:
191         ;
192 }
193
194 static void
195 dns_resolve_reverse(void *ptr)
196 {
197         struct in_addr in;
198         struct event_base *base = event_base_new();
199         struct evdns_base *dns = evdns_base_new(base, 1/* init name servers */);
200         struct evdns_request *req = NULL;
201
202         tt_assert(base);
203         tt_assert(dns);
204         in.s_addr = htonl(0x7f000001ul); /* 127.0.0.1 */
205         dns_ok = 0;
206
207         req = evdns_base_resolve_reverse(
208                 dns, &in, 0, dns_gethostbyname_cb, base);
209         tt_assert(req);
210
211         event_base_dispatch(base);
212
213         tt_int_op(dns_ok, ==, DNS_PTR);
214
215 end:
216         if (dns)
217                 evdns_base_free(dns, 0);
218         if (base)
219                 event_base_free(base);
220 }
221
222 static int n_server_responses = 0;
223
224 static void
225 dns_server_request_cb(struct evdns_server_request *req, void *data)
226 {
227         int i, r;
228         const char TEST_ARPA[] = "11.11.168.192.in-addr.arpa";
229         const char TEST_IN6[] =
230             "f.e.f.e." "0.0.0.0." "0.0.0.0." "1.1.1.1."
231             "a.a.a.a." "0.0.0.0." "0.0.0.0." "0.f.f.f.ip6.arpa";
232
233         for (i = 0; i < req->nquestions; ++i) {
234                 const int qtype = req->questions[i]->type;
235                 const int qclass = req->questions[i]->dns_question_class;
236                 const char *qname = req->questions[i]->name;
237
238                 struct in_addr ans;
239                 ans.s_addr = htonl(0xc0a80b0bUL); /* 192.168.11.11 */
240                 if (qtype == EVDNS_TYPE_A &&
241                     qclass == EVDNS_CLASS_INET &&
242                     !evutil_ascii_strcasecmp(qname, "zz.example.com")) {
243                         r = evdns_server_request_add_a_reply(req, qname,
244                             1, &ans.s_addr, 12345);
245                         if (r<0)
246                                 dns_ok = 0;
247                 } else if (qtype == EVDNS_TYPE_AAAA &&
248                     qclass == EVDNS_CLASS_INET &&
249                     !evutil_ascii_strcasecmp(qname, "zz.example.com")) {
250                         char addr6[17] = "abcdefghijklmnop";
251                         r = evdns_server_request_add_aaaa_reply(req,
252                             qname, 1, addr6, 123);
253                         if (r<0)
254                                 dns_ok = 0;
255                 } else if (qtype == EVDNS_TYPE_PTR &&
256                     qclass == EVDNS_CLASS_INET &&
257                     !evutil_ascii_strcasecmp(qname, TEST_ARPA)) {
258                         r = evdns_server_request_add_ptr_reply(req, NULL,
259                             qname, "ZZ.EXAMPLE.COM", 54321);
260                         if (r<0)
261                                 dns_ok = 0;
262                 } else if (qtype == EVDNS_TYPE_PTR &&
263                     qclass == EVDNS_CLASS_INET &&
264                     !evutil_ascii_strcasecmp(qname, TEST_IN6)){
265                         r = evdns_server_request_add_ptr_reply(req, NULL,
266                             qname,
267                             "ZZ-INET6.EXAMPLE.COM", 54322);
268                         if (r<0)
269                                 dns_ok = 0;
270                 } else if (qtype == EVDNS_TYPE_A &&
271                     qclass == EVDNS_CLASS_INET &&
272                     !evutil_ascii_strcasecmp(qname, "drop.example.com")) {
273                         if (evdns_server_request_drop(req)<0)
274                                 dns_ok = 0;
275                         return;
276                 } else {
277                         printf("Unexpected question %d %d \"%s\" ",
278                             qtype, qclass, qname);
279                         dns_ok = 0;
280                 }
281         }
282         r = evdns_server_request_respond(req, 0);
283         if (r<0) {
284                 printf("Couldn't send reply. ");
285                 dns_ok = 0;
286         }
287 }
288
289 static void
290 dns_server_gethostbyname_cb(int result, char type, int count, int ttl,
291     void *addresses, void *arg)
292 {
293         if (result == DNS_ERR_CANCEL) {
294                 if (arg != (void*)(char*)90909) {
295                         printf("Unexpected cancelation");
296                         dns_ok = 0;
297                 }
298                 dns_got_cancel = 1;
299                 goto out;
300         }
301         if (result != DNS_ERR_NONE) {
302                 printf("Unexpected result %d. ", result);
303                 dns_ok = 0;
304                 goto out;
305         }
306         if (count != 1) {
307                 printf("Unexpected answer count %d. ", count);
308                 dns_ok = 0;
309                 goto out;
310         }
311         switch (type) {
312         case DNS_IPv4_A: {
313                 struct in_addr *in_addrs = addresses;
314                 if (in_addrs[0].s_addr != htonl(0xc0a80b0bUL) || ttl != 12345) {
315                         printf("Bad IPv4 response \"%s\" %d. ",
316                                         inet_ntoa(in_addrs[0]), ttl);
317                         dns_ok = 0;
318                         goto out;
319                 }
320                 break;
321         }
322         case DNS_IPv6_AAAA: {
323 #if defined (_EVENT_HAVE_STRUCT_IN6_ADDR) && defined(_EVENT_HAVE_INET_NTOP) && defined(INET6_ADDRSTRLEN)
324                 struct in6_addr *in6_addrs = addresses;
325                 char buf[INET6_ADDRSTRLEN+1];
326                 if (memcmp(&in6_addrs[0].s6_addr, "abcdefghijklmnop", 16)
327                     || ttl != 123) {
328                         const char *b = inet_ntop(AF_INET6, &in6_addrs[0],buf,sizeof(buf));
329                         printf("Bad IPv6 response \"%s\" %d. ", b, ttl);
330                         dns_ok = 0;
331                         goto out;
332                 }
333 #endif
334                 break;
335         }
336         case DNS_PTR: {
337                 char **addrs = addresses;
338                 if (arg != (void*)6) {
339                         if (strcmp(addrs[0], "ZZ.EXAMPLE.COM") ||
340                             ttl != 54321) {
341                                 printf("Bad PTR response \"%s\" %d. ",
342                                     addrs[0], ttl);
343                                 dns_ok = 0;
344                                 goto out;
345                         }
346                 } else {
347                         if (strcmp(addrs[0], "ZZ-INET6.EXAMPLE.COM") ||
348                             ttl != 54322) {
349                                 printf("Bad ipv6 PTR response \"%s\" %d. ",
350                                     addrs[0], ttl);
351                                 dns_ok = 0;
352                                 goto out;
353                         }
354                 }
355                 break;
356         }
357         default:
358                 printf("Bad response type %d. ", type);
359                 dns_ok = 0;
360         }
361  out:
362         if (++n_server_responses == 3) {
363                 event_loopexit(NULL);
364         }
365 }
366
367 static void
368 dns_server(void)
369 {
370         evutil_socket_t sock=-1;
371         struct sockaddr_in my_addr;
372         struct sockaddr_storage ss;
373         ev_socklen_t slen;
374         struct evdns_server_port *port=NULL;
375         struct in_addr resolve_addr;
376         struct in6_addr resolve_addr6;
377         struct evdns_base *base=NULL;
378         struct evdns_request *req=NULL;
379
380         dns_ok = 1;
381
382         base = evdns_base_new(NULL, 0);
383
384         /* Now configure a nameserver port. */
385         sock = socket(AF_INET, SOCK_DGRAM, 0);
386         if (sock<0) {
387                 tt_abort_perror("socket");
388         }
389
390         evutil_make_socket_nonblocking(sock);
391
392         memset(&my_addr, 0, sizeof(my_addr));
393         my_addr.sin_family = AF_INET;
394         my_addr.sin_port = 0; /* kernel picks */
395         my_addr.sin_addr.s_addr = htonl(0x7f000001UL);
396         if (bind(sock, (struct sockaddr*)&my_addr, sizeof(my_addr)) < 0) {
397                 tt_abort_perror("bind");
398         }
399         slen = sizeof(ss);
400         if (getsockname(sock, (struct sockaddr*)&ss, &slen) < 0) {
401                 tt_abort_perror("getsockname");
402         }
403
404         port = evdns_add_server_port(sock, 0, dns_server_request_cb, NULL);
405
406         /* Add ourself as the only nameserver, and make sure we really are
407          * the only nameserver. */
408         evdns_base_nameserver_sockaddr_add(base, (struct sockaddr*)&ss, slen, 0);
409         tt_int_op(evdns_base_count_nameservers(base), ==, 1);
410
411         /* Send some queries. */
412         evdns_base_resolve_ipv4(base, "zz.example.com", DNS_QUERY_NO_SEARCH,
413                                            dns_server_gethostbyname_cb, NULL);
414         evdns_base_resolve_ipv6(base, "zz.example.com", DNS_QUERY_NO_SEARCH,
415                                            dns_server_gethostbyname_cb, NULL);
416         resolve_addr.s_addr = htonl(0xc0a80b0bUL); /* 192.168.11.11 */
417         evdns_base_resolve_reverse(base, &resolve_addr, 0,
418             dns_server_gethostbyname_cb, NULL);
419         memcpy(resolve_addr6.s6_addr,
420             "\xff\xf0\x00\x00\x00\x00\xaa\xaa"
421             "\x11\x11\x00\x00\x00\x00\xef\xef", 16);
422         evdns_base_resolve_reverse_ipv6(base, &resolve_addr6, 0,
423             dns_server_gethostbyname_cb, (void*)6);
424
425         req = evdns_base_resolve_ipv4(base,
426             "drop.example.com", DNS_QUERY_NO_SEARCH,
427             dns_server_gethostbyname_cb, (void*)(char*)90909);
428
429         evdns_cancel_request(base, req);
430
431         event_dispatch();
432
433         tt_assert(dns_got_cancel);
434         test_ok = dns_ok;
435
436 end:
437         if (port)
438                 evdns_close_server_port(port);
439         if (sock >= 0)
440                 evutil_closesocket(sock);
441         if (base)
442                 evdns_base_free(base, 0);
443 }
444
445 static int n_replies_left;
446 static struct event_base *exit_base;
447
448 struct generic_dns_callback_result {
449         int result;
450         char type;
451         int count;
452         int ttl;
453         size_t addrs_len;
454         void *addrs;
455         char addrs_buf[256];
456 };
457
458 static void
459 generic_dns_callback(int result, char type, int count, int ttl, void *addresses,
460     void *arg)
461 {
462         size_t len;
463         struct generic_dns_callback_result *res = arg;
464         res->result = result;
465         res->type = type;
466         res->count = count;
467         res->ttl = ttl;
468
469         if (type == DNS_IPv4_A)
470                 len = count * 4;
471         else if (type == DNS_IPv6_AAAA)
472                 len = count * 16;
473         else if (type == DNS_PTR)
474                 len = strlen(addresses)+1;
475         else {
476                 res->addrs_len = len = 0;
477                 res->addrs = NULL;
478         }
479         if (len) {
480                 res->addrs_len = len;
481                 if (len > 256)
482                         len = 256;
483                 memcpy(res->addrs_buf, addresses, len);
484                 res->addrs = res->addrs_buf;
485         }
486
487         if (--n_replies_left == 0)
488                 event_base_loopexit(exit_base, NULL);
489 }
490
491 static struct regress_dns_server_table search_table[] = {
492         { "host.a.example.com", "err", "3", 0 },
493         { "host.b.example.com", "err", "3", 0 },
494         { "host.c.example.com", "A", "11.22.33.44", 0 },
495         { "host2.a.example.com", "err", "3", 0 },
496         { "host2.b.example.com", "A", "200.100.0.100", 0 },
497         { "host2.c.example.com", "err", "3", 0 },
498
499         { "host", "err", "3", 0 },
500         { "host2", "err", "3", 0 },
501         { "*", "err", "3", 0 },
502         { NULL, NULL, NULL, 0 }
503 };
504
505 static void
506 dns_search_test(void *arg)
507 {
508         struct basic_test_data *data = arg;
509         struct event_base *base = data->base;
510         struct evdns_base *dns = NULL;
511         ev_uint16_t portnum = 0;
512         char buf[64];
513
514         struct generic_dns_callback_result r1, r2, r3, r4, r5;
515
516         tt_assert(regress_dnsserver(base, &portnum, search_table));
517         evutil_snprintf(buf, sizeof(buf), "127.0.0.1:%d", (int)portnum);
518
519         dns = evdns_base_new(base, 0);
520         tt_assert(!evdns_base_nameserver_ip_add(dns, buf));
521
522         evdns_base_search_add(dns, "a.example.com");
523         evdns_base_search_add(dns, "b.example.com");
524         evdns_base_search_add(dns, "c.example.com");
525
526         n_replies_left = 5;
527         exit_base = base;
528
529         evdns_base_resolve_ipv4(dns, "host", 0, generic_dns_callback, &r1);
530         evdns_base_resolve_ipv4(dns, "host2", 0, generic_dns_callback, &r2);
531         evdns_base_resolve_ipv4(dns, "host", DNS_NO_SEARCH, generic_dns_callback, &r3);
532         evdns_base_resolve_ipv4(dns, "host2", DNS_NO_SEARCH, generic_dns_callback, &r4);
533         evdns_base_resolve_ipv4(dns, "host3", 0, generic_dns_callback, &r5);
534
535         event_base_dispatch(base);
536
537         tt_int_op(r1.type, ==, DNS_IPv4_A);
538         tt_int_op(r1.count, ==, 1);
539         tt_int_op(((ev_uint32_t*)r1.addrs)[0], ==, htonl(0x0b16212c));
540         tt_int_op(r2.type, ==, DNS_IPv4_A);
541         tt_int_op(r2.count, ==, 1);
542         tt_int_op(((ev_uint32_t*)r2.addrs)[0], ==, htonl(0xc8640064));
543         tt_int_op(r3.result, ==, DNS_ERR_NOTEXIST);
544         tt_int_op(r4.result, ==, DNS_ERR_NOTEXIST);
545         tt_int_op(r5.result, ==, DNS_ERR_NOTEXIST);
546
547 end:
548         if (dns)
549                 evdns_base_free(dns, 0);
550
551         regress_clean_dnsserver();
552 }
553
554 static int request_count = 0;
555 static struct evdns_request *current_req = NULL;
556
557 static void
558 search_cancel_server_cb(struct evdns_server_request *req, void *data)
559 {
560         const char *question;
561
562         if (req->nquestions != 1)
563                 TT_DIE(("Only handling one question at a time; got %d",
564                         req->nquestions));
565
566         question = req->questions[0]->name;
567
568         TT_BLATHER(("got question, %s", question));
569
570         tt_assert(request_count > 0);
571         tt_assert(!evdns_server_request_respond(req, 3));
572
573         if (!--request_count)
574                 evdns_cancel_request(NULL, current_req);
575
576 end:
577         ;
578 }
579
580 static void
581 dns_search_cancel_test(void *arg)
582 {
583         struct basic_test_data *data = arg;
584         struct event_base *base = data->base;
585         struct evdns_base *dns = NULL;
586         struct evdns_server_port *port = NULL;
587         ev_uint16_t portnum = 0;
588         struct generic_dns_callback_result r1;
589         char buf[64];
590
591         port = regress_get_dnsserver(base, &portnum, NULL,
592             search_cancel_server_cb, NULL);
593         tt_assert(port);
594         evutil_snprintf(buf, sizeof(buf), "127.0.0.1:%d", (int)portnum);
595
596         dns = evdns_base_new(base, 0);
597         tt_assert(!evdns_base_nameserver_ip_add(dns, buf));
598
599         evdns_base_search_add(dns, "a.example.com");
600         evdns_base_search_add(dns, "b.example.com");
601         evdns_base_search_add(dns, "c.example.com");
602         evdns_base_search_add(dns, "d.example.com");
603
604         exit_base = base;
605         request_count = 3;
606         n_replies_left = 1;
607
608         current_req = evdns_base_resolve_ipv4(dns, "host", 0,
609                                         generic_dns_callback, &r1);
610         event_base_dispatch(base);
611
612         tt_int_op(r1.result, ==, DNS_ERR_CANCEL);
613
614 end:
615         if (port)
616                 evdns_close_server_port(port);
617         if (dns)
618                 evdns_base_free(dns, 0);
619 }
620
621 static void
622 fail_server_cb(struct evdns_server_request *req, void *data)
623 {
624         const char *question;
625         int *count = data;
626         struct in_addr in;
627
628         /* Drop the first N requests that we get. */
629         if (*count > 0) {
630                 --*count;
631                 tt_want(! evdns_server_request_drop(req));
632                 return;
633         }
634
635         if (req->nquestions != 1)
636                 TT_DIE(("Only handling one question at a time; got %d",
637                         req->nquestions));
638
639         question = req->questions[0]->name;
640
641         if (!evutil_ascii_strcasecmp(question, "google.com")) {
642                 /* Detect a probe, and get out of the loop. */
643                 event_base_loopexit(exit_base, NULL);
644         }
645
646         evutil_inet_pton(AF_INET, "16.32.64.128", &in);
647         evdns_server_request_add_a_reply(req, question, 1, &in.s_addr,
648             100);
649         tt_assert(! evdns_server_request_respond(req, 0))
650         return;
651 end:
652         tt_want(! evdns_server_request_drop(req));
653 }
654
655 static void
656 dns_retry_test(void *arg)
657 {
658         struct basic_test_data *data = arg;
659         struct event_base *base = data->base;
660         struct evdns_server_port *port = NULL;
661         struct evdns_base *dns = NULL;
662         int drop_count = 2;
663         ev_uint16_t portnum = 0;
664         char buf[64];
665
666         struct generic_dns_callback_result r1;
667
668         port = regress_get_dnsserver(base, &portnum, NULL,
669             fail_server_cb, &drop_count);
670         tt_assert(port);
671         evutil_snprintf(buf, sizeof(buf), "127.0.0.1:%d", (int)portnum);
672
673         dns = evdns_base_new(base, 0);
674         tt_assert(!evdns_base_nameserver_ip_add(dns, buf));
675         tt_assert(! evdns_base_set_option(dns, "timeout", "0.3"));
676         tt_assert(! evdns_base_set_option(dns, "max-timeouts:", "10"));
677         tt_assert(! evdns_base_set_option(dns, "initial-probe-timeout", "0.5"));
678
679         evdns_base_resolve_ipv4(dns, "host.example.com", 0,
680             generic_dns_callback, &r1);
681
682         n_replies_left = 1;
683         exit_base = base;
684
685         event_base_dispatch(base);
686
687         tt_int_op(drop_count, ==, 0);
688
689         tt_int_op(r1.type, ==, DNS_IPv4_A);
690         tt_int_op(r1.count, ==, 1);
691         tt_int_op(((ev_uint32_t*)r1.addrs)[0], ==, htonl(0x10204080));
692
693         /* Now try again, but this time have the server get treated as
694          * failed, so we can send it a test probe. */
695         drop_count = 4;
696         tt_assert(! evdns_base_set_option(dns, "max-timeouts:", "3"));
697         tt_assert(! evdns_base_set_option(dns, "attempts:", "4"));
698         memset(&r1, 0, sizeof(r1));
699
700         evdns_base_resolve_ipv4(dns, "host.example.com", 0,
701             generic_dns_callback, &r1);
702
703         n_replies_left = 2;
704
705         /* This will run until it answers the "google.com" probe request. */
706         event_base_dispatch(base);
707
708         /* We'll treat the server as failed here. */
709         tt_int_op(r1.result, ==, DNS_ERR_TIMEOUT);
710
711         /* It should work this time. */
712         tt_int_op(drop_count, ==, 0);
713         evdns_base_resolve_ipv4(dns, "host.example.com", 0,
714             generic_dns_callback, &r1);
715
716         event_base_dispatch(base);
717         tt_int_op(r1.result, ==, DNS_ERR_NONE);
718         tt_int_op(r1.type, ==, DNS_IPv4_A);
719         tt_int_op(r1.count, ==, 1);
720         tt_int_op(((ev_uint32_t*)r1.addrs)[0], ==, htonl(0x10204080));
721
722 end:
723         if (dns)
724                 evdns_base_free(dns, 0);
725         if (port)
726                 evdns_close_server_port(port);
727 }
728
729 static struct regress_dns_server_table internal_error_table[] = {
730         /* Error 4 (NOTIMPL) makes us reissue the request to another server
731            if we can.
732
733            XXXX we should reissue under a much wider set of circumstances!
734          */
735         { "foof.example.com", "err", "4", 0 },
736         { NULL, NULL, NULL, 0 }
737 };
738
739 static struct regress_dns_server_table reissue_table[] = {
740         { "foof.example.com", "A", "240.15.240.15", 0 },
741         { NULL, NULL, NULL, 0 }
742 };
743
744 static void
745 dns_reissue_test(void *arg)
746 {
747         struct basic_test_data *data = arg;
748         struct event_base *base = data->base;
749         struct evdns_server_port *port1 = NULL, *port2 = NULL;
750         struct evdns_base *dns = NULL;
751         struct generic_dns_callback_result r1;
752         ev_uint16_t portnum1 = 0, portnum2=0;
753         char buf1[64], buf2[64];
754
755         port1 = regress_get_dnsserver(base, &portnum1, NULL,
756             regress_dns_server_cb, internal_error_table);
757         tt_assert(port1);
758         port2 = regress_get_dnsserver(base, &portnum2, NULL,
759             regress_dns_server_cb, reissue_table);
760         tt_assert(port2);
761         evutil_snprintf(buf1, sizeof(buf1), "127.0.0.1:%d", (int)portnum1);
762         evutil_snprintf(buf2, sizeof(buf2), "127.0.0.1:%d", (int)portnum2);
763
764         dns = evdns_base_new(base, 0);
765         tt_assert(!evdns_base_nameserver_ip_add(dns, buf1));
766         tt_assert(! evdns_base_set_option(dns, "timeout:", "0.3"));
767         tt_assert(! evdns_base_set_option(dns, "max-timeouts:", "2"));
768         tt_assert(! evdns_base_set_option(dns, "attempts:", "5"));
769
770         memset(&r1, 0, sizeof(r1));
771         evdns_base_resolve_ipv4(dns, "foof.example.com", 0,
772             generic_dns_callback, &r1);
773
774         /* Add this after, so that we are sure to get a reissue. */
775         tt_assert(!evdns_base_nameserver_ip_add(dns, buf2));
776
777         n_replies_left = 1;
778         exit_base = base;
779
780         event_base_dispatch(base);
781         tt_int_op(r1.result, ==, DNS_ERR_NONE);
782         tt_int_op(r1.type, ==, DNS_IPv4_A);
783         tt_int_op(r1.count, ==, 1);
784         tt_int_op(((ev_uint32_t*)r1.addrs)[0], ==, htonl(0xf00ff00f));
785
786         /* Make sure we dropped at least once. */
787         tt_int_op(internal_error_table[0].seen, >, 0);
788
789 end:
790         if (dns)
791                 evdns_base_free(dns, 0);
792         if (port1)
793                 evdns_close_server_port(port1);
794         if (port2)
795                 evdns_close_server_port(port2);
796 }
797
798 #if 0
799 static void
800 dumb_bytes_fn(char *p, size_t n)
801 {
802         unsigned i;
803         /* This gets us 6 bits of entropy per transaction ID, which means we
804          * will have probably have collisions and need to pick again. */
805         for (i=0;i<n;++i)
806                 p[i] = (char)(rand() & 7);
807 }
808 #endif
809
810 static void
811 dns_inflight_test(void *arg)
812 {
813         struct basic_test_data *data = arg;
814         struct event_base *base = data->base;
815         struct evdns_base *dns = NULL;
816         ev_uint16_t portnum = 0;
817         char buf[64];
818
819         struct generic_dns_callback_result r[20];
820         int i;
821
822         tt_assert(regress_dnsserver(base, &portnum, reissue_table));
823         evutil_snprintf(buf, sizeof(buf), "127.0.0.1:%d", (int)portnum);
824
825         dns = evdns_base_new(base, 0);
826         tt_assert(!evdns_base_nameserver_ip_add(dns, buf));
827         tt_assert(! evdns_base_set_option(dns, "max-inflight:", "3"));
828         tt_assert(! evdns_base_set_option(dns, "randomize-case:", "0"));
829
830         for (i=0;i<20;++i)
831                 evdns_base_resolve_ipv4(dns, "foof.example.com", 0, generic_dns_callback, &r[i]);
832
833         n_replies_left = 20;
834         exit_base = base;
835
836         event_base_dispatch(base);
837
838         for (i=0;i<20;++i) {
839                 tt_int_op(r[i].type, ==, DNS_IPv4_A);
840                 tt_int_op(r[i].count, ==, 1);
841                 tt_int_op(((ev_uint32_t*)r[i].addrs)[0], ==, htonl(0xf00ff00f));
842         }
843
844 end:
845         if (dns)
846                 evdns_base_free(dns, 0);
847         regress_clean_dnsserver();
848 }
849
850 /* === Test for bufferevent_socket_connect_hostname */
851
852 static int total_connected_or_failed = 0;
853 static struct event_base *be_connect_hostname_base = NULL;
854
855 /* Implements a DNS server for the connect_hostname test and the
856  * getaddrinfo_async test */
857 static void
858 be_getaddrinfo_server_cb(struct evdns_server_request *req, void *data)
859 {
860         int i;
861         int *n_got_p=data;
862         int added_any=0;
863         ++*n_got_p;
864
865         for (i=0;i<req->nquestions;++i) {
866                 const int qtype = req->questions[i]->type;
867                 const int qclass = req->questions[i]->dns_question_class;
868                 const char *qname = req->questions[i]->name;
869                 struct in_addr ans;
870                 struct in6_addr ans6;
871                 memset(&ans6, 0, sizeof(ans6));
872
873                 if (qtype == EVDNS_TYPE_A &&
874                     qclass == EVDNS_CLASS_INET &&
875                     !evutil_ascii_strcasecmp(qname, "nobodaddy.example.com")) {
876                         ans.s_addr = htonl(0x7f000001);
877                         evdns_server_request_add_a_reply(req, qname,
878                             1, &ans.s_addr, 2000);
879                         added_any = 1;
880                 } else if (!evutil_ascii_strcasecmp(qname,
881                         "nosuchplace.example.com")) {
882                         /* ok, just say notfound. */
883                 } else if (!evutil_ascii_strcasecmp(qname,
884                         "both.example.com")) {
885                         if (qtype == EVDNS_TYPE_A) {
886                                 ans.s_addr = htonl(0x50502020);
887                                 evdns_server_request_add_a_reply(req, qname,
888                                     1, &ans.s_addr, 2000);
889                                 added_any = 1;
890                         } else if (qtype == EVDNS_TYPE_AAAA) {
891                                 ans6.s6_addr[0] = 0x80;
892                                 ans6.s6_addr[1] = 0xff;
893                                 ans6.s6_addr[14] = 0xbb;
894                                 ans6.s6_addr[15] = 0xbb;
895                                 evdns_server_request_add_aaaa_reply(req, qname,
896                                     1, &ans6.s6_addr, 2000);
897                                 added_any = 1;
898                         }
899                         evdns_server_request_add_cname_reply(req, qname,
900                             "both-canonical.example.com", 1000);
901                 } else if (!evutil_ascii_strcasecmp(qname,
902                         "v4only.example.com") ||
903                     !evutil_ascii_strcasecmp(qname, "v4assert.example.com")) {
904                         if (qtype == EVDNS_TYPE_A) {
905                                 ans.s_addr = htonl(0x12345678);
906                                 evdns_server_request_add_a_reply(req, qname,
907                                     1, &ans.s_addr, 2000);
908                                 added_any = 1;
909                         } else if (!evutil_ascii_strcasecmp(qname,
910                                 "v4assert.example.com")) {
911                                 TT_FAIL(("Got an AAAA request for v4assert"));
912                         }
913                 } else if (!evutil_ascii_strcasecmp(qname,
914                         "v6only.example.com") ||
915                     !evutil_ascii_strcasecmp(qname, "v6assert.example.com")) {
916                         if (qtype == EVDNS_TYPE_AAAA) {
917                                 ans6.s6_addr[0] = 0x0b;
918                                 ans6.s6_addr[1] = 0x0b;
919                                 ans6.s6_addr[14] = 0xf0;
920                                 ans6.s6_addr[15] = 0x0d;
921                                 evdns_server_request_add_aaaa_reply(req, qname,
922                                     1, &ans6.s6_addr, 2000);
923                                 added_any = 1;
924                         }  else if (!evutil_ascii_strcasecmp(qname,
925                                 "v6assert.example.com")) {
926                                 TT_FAIL(("Got a A request for v6assert"));
927                         }
928                 } else if (!evutil_ascii_strcasecmp(qname,
929                         "v6timeout.example.com")) {
930                         if (qtype == EVDNS_TYPE_A) {
931                                 ans.s_addr = htonl(0xabcdef01);
932                                 evdns_server_request_add_a_reply(req, qname,
933                                     1, &ans.s_addr, 2000);
934                                 added_any = 1;
935                         } else if (qtype == EVDNS_TYPE_AAAA) {
936                                 /* Let the v6 request time out.*/
937                                 evdns_server_request_drop(req);
938                                 return;
939                         }
940                 } else if (!evutil_ascii_strcasecmp(qname,
941                         "v4timeout.example.com")) {
942                         if (qtype == EVDNS_TYPE_AAAA) {
943                                 ans6.s6_addr[0] = 0x0a;
944                                 ans6.s6_addr[1] = 0x0a;
945                                 ans6.s6_addr[14] = 0xff;
946                                 ans6.s6_addr[15] = 0x01;
947                                 evdns_server_request_add_aaaa_reply(req, qname,
948                                     1, &ans6.s6_addr, 2000);
949                                 added_any = 1;
950                         } else if (qtype == EVDNS_TYPE_A) {
951                                 /* Let the v4 request time out.*/
952                                 evdns_server_request_drop(req);
953                                 return;
954                         }
955                 } else if (!evutil_ascii_strcasecmp(qname,
956                         "v6timeout-nonexist.example.com")) {
957                         if (qtype == EVDNS_TYPE_A) {
958                                 /* Fall through, give an nexist. */
959                         } else if (qtype == EVDNS_TYPE_AAAA) {
960                                 /* Let the v6 request time out.*/
961                                 evdns_server_request_drop(req);
962                                 return;
963                         }
964                 } else if (!evutil_ascii_strcasecmp(qname,
965                         "all-timeout.example.com")) {
966                         /* drop all requests */
967                         evdns_server_request_drop(req);
968                         return;
969                 } else {
970                         TT_GRIPE(("Got weird request for %s",qname));
971                 }
972         }
973         if (added_any)
974                 evdns_server_request_respond(req, 0);
975         else
976                 evdns_server_request_respond(req, 3);
977 }
978
979 /* Implements a listener for connect_hostname test. */
980 static void
981 nil_accept_cb(struct evconnlistener *l, evutil_socket_t fd, struct sockaddr *s,
982     int socklen, void *arg)
983 {
984         int *p = arg;
985         (*p)++;
986         /* don't do anything with the socket; let it close when we exit() */
987 }
988
989 struct be_conn_hostname_result {
990         int dnserr;
991         int what;
992 };
993
994 /* Bufferevent event callback for the connect_hostname test: remembers what
995  * event we got. */
996 static void
997 be_connect_hostname_event_cb(struct bufferevent *bev, short what, void *ctx)
998 {
999         struct be_conn_hostname_result *got = ctx;
1000         if (!got->what) {
1001                 TT_BLATHER(("Got a bufferevent event %d", what));
1002                 got->what = what;
1003
1004                 if ((what & BEV_EVENT_CONNECTED) || (what & BEV_EVENT_ERROR)) {
1005                         int r;
1006                         ++total_connected_or_failed;
1007                         TT_BLATHER(("Got %d connections or errors.", total_connected_or_failed));
1008                         if ((r = bufferevent_socket_get_dns_error(bev))) {
1009                                 got->dnserr = r;
1010                                 TT_BLATHER(("DNS error %d: %s", r,
1011                                            evutil_gai_strerror(r)));
1012                         }
1013                         if (total_connected_or_failed >= 5)
1014                                 event_base_loopexit(be_connect_hostname_base,
1015                                     NULL);
1016                 }
1017         } else {
1018                 TT_FAIL(("Two events on one bufferevent. %d,%d",
1019                         got->what, (int)what));
1020         }
1021 }
1022
1023 static void
1024 test_bufferevent_connect_hostname(void *arg)
1025 {
1026         struct basic_test_data *data = arg;
1027         struct evconnlistener *listener = NULL;
1028         struct bufferevent *be1=NULL, *be2=NULL, *be3=NULL, *be4=NULL, *be5=NULL;
1029         struct be_conn_hostname_result be1_outcome={0,0}, be2_outcome={0,0},
1030                be3_outcome={0,0}, be4_outcome={0,0}, be5_outcome={0,0};
1031         int expect_err5;
1032         struct evdns_base *dns=NULL;
1033         struct evdns_server_port *port=NULL;
1034         evutil_socket_t server_fd=-1;
1035         struct sockaddr_in sin;
1036         int listener_port=-1;
1037         ev_uint16_t dns_port=0;
1038         int n_accept=0, n_dns=0;
1039         char buf[128];
1040
1041         be_connect_hostname_base = data->base;
1042
1043         /* Bind an address and figure out what port it's on. */
1044         memset(&sin, 0, sizeof(sin));
1045         sin.sin_family = AF_INET;
1046         sin.sin_addr.s_addr = htonl(0x7f000001); /* 127.0.0.1 */
1047         sin.sin_port = 0;
1048         listener = evconnlistener_new_bind(data->base, nil_accept_cb,
1049             &n_accept,
1050             LEV_OPT_REUSEABLE|LEV_OPT_CLOSE_ON_EXEC,
1051             -1, (struct sockaddr *)&sin, sizeof(sin));
1052         listener_port = regress_get_socket_port(
1053                 evconnlistener_get_fd(listener));
1054
1055         port = regress_get_dnsserver(data->base, &dns_port, NULL,
1056             be_getaddrinfo_server_cb, &n_dns);
1057         tt_assert(port);
1058         tt_int_op(dns_port, >=, 0);
1059
1060         /* Start an evdns_base that uses the server as its resolver. */
1061         dns = evdns_base_new(data->base, 0);
1062         evutil_snprintf(buf, sizeof(buf), "127.0.0.1:%d", (int)dns_port);
1063         evdns_base_nameserver_ip_add(dns, buf);
1064
1065         /* Now, finally, at long last, launch the bufferevents.  One should do
1066          * a failing lookup IP, one should do a successful lookup by IP,
1067          * and one should do a successful lookup by hostname. */
1068         be1 = bufferevent_socket_new(data->base, -1, BEV_OPT_CLOSE_ON_FREE);
1069         be2 = bufferevent_socket_new(data->base, -1, BEV_OPT_CLOSE_ON_FREE);
1070         be3 = bufferevent_socket_new(data->base, -1, BEV_OPT_CLOSE_ON_FREE);
1071         be4 = bufferevent_socket_new(data->base, -1, BEV_OPT_CLOSE_ON_FREE);
1072         be5 = bufferevent_socket_new(data->base, -1, BEV_OPT_CLOSE_ON_FREE);
1073
1074         bufferevent_setcb(be1, NULL, NULL, be_connect_hostname_event_cb,
1075             &be1_outcome);
1076         bufferevent_setcb(be2, NULL, NULL, be_connect_hostname_event_cb,
1077             &be2_outcome);
1078         bufferevent_setcb(be3, NULL, NULL, be_connect_hostname_event_cb,
1079             &be3_outcome);
1080         bufferevent_setcb(be4, NULL, NULL, be_connect_hostname_event_cb,
1081             &be4_outcome);
1082         bufferevent_setcb(be5, NULL, NULL, be_connect_hostname_event_cb,
1083             &be5_outcome);
1084
1085         /* Launch an async resolve that will fail. */
1086         tt_assert(!bufferevent_socket_connect_hostname(be1, dns, AF_INET,
1087                 "nosuchplace.example.com", listener_port));
1088         /* Connect to the IP without resolving. */
1089         tt_assert(!bufferevent_socket_connect_hostname(be2, dns, AF_INET,
1090                 "127.0.0.1", listener_port));
1091         /* Launch an async resolve that will succeed. */
1092         tt_assert(!bufferevent_socket_connect_hostname(be3, dns, AF_INET,
1093                 "nobodaddy.example.com", listener_port));
1094         /* Use the blocking resolver.  This one will fail if your resolver
1095          * can't resolve localhost to 127.0.0.1 */
1096         tt_assert(!bufferevent_socket_connect_hostname(be4, NULL, AF_INET,
1097                 "localhost", listener_port));
1098         /* Use the blocking resolver with a nonexistent hostname. */
1099         tt_assert(!bufferevent_socket_connect_hostname(be5, NULL, AF_INET,
1100                 "nonesuch.nowhere.example.com", 80));
1101         {
1102                 /* The blocking resolver will use the system nameserver, which
1103                  * might tell us anything.  (Yes, some twits even pretend that
1104                  * example.com is real.) Let's see what answer to expect. */
1105                 struct evutil_addrinfo hints, *ai = NULL;
1106                 memset(&hints, 0, sizeof(hints));
1107                 hints.ai_family = AF_INET;
1108                 hints.ai_socktype = SOCK_STREAM;
1109                 hints.ai_protocol = IPPROTO_TCP;
1110                 expect_err5 = evutil_getaddrinfo(
1111                         "nonesuch.nowhere.example.com", "80", &hints, &ai);
1112         }
1113
1114         event_base_dispatch(data->base);
1115
1116         tt_int_op(be1_outcome.what, ==, BEV_EVENT_ERROR);
1117         tt_int_op(be1_outcome.dnserr, ==, EVUTIL_EAI_NONAME);
1118         tt_int_op(be2_outcome.what, ==, BEV_EVENT_CONNECTED);
1119         tt_int_op(be2_outcome.dnserr, ==, 0);
1120         tt_int_op(be3_outcome.what, ==, BEV_EVENT_CONNECTED);
1121         tt_int_op(be3_outcome.dnserr, ==, 0);
1122         tt_int_op(be4_outcome.what, ==, BEV_EVENT_CONNECTED);
1123         tt_int_op(be4_outcome.dnserr, ==, 0);
1124         if (expect_err5) {
1125                 tt_int_op(be5_outcome.what, ==, BEV_EVENT_ERROR);
1126                 tt_int_op(be5_outcome.dnserr, ==, expect_err5);
1127         }
1128
1129         tt_int_op(n_accept, ==, 3);
1130         tt_int_op(n_dns, ==, 2);
1131
1132 end:
1133         if (listener)
1134                 evconnlistener_free(listener);
1135         if (server_fd>=0)
1136                 evutil_closesocket(server_fd);
1137         if (port)
1138                 evdns_close_server_port(port);
1139         if (dns)
1140                 evdns_base_free(dns, 0);
1141         if (be1)
1142                 bufferevent_free(be1);
1143         if (be2)
1144                 bufferevent_free(be2);
1145         if (be3)
1146                 bufferevent_free(be3);
1147         if (be4)
1148                 bufferevent_free(be4);
1149         if (be5)
1150                 bufferevent_free(be5);
1151 }
1152
1153
1154 struct gai_outcome {
1155         int err;
1156         struct evutil_addrinfo *ai;
1157 };
1158
1159 static int n_gai_results_pending = 0;
1160 static struct event_base *exit_base_on_no_pending_results = NULL;
1161
1162 static void
1163 gai_cb(int err, struct evutil_addrinfo *res, void *ptr)
1164 {
1165         struct gai_outcome *go = ptr;
1166         go->err = err;
1167         go->ai = res;
1168         if (--n_gai_results_pending <= 0 && exit_base_on_no_pending_results)
1169                 event_base_loopexit(exit_base_on_no_pending_results, NULL);
1170         if (n_gai_results_pending < 900)
1171                 TT_BLATHER(("Got an answer; expecting %d more.",
1172                         n_gai_results_pending));
1173 }
1174
1175 static void
1176 cancel_gai_cb(evutil_socket_t fd, short what, void *ptr)
1177 {
1178         struct evdns_getaddrinfo_request *r = ptr;
1179         evdns_getaddrinfo_cancel(r);
1180 }
1181
1182 static void
1183 test_getaddrinfo_async(void *arg)
1184 {
1185         struct basic_test_data *data = arg;
1186         struct evutil_addrinfo hints, *a;
1187         struct gai_outcome local_outcome;
1188         struct gai_outcome a_out[12];
1189         int i;
1190         struct evdns_getaddrinfo_request *r;
1191         char buf[128];
1192         struct evdns_server_port *port = NULL;
1193         ev_uint16_t dns_port = 0;
1194         int n_dns_questions = 0;
1195
1196         struct evdns_base *dns_base = evdns_base_new(data->base, 0);
1197
1198         /* for localhost */
1199         evdns_base_load_hosts(dns_base, NULL);
1200
1201         memset(a_out, 0, sizeof(a_out));
1202
1203         n_gai_results_pending = 10000; /* don't think about exiting yet. */
1204
1205         /* 1. Try some cases that will never hit the asynchronous resolver. */
1206         /* 1a. Simple case with a symbolic service name */
1207         memset(&hints, 0, sizeof(hints));
1208         hints.ai_family = PF_UNSPEC;
1209         hints.ai_socktype = SOCK_STREAM;
1210         memset(&local_outcome, 0, sizeof(local_outcome));
1211         r = evdns_getaddrinfo(dns_base, "1.2.3.4", "http",
1212             &hints, gai_cb, &local_outcome);
1213         tt_assert(! r);
1214         if (!local_outcome.err) {
1215                 tt_ptr_op(local_outcome.ai,!=,NULL);
1216                 test_ai_eq(local_outcome.ai, "1.2.3.4:80", SOCK_STREAM, IPPROTO_TCP);
1217                 evutil_freeaddrinfo(local_outcome.ai);
1218                 local_outcome.ai = NULL;
1219         } else {
1220                 TT_BLATHER(("Apparently we have no getservbyname."));
1221         }
1222
1223         /* 1b. EVUTIL_AI_NUMERICHOST is set */
1224         memset(&hints, 0, sizeof(hints));
1225         hints.ai_family = PF_UNSPEC;
1226         hints.ai_flags = EVUTIL_AI_NUMERICHOST;
1227         memset(&local_outcome, 0, sizeof(local_outcome));
1228         r = evdns_getaddrinfo(dns_base, "www.google.com", "80",
1229             &hints, gai_cb, &local_outcome);
1230         tt_int_op(r,==,0);
1231         tt_int_op(local_outcome.err,==,EVUTIL_EAI_NONAME);
1232         tt_ptr_op(local_outcome.ai,==,NULL);
1233
1234         /* 1c. We give a numeric address (ipv6) */
1235         memset(&hints, 0, sizeof(hints));
1236         memset(&local_outcome, 0, sizeof(local_outcome));
1237         hints.ai_family = PF_UNSPEC;
1238         hints.ai_protocol = IPPROTO_TCP;
1239         r = evdns_getaddrinfo(dns_base, "f::f", "8008",
1240             &hints, gai_cb, &local_outcome);
1241         tt_assert(!r);
1242         tt_int_op(local_outcome.err,==,0);
1243         tt_assert(local_outcome.ai);
1244         tt_ptr_op(local_outcome.ai->ai_next,==,NULL);
1245         test_ai_eq(local_outcome.ai, "[f::f]:8008", SOCK_STREAM, IPPROTO_TCP);
1246         evutil_freeaddrinfo(local_outcome.ai);
1247         local_outcome.ai = NULL;
1248
1249         /* 1d. We give a numeric address (ipv4) */
1250         memset(&hints, 0, sizeof(hints));
1251         memset(&local_outcome, 0, sizeof(local_outcome));
1252         hints.ai_family = PF_UNSPEC;
1253         r = evdns_getaddrinfo(dns_base, "5.6.7.8", NULL,
1254             &hints, gai_cb, &local_outcome);
1255         tt_assert(!r);
1256         tt_int_op(local_outcome.err,==,0);
1257         tt_assert(local_outcome.ai);
1258         a = ai_find_by_protocol(local_outcome.ai, IPPROTO_TCP);
1259         tt_assert(a);
1260         test_ai_eq(a, "5.6.7.8", SOCK_STREAM, IPPROTO_TCP);
1261         a = ai_find_by_protocol(local_outcome.ai, IPPROTO_UDP);
1262         tt_assert(a);
1263         test_ai_eq(a, "5.6.7.8", SOCK_DGRAM, IPPROTO_UDP);
1264         evutil_freeaddrinfo(local_outcome.ai);
1265         local_outcome.ai = NULL;
1266
1267         /* 1e. nodename is NULL (bind) */
1268         memset(&hints, 0, sizeof(hints));
1269         memset(&local_outcome, 0, sizeof(local_outcome));
1270         hints.ai_family = PF_UNSPEC;
1271         hints.ai_socktype = SOCK_DGRAM;
1272         hints.ai_flags = EVUTIL_AI_PASSIVE;
1273         r = evdns_getaddrinfo(dns_base, NULL, "9090",
1274             &hints, gai_cb, &local_outcome);
1275         tt_assert(!r);
1276         tt_int_op(local_outcome.err,==,0);
1277         tt_assert(local_outcome.ai);
1278         /* we should get a v4 address of 0.0.0.0... */
1279         a = ai_find_by_family(local_outcome.ai, PF_INET);
1280         tt_assert(a);
1281         test_ai_eq(a, "0.0.0.0:9090", SOCK_DGRAM, IPPROTO_UDP);
1282         /* ... and a v6 address of ::0 */
1283         a = ai_find_by_family(local_outcome.ai, PF_INET6);
1284         tt_assert(a);
1285         test_ai_eq(a, "[::]:9090", SOCK_DGRAM, IPPROTO_UDP);
1286         evutil_freeaddrinfo(local_outcome.ai);
1287         local_outcome.ai = NULL;
1288
1289         /* 1f. nodename is NULL (connect) */
1290         memset(&hints, 0, sizeof(hints));
1291         memset(&local_outcome, 0, sizeof(local_outcome));
1292         hints.ai_family = PF_UNSPEC;
1293         hints.ai_socktype = SOCK_STREAM;
1294         r = evdns_getaddrinfo(dns_base, NULL, "2",
1295             &hints, gai_cb, &local_outcome);
1296         tt_assert(!r);
1297         tt_int_op(local_outcome.err,==,0);
1298         tt_assert(local_outcome.ai);
1299         /* we should get a v4 address of 127.0.0.1 .... */
1300         a = ai_find_by_family(local_outcome.ai, PF_INET);
1301         tt_assert(a);
1302         test_ai_eq(a, "127.0.0.1:2", SOCK_STREAM, IPPROTO_TCP);
1303         /* ... and a v6 address of ::1 */
1304         a = ai_find_by_family(local_outcome.ai, PF_INET6);
1305         tt_assert(a);
1306         test_ai_eq(a, "[::1]:2", SOCK_STREAM, IPPROTO_TCP);
1307         evutil_freeaddrinfo(local_outcome.ai);
1308         local_outcome.ai = NULL;
1309
1310         /* 1g. We find localhost immediately. (pf_unspec) */
1311         memset(&hints, 0, sizeof(hints));
1312         memset(&local_outcome, 0, sizeof(local_outcome));
1313         hints.ai_family = PF_UNSPEC;
1314         hints.ai_socktype = SOCK_STREAM;
1315         r = evdns_getaddrinfo(dns_base, "LOCALHOST", "80",
1316             &hints, gai_cb, &local_outcome);
1317         tt_assert(!r);
1318         tt_int_op(local_outcome.err,==,0);
1319         tt_assert(local_outcome.ai);
1320         /* we should get a v4 address of 127.0.0.1 .... */
1321         a = ai_find_by_family(local_outcome.ai, PF_INET);
1322         tt_assert(a);
1323         test_ai_eq(a, "127.0.0.1:80", SOCK_STREAM, IPPROTO_TCP);
1324         /* ... and a v6 address of ::1 */
1325         a = ai_find_by_family(local_outcome.ai, PF_INET6);
1326         tt_assert(a);
1327         test_ai_eq(a, "[::1]:80", SOCK_STREAM, IPPROTO_TCP);
1328         evutil_freeaddrinfo(local_outcome.ai);
1329         local_outcome.ai = NULL;
1330
1331         /* 1g. We find localhost immediately. (pf_inet6) */
1332         memset(&hints, 0, sizeof(hints));
1333         memset(&local_outcome, 0, sizeof(local_outcome));
1334         hints.ai_family = PF_INET6;
1335         hints.ai_socktype = SOCK_STREAM;
1336         r = evdns_getaddrinfo(dns_base, "LOCALHOST", "9999",
1337             &hints, gai_cb, &local_outcome);
1338         tt_assert(! r);
1339         tt_int_op(local_outcome.err,==,0);
1340         tt_assert(local_outcome.ai);
1341         a = local_outcome.ai;
1342         test_ai_eq(a, "[::1]:9999", SOCK_STREAM, IPPROTO_TCP);
1343         tt_ptr_op(a->ai_next, ==, NULL);
1344         evutil_freeaddrinfo(local_outcome.ai);
1345         local_outcome.ai = NULL;
1346
1347         /* 2. Okay, now we can actually test the asynchronous resolver. */
1348         /* Start a dummy local dns server... */
1349         port = regress_get_dnsserver(data->base, &dns_port, NULL,
1350             be_getaddrinfo_server_cb, &n_dns_questions);
1351         tt_assert(port);
1352         tt_int_op(dns_port, >=, 0);
1353         /* ... and tell the evdns_base about it. */
1354         evutil_snprintf(buf, sizeof(buf), "127.0.0.1:%d", dns_port);
1355         evdns_base_nameserver_ip_add(dns_base, buf);
1356
1357         memset(&hints, 0, sizeof(hints));
1358         hints.ai_family = PF_UNSPEC;
1359         hints.ai_socktype = SOCK_STREAM;
1360         hints.ai_flags = EVUTIL_AI_CANONNAME;
1361         /* 0: Request for both.example.com should return both addresses. */
1362         r = evdns_getaddrinfo(dns_base, "both.example.com", "8000",
1363             &hints, gai_cb, &a_out[0]);
1364         tt_assert(r);
1365
1366         /* 1: Request for v4only.example.com should return one address. */
1367         r = evdns_getaddrinfo(dns_base, "v4only.example.com", "8001",
1368             &hints, gai_cb, &a_out[1]);
1369         tt_assert(r);
1370
1371         /* 2: Request for v6only.example.com should return one address. */
1372         hints.ai_flags = 0;
1373         r = evdns_getaddrinfo(dns_base, "v6only.example.com", "8002",
1374             &hints, gai_cb, &a_out[2]);
1375         tt_assert(r);
1376
1377         /* 3: PF_INET request for v4assert.example.com should not generate a
1378          * v6 request.  The server will fail the test if it does. */
1379         hints.ai_family = PF_INET;
1380         r = evdns_getaddrinfo(dns_base, "v4assert.example.com", "8003",
1381             &hints, gai_cb, &a_out[3]);
1382         tt_assert(r);
1383
1384         /* 4: PF_INET6 request for v6assert.example.com should not generate a
1385          * v4 request.  The server will fail the test if it does. */
1386         hints.ai_family = PF_INET6;
1387         r = evdns_getaddrinfo(dns_base, "v6assert.example.com", "8004",
1388             &hints, gai_cb, &a_out[4]);
1389         tt_assert(r);
1390
1391         /* 5: PF_INET request for nosuchplace.example.com should give NEXIST. */
1392         hints.ai_family = PF_INET;
1393         r = evdns_getaddrinfo(dns_base, "nosuchplace.example.com", "8005",
1394             &hints, gai_cb, &a_out[5]);
1395         tt_assert(r);
1396
1397         /* 6: PF_UNSPEC request for nosuchplace.example.com should give NEXIST.
1398          */
1399         hints.ai_family = PF_UNSPEC;
1400         r = evdns_getaddrinfo(dns_base, "nosuchplace.example.com", "8006",
1401             &hints, gai_cb, &a_out[6]);
1402         tt_assert(r);
1403
1404         /* 7: PF_UNSPEC request for v6timeout.example.com should give an ipv4
1405          * address only. */
1406         hints.ai_family = PF_UNSPEC;
1407         r = evdns_getaddrinfo(dns_base, "v6timeout.example.com", "8007",
1408             &hints, gai_cb, &a_out[7]);
1409         tt_assert(r);
1410
1411         /* 8: PF_UNSPEC request for v6timeout-nonexist.example.com should give
1412          * a NEXIST */
1413         hints.ai_family = PF_UNSPEC;
1414         r = evdns_getaddrinfo(dns_base, "v6timeout-nonexist.example.com",
1415             "8008", &hints, gai_cb, &a_out[8]);
1416         tt_assert(r);
1417
1418         /* 9: AI_ADDRCONFIG should at least not crash.  Can't test it more
1419          * without knowing what kind of internet we have. */
1420         hints.ai_flags |= EVUTIL_AI_ADDRCONFIG;
1421         r = evdns_getaddrinfo(dns_base, "both.example.com",
1422             "8009", &hints, gai_cb, &a_out[9]);
1423         tt_assert(r);
1424
1425         /* 10: PF_UNSPEC for v4timeout.example.com should give an ipv6 address
1426          * only. */
1427         hints.ai_family = PF_UNSPEC;
1428         hints.ai_flags = 0;
1429         r = evdns_getaddrinfo(dns_base, "v4timeout.example.com", "8010",
1430             &hints, gai_cb, &a_out[10]);
1431         tt_assert(r);
1432
1433         /* 11: timeout.example.com: cancel it after 100 msec. */
1434         r = evdns_getaddrinfo(dns_base, "all-timeout.example.com", "8011",
1435             &hints, gai_cb, &a_out[11]);
1436         tt_assert(r);
1437         {
1438                 struct timeval tv;
1439                 tv.tv_sec = 0;
1440                 tv.tv_usec = 100*1000; /* 100 msec */
1441                 event_base_once(data->base, -1, EV_TIMEOUT, cancel_gai_cb,
1442                     r, &tv);
1443         }
1444
1445         /* XXXXX There are more tests we could do, including:
1446
1447            - A test to elicit NODATA.
1448
1449          */
1450
1451         n_gai_results_pending = 12;
1452         exit_base_on_no_pending_results = data->base;
1453
1454         event_base_dispatch(data->base);
1455
1456         /* 0: both.example.com */
1457         tt_int_op(a_out[0].err, ==, 0);
1458         tt_assert(a_out[0].ai);
1459         tt_assert(a_out[0].ai->ai_next);
1460         tt_assert(!a_out[0].ai->ai_next->ai_next);
1461         a = ai_find_by_family(a_out[0].ai, PF_INET);
1462         tt_assert(a);
1463         test_ai_eq(a, "80.80.32.32:8000", SOCK_STREAM, IPPROTO_TCP);
1464         a = ai_find_by_family(a_out[0].ai, PF_INET6);
1465         tt_assert(a);
1466         test_ai_eq(a, "[80ff::bbbb]:8000", SOCK_STREAM, IPPROTO_TCP);
1467         tt_assert(a_out[0].ai->ai_canonname);
1468         tt_str_op(a_out[0].ai->ai_canonname, ==, "both-canonical.example.com");
1469
1470         /* 1: v4only.example.com */
1471         tt_int_op(a_out[1].err, ==, 0);
1472         tt_assert(a_out[1].ai);
1473         tt_assert(! a_out[1].ai->ai_next);
1474         test_ai_eq(a_out[1].ai, "18.52.86.120:8001", SOCK_STREAM, IPPROTO_TCP);
1475         tt_assert(a_out[1].ai->ai_canonname == NULL);
1476
1477
1478         /* 2: v6only.example.com */
1479         tt_int_op(a_out[2].err, ==, 0);
1480         tt_assert(a_out[2].ai);
1481         tt_assert(! a_out[2].ai->ai_next);
1482         test_ai_eq(a_out[2].ai, "[b0b::f00d]:8002", SOCK_STREAM, IPPROTO_TCP);
1483
1484         /* 3: v4assert.example.com */
1485         tt_int_op(a_out[3].err, ==, 0);
1486         tt_assert(a_out[3].ai);
1487         tt_assert(! a_out[3].ai->ai_next);
1488         test_ai_eq(a_out[3].ai, "18.52.86.120:8003", SOCK_STREAM, IPPROTO_TCP);
1489
1490         /* 4: v6assert.example.com */
1491         tt_int_op(a_out[4].err, ==, 0);
1492         tt_assert(a_out[4].ai);
1493         tt_assert(! a_out[4].ai->ai_next);
1494         test_ai_eq(a_out[4].ai, "[b0b::f00d]:8004", SOCK_STREAM, IPPROTO_TCP);
1495
1496         /* 5: nosuchplace.example.com (inet) */
1497         tt_int_op(a_out[5].err, ==, EVUTIL_EAI_NONAME);
1498         tt_assert(! a_out[5].ai);
1499
1500         /* 6: nosuchplace.example.com (unspec) */
1501         tt_int_op(a_out[6].err, ==, EVUTIL_EAI_NONAME);
1502         tt_assert(! a_out[6].ai);
1503
1504         /* 7: v6timeout.example.com */
1505         tt_int_op(a_out[7].err, ==, 0);
1506         tt_assert(a_out[7].ai);
1507         tt_assert(! a_out[7].ai->ai_next);
1508         test_ai_eq(a_out[7].ai, "171.205.239.1:8007", SOCK_STREAM, IPPROTO_TCP);
1509
1510         /* 8: v6timeout-nonexist.example.com */
1511         tt_int_op(a_out[8].err, ==, EVUTIL_EAI_NONAME);
1512         tt_assert(! a_out[8].ai);
1513
1514         /* 9: both (ADDRCONFIG) */
1515         tt_int_op(a_out[9].err, ==, 0);
1516         tt_assert(a_out[9].ai);
1517         a = ai_find_by_family(a_out[9].ai, PF_INET);
1518         if (a)
1519                 test_ai_eq(a, "80.80.32.32:8009", SOCK_STREAM, IPPROTO_TCP);
1520         else
1521                 tt_assert(ai_find_by_family(a_out[9].ai, PF_INET6));
1522         a = ai_find_by_family(a_out[9].ai, PF_INET6);
1523         if (a)
1524                 test_ai_eq(a, "[80ff::bbbb]:8009", SOCK_STREAM, IPPROTO_TCP);
1525         else
1526                 tt_assert(ai_find_by_family(a_out[9].ai, PF_INET));
1527
1528         /* 10: v4timeout.example.com */
1529         tt_int_op(a_out[10].err, ==, 0);
1530         tt_assert(a_out[10].ai);
1531         tt_assert(! a_out[10].ai->ai_next);
1532         test_ai_eq(a_out[10].ai, "[a0a::ff01]:8010", SOCK_STREAM, IPPROTO_TCP);
1533
1534         /* 11: cancelled request. */
1535         tt_int_op(a_out[11].err, ==, EVUTIL_EAI_CANCEL);
1536         tt_assert(a_out[11].ai == NULL);
1537
1538 end:
1539         if (local_outcome.ai)
1540                 evutil_freeaddrinfo(local_outcome.ai);
1541         for (i=0;i<10;++i) {
1542                 if (a_out[i].ai)
1543                         evutil_freeaddrinfo(a_out[i].ai);
1544         }
1545         if (port)
1546                 evdns_close_server_port(port);
1547         if (dns_base)
1548                 evdns_base_free(dns_base, 0);
1549 }
1550
1551 struct gaic_request_status {
1552         int magic;
1553         struct event_base *base;
1554         struct evdns_base *dns_base;
1555         struct evdns_getaddrinfo_request *request;
1556         struct event cancel_event;
1557         int canceled;
1558 };
1559
1560 #define GAIC_MAGIC 0x1234abcd
1561
1562 static int pending = 0;
1563
1564 static void
1565 gaic_cancel_request_cb(evutil_socket_t fd, short what, void *arg)
1566 {
1567         struct gaic_request_status *status = arg;
1568
1569         tt_assert(status->magic == GAIC_MAGIC);
1570         status->canceled = 1;
1571         evdns_getaddrinfo_cancel(status->request);
1572         return;
1573 end:
1574         event_base_loopexit(status->base, NULL);
1575 }
1576
1577 static void
1578 gaic_server_cb(struct evdns_server_request *req, void *arg)
1579 {
1580         ev_uint32_t answer = 0x7f000001;
1581         tt_assert(req->nquestions);
1582         evdns_server_request_add_a_reply(req, req->questions[0]->name, 1,
1583             &answer, 100);
1584         evdns_server_request_respond(req, 0);
1585         return;
1586 end:
1587         evdns_server_request_respond(req, DNS_ERR_REFUSED);
1588 }
1589
1590
1591 static void
1592 gaic_getaddrinfo_cb(int result, struct evutil_addrinfo *res, void *arg)
1593 {
1594         struct gaic_request_status *status = arg;
1595         struct event_base *base = status->base;
1596         tt_assert(status->magic == GAIC_MAGIC);
1597
1598         if (result == EVUTIL_EAI_CANCEL) {
1599                 tt_assert(status->canceled);
1600         }
1601         event_del(&status->cancel_event);
1602
1603         memset(status, 0xf0, sizeof(*status));
1604         free(status);
1605
1606 end:
1607         if (--pending <= 0)
1608                 event_base_loopexit(base, NULL);
1609 }
1610
1611 static void
1612 gaic_launch(struct event_base *base, struct evdns_base *dns_base)
1613 {
1614         struct gaic_request_status *status = calloc(1,sizeof(*status));
1615         struct timeval tv = { 0, 10000 };
1616         status->magic = GAIC_MAGIC;
1617         status->base = base;
1618         status->dns_base = dns_base;
1619         event_assign(&status->cancel_event, base, -1, 0, gaic_cancel_request_cb,
1620             status);
1621         status->request = evdns_getaddrinfo(dns_base,
1622             "foobar.bazquux.example.com", "80", NULL, gaic_getaddrinfo_cb,
1623             status);
1624         event_add(&status->cancel_event, &tv);
1625         ++pending;
1626 }
1627
1628 static void
1629 test_getaddrinfo_async_cancel_stress(void *ptr)
1630 {
1631         struct event_base *base;
1632         struct evdns_base *dns_base = NULL;
1633         struct evdns_server_port *server = NULL;
1634         evutil_socket_t fd = -1;
1635         struct sockaddr_in sin;
1636         struct sockaddr_storage ss;
1637         ev_socklen_t slen;
1638         int i;
1639
1640         base = event_base_new();
1641         dns_base = evdns_base_new(base, 0);
1642
1643         memset(&sin, 0, sizeof(sin));
1644         sin.sin_family = AF_INET;
1645         sin.sin_port = 0;
1646         sin.sin_addr.s_addr = htonl(0x7f000001);
1647         if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
1648                 tt_abort_perror("socket");
1649         }
1650         evutil_make_socket_nonblocking(fd);
1651         if (bind(fd, (struct sockaddr*)&sin, sizeof(sin))<0) {
1652                 tt_abort_perror("bind");
1653         }
1654         server = evdns_add_server_port_with_base(base, fd, 0, gaic_server_cb,
1655             base);
1656
1657         memset(&ss, 0, sizeof(ss));
1658         slen = sizeof(ss);
1659         if (getsockname(fd, (struct sockaddr*)&ss, &slen)<0) {
1660                 tt_abort_perror("getsockname");
1661         }
1662         evdns_base_nameserver_sockaddr_add(dns_base,
1663             (struct sockaddr*)&ss, slen, 0);
1664
1665         for (i = 0; i < 1000; ++i) {
1666                 gaic_launch(base, dns_base);
1667         }
1668
1669         event_base_dispatch(base);
1670
1671 end:
1672         if (dns_base)
1673                 evdns_base_free(dns_base, 1);
1674         if (server)
1675                 evdns_close_server_port(server);
1676         if (fd >= 0)
1677                 evutil_closesocket(fd);
1678 }
1679
1680
1681 #define DNS_LEGACY(name, flags)                                        \
1682         { #name, run_legacy_test_fn, flags|TT_LEGACY, &legacy_setup,   \
1683                     dns_##name }
1684
1685 struct testcase_t dns_testcases[] = {
1686         DNS_LEGACY(server, TT_FORK|TT_NEED_BASE),
1687         DNS_LEGACY(gethostbyname, TT_FORK|TT_NEED_BASE|TT_NEED_DNS),
1688         DNS_LEGACY(gethostbyname6, TT_FORK|TT_NEED_BASE|TT_NEED_DNS),
1689         DNS_LEGACY(gethostbyaddr, TT_FORK|TT_NEED_BASE|TT_NEED_DNS),
1690         { "resolve_reverse", dns_resolve_reverse, TT_FORK, NULL, NULL },
1691         { "search", dns_search_test, TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
1692         { "search_cancel", dns_search_cancel_test,
1693           TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
1694         { "retry", dns_retry_test, TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
1695         { "reissue", dns_reissue_test, TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
1696         { "inflight", dns_inflight_test, TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
1697         { "bufferevent_connect_hostname", test_bufferevent_connect_hostname,
1698           TT_FORK|TT_NEED_BASE, &basic_setup, NULL },
1699
1700         { "getaddrinfo_async", test_getaddrinfo_async,
1701           TT_FORK|TT_NEED_BASE, &basic_setup, (char*)"" },
1702         { "getaddrinfo_cancel_stress", test_getaddrinfo_async_cancel_stress,
1703           TT_FORK, NULL, NULL },
1704
1705         END_OF_TESTCASES
1706 };
1707