]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - testcode/asynclook.c
Vendor import of Unbound 1.7.2.
[FreeBSD/FreeBSD.git] / testcode / asynclook.c
1 /*
2  * testcode/asynclook.c - debug program perform async libunbound queries.
3  *
4  * Copyright (c) 2008, NLnet Labs. All rights reserved.
5  *
6  * This software is open source.
7  * 
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 
12  * Redistributions of source code must retain the above copyright notice,
13  * this list of conditions and the following disclaimer.
14  * 
15  * Redistributions in binary form must reproduce the above copyright notice,
16  * this list of conditions and the following disclaimer in the documentation
17  * and/or other materials provided with the distribution.
18  * 
19  * Neither the name of the NLNET LABS nor the names of its contributors may
20  * be used to endorse or promote products derived from this software without
21  * specific prior written permission.
22  * 
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27  * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
29  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  */
35
36 /**
37  * \file
38  *
39  * This program shows the results from several background lookups,
40  * while printing time in the foreground.
41  */
42
43 #include "config.h"
44 #ifdef HAVE_GETOPT_H
45 #include <getopt.h>
46 #endif
47 #include "libunbound/unbound.h"
48 #include "libunbound/context.h"
49 #include "util/locks.h"
50 #include "util/log.h"
51 #include "sldns/rrdef.h"
52 #ifdef UNBOUND_ALLOC_LITE
53 #undef malloc
54 #undef calloc
55 #undef realloc
56 #undef free
57 #undef strdup
58 #endif
59 #ifdef HAVE_SSL
60 #ifdef HAVE_OPENSSL_SSL_H
61 #include <openssl/ssl.h>
62 #endif
63 #ifdef HAVE_OPENSSL_ERR_H
64 #include <openssl/err.h>
65 #endif
66 #endif /* HAVE_SSL */
67
68
69 /** keeping track of the async ids */
70 struct track_id {
71         /** the id to pass to libunbound to cancel */
72         int id;
73         /** true if cancelled */
74         int cancel;
75         /** a lock on this structure for thread safety */
76         lock_basic_type lock;
77 };
78
79 /**
80  * result list for the lookups
81  */
82 struct lookinfo {
83         /** name to look up */
84         char* name;
85         /** tracking number that can be used to cancel the query */
86         int async_id;
87         /** error code from libunbound */
88         int err;
89         /** result from lookup */
90         struct ub_result* result;
91 };
92
93 /** global variable to see how many queries we have left */
94 static int num_wait = 0;
95
96 /** usage information for asynclook */
97 static void usage(char* argv[])
98 {
99         printf("usage: %s [options] name ...\n", argv[0]);
100         printf("names are looked up at the same time, asynchronously.\n");
101         printf("        -b : use blocking requests\n");
102         printf("        -c : cancel the requests\n");
103         printf("        -d : enable debug output\n");
104         printf("        -f addr : use addr, forward to that server\n");
105         printf("        -h : this help message\n");
106         printf("        -H fname : read hosts from fname\n");
107         printf("        -r fname : read resolv.conf from fname\n");
108         printf("        -t : use a resolver thread instead of forking a process\n");
109         printf("        -x : perform extended threaded test\n");
110         exit(1);
111 }
112
113 /** print result from lookup nicely */
114 static void
115 print_result(struct lookinfo* info)
116 {
117         char buf[100];
118         if(info->err) /* error (from libunbound) */
119                 printf("%s: error %s\n", info->name,
120                         ub_strerror(info->err));
121         else if(!info->result)
122                 printf("%s: cancelled\n", info->name);
123         else if(info->result->havedata)
124                 printf("%s: %s\n", info->name,
125                         inet_ntop(AF_INET, info->result->data[0],
126                         buf, (socklen_t)sizeof(buf)));
127         else {
128                 /* there is no data, why that? */
129                 if(info->result->rcode == 0 /*noerror*/ ||
130                         info->result->nxdomain)
131                         printf("%s: no data %s\n", info->name,
132                         info->result->nxdomain?"(no such host)":
133                         "(no IP4 address)");
134                 else    /* some error (from the server) */
135                         printf("%s: DNS error %d\n", info->name,
136                                 info->result->rcode);
137         }
138 }
139
140 /** this is a function of type ub_callback_t */
141 static void 
142 lookup_is_done(void* mydata, int err, struct ub_result* result)
143 {
144         /* cast mydata back to the correct type */
145         struct lookinfo* info = (struct lookinfo*)mydata;
146         fprintf(stderr, "name %s resolved\n", info->name);
147         info->err = err;
148         info->result = result;
149         /* one less to wait for */
150         num_wait--;
151 }
152
153 /** check error, if bad, exit with error message */
154 static void 
155 checkerr(const char* desc, int err)
156 {
157         if(err != 0) {
158                 printf("%s error: %s\n", desc, ub_strerror(err));
159                 exit(1);
160         }
161 }
162
163 #ifdef THREADS_DISABLED
164 /** only one process can communicate with async worker */
165 #define NUMTHR 1
166 #else /* have threads */
167 /** number of threads to make in extended test */
168 #define NUMTHR 10
169 #endif
170
171 /** struct for extended thread info */
172 struct ext_thr_info {
173         /** thread num for debug */
174         int thread_num;
175         /** thread id */
176         ub_thread_type tid;
177         /** context */
178         struct ub_ctx* ctx;
179         /** size of array to query */
180         int argc;
181         /** array of names to query */
182         char** argv;
183         /** number of queries to do */
184         int numq;
185 };
186
187 /** if true, we are testing against 'localhost' and extra checking is done */
188 static int q_is_localhost = 0;
189
190 /** check result structure for the 'correct' answer */
191 static void
192 ext_check_result(const char* desc, int err, struct ub_result* result)
193 {
194         checkerr(desc, err);
195         if(result == NULL) {
196                 printf("%s: error result is NULL.\n", desc);
197                 exit(1);
198         }
199         if(q_is_localhost) {
200                 if(strcmp(result->qname, "localhost") != 0) {
201                         printf("%s: error result has wrong qname.\n", desc);
202                         exit(1);
203                 }
204                 if(result->qtype != LDNS_RR_TYPE_A) {
205                         printf("%s: error result has wrong qtype.\n", desc);
206                         exit(1);
207                 }
208                 if(result->qclass != LDNS_RR_CLASS_IN) {
209                         printf("%s: error result has wrong qclass.\n", desc);
210                         exit(1);
211                 }
212                 if(result->data == NULL) {
213                         printf("%s: error result->data is NULL.\n", desc);
214                         exit(1);
215                 }
216                 if(result->len == NULL) {
217                         printf("%s: error result->len is NULL.\n", desc);
218                         exit(1);
219                 }
220                 if(result->rcode != 0) {
221                         printf("%s: error result->rcode is set.\n", desc);
222                         exit(1);
223                 }
224                 if(result->havedata == 0) {
225                         printf("%s: error result->havedata is unset.\n", desc);
226                         exit(1);
227                 }
228                 if(result->nxdomain != 0) {
229                         printf("%s: error result->nxdomain is set.\n", desc);
230                         exit(1);
231                 }
232                 if(result->secure || result->bogus) {
233                         printf("%s: error result->secure or bogus is set.\n", 
234                                 desc);
235                         exit(1);
236                 }
237                 if(result->data[0] == NULL) {
238                         printf("%s: error result->data[0] is NULL.\n", desc);
239                         exit(1);
240                 }
241                 if(result->len[0] != 4) {
242                         printf("%s: error result->len[0] is wrong.\n", desc);
243                         exit(1);
244                 }
245                 if(result->len[1] != 0 || result->data[1] != NULL) {
246                         printf("%s: error result->data[1] or len[1] is "
247                                 "wrong.\n", desc);
248                         exit(1);
249                 }
250                 if(result->answer_packet == NULL) {
251                         printf("%s: error result->answer_packet is NULL.\n", 
252                                 desc);
253                         exit(1);
254                 }
255                 if(result->answer_len != 54) {
256                         printf("%s: error result->answer_len is wrong.\n", 
257                                 desc);
258                         exit(1);
259                 }
260         }
261 }
262
263 /** extended bg result callback, this function is ub_callback_t */
264 static void 
265 ext_callback(void* mydata, int err, struct ub_result* result)
266 {
267         struct track_id* my_id = (struct track_id*)mydata;
268         int doprint = 0;
269         if(my_id) {
270                 /* I have an id, make sure we are not cancelled */
271                 lock_basic_lock(&my_id->lock);
272                 if(doprint) 
273                         printf("cb %d: ", my_id->id);
274                 if(my_id->cancel) {
275                         printf("error: query id=%d returned, but was cancelled\n",
276                                 my_id->id);
277                         abort();
278                         exit(1);
279                 }
280                 lock_basic_unlock(&my_id->lock);
281         }
282         ext_check_result("ext_callback", err, result);
283         log_assert(result);
284         if(doprint) {
285                 struct lookinfo pi;
286                 pi.name = result?result->qname:"noname";
287                 pi.result = result;
288                 pi.err = 0;
289                 print_result(&pi);
290         }
291         ub_resolve_free(result);
292 }
293
294 /** extended thread worker */
295 static void*
296 ext_thread(void* arg)
297 {
298         struct ext_thr_info* inf = (struct ext_thr_info*)arg;
299         int i, r;
300         struct ub_result* result;
301         struct track_id* async_ids = NULL;
302         log_thread_set(&inf->thread_num);
303         if(inf->thread_num > NUMTHR*2/3) {
304                 async_ids = (struct track_id*)calloc((size_t)inf->numq, sizeof(struct track_id));
305                 if(!async_ids) {
306                         printf("out of memory\n");
307                         exit(1);
308                 }
309                 for(i=0; i<inf->numq; i++) {
310                         lock_basic_init(&async_ids[i].lock);
311                 }
312         }
313         for(i=0; i<inf->numq; i++) {
314                 if(async_ids) {
315                         r = ub_resolve_async(inf->ctx, 
316                                 inf->argv[i%inf->argc], LDNS_RR_TYPE_A, 
317                                 LDNS_RR_CLASS_IN, &async_ids[i], ext_callback, 
318                                 &async_ids[i].id);
319                         checkerr("ub_resolve_async", r);
320                         if(i > 100) {
321                                 lock_basic_lock(&async_ids[i-100].lock);
322                                 r = ub_cancel(inf->ctx, async_ids[i-100].id);
323                                 if(r != UB_NOID)
324                                         async_ids[i-100].cancel=1;
325                                 lock_basic_unlock(&async_ids[i-100].lock);
326                                 if(r != UB_NOID) 
327                                         checkerr("ub_cancel", r);
328                         }
329                 } else if(inf->thread_num > NUMTHR/2) {
330                         /* async */
331                         r = ub_resolve_async(inf->ctx, 
332                                 inf->argv[i%inf->argc], LDNS_RR_TYPE_A, 
333                                 LDNS_RR_CLASS_IN, NULL, ext_callback, NULL);
334                         checkerr("ub_resolve_async", r);
335                 } else  {
336                         /* blocking */
337                         r = ub_resolve(inf->ctx, inf->argv[i%inf->argc], 
338                                 LDNS_RR_TYPE_A, LDNS_RR_CLASS_IN, &result);
339                         ext_check_result("ub_resolve", r, result);
340                         ub_resolve_free(result);
341                 }
342         }
343         if(inf->thread_num > NUMTHR/2) {
344                 r = ub_wait(inf->ctx);
345                 checkerr("ub_ctx_wait", r);
346         }
347         /* if these locks are destroyed, or if the async_ids is freed, then
348            a use-after-free happens in another thread.
349            The allocation is only part of this test, though. */
350         /*
351         if(async_ids) {
352                 for(i=0; i<inf->numq; i++) {
353                         lock_basic_destroy(&async_ids[i].lock);
354                 }
355         }
356         free(async_ids);
357         */
358         
359         return NULL;
360 }
361
362 /** perform extended threaded test */
363 static int
364 ext_test(struct ub_ctx* ctx, int argc, char** argv)
365 {
366         struct ext_thr_info inf[NUMTHR];
367         int i;
368         if(argc == 1 && strcmp(argv[0], "localhost") == 0)
369                 q_is_localhost = 1;
370         printf("extended test start (%d threads)\n", NUMTHR);
371         for(i=0; i<NUMTHR; i++) {
372                 /* 0 = this, 1 = library bg worker */
373                 inf[i].thread_num = i+2;
374                 inf[i].ctx = ctx;
375                 inf[i].argc = argc;
376                 inf[i].argv = argv;
377                 inf[i].numq = 100;
378                 ub_thread_create(&inf[i].tid, ext_thread, &inf[i]);
379         }
380         /* the work happens here */
381         for(i=0; i<NUMTHR; i++) {
382                 ub_thread_join(inf[i].tid);
383         }
384         printf("extended test end\n");
385         ub_ctx_delete(ctx);
386         checklock_stop();
387         return 0;
388 }
389
390 /** getopt global, in case header files fail to declare it. */
391 extern int optind;
392 /** getopt global, in case header files fail to declare it. */
393 extern char* optarg;
394
395 /** main program for asynclook */
396 int main(int argc, char** argv) 
397 {
398         int c;
399         struct ub_ctx* ctx;
400         struct lookinfo* lookups;
401         int i, r, cancel=0, blocking=0, ext=0;
402
403         /* init log now because solaris thr_key_create() is not threadsafe */
404         log_init(0,0,0);
405         /* lock debug start (if any) */
406         checklock_start();
407
408         /* create context */
409         ctx = ub_ctx_create();
410         if(!ctx) {
411                 printf("could not create context, %s\n", strerror(errno));
412                 return 1;
413         }
414
415         /* command line options */
416         if(argc == 1) {
417                 usage(argv);
418         }
419         while( (c=getopt(argc, argv, "bcdf:hH:r:tx")) != -1) {
420                 switch(c) {
421                         case 'd':
422                                 r = ub_ctx_debuglevel(ctx, 3);
423                                 checkerr("ub_ctx_debuglevel", r);
424                                 break;
425                         case 't':
426                                 r = ub_ctx_async(ctx, 1);
427                                 checkerr("ub_ctx_async", r);
428                                 break;
429                         case 'c':
430                                 cancel = 1;
431                                 break;
432                         case 'b':
433                                 blocking = 1;
434                                 break;
435                         case 'r':
436                                 r = ub_ctx_resolvconf(ctx, optarg);
437                                 if(r != 0) {
438                                         printf("ub_ctx_resolvconf "
439                                                 "error: %s : %s\n",
440                                                 ub_strerror(r), 
441                                                 strerror(errno));
442                                         return 1;
443                                 }
444                                 break;
445                         case 'H':
446                                 r = ub_ctx_hosts(ctx, optarg);
447                                 if(r != 0) {
448                                         printf("ub_ctx_hosts "
449                                                 "error: %s : %s\n",
450                                                 ub_strerror(r), 
451                                                 strerror(errno));
452                                         return 1;
453                                 }
454                                 break;
455                         case 'f':
456                                 r = ub_ctx_set_fwd(ctx, optarg);
457                                 checkerr("ub_ctx_set_fwd", r);
458                                 break;
459                         case 'x':
460                                 ext = 1;
461                                 break;
462                         case 'h':
463                         case '?':
464                         default:
465                                 usage(argv);
466                 }
467         }
468         argc -= optind;
469         argv += optind;
470
471 #ifdef HAVE_SSL
472 #ifdef HAVE_ERR_LOAD_CRYPTO_STRINGS
473         ERR_load_crypto_strings();
474 #endif
475 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
476         ERR_load_SSL_strings();
477 #endif
478 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_CRYPTO)
479         OpenSSL_add_all_algorithms();
480 #else
481         OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS
482                 | OPENSSL_INIT_ADD_ALL_DIGESTS
483                 | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
484 #endif
485 #if OPENSSL_VERSION_NUMBER < 0x10100000 || !defined(HAVE_OPENSSL_INIT_SSL)
486         (void)SSL_library_init();
487 #else
488         (void)OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS, NULL);
489 #endif
490 #endif /* HAVE_SSL */
491
492         if(ext)
493                 return ext_test(ctx, argc, argv);
494
495         /* allocate array for results. */
496         lookups = (struct lookinfo*)calloc((size_t)argc, 
497                 sizeof(struct lookinfo));
498         if(!lookups) {
499                 printf("out of memory\n");
500                 return 1;
501         }
502
503         /* perform asynchronous calls */
504         num_wait = argc;
505         for(i=0; i<argc; i++) {
506                 lookups[i].name = argv[i];
507                 if(blocking) {
508                         fprintf(stderr, "lookup %s\n", argv[i]);
509                         r = ub_resolve(ctx, argv[i], LDNS_RR_TYPE_A,
510                                 LDNS_RR_CLASS_IN, &lookups[i].result);
511                         checkerr("ub_resolve", r);
512                 } else {
513                         fprintf(stderr, "start async lookup %s\n", argv[i]);
514                         r = ub_resolve_async(ctx, argv[i], LDNS_RR_TYPE_A,
515                                 LDNS_RR_CLASS_IN, &lookups[i], &lookup_is_done, 
516                                 &lookups[i].async_id);
517                         checkerr("ub_resolve_async", r);
518                 }
519         }
520         if(blocking)
521                 num_wait = 0;
522         else if(cancel) {
523                 for(i=0; i<argc; i++) {
524                         fprintf(stderr, "cancel %s\n", argv[i]);
525                         r = ub_cancel(ctx, lookups[i].async_id);
526                         if(r != UB_NOID) 
527                                 checkerr("ub_cancel", r);
528                 }
529                 num_wait = 0;
530         }
531
532         /* wait while the hostnames are looked up. Do something useful here */
533         if(num_wait > 0)
534             for(i=0; i<1000; i++) {
535                 usleep(100000);
536                 fprintf(stderr, "%g seconds passed\n", 0.1*(double)i);
537                 r = ub_process(ctx);
538                 checkerr("ub_process", r);
539                 if(num_wait == 0)
540                         break;
541         }
542         if(i>=999) {
543                 printf("timed out\n");
544                 return 0;
545         }
546         printf("lookup complete\n");
547
548         /* print lookup results */
549         for(i=0; i<argc; i++) {
550                 print_result(&lookups[i]);
551                 ub_resolve_free(lookups[i].result);
552         }
553
554         ub_ctx_delete(ctx);
555         free(lookups);
556         checklock_stop();
557         return 0;
558 }