Fix bug 1113.
[tor.git] / src / test / test.c
blobd85f1f0f871715b2f006f18435d2c47f656d8ec3
1 /* Copyright (c) 2001-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2009, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
6 /* Ordinarily defined in tor_main.c; this bit is just here to provide one
7 * since we're not linking to tor_main.c */
8 const char tor_git_revision[] = "";
10 /**
11 * \file test.c
12 * \brief Unit tests for many pieces of the lower level Tor modules.
13 **/
15 #include "orconfig.h"
17 #include <stdio.h>
18 #ifdef HAVE_FCNTL_H
19 #include <fcntl.h>
20 #endif
22 #ifdef MS_WINDOWS
23 /* For mkdir() */
24 #include <direct.h>
25 #else
26 #include <dirent.h>
27 #endif
29 /* These macros pull in declarations for some functions and structures that
30 * are typically file-private. */
31 #define BUFFERS_PRIVATE
32 #define CONFIG_PRIVATE
33 #define GEOIP_PRIVATE
34 #define ROUTER_PRIVATE
35 #define CIRCUIT_PRIVATE
38 * Linux doesn't provide lround in math.h by default, but mac os does...
39 * It's best just to leave math.h out of the picture entirely.
41 //#include <math.h>
42 long int lround(double x);
43 double fabs(double x);
45 #include "or.h"
46 #include "test.h"
47 #include "torgzip.h"
48 #include "mempool.h"
49 #include "memarea.h"
51 #ifdef USE_DMALLOC
52 #include <dmalloc.h>
53 #include <openssl/crypto.h>
54 #endif
56 /** Set to true if any unit test has failed. Mostly, this is set by the macros
57 * in test.h */
58 int have_failed = 0;
60 /** Temporary directory (set up by setup_directory) under which we store all
61 * our files during testing. */
62 static char temp_dir[256];
64 /** Select and create the temporary directory we'll use to run our unit tests.
65 * Store it in <b>temp_dir</b>. Exit immediately if we can't create it.
66 * idempotent. */
67 static void
68 setup_directory(void)
70 static int is_setup = 0;
71 int r;
72 if (is_setup) return;
74 #ifdef MS_WINDOWS
75 // XXXX
76 tor_snprintf(temp_dir, sizeof(temp_dir),
77 "c:\\windows\\temp\\tor_test_%d", (int)getpid());
78 r = mkdir(temp_dir);
79 #else
80 tor_snprintf(temp_dir, sizeof(temp_dir), "/tmp/tor_test_%d", (int) getpid());
81 r = mkdir(temp_dir, 0700);
82 #endif
83 if (r) {
84 fprintf(stderr, "Can't create directory %s:", temp_dir);
85 perror("");
86 exit(1);
88 is_setup = 1;
91 /** Return a filename relative to our testing temporary directory */
92 const char *
93 get_fname(const char *name)
95 static char buf[1024];
96 setup_directory();
97 tor_snprintf(buf,sizeof(buf),"%s/%s",temp_dir,name);
98 return buf;
101 /** Remove all files stored under the temporary directory, and the directory
102 * itself. */
103 static void
104 remove_directory(void)
106 smartlist_t *elements = tor_listdir(temp_dir);
107 if (elements) {
108 SMARTLIST_FOREACH(elements, const char *, cp,
110 size_t len = strlen(cp)+strlen(temp_dir)+16;
111 char *tmp = tor_malloc(len);
112 tor_snprintf(tmp, len, "%s"PATH_SEPARATOR"%s", temp_dir, cp);
113 unlink(tmp);
114 tor_free(tmp);
116 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
117 smartlist_free(elements);
119 rmdir(temp_dir);
122 /** Define this if unit tests spend too much time generating public keys*/
123 #undef CACHE_GENERATED_KEYS
125 static crypto_pk_env_t *pregen_keys[5] = {NULL, NULL, NULL, NULL, NULL};
126 #define N_PREGEN_KEYS ((int)(sizeof(pregen_keys)/sizeof(pregen_keys[0])))
128 /** Generate and return a new keypair for use in unit tests. If we're using
129 * the key cache optimization, we might reuse keys: we only guarantee that
130 * keys made with distinct values for <b>idx</b> are different. The value of
131 * <b>idx</b> must be at least 0, and less than N_PREGEN_KEYS. */
132 crypto_pk_env_t *
133 pk_generate(int idx)
135 #ifdef CACHE_GENERATED_KEYS
136 tor_assert(idx < N_PREGEN_KEYS);
137 if (! pregen_keys[idx]) {
138 pregen_keys[idx] = crypto_new_pk_env();
139 tor_assert(!crypto_pk_generate_key(pregen_keys[idx]));
141 return crypto_pk_dup_key(pregen_keys[idx]);
142 #else
143 crypto_pk_env_t *result;
144 (void) idx;
145 result = crypto_new_pk_env();
146 tor_assert(!crypto_pk_generate_key(result));
147 return result;
148 #endif
151 /** Free all storage used for the cached key optimization. */
152 static void
153 free_pregenerated_keys(void)
155 unsigned idx;
156 for (idx = 0; idx < N_PREGEN_KEYS; ++idx) {
157 if (pregen_keys[idx]) {
158 crypto_free_pk_env(pregen_keys[idx]);
159 pregen_keys[idx] = NULL;
164 /** Run unit tests for buffers.c */
165 static void
166 test_buffers(void)
168 char str[256];
169 char str2[256];
171 buf_t *buf = NULL, *buf2 = NULL;
172 const char *cp;
174 int j;
175 size_t r;
177 /****
178 * buf_new
179 ****/
180 if (!(buf = buf_new()))
181 test_fail();
183 //test_eq(buf_capacity(buf), 4096);
184 test_eq(buf_datalen(buf), 0);
186 /****
187 * General pointer frobbing
189 for (j=0;j<256;++j) {
190 str[j] = (char)j;
192 write_to_buf(str, 256, buf);
193 write_to_buf(str, 256, buf);
194 test_eq(buf_datalen(buf), 512);
195 fetch_from_buf(str2, 200, buf);
196 test_memeq(str, str2, 200);
197 test_eq(buf_datalen(buf), 312);
198 memset(str2, 0, sizeof(str2));
200 fetch_from_buf(str2, 256, buf);
201 test_memeq(str+200, str2, 56);
202 test_memeq(str, str2+56, 200);
203 test_eq(buf_datalen(buf), 56);
204 memset(str2, 0, sizeof(str2));
205 /* Okay, now we should be 512 bytes into the 4096-byte buffer. If we add
206 * another 3584 bytes, we hit the end. */
207 for (j=0;j<15;++j) {
208 write_to_buf(str, 256, buf);
210 assert_buf_ok(buf);
211 test_eq(buf_datalen(buf), 3896);
212 fetch_from_buf(str2, 56, buf);
213 test_eq(buf_datalen(buf), 3840);
214 test_memeq(str+200, str2, 56);
215 for (j=0;j<15;++j) {
216 memset(str2, 0, sizeof(str2));
217 fetch_from_buf(str2, 256, buf);
218 test_memeq(str, str2, 256);
220 test_eq(buf_datalen(buf), 0);
221 buf_free(buf);
222 buf = NULL;
224 /* Okay, now make sure growing can work. */
225 buf = buf_new_with_capacity(16);
226 //test_eq(buf_capacity(buf), 16);
227 write_to_buf(str+1, 255, buf);
228 //test_eq(buf_capacity(buf), 256);
229 fetch_from_buf(str2, 254, buf);
230 test_memeq(str+1, str2, 254);
231 //test_eq(buf_capacity(buf), 256);
232 assert_buf_ok(buf);
233 write_to_buf(str, 32, buf);
234 //test_eq(buf_capacity(buf), 256);
235 assert_buf_ok(buf);
236 write_to_buf(str, 256, buf);
237 assert_buf_ok(buf);
238 //test_eq(buf_capacity(buf), 512);
239 test_eq(buf_datalen(buf), 33+256);
240 fetch_from_buf(str2, 33, buf);
241 test_eq(*str2, str[255]);
243 test_memeq(str2+1, str, 32);
244 //test_eq(buf_capacity(buf), 512);
245 test_eq(buf_datalen(buf), 256);
246 fetch_from_buf(str2, 256, buf);
247 test_memeq(str, str2, 256);
249 /* now try shrinking: case 1. */
250 buf_free(buf);
251 buf = buf_new_with_capacity(33668);
252 for (j=0;j<67;++j) {
253 write_to_buf(str,255, buf);
255 //test_eq(buf_capacity(buf), 33668);
256 test_eq(buf_datalen(buf), 17085);
257 for (j=0; j < 40; ++j) {
258 fetch_from_buf(str2, 255,buf);
259 test_memeq(str2, str, 255);
262 /* now try shrinking: case 2. */
263 buf_free(buf);
264 buf = buf_new_with_capacity(33668);
265 for (j=0;j<67;++j) {
266 write_to_buf(str,255, buf);
268 for (j=0; j < 20; ++j) {
269 fetch_from_buf(str2, 255,buf);
270 test_memeq(str2, str, 255);
272 for (j=0;j<80;++j) {
273 write_to_buf(str,255, buf);
275 //test_eq(buf_capacity(buf),33668);
276 for (j=0; j < 120; ++j) {
277 fetch_from_buf(str2, 255,buf);
278 test_memeq(str2, str, 255);
281 /* Move from buf to buf. */
282 buf_free(buf);
283 buf = buf_new_with_capacity(4096);
284 buf2 = buf_new_with_capacity(4096);
285 for (j=0;j<100;++j)
286 write_to_buf(str, 255, buf);
287 test_eq(buf_datalen(buf), 25500);
288 for (j=0;j<100;++j) {
289 r = 10;
290 move_buf_to_buf(buf2, buf, &r);
291 test_eq(r, 0);
293 test_eq(buf_datalen(buf), 24500);
294 test_eq(buf_datalen(buf2), 1000);
295 for (j=0;j<3;++j) {
296 fetch_from_buf(str2, 255, buf2);
297 test_memeq(str2, str, 255);
299 r = 8192; /*big move*/
300 move_buf_to_buf(buf2, buf, &r);
301 test_eq(r, 0);
302 r = 30000; /* incomplete move */
303 move_buf_to_buf(buf2, buf, &r);
304 test_eq(r, 13692);
305 for (j=0;j<97;++j) {
306 fetch_from_buf(str2, 255, buf2);
307 test_memeq(str2, str, 255);
309 buf_free(buf);
310 buf_free(buf2);
311 buf = buf2 = NULL;
313 buf = buf_new_with_capacity(5);
314 cp = "Testing. This is a moderately long Testing string.";
315 for (j = 0; cp[j]; j++)
316 write_to_buf(cp+j, 1, buf);
317 test_eq(0, buf_find_string_offset(buf, "Testing", 7));
318 test_eq(1, buf_find_string_offset(buf, "esting", 6));
319 test_eq(1, buf_find_string_offset(buf, "est", 3));
320 test_eq(39, buf_find_string_offset(buf, "ing str", 7));
321 test_eq(35, buf_find_string_offset(buf, "Testing str", 11));
322 test_eq(32, buf_find_string_offset(buf, "ng ", 3));
323 test_eq(43, buf_find_string_offset(buf, "string.", 7));
324 test_eq(-1, buf_find_string_offset(buf, "shrdlu", 6));
325 test_eq(-1, buf_find_string_offset(buf, "Testing thing", 13));
326 test_eq(-1, buf_find_string_offset(buf, "ngx", 3));
327 buf_free(buf);
328 buf = NULL;
330 #if 0
332 int s;
333 int eof;
334 int i;
335 buf_t *buf2;
336 /****
337 * read_to_buf
338 ****/
339 s = open(get_fname("data"), O_WRONLY|O_CREAT|O_TRUNC, 0600);
340 write(s, str, 256);
341 close(s);
343 s = open(get_fname("data"), O_RDONLY, 0);
344 eof = 0;
345 errno = 0; /* XXXX */
346 i = read_to_buf(s, 10, buf, &eof);
347 printf("%s\n", strerror(errno));
348 test_eq(i, 10);
349 test_eq(eof, 0);
350 //test_eq(buf_capacity(buf), 4096);
351 test_eq(buf_datalen(buf), 10);
353 test_memeq(str, (char*)_buf_peek_raw_buffer(buf), 10);
355 /* Test reading 0 bytes. */
356 i = read_to_buf(s, 0, buf, &eof);
357 //test_eq(buf_capacity(buf), 512*1024);
358 test_eq(buf_datalen(buf), 10);
359 test_eq(eof, 0);
360 test_eq(i, 0);
362 /* Now test when buffer is filled exactly. */
363 buf2 = buf_new_with_capacity(6);
364 i = read_to_buf(s, 6, buf2, &eof);
365 //test_eq(buf_capacity(buf2), 6);
366 test_eq(buf_datalen(buf2), 6);
367 test_eq(eof, 0);
368 test_eq(i, 6);
369 test_memeq(str+10, (char*)_buf_peek_raw_buffer(buf2), 6);
370 buf_free(buf2);
371 buf2 = NULL;
373 /* Now test when buffer is filled with more data to read. */
374 buf2 = buf_new_with_capacity(32);
375 i = read_to_buf(s, 128, buf2, &eof);
376 //test_eq(buf_capacity(buf2), 128);
377 test_eq(buf_datalen(buf2), 32);
378 test_eq(eof, 0);
379 test_eq(i, 32);
380 buf_free(buf2);
381 buf2 = NULL;
383 /* Now read to eof. */
384 test_assert(buf_capacity(buf) > 256);
385 i = read_to_buf(s, 1024, buf, &eof);
386 test_eq(i, (256-32-10-6));
387 test_eq(buf_capacity(buf), MAX_BUF_SIZE);
388 test_eq(buf_datalen(buf), 256-6-32);
389 test_memeq(str, (char*)_buf_peek_raw_buffer(buf), 10); /* XXX Check rest. */
390 test_eq(eof, 0);
392 i = read_to_buf(s, 1024, buf, &eof);
393 test_eq(i, 0);
394 test_eq(buf_capacity(buf), MAX_BUF_SIZE);
395 test_eq(buf_datalen(buf), 256-6-32);
396 test_eq(eof, 1);
398 #endif
400 done:
401 if (buf)
402 buf_free(buf);
403 if (buf2)
404 buf_free(buf2);
407 /** Run unit tests for the onion handshake code. */
408 static void
409 test_onion_handshake(void)
411 /* client-side */
412 crypto_dh_env_t *c_dh = NULL;
413 char c_buf[ONIONSKIN_CHALLENGE_LEN];
414 char c_keys[40];
416 /* server-side */
417 char s_buf[ONIONSKIN_REPLY_LEN];
418 char s_keys[40];
420 /* shared */
421 crypto_pk_env_t *pk = NULL;
423 pk = pk_generate(0);
425 /* client handshake 1. */
426 memset(c_buf, 0, ONIONSKIN_CHALLENGE_LEN);
427 test_assert(! onion_skin_create(pk, &c_dh, c_buf));
429 /* server handshake */
430 memset(s_buf, 0, ONIONSKIN_REPLY_LEN);
431 memset(s_keys, 0, 40);
432 test_assert(! onion_skin_server_handshake(c_buf, pk, NULL,
433 s_buf, s_keys, 40));
435 /* client handshake 2 */
436 memset(c_keys, 0, 40);
437 test_assert(! onion_skin_client_handshake(c_dh, s_buf, c_keys, 40));
439 if (memcmp(c_keys, s_keys, 40)) {
440 puts("Aiiiie");
441 exit(1);
443 test_memeq(c_keys, s_keys, 40);
444 memset(s_buf, 0, 40);
445 test_memneq(c_keys, s_buf, 40);
447 done:
448 if (c_dh)
449 crypto_dh_free(c_dh);
450 if (pk)
451 crypto_free_pk_env(pk);
454 static void
455 test_circuit_timeout(void)
457 /* Plan:
458 * 1. Generate 1000 samples
459 * 2. Estimate parameters
460 * 3. If difference, repeat
461 * 4. Save state
462 * 5. load state
463 * 6. Estimate parameters
464 * 7. compare differences
466 circuit_build_times_t initial;
467 circuit_build_times_t estimate;
468 circuit_build_times_t final;
469 double timeout1, timeout2;
470 or_state_t state;
471 char *msg;
472 int i, runs;
473 circuit_build_times_init(&initial);
474 circuit_build_times_init(&estimate);
475 circuit_build_times_init(&final);
477 memset(&state, 0, sizeof(or_state_t));
479 circuitbuild_running_unit_tests();
480 #define timeout0 (build_time_t)(30*1000.0)
481 initial.Xm = 750;
482 circuit_build_times_initial_alpha(&initial, BUILDTIMEOUT_QUANTILE_CUTOFF,
483 timeout0);
484 do {
485 int n = 0;
486 for (i=0; i < MIN_CIRCUITS_TO_OBSERVE; i++) {
487 if (circuit_build_times_add_time(&estimate,
488 circuit_build_times_generate_sample(&initial, 0, 1)) == 0) {
489 n++;
492 circuit_build_times_update_alpha(&estimate);
493 timeout1 = circuit_build_times_calculate_timeout(&estimate,
494 BUILDTIMEOUT_QUANTILE_CUTOFF);
495 circuit_build_times_set_timeout(&estimate);
496 log_warn(LD_CIRC, "Timeout is %lf, Xm is %d", timeout1, estimate.Xm);
497 /* XXX: 5% distribution error may not be the right metric */
498 } while (fabs(circuit_build_times_cdf(&initial, timeout0) -
499 circuit_build_times_cdf(&initial, timeout1)) > 0.05
500 /* 5% error */
501 && estimate.total_build_times < NCIRCUITS_TO_OBSERVE);
503 test_assert(estimate.total_build_times < NCIRCUITS_TO_OBSERVE);
505 circuit_build_times_update_state(&estimate, &state);
506 test_assert(circuit_build_times_parse_state(&final, &state, &msg) == 0);
508 circuit_build_times_update_alpha(&final);
509 timeout2 = circuit_build_times_calculate_timeout(&final,
510 BUILDTIMEOUT_QUANTILE_CUTOFF);
512 circuit_build_times_set_timeout(&final);
513 log_warn(LD_CIRC, "Timeout is %lf, Xm is %d", timeout2, final.Xm);
515 test_assert(fabs(circuit_build_times_cdf(&initial, timeout0) -
516 circuit_build_times_cdf(&initial, timeout2)) < 0.05);
518 for (runs = 0; runs < 50; runs++) {
519 int build_times_idx = 0;
520 int total_build_times = 0;
522 final.timeout_ms = BUILD_TIMEOUT_INITIAL_VALUE;
523 estimate.timeout_ms = BUILD_TIMEOUT_INITIAL_VALUE;
525 for (i = 0; i < RECENT_CIRCUITS*2; i++) {
526 circuit_build_times_network_circ_success(&estimate);
527 circuit_build_times_add_time(&estimate,
528 circuit_build_times_generate_sample(&estimate, 0,
529 BUILDTIMEOUT_QUANTILE_CUTOFF));
530 estimate.have_computed_timeout = 1;
531 circuit_build_times_network_circ_success(&estimate);
532 circuit_build_times_add_time(&final,
533 circuit_build_times_generate_sample(&final, 0,
534 BUILDTIMEOUT_QUANTILE_CUTOFF));
535 final.have_computed_timeout = 1;
538 test_assert(!circuit_build_times_network_check_changed(&estimate));
539 test_assert(!circuit_build_times_network_check_changed(&final));
541 /* Reset liveness to be non-live */
542 final.liveness.network_last_live = 0;
543 estimate.liveness.network_last_live = 0;
545 build_times_idx = estimate.build_times_idx;
546 total_build_times = estimate.total_build_times;
547 for (i = 0; i < NETWORK_NONLIVE_TIMEOUT_COUNT; i++) {
548 test_assert(circuit_build_times_network_check_live(&estimate));
549 test_assert(circuit_build_times_network_check_live(&final));
551 if (circuit_build_times_add_timeout(&estimate, 0,
552 (time_t)(approx_time()-estimate.timeout_ms/1000.0-1)))
553 estimate.have_computed_timeout = 1;
554 if (circuit_build_times_add_timeout(&final, 0,
555 (time_t)(approx_time()-final.timeout_ms/1000.0-1)))
556 final.have_computed_timeout = 1;
559 test_assert(!circuit_build_times_network_check_live(&estimate));
560 test_assert(!circuit_build_times_network_check_live(&final));
562 for ( ; i < NETWORK_NONLIVE_DISCARD_COUNT; i++) {
563 if (circuit_build_times_add_timeout(&estimate, 0,
564 (time_t)(approx_time()-estimate.timeout_ms/1000.0-1)))
565 estimate.have_computed_timeout = 1;
567 if (i < NETWORK_NONLIVE_DISCARD_COUNT-1) {
568 if (circuit_build_times_add_timeout(&final, 0,
569 (time_t)(approx_time()-final.timeout_ms/1000.0-1)))
570 final.have_computed_timeout = 1;
574 test_assert(!circuit_build_times_network_check_live(&estimate));
575 test_assert(!circuit_build_times_network_check_live(&final));
577 log_info(LD_CIRC, "idx: %d %d, tot: %d %d",
578 build_times_idx, estimate.build_times_idx,
579 total_build_times, estimate.total_build_times);
581 /* Check rollback index. Should match top of loop. */
582 test_assert(build_times_idx == estimate.build_times_idx);
583 test_assert(total_build_times == estimate.total_build_times);
585 /* Now simulate that the network has become live and we need
586 * a change */
587 circuit_build_times_network_is_live(&estimate);
588 circuit_build_times_network_is_live(&final);
590 for (i = 0; i < MAX_RECENT_TIMEOUT_COUNT; i++) {
591 if (circuit_build_times_add_timeout(&estimate, 1, approx_time()-1))
592 estimate.have_computed_timeout = 1;
594 if (i < MAX_RECENT_TIMEOUT_COUNT-1) {
595 if (circuit_build_times_add_timeout(&final, 1, approx_time()-1))
596 final.have_computed_timeout = 1;
600 test_assert(estimate.liveness.after_firsthop_idx == 0);
601 test_assert(final.liveness.after_firsthop_idx ==
602 MAX_RECENT_TIMEOUT_COUNT-1);
604 test_assert(circuit_build_times_network_check_live(&estimate));
605 test_assert(circuit_build_times_network_check_live(&final));
607 if (circuit_build_times_add_timeout(&final, 1, approx_time()-1))
608 final.have_computed_timeout = 1;
612 done:
613 return;
616 /** Helper: Parse the exit policy string in <b>policy_str</b>, and make sure
617 * that policies_summarize() produces the string <b>expected_summary</b> from
618 * it. */
619 static void
620 test_policy_summary_helper(const char *policy_str,
621 const char *expected_summary)
623 config_line_t line;
624 smartlist_t *policy = smartlist_create();
625 char *summary = NULL;
626 int r;
628 line.key = (char*)"foo";
629 line.value = (char *)policy_str;
630 line.next = NULL;
632 r = policies_parse_exit_policy(&line, &policy, 0, NULL, 1);
633 test_eq(r, 0);
634 summary = policy_summarize(policy);
636 test_assert(summary != NULL);
637 test_streq(summary, expected_summary);
639 done:
640 tor_free(summary);
641 if (policy)
642 addr_policy_list_free(policy);
645 /** Run unit tests for generating summary lines of exit policies */
646 static void
647 test_policies(void)
649 int i;
650 smartlist_t *policy = NULL, *policy2 = NULL;
651 addr_policy_t *p;
652 tor_addr_t tar;
653 config_line_t line;
654 smartlist_t *sm = NULL;
655 char *policy_str = NULL;
657 policy = smartlist_create();
659 p = router_parse_addr_policy_item_from_string("reject 192.168.0.0/16:*",-1);
660 test_assert(p != NULL);
661 test_eq(ADDR_POLICY_REJECT, p->policy_type);
662 tor_addr_from_ipv4h(&tar, 0xc0a80000u);
663 test_eq(0, tor_addr_compare(&p->addr, &tar, CMP_EXACT));
664 test_eq(16, p->maskbits);
665 test_eq(1, p->prt_min);
666 test_eq(65535, p->prt_max);
668 smartlist_add(policy, p);
670 test_assert(ADDR_POLICY_ACCEPTED ==
671 compare_addr_to_addr_policy(0x01020304u, 2, policy));
672 test_assert(ADDR_POLICY_PROBABLY_ACCEPTED ==
673 compare_addr_to_addr_policy(0, 2, policy));
674 test_assert(ADDR_POLICY_REJECTED ==
675 compare_addr_to_addr_policy(0xc0a80102, 2, policy));
677 policy2 = NULL;
678 test_assert(0 == policies_parse_exit_policy(NULL, &policy2, 1, NULL, 1));
679 test_assert(policy2);
681 test_assert(!exit_policy_is_general_exit(policy));
682 test_assert(exit_policy_is_general_exit(policy2));
683 test_assert(!exit_policy_is_general_exit(NULL));
685 test_assert(cmp_addr_policies(policy, policy2));
686 test_assert(cmp_addr_policies(policy, NULL));
687 test_assert(!cmp_addr_policies(policy2, policy2));
688 test_assert(!cmp_addr_policies(NULL, NULL));
690 test_assert(!policy_is_reject_star(policy2));
691 test_assert(policy_is_reject_star(policy));
692 test_assert(policy_is_reject_star(NULL));
694 addr_policy_list_free(policy);
695 policy = NULL;
697 /* make sure compacting logic works. */
698 policy = NULL;
699 line.key = (char*)"foo";
700 line.value = (char*)"accept *:80,reject private:*,reject *:*";
701 line.next = NULL;
702 test_assert(0 == policies_parse_exit_policy(&line, &policy, 0, NULL, 1));
703 test_assert(policy);
704 //test_streq(policy->string, "accept *:80");
705 //test_streq(policy->next->string, "reject *:*");
706 test_eq(smartlist_len(policy), 2);
708 /* test policy summaries */
709 /* check if we properly ignore private IP addresses */
710 test_policy_summary_helper("reject 192.168.0.0/16:*,"
711 "reject 0.0.0.0/8:*,"
712 "reject 10.0.0.0/8:*,"
713 "accept *:10-30,"
714 "accept *:90,"
715 "reject *:*",
716 "accept 10-30,90");
717 /* check all accept policies, and proper counting of rejects */
718 test_policy_summary_helper("reject 11.0.0.0/9:80,"
719 "reject 12.0.0.0/9:80,"
720 "reject 13.0.0.0/9:80,"
721 "reject 14.0.0.0/9:80,"
722 "accept *:*", "accept 1-65535");
723 test_policy_summary_helper("reject 11.0.0.0/9:80,"
724 "reject 12.0.0.0/9:80,"
725 "reject 13.0.0.0/9:80,"
726 "reject 14.0.0.0/9:80,"
727 "reject 15.0.0.0:81,"
728 "accept *:*", "accept 1-65535");
729 test_policy_summary_helper("reject 11.0.0.0/9:80,"
730 "reject 12.0.0.0/9:80,"
731 "reject 13.0.0.0/9:80,"
732 "reject 14.0.0.0/9:80,"
733 "reject 15.0.0.0:80,"
734 "accept *:*",
735 "reject 80");
736 /* no exits */
737 test_policy_summary_helper("accept 11.0.0.0/9:80,"
738 "reject *:*",
739 "reject 1-65535");
740 /* port merging */
741 test_policy_summary_helper("accept *:80,"
742 "accept *:81,"
743 "accept *:100-110,"
744 "accept *:111,"
745 "reject *:*",
746 "accept 80-81,100-111");
747 /* border ports */
748 test_policy_summary_helper("accept *:1,"
749 "accept *:3,"
750 "accept *:65535,"
751 "reject *:*",
752 "accept 1,3,65535");
753 /* holes */
754 test_policy_summary_helper("accept *:1,"
755 "accept *:3,"
756 "accept *:5,"
757 "accept *:7,"
758 "reject *:*",
759 "accept 1,3,5,7");
760 test_policy_summary_helper("reject *:1,"
761 "reject *:3,"
762 "reject *:5,"
763 "reject *:7,"
764 "accept *:*",
765 "reject 1,3,5,7");
767 /* truncation ports */
768 sm = smartlist_create();
769 for (i=1; i<2000; i+=2) {
770 char buf[POLICY_BUF_LEN];
771 tor_snprintf(buf, sizeof(buf), "reject *:%d", i);
772 smartlist_add(sm, tor_strdup(buf));
774 smartlist_add(sm, tor_strdup("accept *:*"));
775 policy_str = smartlist_join_strings(sm, ",", 0, NULL);
776 test_policy_summary_helper( policy_str,
777 "accept 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,"
778 "46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,"
779 "92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,"
780 "130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,"
781 "166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198,200,"
782 "202,204,206,208,210,212,214,216,218,220,222,224,226,228,230,232,234,236,"
783 "238,240,242,244,246,248,250,252,254,256,258,260,262,264,266,268,270,272,"
784 "274,276,278,280,282,284,286,288,290,292,294,296,298,300,302,304,306,308,"
785 "310,312,314,316,318,320,322,324,326,328,330,332,334,336,338,340,342,344,"
786 "346,348,350,352,354,356,358,360,362,364,366,368,370,372,374,376,378,380,"
787 "382,384,386,388,390,392,394,396,398,400,402,404,406,408,410,412,414,416,"
788 "418,420,422,424,426,428,430,432,434,436,438,440,442,444,446,448,450,452,"
789 "454,456,458,460,462,464,466,468,470,472,474,476,478,480,482,484,486,488,"
790 "490,492,494,496,498,500,502,504,506,508,510,512,514,516,518,520,522");
792 done:
793 if (policy)
794 addr_policy_list_free(policy);
795 if (policy2)
796 addr_policy_list_free(policy2);
797 tor_free(policy_str);
798 if (sm) {
799 SMARTLIST_FOREACH(sm, char *, s, tor_free(s));
800 smartlist_free(sm);
804 /** Run AES performance benchmarks. */
805 static void
806 bench_aes(void)
808 int len, i;
809 char *b1, *b2;
810 crypto_cipher_env_t *c;
811 struct timeval start, end;
812 const int iters = 100000;
813 uint64_t nsec;
814 c = crypto_new_cipher_env();
815 crypto_cipher_generate_key(c);
816 crypto_cipher_encrypt_init_cipher(c);
817 for (len = 1; len <= 8192; len *= 2) {
818 b1 = tor_malloc_zero(len);
819 b2 = tor_malloc_zero(len);
820 tor_gettimeofday(&start);
821 for (i = 0; i < iters; ++i) {
822 crypto_cipher_encrypt(c, b1, b2, len);
824 tor_gettimeofday(&end);
825 tor_free(b1);
826 tor_free(b2);
827 nsec = (uint64_t) tv_udiff(&start,&end);
828 nsec *= 1000;
829 nsec /= (iters*len);
830 printf("%d bytes: "U64_FORMAT" nsec per byte\n", len,
831 U64_PRINTF_ARG(nsec));
833 crypto_free_cipher_env(c);
836 /** Run digestmap_t performance benchmarks. */
837 static void
838 bench_dmap(void)
840 smartlist_t *sl = smartlist_create();
841 smartlist_t *sl2 = smartlist_create();
842 struct timeval start, end, pt2, pt3, pt4;
843 const int iters = 10000;
844 const int elts = 4000;
845 const int fpostests = 1000000;
846 char d[20];
847 int i,n=0, fp = 0;
848 digestmap_t *dm = digestmap_new();
849 digestset_t *ds = digestset_new(elts);
851 for (i = 0; i < elts; ++i) {
852 crypto_rand(d, 20);
853 smartlist_add(sl, tor_memdup(d, 20));
855 for (i = 0; i < elts; ++i) {
856 crypto_rand(d, 20);
857 smartlist_add(sl2, tor_memdup(d, 20));
859 printf("nbits=%d\n", ds->mask+1);
861 tor_gettimeofday(&start);
862 for (i = 0; i < iters; ++i) {
863 SMARTLIST_FOREACH(sl, const char *, cp, digestmap_set(dm, cp, (void*)1));
865 tor_gettimeofday(&pt2);
866 for (i = 0; i < iters; ++i) {
867 SMARTLIST_FOREACH(sl, const char *, cp, digestmap_get(dm, cp));
868 SMARTLIST_FOREACH(sl2, const char *, cp, digestmap_get(dm, cp));
870 tor_gettimeofday(&pt3);
871 for (i = 0; i < iters; ++i) {
872 SMARTLIST_FOREACH(sl, const char *, cp, digestset_add(ds, cp));
874 tor_gettimeofday(&pt4);
875 for (i = 0; i < iters; ++i) {
876 SMARTLIST_FOREACH(sl, const char *, cp, n += digestset_isin(ds, cp));
877 SMARTLIST_FOREACH(sl2, const char *, cp, n += digestset_isin(ds, cp));
879 tor_gettimeofday(&end);
881 for (i = 0; i < fpostests; ++i) {
882 crypto_rand(d, 20);
883 if (digestset_isin(ds, d)) ++fp;
886 printf("%ld\n",(unsigned long)tv_udiff(&start, &pt2));
887 printf("%ld\n",(unsigned long)tv_udiff(&pt2, &pt3));
888 printf("%ld\n",(unsigned long)tv_udiff(&pt3, &pt4));
889 printf("%ld\n",(unsigned long)tv_udiff(&pt4, &end));
890 printf("-- %d\n", n);
891 printf("++ %f\n", fp/(double)fpostests);
892 digestmap_free(dm, NULL);
893 digestset_free(ds);
894 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
895 SMARTLIST_FOREACH(sl2, char *, cp, tor_free(cp));
896 smartlist_free(sl);
897 smartlist_free(sl2);
900 /** Test encoding and parsing of rendezvous service descriptors. */
901 static void
902 test_rend_fns(void)
904 rend_service_descriptor_t *generated = NULL, *parsed = NULL;
905 char service_id[DIGEST_LEN];
906 char service_id_base32[REND_SERVICE_ID_LEN_BASE32+1];
907 const char *next_desc;
908 smartlist_t *descs = smartlist_create();
909 char computed_desc_id[DIGEST_LEN];
910 char parsed_desc_id[DIGEST_LEN];
911 crypto_pk_env_t *pk1 = NULL, *pk2 = NULL;
912 time_t now;
913 char *intro_points_encrypted = NULL;
914 size_t intro_points_size;
915 size_t encoded_size;
916 int i;
917 char address1[] = "fooaddress.onion";
918 char address2[] = "aaaaaaaaaaaaaaaa.onion";
919 char address3[] = "fooaddress.exit";
920 char address4[] = "www.torproject.org";
922 test_assert(BAD_HOSTNAME == parse_extended_hostname(address1, 1));
923 test_assert(ONION_HOSTNAME == parse_extended_hostname(address2, 1));
924 test_assert(EXIT_HOSTNAME == parse_extended_hostname(address3, 1));
925 test_assert(NORMAL_HOSTNAME == parse_extended_hostname(address4, 1));
927 pk1 = pk_generate(0);
928 pk2 = pk_generate(1);
929 generated = tor_malloc_zero(sizeof(rend_service_descriptor_t));
930 generated->pk = crypto_pk_dup_key(pk1);
931 crypto_pk_get_digest(generated->pk, service_id);
932 base32_encode(service_id_base32, REND_SERVICE_ID_LEN_BASE32+1,
933 service_id, REND_SERVICE_ID_LEN);
934 now = time(NULL);
935 generated->timestamp = now;
936 generated->version = 2;
937 generated->protocols = 42;
938 generated->intro_nodes = smartlist_create();
940 for (i = 0; i < 3; i++) {
941 rend_intro_point_t *intro = tor_malloc_zero(sizeof(rend_intro_point_t));
942 crypto_pk_env_t *okey = pk_generate(2 + i);
943 intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
944 intro->extend_info->onion_key = okey;
945 crypto_pk_get_digest(intro->extend_info->onion_key,
946 intro->extend_info->identity_digest);
947 //crypto_rand(info->identity_digest, DIGEST_LEN); /* Would this work? */
948 intro->extend_info->nickname[0] = '$';
949 base16_encode(intro->extend_info->nickname + 1,
950 sizeof(intro->extend_info->nickname) - 1,
951 intro->extend_info->identity_digest, DIGEST_LEN);
952 /* Does not cover all IP addresses. */
953 tor_addr_from_ipv4h(&intro->extend_info->addr, crypto_rand_int(65536));
954 intro->extend_info->port = crypto_rand_int(65536);
955 intro->intro_key = crypto_pk_dup_key(pk2);
956 smartlist_add(generated->intro_nodes, intro);
958 test_assert(rend_encode_v2_descriptors(descs, generated, now, 0,
959 REND_NO_AUTH, NULL, NULL) > 0);
960 test_assert(rend_compute_v2_desc_id(computed_desc_id, service_id_base32,
961 NULL, now, 0) == 0);
962 test_memeq(((rend_encoded_v2_service_descriptor_t *)
963 smartlist_get(descs, 0))->desc_id, computed_desc_id, DIGEST_LEN);
964 test_assert(rend_parse_v2_service_descriptor(&parsed, parsed_desc_id,
965 &intro_points_encrypted,
966 &intro_points_size,
967 &encoded_size,
968 &next_desc,
969 ((rend_encoded_v2_service_descriptor_t *)
970 smartlist_get(descs, 0))->desc_str) == 0);
971 test_assert(parsed);
972 test_memeq(((rend_encoded_v2_service_descriptor_t *)
973 smartlist_get(descs, 0))->desc_id, parsed_desc_id, DIGEST_LEN);
974 test_eq(rend_parse_introduction_points(parsed, intro_points_encrypted,
975 intro_points_size), 3);
976 test_assert(!crypto_pk_cmp_keys(generated->pk, parsed->pk));
977 test_eq(parsed->timestamp, now);
978 test_eq(parsed->version, 2);
979 test_eq(parsed->protocols, 42);
980 test_eq(smartlist_len(parsed->intro_nodes), 3);
981 for (i = 0; i < smartlist_len(parsed->intro_nodes); i++) {
982 rend_intro_point_t *par_intro = smartlist_get(parsed->intro_nodes, i),
983 *gen_intro = smartlist_get(generated->intro_nodes, i);
984 extend_info_t *par_info = par_intro->extend_info;
985 extend_info_t *gen_info = gen_intro->extend_info;
986 test_assert(!crypto_pk_cmp_keys(gen_info->onion_key, par_info->onion_key));
987 test_memeq(gen_info->identity_digest, par_info->identity_digest,
988 DIGEST_LEN);
989 test_streq(gen_info->nickname, par_info->nickname);
990 test_assert(tor_addr_eq(&gen_info->addr, &par_info->addr));
991 test_eq(gen_info->port, par_info->port);
994 rend_service_descriptor_free(parsed);
995 rend_service_descriptor_free(generated);
996 parsed = generated = NULL;
998 done:
999 if (descs) {
1000 for (i = 0; i < smartlist_len(descs); i++)
1001 rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
1002 smartlist_free(descs);
1004 if (parsed)
1005 rend_service_descriptor_free(parsed);
1006 if (generated)
1007 rend_service_descriptor_free(generated);
1008 if (pk1)
1009 crypto_free_pk_env(pk1);
1010 if (pk2)
1011 crypto_free_pk_env(pk2);
1012 tor_free(intro_points_encrypted);
1015 /** Run unit tests for GeoIP code. */
1016 static void
1017 test_geoip(void)
1019 int i, j;
1020 time_t now = time(NULL);
1021 char *s = NULL;
1023 /* Populate the DB a bit. Add these in order, since we can't do the final
1024 * 'sort' step. These aren't very good IP addresses, but they're perfectly
1025 * fine uint32_t values. */
1026 test_eq(0, geoip_parse_entry("10,50,AB"));
1027 test_eq(0, geoip_parse_entry("52,90,XY"));
1028 test_eq(0, geoip_parse_entry("95,100,AB"));
1029 test_eq(0, geoip_parse_entry("\"105\",\"140\",\"ZZ\""));
1030 test_eq(0, geoip_parse_entry("\"150\",\"190\",\"XY\""));
1031 test_eq(0, geoip_parse_entry("\"200\",\"250\",\"AB\""));
1033 /* We should have 3 countries: ab, xy, zz. */
1034 test_eq(3, geoip_get_n_countries());
1035 /* Make sure that country ID actually works. */
1036 #define NAMEFOR(x) geoip_get_country_name(geoip_get_country_by_ip(x))
1037 test_streq("ab", NAMEFOR(32));
1038 test_streq("??", NAMEFOR(5));
1039 test_streq("??", NAMEFOR(51));
1040 test_streq("xy", NAMEFOR(150));
1041 test_streq("xy", NAMEFOR(190));
1042 test_streq("??", NAMEFOR(2000));
1043 #undef NAMEFOR
1045 get_options()->BridgeRelay = 1;
1046 get_options()->BridgeRecordUsageByCountry = 1;
1047 /* Put 9 observations in AB... */
1048 for (i=32; i < 40; ++i)
1049 geoip_note_client_seen(GEOIP_CLIENT_CONNECT, i, now-7200);
1050 geoip_note_client_seen(GEOIP_CLIENT_CONNECT, 225, now-7200);
1051 /* and 3 observations in XY, several times. */
1052 for (j=0; j < 10; ++j)
1053 for (i=52; i < 55; ++i)
1054 geoip_note_client_seen(GEOIP_CLIENT_CONNECT, i, now-3600);
1055 /* and 17 observations in ZZ... */
1056 for (i=110; i < 127; ++i)
1057 geoip_note_client_seen(GEOIP_CLIENT_CONNECT, i, now);
1058 s = geoip_get_client_history_bridge(now+5*24*60*60,
1059 GEOIP_CLIENT_CONNECT);
1060 test_assert(s);
1061 test_streq("zz=24,ab=16,xy=8", s);
1062 tor_free(s);
1064 /* Now clear out all the AB observations. */
1065 geoip_remove_old_clients(now-6000);
1066 s = geoip_get_client_history_bridge(now+5*24*60*60,
1067 GEOIP_CLIENT_CONNECT);
1068 test_assert(s);
1069 test_streq("zz=24,xy=8", s);
1071 done:
1072 tor_free(s);
1075 static void *
1076 legacy_test_setup(const struct testcase_t *testcase)
1078 return testcase->setup_data;
1081 void
1082 legacy_test_helper(void *data)
1084 void (*fn)(void) = data;
1085 fn();
1088 static int
1089 legacy_test_cleanup(const struct testcase_t *testcase, void *ptr)
1091 (void)ptr;
1092 (void)testcase;
1093 return 1;
1096 const struct testcase_setup_t legacy_setup = {
1097 legacy_test_setup, legacy_test_cleanup
1100 #define ENT(name) \
1101 { #name, legacy_test_helper, 0, &legacy_setup, test_ ## name }
1102 #define SUBENT(group, name) \
1103 { #group "_" #name, legacy_test_helper, 0, &legacy_setup, \
1104 test_ ## group ## _ ## name }
1105 #define DISABLED(name) \
1106 { #name, legacy_test_helper, TT_SKIP, &legacy_setup, name }
1108 static struct testcase_t test_array[] = {
1109 ENT(buffers),
1110 ENT(onion_handshake),
1111 ENT(circuit_timeout),
1112 ENT(policies),
1113 ENT(rend_fns),
1114 ENT(geoip),
1116 DISABLED(bench_aes),
1117 DISABLED(bench_dmap),
1118 END_OF_TESTCASES
1121 extern struct testcase_t addr_tests[];
1122 extern struct testcase_t crypto_tests[];
1123 extern struct testcase_t container_tests[];
1124 extern struct testcase_t util_tests[];
1125 extern struct testcase_t dir_tests[];
1127 static struct testgroup_t testgroups[] = {
1128 { "", test_array },
1129 { "addr/", addr_tests },
1130 { "crypto/", crypto_tests },
1131 { "container/", container_tests },
1132 { "util/", util_tests },
1133 { "dir/", dir_tests },
1134 END_OF_GROUPS
1137 /** Main entry point for unit test code: parse the command line, and run
1138 * some unit tests. */
1140 main(int c, const char **v)
1142 or_options_t *options;
1143 char *errmsg = NULL;
1144 int i, i_out;
1145 int loglevel = LOG_ERR;
1147 #ifdef USE_DMALLOC
1149 int r = CRYPTO_set_mem_ex_functions(_tor_malloc, _tor_realloc, _tor_free);
1150 tor_assert(r);
1152 #endif
1154 update_approx_time(time(NULL));
1155 options = options_new();
1156 tor_threads_init();
1157 init_logging();
1159 for (i_out = i = 1; i < c; ++i) {
1160 if (!strcmp(v[i], "--warn")) {
1161 loglevel = LOG_WARN;
1162 } else if (!strcmp(v[i], "--notice")) {
1163 loglevel = LOG_NOTICE;
1164 } else if (!strcmp(v[i], "--info")) {
1165 loglevel = LOG_INFO;
1166 } else if (!strcmp(v[i], "--debug")) {
1167 loglevel = LOG_DEBUG;
1168 } else {
1169 v[i_out++] = v[i];
1172 c = i_out;
1175 log_severity_list_t s;
1176 memset(&s, 0, sizeof(s));
1177 set_log_severity_config(loglevel, LOG_ERR, &s);
1178 add_stream_log(&s, "", fileno(stdout));
1181 options->command = CMD_RUN_UNITTESTS;
1182 crypto_global_init(0, NULL, NULL);
1183 rep_hist_init();
1184 network_init();
1185 setup_directory();
1186 options_init(options);
1187 options->DataDirectory = tor_strdup(temp_dir);
1188 options->EntryStatistics = 1;
1189 if (set_options(options, &errmsg) < 0) {
1190 printf("Failed to set initial options: %s\n", errmsg);
1191 tor_free(errmsg);
1192 return 1;
1195 crypto_seed_rng(1);
1197 atexit(remove_directory);
1199 have_failed = (tinytest_main(c, v, testgroups) != 0);
1201 free_pregenerated_keys();
1202 #ifdef USE_DMALLOC
1203 tor_free_all(0);
1204 dmalloc_log_unfreed();
1205 #endif
1207 if (have_failed)
1208 return 1;
1209 else
1210 return 0;