xref: /openbsd-src/usr.sbin/unbound/testcode/testbound.c (revision 4e1ee0786f11cc571bd0be17d38e46f635c719fc)
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 	strip_end_white(id);
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 	strip_end_white(id);
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 			strip_end_white(tid);
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 	strip_end_white(id);
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, "		log-servfail: yes\n");
283 	fprintf(cfg, "remote-control:	control-enable: no\n");
284 	while(fgets(line, MAX_LINE_LEN-1, in)) {
285 		parse = line;
286 		(*lineno)++;
287 		while(isspace((unsigned char)*parse))
288 			parse++;
289 		if(!*parse || parse[0] == ';')
290 			continue;
291 		if(strncmp(parse, "COMMANDLINE", 11) == 0) {
292 			parse[strlen(parse)-1] = 0; /* strip off \n */
293 			add_opts(parse+11, pass_argc, pass_argv);
294 			continue;
295 		}
296 		if(strncmp(parse, "AUTOTRUST_FILE", 14) == 0) {
297 			spool_auto_file(in, lineno, cfg, parse+14);
298 			continue;
299 		}
300 		if(strncmp(parse, "TEMPFILE_NAME", 13) == 0) {
301 			spool_temp_file_name(lineno, cfg, parse+13);
302 			continue;
303 		}
304 		if(strncmp(parse, "TEMPFILE_CONTENTS", 17) == 0) {
305 			spool_temp_file(in, lineno, parse+17);
306 			continue;
307 		}
308 		if(strncmp(parse, "CONFIG_END", 10) == 0) {
309 			fclose(cfg);
310 			return;
311 		}
312 		fputs(line, cfg);
313 	}
314 	fatal_exit("No CONFIG_END in input file");
315 
316 }
317 
318 /** read playback file */
319 static struct replay_scenario*
320 setup_playback(const char* filename, int* pass_argc, char* pass_argv[])
321 {
322 	struct replay_scenario* scen = NULL;
323 	int lineno = 0;
324 
325 	if(filename) {
326 		FILE *in = fopen(filename, "rb");
327 		if(!in) {
328 			perror(filename);
329 			exit(1);
330 		}
331 		setup_config(in, &lineno, pass_argc, pass_argv);
332 		scen = replay_scenario_read(in, filename, &lineno);
333 		fclose(in);
334 		if(!scen)
335 			fatal_exit("Could not read: %s", filename);
336 	}
337 	else fatal_exit("need a playback file (-p)");
338 	log_info("Scenario: %s", scen->title);
339 	return scen;
340 }
341 
342 /** remove config file at exit */
343 static void remove_configfile(void)
344 {
345 	struct config_strlist* p;
346 	for(p=cfgfiles; p; p=p->next)
347 		unlink(p->str);
348 	config_delstrlist(cfgfiles);
349 	cfgfiles = NULL;
350 }
351 
352 /**
353  * Main fake event test program. Setup, teardown and report errors.
354  * @param argc: arg count.
355  * @param argv: array of commandline arguments.
356  * @return program failure if test fails.
357  */
358 int
359 main(int argc, char* argv[])
360 {
361 	int c, res;
362 	int pass_argc = 0;
363 	char* pass_argv[MAXARG];
364 	char* playback_file = NULL;
365 	int init_optind = optind;
366 	char* init_optarg = optarg;
367 	struct replay_scenario* scen = NULL;
368 
369 	/* we do not want the test to depend on the timezone */
370 	(void)putenv("TZ=UTC");
371 	memset(pass_argv, 0, sizeof(pass_argv));
372 #ifdef HAVE_SYSTEMD
373 	/* we do not want the test to use systemd daemon startup notification*/
374 	(void)unsetenv("NOTIFY_SOCKET");
375 #endif /* HAVE_SYSTEMD */
376 
377 	log_init(NULL, 0, NULL);
378 	/* determine commandline options for the daemon */
379 	pass_argc = 1;
380 	pass_argv[0] = "unbound";
381 	add_opts("-d", &pass_argc, pass_argv);
382 	while( (c=getopt(argc, argv, "12egciho:p:s")) != -1) {
383 		switch(c) {
384 		case 's':
385 			free(pass_argv[1]);
386 			testbound_selftest();
387 			checklock_stop();
388 			if(log_get_lock()) {
389 				lock_basic_destroy((lock_basic_type*)log_get_lock());
390 			}
391 			exit(0);
392 		case '1':
393 #ifdef USE_SHA1
394 			printf("SHA1 supported\n");
395 			exit(0);
396 #else
397 			printf("SHA1 not supported\n");
398 			exit(1);
399 #endif
400 			break;
401 		case '2':
402 #if (defined(HAVE_EVP_SHA256) || defined(HAVE_NSS) || defined(HAVE_NETTLE)) && defined(USE_SHA2)
403 			printf("SHA256 supported\n");
404 			exit(0);
405 #else
406 			printf("SHA256 not supported\n");
407 			exit(1);
408 #endif
409 			break;
410 		case 'e':
411 #if defined(USE_ECDSA)
412 			printf("ECDSA supported\n");
413 			exit(0);
414 #else
415 			printf("ECDSA not supported\n");
416 			exit(1);
417 #endif
418 			break;
419 		case 'g':
420 #ifdef USE_GOST
421 			if(sldns_key_EVP_load_gost_id()) {
422 				printf("GOST supported\n");
423 				exit(0);
424 			} else {
425 				printf("GOST not supported\n");
426 				exit(1);
427 			}
428 #else
429 			printf("GOST not supported\n");
430 			exit(1);
431 #endif
432 			break;
433 		case 'c':
434 #ifdef CLIENT_SUBNET
435 			printf("CLIENT_SUBNET supported\n");
436 			exit(0);
437 #else
438 			printf("CLIENT_SUBNET not supported\n");
439 			exit(1);
440 #endif
441 			break;
442 		case 'i':
443 #ifdef USE_IPSECMOD
444 			printf("IPSECMOD supported\n");
445 			exit(0);
446 #else
447 			printf("IPSECMOD not supported\n");
448 			exit(1);
449 #endif
450 			break;
451 		case 'p':
452 			playback_file = optarg;
453 			break;
454 		case 'o':
455 			add_opts(optarg, &pass_argc, pass_argv);
456 			break;
457 		case '?':
458 		case 'h':
459 		default:
460 			testbound_usage();
461 			exit(1);
462 		}
463 	}
464 	argc -= optind;
465 	/* argv += optind; not using further arguments */
466 	if(argc != 0) {
467 		testbound_usage();
468 		exit(1);
469 	}
470 	log_info("Start of %s testbound program.", PACKAGE_STRING);
471 	if(atexit(&remove_configfile) != 0)
472 		fatal_exit("atexit() failed: %s", strerror(errno));
473 
474 	/* setup test environment */
475 	scen = setup_playback(playback_file, &pass_argc, pass_argv);
476 	/* init fake event backend */
477 	fake_event_init(scen);
478 
479 	pass_argv[pass_argc] = NULL;
480 	echo_cmdline(pass_argc, pass_argv);
481 
482 	/* reset getopt processing */
483 	optind = init_optind;
484 	optarg = init_optarg;
485 
486 	/* run the normal daemon */
487 	res = daemon_main(pass_argc, pass_argv);
488 
489 	fake_event_cleanup();
490 	for(c=1; c<pass_argc; c++)
491 		free(pass_argv[c]);
492 	if(res == 0) {
493 		log_info("Testbound Exit Success\n");
494 		/* remove configfile from here, the atexit() is for when
495 		 * there is a crash to remove the tmpdir file.
496 		 * This one removes the file while alloc and log locks are
497 		 * still valid, and can be logged (for memory calculation),
498 		 * it leaves the ptr NULL so the atexit does nothing. */
499 		remove_configfile();
500 		if(log_get_lock()) {
501 			lock_basic_destroy((lock_basic_type*)log_get_lock());
502 		}
503 #ifdef HAVE_PTHREAD
504 		/* dlopen frees its thread state (dlopen of gost engine) */
505 		pthread_exit(NULL);
506 #endif
507 	}
508 	return res;
509 }
510 
511 /* fake remote control */
512 struct listen_port* daemon_remote_open_ports(struct config_file*
513 	ATTR_UNUSED(cfg))
514 {
515 	return NULL;
516 }
517 
518 struct daemon_remote* daemon_remote_create(struct config_file* ATTR_UNUSED(cfg))
519 {
520 	return (struct daemon_remote*)calloc(1,1);
521 }
522 
523 void daemon_remote_delete(struct daemon_remote* rc)
524 {
525 	free(rc);
526 }
527 
528 void daemon_remote_clear(struct daemon_remote* ATTR_UNUSED(rc))
529 {
530 	/* nothing */
531 }
532 
533 int daemon_remote_open_accept(struct daemon_remote* ATTR_UNUSED(rc),
534         struct listen_port* ATTR_UNUSED(ports),
535 	struct worker* ATTR_UNUSED(worker))
536 {
537 	return 1;
538 }
539 
540 int remote_accept_callback(struct comm_point* ATTR_UNUSED(c),
541 	void* ATTR_UNUSED(arg), int ATTR_UNUSED(error),
542         struct comm_reply* ATTR_UNUSED(repinfo))
543 {
544 	log_assert(0);
545 	return 0;
546 }
547 
548 int remote_control_callback(struct comm_point* ATTR_UNUSED(c),
549 	void* ATTR_UNUSED(arg), int ATTR_UNUSED(error),
550         struct comm_reply* ATTR_UNUSED(repinfo))
551 {
552 	log_assert(0);
553 	return 0;
554 }
555 
556 void remote_get_opt_ssl(char* ATTR_UNUSED(str), void* ATTR_UNUSED(arg))
557 {
558         log_assert(0);
559 }
560 
561 #ifdef UB_ON_WINDOWS
562 void wsvc_command_option(const char* ATTR_UNUSED(wopt),
563 	const char* ATTR_UNUSED(cfgfile), int ATTR_UNUSED(v),
564 	int ATTR_UNUSED(c))
565 {
566 	log_assert(0);
567 }
568 #endif
569 
570 #ifdef UB_ON_WINDOWS
571 void wsvc_setup_worker(struct worker* ATTR_UNUSED(worker))
572 {
573 	/* do nothing */
574 }
575 #endif
576 
577 #ifdef UB_ON_WINDOWS
578 void wsvc_desetup_worker(struct worker* ATTR_UNUSED(worker))
579 {
580 	/* do nothing */
581 }
582 #endif
583 
584 #ifdef UB_ON_WINDOWS
585 void worker_win_stop_cb(int ATTR_UNUSED(fd), short ATTR_UNUSED(ev),
586 	void* ATTR_UNUSED(arg))
587 {
588 	log_assert(0);
589 }
590 
591 void wsvc_cron_cb(void* ATTR_UNUSED(arg))
592 {
593 	log_assert(0);
594 }
595 #endif /* UB_ON_WINDOWS */
596 
597 int tcp_connect_errno_needs_log(struct sockaddr* ATTR_UNUSED(addr),
598 	socklen_t ATTR_UNUSED(addrlen))
599 {
600 	return 1;
601 }
602 
603 int squelch_err_ssl_handshake(unsigned long ATTR_UNUSED(err))
604 {
605 	return 0;
606 }
607