xref: /openbsd-src/usr.sbin/unbound/testcode/testbound.c (revision 24bb5fcea3ed904bc467217bdaadb5dfc618d5bf)
1 /*
2  * testcode/testbound.c - test program for unbound.
3  *
4  * Copyright (c) 2007, 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  * Exits with code 1 on a failure. 0 if all unit tests are successful.
39  */
40 
41 #include "config.h"
42 #ifdef HAVE_TIME_H
43 #  include <time.h>
44 #endif
45 #include <ctype.h>
46 #include "testcode/testpkts.h"
47 #include "testcode/replay.h"
48 #include "testcode/fake_event.h"
49 #include "daemon/remote.h"
50 #include "libunbound/worker.h"
51 #include "util/config_file.h"
52 #include "sldns/keyraw.h"
53 #ifdef UB_ON_WINDOWS
54 #include "winrc/win_svc.h"
55 #endif
56 
57 /** signal that this is a testbound compile */
58 #define unbound_testbound 1
59 /** renamed main routine */
60 int daemon_main(int argc, char* argv[]);
61 /**
62  * include the main program from the unbound daemon.
63  * rename main to daemon_main to call it
64  */
65 #define main daemon_main
66 #include "daemon/unbound.c"
67 #undef main
68 
69 /** maximum line length for lines in the replay file. */
70 #define MAX_LINE_LEN 1024
71 /** config files (removed at exit) */
72 static struct config_strlist* cfgfiles = NULL;
73 
74 #ifdef UNBOUND_ALLOC_STATS
75 #  define strdup(s) unbound_stat_strdup_log(s, __FILE__, __LINE__, __func__)
76 char* unbound_stat_strdup_log(char* s, const char* file, int line,
77 	const char* func);
78 char* unbound_stat_strdup_log(char* s, const char* file, int line,
79         const char* func) {
80 	char* result;
81 	size_t len;
82 	if(!s) return NULL;
83 	len = strlen(s);
84 	log_info("%s:%d %s strdup(%u)", file, line, func, (unsigned)len+1);
85 	result = unbound_stat_malloc(len+1);
86 	memmove(result, s, len+1);
87 	return result;
88 }
89 #endif /* UNBOUND_ALLOC_STATS */
90 
91 /** give commandline usage for testbound. */
92 static void
93 testbound_usage(void)
94 {
95 	printf("usage: testbound [options]\n");
96 	printf("\ttest the unbound daemon.\n");
97 	printf("-h      this help\n");
98 	printf("-p file	playback text file\n");
99 	printf("-1 	detect SHA1 support (exit code 0 or 1)\n");
100 	printf("-2 	detect SHA256 support (exit code 0 or 1)\n");
101 	printf("-g 	detect GOST support (exit code 0 or 1)\n");
102 	printf("-e 	detect ECDSA support (exit code 0 or 1)\n");
103 	printf("-c 	detect CLIENT_SUBNET support (exit code 0 or 1)\n");
104 	printf("-i 	detect IPSECMOD support (exit code 0 or 1)\n");
105 	printf("-s 	testbound self-test - unit test of testbound parts.\n");
106 	printf("-o str  unbound commandline options separated by spaces.\n");
107 	printf("Version %s\n", PACKAGE_VERSION);
108 	printf("BSD licensed, see LICENSE file in source package.\n");
109 	printf("Report bugs to %s.\n", PACKAGE_BUGREPORT);
110 }
111 
112 /** Max number of arguments to pass to unbound. */
113 #define MAXARG 100
114 
115 /**
116  * Add options from string to passed argc. splits on whitespace.
117  * @param args: the option argument, "-v -p 12345" or so.
118  * @param pass_argc: ptr to the argc for unbound. Modified.
119  * @param pass_argv: the argv to pass to unbound. Modified.
120  */
121 static void
122 add_opts(const char* args, int* pass_argc, char* pass_argv[])
123 {
124 	const char *p = args, *np;
125 	size_t len;
126 	while(p && isspace((unsigned char)*p))
127 		p++;
128 	while(p && *p) {
129 		/* find location of next string and length of this one */
130 		if((np = strchr(p, ' ')))
131 			len = (size_t)(np-p);
132 		else	len = strlen(p);
133 		/* allocate and copy option */
134 		if(*pass_argc >= MAXARG-1)
135 			fatal_exit("too many arguments: '%s'", p);
136 		pass_argv[*pass_argc] = (char*)malloc(len+1);
137 		if(!pass_argv[*pass_argc])
138 			fatal_exit("add_opts: out of memory");
139 		memcpy(pass_argv[*pass_argc], p, len);
140 		pass_argv[*pass_argc][len] = 0;
141 		(*pass_argc)++;
142 		/* go to next option */
143 	        p = np;
144 		while(p && isspace((unsigned char)*p))
145 			p++;
146 	}
147 }
148 
149 /** pretty print commandline for unbound in this test */
150 static void
151 echo_cmdline(int argc, char* argv[])
152 {
153 	int i;
154 	fprintf(stderr, "testbound is starting:");
155 	for(i=0; i<argc; i++) {
156 		fprintf(stderr, " [%s]", argv[i]);
157 	}
158 	fprintf(stderr, "\n");
159 }
160 
161 /** spool temp file name */
162 static void
163 spool_temp_file_name(int* lineno, FILE* cfg, char* id)
164 {
165 	char line[MAX_LINE_LEN];
166 	/* find filename for new file */
167 	while(isspace((unsigned char)*id))
168 		id++;
169 	if(*id == '\0')
170 		fatal_exit("TEMPFILE_NAME must have id, line %d", *lineno);
171 	id[strlen(id)-1]=0; /* remove newline */
172 	fake_temp_file("_temp_", id, line, sizeof(line));
173 	fprintf(cfg, "\"%s\"\n", line);
174 }
175 
176 /** spool temp file */
177 static void
178 spool_temp_file(FILE* in, int* lineno, char* id)
179 {
180 	char line[MAX_LINE_LEN];
181 	char* parse;
182 	FILE* spool;
183 	/* find filename for new file */
184 	while(isspace((unsigned char)*id))
185 		id++;
186 	if(*id == '\0')
187 		fatal_exit("TEMPFILE_CONTENTS must have id, line %d", *lineno);
188 	id[strlen(id)-1]=0; /* remove newline */
189 	fake_temp_file("_temp_", id, line, sizeof(line));
190 	/* open file and spool to it */
191 	spool = fopen(line, "w");
192 	if(!spool) fatal_exit("could not open %s: %s", line, strerror(errno));
193 	fprintf(stderr, "testbound is spooling temp file: %s\n", line);
194 	if(!cfg_strlist_insert(&cfgfiles, strdup(line)))
195 		fatal_exit("out of memory");
196 	line[sizeof(line)-1] = 0;
197 	while(fgets(line, MAX_LINE_LEN-1, in)) {
198 		parse = line;
199 		(*lineno)++;
200 		while(isspace((unsigned char)*parse))
201 			parse++;
202 		if(strncmp(parse, "$INCLUDE_TEMPFILE", 17) == 0) {
203 			char l2[MAX_LINE_LEN-30]; /* -30 makes it fit with
204 				a preceding $INCLUDE in the buf line[] */
205 			char* tid = parse+17;
206 			while(isspace((unsigned char)*tid))
207 				tid++;
208 			tid[strlen(tid)-1]=0; /* remove newline */
209 			fake_temp_file("_temp_", tid, l2, sizeof(l2));
210 			snprintf(line, sizeof(line), "$INCLUDE %s\n", l2);
211 		}
212 		if(strncmp(parse, "TEMPFILE_END", 12) == 0) {
213 			fclose(spool);
214 			return;
215 		}
216 		fputs(line, spool);
217 	}
218 	fatal_exit("no TEMPFILE_END in input file");
219 }
220 
221 /** spool autotrust file */
222 static void
223 spool_auto_file(FILE* in, int* lineno, FILE* cfg, char* id)
224 {
225 	char line[MAX_LINE_LEN];
226 	char* parse;
227 	FILE* spool;
228 	/* find filename for new file */
229 	while(isspace((unsigned char)*id))
230 		id++;
231 	if(*id == '\0')
232 		fatal_exit("AUTROTRUST_FILE must have id, line %d", *lineno);
233 	id[strlen(id)-1]=0; /* remove newline */
234 	fake_temp_file("_auto_", id, line, sizeof(line));
235 	/* add option for the file */
236 	fprintf(cfg, "server:	auto-trust-anchor-file: \"%s\"\n", line);
237 	/* open file and spool to it */
238 	spool = fopen(line, "w");
239 	if(!spool) fatal_exit("could not open %s: %s", line, strerror(errno));
240 	fprintf(stderr, "testbound is spooling key file: %s\n", line);
241 	if(!cfg_strlist_insert(&cfgfiles, strdup(line)))
242 		fatal_exit("out of memory");
243 	line[sizeof(line)-1] = 0;
244 	while(fgets(line, MAX_LINE_LEN-1, in)) {
245 		parse = line;
246 		(*lineno)++;
247 		while(isspace((unsigned char)*parse))
248 			parse++;
249 		if(strncmp(parse, "AUTOTRUST_END", 13) == 0) {
250 			fclose(spool);
251 			return;
252 		}
253 		fputs(line, spool);
254 	}
255 	fatal_exit("no AUTOTRUST_END in input file");
256 }
257 
258 /** process config elements */
259 static void
260 setup_config(FILE* in, int* lineno, int* pass_argc, char* pass_argv[])
261 {
262 	char configfile[MAX_LINE_LEN];
263 	char line[MAX_LINE_LEN];
264 	char* parse;
265 	FILE* cfg;
266 	fake_temp_file("_cfg", "", configfile, sizeof(configfile));
267 	add_opts("-c", pass_argc, pass_argv);
268 	add_opts(configfile, pass_argc, pass_argv);
269 	cfg = fopen(configfile, "w");
270 	if(!cfg) fatal_exit("could not open %s: %s",
271 			configfile, strerror(errno));
272 	if(!cfg_strlist_insert(&cfgfiles, strdup(configfile)))
273 		fatal_exit("out of memory");
274 	line[sizeof(line)-1] = 0;
275 	/* some basic settings to not pollute the host system */
276 	fprintf(cfg, "server:	use-syslog: no\n");
277 	fprintf(cfg, "		directory: \"\"\n");
278 	fprintf(cfg, "		chroot: \"\"\n");
279 	fprintf(cfg, "		username: \"\"\n");
280 	fprintf(cfg, "		pidfile: \"\"\n");
281 	fprintf(cfg, "		val-log-level: 2\n");
282 	fprintf(cfg, "remote-control:	control-enable: no\n");
283 	while(fgets(line, MAX_LINE_LEN-1, in)) {
284 		parse = line;
285 		(*lineno)++;
286 		while(isspace((unsigned char)*parse))
287 			parse++;
288 		if(!*parse || parse[0] == ';')
289 			continue;
290 		if(strncmp(parse, "COMMANDLINE", 11) == 0) {
291 			parse[strlen(parse)-1] = 0; /* strip off \n */
292 			add_opts(parse+11, pass_argc, pass_argv);
293 			continue;
294 		}
295 		if(strncmp(parse, "AUTOTRUST_FILE", 14) == 0) {
296 			spool_auto_file(in, lineno, cfg, parse+14);
297 			continue;
298 		}
299 		if(strncmp(parse, "TEMPFILE_NAME", 13) == 0) {
300 			spool_temp_file_name(lineno, cfg, parse+13);
301 			continue;
302 		}
303 		if(strncmp(parse, "TEMPFILE_CONTENTS", 17) == 0) {
304 			spool_temp_file(in, lineno, parse+17);
305 			continue;
306 		}
307 		if(strncmp(parse, "CONFIG_END", 10) == 0) {
308 			fclose(cfg);
309 			return;
310 		}
311 		fputs(line, cfg);
312 	}
313 	fatal_exit("No CONFIG_END in input file");
314 
315 }
316 
317 /** read playback file */
318 static struct replay_scenario*
319 setup_playback(const char* filename, int* pass_argc, char* pass_argv[])
320 {
321 	struct replay_scenario* scen = NULL;
322 	int lineno = 0;
323 
324 	if(filename) {
325 		FILE *in = fopen(filename, "rb");
326 		if(!in) {
327 			perror(filename);
328 			exit(1);
329 		}
330 		setup_config(in, &lineno, pass_argc, pass_argv);
331 		scen = replay_scenario_read(in, filename, &lineno);
332 		fclose(in);
333 		if(!scen)
334 			fatal_exit("Could not read: %s", filename);
335 	}
336 	else fatal_exit("need a playback file (-p)");
337 	log_info("Scenario: %s", scen->title);
338 	return scen;
339 }
340 
341 /** remove config file at exit */
342 static void remove_configfile(void)
343 {
344 	struct config_strlist* p;
345 	for(p=cfgfiles; p; p=p->next)
346 		unlink(p->str);
347 	config_delstrlist(cfgfiles);
348 	cfgfiles = NULL;
349 }
350 
351 /**
352  * Main fake event test program. Setup, teardown and report errors.
353  * @param argc: arg count.
354  * @param argv: array of commandline arguments.
355  * @return program failure if test fails.
356  */
357 int
358 main(int argc, char* argv[])
359 {
360 	int c, res;
361 	int pass_argc = 0;
362 	char* pass_argv[MAXARG];
363 	char* playback_file = NULL;
364 	int init_optind = optind;
365 	char* init_optarg = optarg;
366 	struct replay_scenario* scen = NULL;
367 
368 	/* we do not want the test to depend on the timezone */
369 	(void)putenv("TZ=UTC");
370 	memset(pass_argv, 0, sizeof(pass_argv));
371 #ifdef HAVE_SYSTEMD
372 	/* we do not want the test to use systemd daemon startup notification*/
373 	(void)unsetenv("NOTIFY_SOCKET");
374 #endif /* HAVE_SYSTEMD */
375 
376 	log_init(NULL, 0, NULL);
377 	/* determine commandline options for the daemon */
378 	pass_argc = 1;
379 	pass_argv[0] = "unbound";
380 	add_opts("-d", &pass_argc, pass_argv);
381 	while( (c=getopt(argc, argv, "12egciho:p:s")) != -1) {
382 		switch(c) {
383 		case 's':
384 			free(pass_argv[1]);
385 			testbound_selftest();
386 			checklock_stop();
387 			if(log_get_lock()) {
388 				lock_basic_destroy((lock_basic_type*)log_get_lock());
389 			}
390 			exit(0);
391 		case '1':
392 #ifdef USE_SHA1
393 			printf("SHA1 supported\n");
394 			exit(0);
395 #else
396 			printf("SHA1 not supported\n");
397 			exit(1);
398 #endif
399 			break;
400 		case '2':
401 #if (defined(HAVE_EVP_SHA256) || defined(HAVE_NSS) || defined(HAVE_NETTLE)) && defined(USE_SHA2)
402 			printf("SHA256 supported\n");
403 			exit(0);
404 #else
405 			printf("SHA256 not supported\n");
406 			exit(1);
407 #endif
408 			break;
409 		case 'e':
410 #if defined(USE_ECDSA)
411 			printf("ECDSA supported\n");
412 			exit(0);
413 #else
414 			printf("ECDSA not supported\n");
415 			exit(1);
416 #endif
417 			break;
418 		case 'g':
419 #ifdef USE_GOST
420 			if(sldns_key_EVP_load_gost_id()) {
421 				printf("GOST supported\n");
422 				exit(0);
423 			} else {
424 				printf("GOST not supported\n");
425 				exit(1);
426 			}
427 #else
428 			printf("GOST not supported\n");
429 			exit(1);
430 #endif
431 			break;
432 		case 'c':
433 #ifdef CLIENT_SUBNET
434 			printf("CLIENT_SUBNET supported\n");
435 			exit(0);
436 #else
437 			printf("CLIENT_SUBNET not supported\n");
438 			exit(1);
439 #endif
440 			break;
441 		case 'i':
442 #ifdef USE_IPSECMOD
443 			printf("IPSECMOD supported\n");
444 			exit(0);
445 #else
446 			printf("IPSECMOD not supported\n");
447 			exit(1);
448 #endif
449 			break;
450 		case 'p':
451 			playback_file = optarg;
452 			break;
453 		case 'o':
454 			add_opts(optarg, &pass_argc, pass_argv);
455 			break;
456 		case '?':
457 		case 'h':
458 		default:
459 			testbound_usage();
460 			exit(1);
461 		}
462 	}
463 	argc -= optind;
464 	/* argv += optind; not using further arguments */
465 	if(argc != 0) {
466 		testbound_usage();
467 		exit(1);
468 	}
469 	log_info("Start of %s testbound program.", PACKAGE_STRING);
470 	if(atexit(&remove_configfile) != 0)
471 		fatal_exit("atexit() failed: %s", strerror(errno));
472 
473 	/* setup test environment */
474 	scen = setup_playback(playback_file, &pass_argc, pass_argv);
475 	/* init fake event backend */
476 	fake_event_init(scen);
477 
478 	pass_argv[pass_argc] = NULL;
479 	echo_cmdline(pass_argc, pass_argv);
480 
481 	/* reset getopt processing */
482 	optind = init_optind;
483 	optarg = init_optarg;
484 
485 	/* run the normal daemon */
486 	res = daemon_main(pass_argc, pass_argv);
487 
488 	fake_event_cleanup();
489 	for(c=1; c<pass_argc; c++)
490 		free(pass_argv[c]);
491 	if(res == 0) {
492 		log_info("Testbound Exit Success\n");
493 		/* remove configfile from here, the atexit() is for when
494 		 * there is a crash to remove the tmpdir file.
495 		 * This one removes the file while alloc and log locks are
496 		 * still valid, and can be logged (for memory calculation),
497 		 * it leaves the ptr NULL so the atexit does nothing. */
498 		remove_configfile();
499 		if(log_get_lock()) {
500 			lock_basic_destroy((lock_basic_type*)log_get_lock());
501 		}
502 #ifdef HAVE_PTHREAD
503 		/* dlopen frees its thread state (dlopen of gost engine) */
504 		pthread_exit(NULL);
505 #endif
506 	}
507 	return res;
508 }
509 
510 /* fake remote control */
511 struct listen_port* daemon_remote_open_ports(struct config_file*
512 	ATTR_UNUSED(cfg))
513 {
514 	return NULL;
515 }
516 
517 struct daemon_remote* daemon_remote_create(struct config_file* ATTR_UNUSED(cfg))
518 {
519 	return (struct daemon_remote*)calloc(1,1);
520 }
521 
522 void daemon_remote_delete(struct daemon_remote* rc)
523 {
524 	free(rc);
525 }
526 
527 void daemon_remote_clear(struct daemon_remote* ATTR_UNUSED(rc))
528 {
529 	/* nothing */
530 }
531 
532 int daemon_remote_open_accept(struct daemon_remote* ATTR_UNUSED(rc),
533         struct listen_port* ATTR_UNUSED(ports),
534 	struct worker* ATTR_UNUSED(worker))
535 {
536 	return 1;
537 }
538 
539 int remote_accept_callback(struct comm_point* ATTR_UNUSED(c),
540 	void* ATTR_UNUSED(arg), int ATTR_UNUSED(error),
541         struct comm_reply* ATTR_UNUSED(repinfo))
542 {
543 	log_assert(0);
544 	return 0;
545 }
546 
547 int remote_control_callback(struct comm_point* ATTR_UNUSED(c),
548 	void* ATTR_UNUSED(arg), int ATTR_UNUSED(error),
549         struct comm_reply* ATTR_UNUSED(repinfo))
550 {
551 	log_assert(0);
552 	return 0;
553 }
554 
555 void remote_get_opt_ssl(char* ATTR_UNUSED(str), void* ATTR_UNUSED(arg))
556 {
557         log_assert(0);
558 }
559 
560 #ifdef UB_ON_WINDOWS
561 void wsvc_command_option(const char* ATTR_UNUSED(wopt),
562 	const char* ATTR_UNUSED(cfgfile), int ATTR_UNUSED(v),
563 	int ATTR_UNUSED(c))
564 {
565 	log_assert(0);
566 }
567 #endif
568 
569 #ifdef UB_ON_WINDOWS
570 void wsvc_setup_worker(struct worker* ATTR_UNUSED(worker))
571 {
572 	/* do nothing */
573 }
574 #endif
575 
576 #ifdef UB_ON_WINDOWS
577 void wsvc_desetup_worker(struct worker* ATTR_UNUSED(worker))
578 {
579 	/* do nothing */
580 }
581 #endif
582 
583 #ifdef UB_ON_WINDOWS
584 void worker_win_stop_cb(int ATTR_UNUSED(fd), short ATTR_UNUSED(ev),
585 	void* ATTR_UNUSED(arg))
586 {
587 	log_assert(0);
588 }
589 
590 void wsvc_cron_cb(void* ATTR_UNUSED(arg))
591 {
592 	log_assert(0);
593 }
594 #endif /* UB_ON_WINDOWS */
595 
596 int tcp_connect_errno_needs_log(struct sockaddr* ATTR_UNUSED(addr),
597 	socklen_t ATTR_UNUSED(addrlen))
598 {
599 	return 1;
600 }
601 
602 int squelch_err_ssl_handshake(unsigned long ATTR_UNUSED(err))
603 {
604 	return 0;
605 }
606