Merge branch 'log_domains' into maint-0.2.2
[tor/rransom.git] / src / test / test.c
blobf5b6a222a745e43a837385f7844b5181d6900551
1 /* Copyright (c) 2001-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2011, 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 "buffers.h"
47 #include "circuitbuild.h"
48 #include "config.h"
49 #include "connection_edge.h"
50 #include "geoip.h"
51 #include "rendcommon.h"
52 #include "test.h"
53 #include "torgzip.h"
54 #include "mempool.h"
55 #include "memarea.h"
56 #include "onion.h"
57 #include "policies.h"
58 #include "rephist.h"
59 #include "routerparse.h"
61 #ifdef USE_DMALLOC
62 #include <dmalloc.h>
63 #include <openssl/crypto.h>
64 #include "main.h"
65 #endif
67 /** Set to true if any unit test has failed. Mostly, this is set by the macros
68 * in test.h */
69 int have_failed = 0;
71 /** Temporary directory (set up by setup_directory) under which we store all
72 * our files during testing. */
73 static char temp_dir[256];
74 static pid_t temp_dir_setup_in_pid = 0;
76 /** Select and create the temporary directory we'll use to run our unit tests.
77 * Store it in <b>temp_dir</b>. Exit immediately if we can't create it.
78 * idempotent. */
79 static void
80 setup_directory(void)
82 static int is_setup = 0;
83 int r;
84 if (is_setup) return;
86 #ifdef MS_WINDOWS
87 // XXXX
88 tor_snprintf(temp_dir, sizeof(temp_dir),
89 "c:\\windows\\temp\\tor_test_%d", (int)getpid());
90 r = mkdir(temp_dir);
91 #else
92 tor_snprintf(temp_dir, sizeof(temp_dir), "/tmp/tor_test_%d", (int) getpid());
93 r = mkdir(temp_dir, 0700);
94 #endif
95 if (r) {
96 fprintf(stderr, "Can't create directory %s:", temp_dir);
97 perror("");
98 exit(1);
100 is_setup = 1;
101 temp_dir_setup_in_pid = getpid();
104 /** Return a filename relative to our testing temporary directory */
105 const char *
106 get_fname(const char *name)
108 static char buf[1024];
109 setup_directory();
110 if (!name)
111 return temp_dir;
112 tor_snprintf(buf,sizeof(buf),"%s/%s",temp_dir,name);
113 return buf;
116 /** Remove all files stored under the temporary directory, and the directory
117 * itself. Called by atexit(). */
118 static void
119 remove_directory(void)
121 smartlist_t *elements;
122 if (getpid() != temp_dir_setup_in_pid) {
123 /* Only clean out the tempdir when the main process is exiting. */
124 return;
126 elements = tor_listdir(temp_dir);
127 if (elements) {
128 SMARTLIST_FOREACH(elements, const char *, cp,
130 size_t len = strlen(cp)+strlen(temp_dir)+16;
131 char *tmp = tor_malloc(len);
132 tor_snprintf(tmp, len, "%s"PATH_SEPARATOR"%s", temp_dir, cp);
133 unlink(tmp);
134 tor_free(tmp);
136 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
137 smartlist_free(elements);
139 rmdir(temp_dir);
142 /** Define this if unit tests spend too much time generating public keys*/
143 #undef CACHE_GENERATED_KEYS
145 static crypto_pk_env_t *pregen_keys[5] = {NULL, NULL, NULL, NULL, NULL};
146 #define N_PREGEN_KEYS ((int)(sizeof(pregen_keys)/sizeof(pregen_keys[0])))
148 /** Generate and return a new keypair for use in unit tests. If we're using
149 * the key cache optimization, we might reuse keys: we only guarantee that
150 * keys made with distinct values for <b>idx</b> are different. The value of
151 * <b>idx</b> must be at least 0, and less than N_PREGEN_KEYS. */
152 crypto_pk_env_t *
153 pk_generate(int idx)
155 #ifdef CACHE_GENERATED_KEYS
156 tor_assert(idx < N_PREGEN_KEYS);
157 if (! pregen_keys[idx]) {
158 pregen_keys[idx] = crypto_new_pk_env();
159 tor_assert(!crypto_pk_generate_key(pregen_keys[idx]));
161 return crypto_pk_dup_key(pregen_keys[idx]);
162 #else
163 crypto_pk_env_t *result;
164 (void) idx;
165 result = crypto_new_pk_env();
166 tor_assert(!crypto_pk_generate_key(result));
167 return result;
168 #endif
171 /** Free all storage used for the cached key optimization. */
172 static void
173 free_pregenerated_keys(void)
175 unsigned idx;
176 for (idx = 0; idx < N_PREGEN_KEYS; ++idx) {
177 if (pregen_keys[idx]) {
178 crypto_free_pk_env(pregen_keys[idx]);
179 pregen_keys[idx] = NULL;
184 /** Run unit tests for buffers.c */
185 static void
186 test_buffers(void)
188 char str[256];
189 char str2[256];
191 buf_t *buf = NULL, *buf2 = NULL;
192 const char *cp;
194 int j;
195 size_t r;
197 /****
198 * buf_new
199 ****/
200 if (!(buf = buf_new()))
201 test_fail();
203 //test_eq(buf_capacity(buf), 4096);
204 test_eq(buf_datalen(buf), 0);
206 /****
207 * General pointer frobbing
209 for (j=0;j<256;++j) {
210 str[j] = (char)j;
212 write_to_buf(str, 256, buf);
213 write_to_buf(str, 256, buf);
214 test_eq(buf_datalen(buf), 512);
215 fetch_from_buf(str2, 200, buf);
216 test_memeq(str, str2, 200);
217 test_eq(buf_datalen(buf), 312);
218 memset(str2, 0, sizeof(str2));
220 fetch_from_buf(str2, 256, buf);
221 test_memeq(str+200, str2, 56);
222 test_memeq(str, str2+56, 200);
223 test_eq(buf_datalen(buf), 56);
224 memset(str2, 0, sizeof(str2));
225 /* Okay, now we should be 512 bytes into the 4096-byte buffer. If we add
226 * another 3584 bytes, we hit the end. */
227 for (j=0;j<15;++j) {
228 write_to_buf(str, 256, buf);
230 assert_buf_ok(buf);
231 test_eq(buf_datalen(buf), 3896);
232 fetch_from_buf(str2, 56, buf);
233 test_eq(buf_datalen(buf), 3840);
234 test_memeq(str+200, str2, 56);
235 for (j=0;j<15;++j) {
236 memset(str2, 0, sizeof(str2));
237 fetch_from_buf(str2, 256, buf);
238 test_memeq(str, str2, 256);
240 test_eq(buf_datalen(buf), 0);
241 buf_free(buf);
242 buf = NULL;
244 /* Okay, now make sure growing can work. */
245 buf = buf_new_with_capacity(16);
246 //test_eq(buf_capacity(buf), 16);
247 write_to_buf(str+1, 255, buf);
248 //test_eq(buf_capacity(buf), 256);
249 fetch_from_buf(str2, 254, buf);
250 test_memeq(str+1, str2, 254);
251 //test_eq(buf_capacity(buf), 256);
252 assert_buf_ok(buf);
253 write_to_buf(str, 32, buf);
254 //test_eq(buf_capacity(buf), 256);
255 assert_buf_ok(buf);
256 write_to_buf(str, 256, buf);
257 assert_buf_ok(buf);
258 //test_eq(buf_capacity(buf), 512);
259 test_eq(buf_datalen(buf), 33+256);
260 fetch_from_buf(str2, 33, buf);
261 test_eq(*str2, str[255]);
263 test_memeq(str2+1, str, 32);
264 //test_eq(buf_capacity(buf), 512);
265 test_eq(buf_datalen(buf), 256);
266 fetch_from_buf(str2, 256, buf);
267 test_memeq(str, str2, 256);
269 /* now try shrinking: case 1. */
270 buf_free(buf);
271 buf = buf_new_with_capacity(33668);
272 for (j=0;j<67;++j) {
273 write_to_buf(str,255, buf);
275 //test_eq(buf_capacity(buf), 33668);
276 test_eq(buf_datalen(buf), 17085);
277 for (j=0; j < 40; ++j) {
278 fetch_from_buf(str2, 255,buf);
279 test_memeq(str2, str, 255);
282 /* now try shrinking: case 2. */
283 buf_free(buf);
284 buf = buf_new_with_capacity(33668);
285 for (j=0;j<67;++j) {
286 write_to_buf(str,255, buf);
288 for (j=0; j < 20; ++j) {
289 fetch_from_buf(str2, 255,buf);
290 test_memeq(str2, str, 255);
292 for (j=0;j<80;++j) {
293 write_to_buf(str,255, buf);
295 //test_eq(buf_capacity(buf),33668);
296 for (j=0; j < 120; ++j) {
297 fetch_from_buf(str2, 255,buf);
298 test_memeq(str2, str, 255);
301 /* Move from buf to buf. */
302 buf_free(buf);
303 buf = buf_new_with_capacity(4096);
304 buf2 = buf_new_with_capacity(4096);
305 for (j=0;j<100;++j)
306 write_to_buf(str, 255, buf);
307 test_eq(buf_datalen(buf), 25500);
308 for (j=0;j<100;++j) {
309 r = 10;
310 move_buf_to_buf(buf2, buf, &r);
311 test_eq(r, 0);
313 test_eq(buf_datalen(buf), 24500);
314 test_eq(buf_datalen(buf2), 1000);
315 for (j=0;j<3;++j) {
316 fetch_from_buf(str2, 255, buf2);
317 test_memeq(str2, str, 255);
319 r = 8192; /*big move*/
320 move_buf_to_buf(buf2, buf, &r);
321 test_eq(r, 0);
322 r = 30000; /* incomplete move */
323 move_buf_to_buf(buf2, buf, &r);
324 test_eq(r, 13692);
325 for (j=0;j<97;++j) {
326 fetch_from_buf(str2, 255, buf2);
327 test_memeq(str2, str, 255);
329 buf_free(buf);
330 buf_free(buf2);
331 buf = buf2 = NULL;
333 buf = buf_new_with_capacity(5);
334 cp = "Testing. This is a moderately long Testing string.";
335 for (j = 0; cp[j]; j++)
336 write_to_buf(cp+j, 1, buf);
337 test_eq(0, buf_find_string_offset(buf, "Testing", 7));
338 test_eq(1, buf_find_string_offset(buf, "esting", 6));
339 test_eq(1, buf_find_string_offset(buf, "est", 3));
340 test_eq(39, buf_find_string_offset(buf, "ing str", 7));
341 test_eq(35, buf_find_string_offset(buf, "Testing str", 11));
342 test_eq(32, buf_find_string_offset(buf, "ng ", 3));
343 test_eq(43, buf_find_string_offset(buf, "string.", 7));
344 test_eq(-1, buf_find_string_offset(buf, "shrdlu", 6));
345 test_eq(-1, buf_find_string_offset(buf, "Testing thing", 13));
346 test_eq(-1, buf_find_string_offset(buf, "ngx", 3));
347 buf_free(buf);
348 buf = NULL;
350 done:
351 if (buf)
352 buf_free(buf);
353 if (buf2)
354 buf_free(buf2);
357 /** Run unit tests for the onion handshake code. */
358 static void
359 test_onion_handshake(void)
361 /* client-side */
362 crypto_dh_env_t *c_dh = NULL;
363 char c_buf[ONIONSKIN_CHALLENGE_LEN];
364 char c_keys[40];
366 /* server-side */
367 char s_buf[ONIONSKIN_REPLY_LEN];
368 char s_keys[40];
370 /* shared */
371 crypto_pk_env_t *pk = NULL;
373 pk = pk_generate(0);
375 /* client handshake 1. */
376 memset(c_buf, 0, ONIONSKIN_CHALLENGE_LEN);
377 test_assert(! onion_skin_create(pk, &c_dh, c_buf));
379 /* server handshake */
380 memset(s_buf, 0, ONIONSKIN_REPLY_LEN);
381 memset(s_keys, 0, 40);
382 test_assert(! onion_skin_server_handshake(c_buf, pk, NULL,
383 s_buf, s_keys, 40));
385 /* client handshake 2 */
386 memset(c_keys, 0, 40);
387 test_assert(! onion_skin_client_handshake(c_dh, s_buf, c_keys, 40));
389 if (memcmp(c_keys, s_keys, 40)) {
390 puts("Aiiiie");
391 exit(1);
393 test_memeq(c_keys, s_keys, 40);
394 memset(s_buf, 0, 40);
395 test_memneq(c_keys, s_buf, 40);
397 done:
398 if (c_dh)
399 crypto_dh_free(c_dh);
400 if (pk)
401 crypto_free_pk_env(pk);
404 static void
405 test_circuit_timeout(void)
407 /* Plan:
408 * 1. Generate 1000 samples
409 * 2. Estimate parameters
410 * 3. If difference, repeat
411 * 4. Save state
412 * 5. load state
413 * 6. Estimate parameters
414 * 7. compare differences
416 circuit_build_times_t initial;
417 circuit_build_times_t estimate;
418 circuit_build_times_t final;
419 double timeout1, timeout2;
420 or_state_t state;
421 int i, runs;
422 double close_ms;
423 circuit_build_times_init(&initial);
424 circuit_build_times_init(&estimate);
425 circuit_build_times_init(&final);
427 memset(&state, 0, sizeof(or_state_t));
429 circuitbuild_running_unit_tests();
430 #define timeout0 (build_time_t)(30*1000.0)
431 initial.Xm = 3000;
432 circuit_build_times_initial_alpha(&initial,
433 CBT_DEFAULT_QUANTILE_CUTOFF/100.0,
434 timeout0);
435 close_ms = MAX(circuit_build_times_calculate_timeout(&initial,
436 CBT_DEFAULT_CLOSE_QUANTILE/100.0),
437 CBT_DEFAULT_TIMEOUT_INITIAL_VALUE);
438 do {
439 for (i=0; i < CBT_DEFAULT_MIN_CIRCUITS_TO_OBSERVE; i++) {
440 build_time_t sample = circuit_build_times_generate_sample(&initial,0,1);
442 if (sample > close_ms) {
443 circuit_build_times_add_time(&estimate, CBT_BUILD_ABANDONED);
444 } else {
445 circuit_build_times_add_time(&estimate, sample);
448 circuit_build_times_update_alpha(&estimate);
449 timeout1 = circuit_build_times_calculate_timeout(&estimate,
450 CBT_DEFAULT_QUANTILE_CUTOFF/100.0);
451 circuit_build_times_set_timeout(&estimate);
452 log_notice(LD_CIRC, "Timeout1 is %lf, Xm is %d", timeout1, estimate.Xm);
453 /* 2% error */
454 } while (fabs(circuit_build_times_cdf(&initial, timeout0) -
455 circuit_build_times_cdf(&initial, timeout1)) > 0.02);
457 test_assert(estimate.total_build_times <= CBT_NCIRCUITS_TO_OBSERVE);
459 circuit_build_times_update_state(&estimate, &state);
460 test_assert(circuit_build_times_parse_state(&final, &state) == 0);
462 circuit_build_times_update_alpha(&final);
463 timeout2 = circuit_build_times_calculate_timeout(&final,
464 CBT_DEFAULT_QUANTILE_CUTOFF/100.0);
466 circuit_build_times_set_timeout(&final);
467 log_notice(LD_CIRC, "Timeout2 is %lf, Xm is %d", timeout2, final.Xm);
469 /* 5% here because some accuracy is lost due to histogram conversion */
470 test_assert(fabs(circuit_build_times_cdf(&initial, timeout0) -
471 circuit_build_times_cdf(&initial, timeout2)) < 0.05);
473 for (runs = 0; runs < 50; runs++) {
474 int build_times_idx = 0;
475 int total_build_times = 0;
477 final.close_ms = final.timeout_ms = CBT_DEFAULT_TIMEOUT_INITIAL_VALUE;
478 estimate.close_ms = estimate.timeout_ms
479 = CBT_DEFAULT_TIMEOUT_INITIAL_VALUE;
481 for (i = 0; i < CBT_DEFAULT_RECENT_CIRCUITS*2; i++) {
482 circuit_build_times_network_circ_success(&estimate);
483 circuit_build_times_add_time(&estimate,
484 circuit_build_times_generate_sample(&estimate, 0,
485 CBT_DEFAULT_QUANTILE_CUTOFF/100.0));
487 circuit_build_times_network_circ_success(&estimate);
488 circuit_build_times_add_time(&final,
489 circuit_build_times_generate_sample(&final, 0,
490 CBT_DEFAULT_QUANTILE_CUTOFF/100.0));
493 test_assert(!circuit_build_times_network_check_changed(&estimate));
494 test_assert(!circuit_build_times_network_check_changed(&final));
496 /* Reset liveness to be non-live */
497 final.liveness.network_last_live = 0;
498 estimate.liveness.network_last_live = 0;
500 build_times_idx = estimate.build_times_idx;
501 total_build_times = estimate.total_build_times;
503 test_assert(circuit_build_times_network_check_live(&estimate));
504 test_assert(circuit_build_times_network_check_live(&final));
506 circuit_build_times_count_close(&estimate, 0,
507 (time_t)(approx_time()-estimate.close_ms/1000.0-1));
508 circuit_build_times_count_close(&final, 0,
509 (time_t)(approx_time()-final.close_ms/1000.0-1));
511 test_assert(!circuit_build_times_network_check_live(&estimate));
512 test_assert(!circuit_build_times_network_check_live(&final));
514 log_info(LD_CIRC, "idx: %d %d, tot: %d %d",
515 build_times_idx, estimate.build_times_idx,
516 total_build_times, estimate.total_build_times);
518 /* Check rollback index. Should match top of loop. */
519 test_assert(build_times_idx == estimate.build_times_idx);
520 // This can fail if estimate.total_build_times == 1000, because
521 // in that case, rewind actually causes us to lose timeouts
522 if (total_build_times != CBT_NCIRCUITS_TO_OBSERVE)
523 test_assert(total_build_times == estimate.total_build_times);
525 /* Now simulate that the network has become live and we need
526 * a change */
527 circuit_build_times_network_is_live(&estimate);
528 circuit_build_times_network_is_live(&final);
530 for (i = 0; i < CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT; i++) {
531 circuit_build_times_count_timeout(&estimate, 1);
533 if (i < CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT-1) {
534 circuit_build_times_count_timeout(&final, 1);
538 test_assert(estimate.liveness.after_firsthop_idx == 0);
539 test_assert(final.liveness.after_firsthop_idx ==
540 CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT-1);
542 test_assert(circuit_build_times_network_check_live(&estimate));
543 test_assert(circuit_build_times_network_check_live(&final));
545 circuit_build_times_count_timeout(&final, 1);
548 done:
549 return;
552 /** Helper: Parse the exit policy string in <b>policy_str</b>, and make sure
553 * that policies_summarize() produces the string <b>expected_summary</b> from
554 * it. */
555 static void
556 test_policy_summary_helper(const char *policy_str,
557 const char *expected_summary)
559 config_line_t line;
560 smartlist_t *policy = smartlist_create();
561 char *summary = NULL;
562 int r;
564 line.key = (char*)"foo";
565 line.value = (char *)policy_str;
566 line.next = NULL;
568 r = policies_parse_exit_policy(&line, &policy, 0, NULL, 1);
569 test_eq(r, 0);
570 summary = policy_summarize(policy);
572 test_assert(summary != NULL);
573 test_streq(summary, expected_summary);
575 done:
576 tor_free(summary);
577 if (policy)
578 addr_policy_list_free(policy);
581 /** Run unit tests for generating summary lines of exit policies */
582 static void
583 test_policies(void)
585 int i;
586 smartlist_t *policy = NULL, *policy2 = NULL, *policy3 = NULL,
587 *policy4 = NULL, *policy5 = NULL, *policy6 = NULL,
588 *policy7 = NULL;
589 addr_policy_t *p;
590 tor_addr_t tar;
591 config_line_t line;
592 smartlist_t *sm = NULL;
593 char *policy_str = NULL;
595 policy = smartlist_create();
597 p = router_parse_addr_policy_item_from_string("reject 192.168.0.0/16:*",-1);
598 test_assert(p != NULL);
599 test_eq(ADDR_POLICY_REJECT, p->policy_type);
600 tor_addr_from_ipv4h(&tar, 0xc0a80000u);
601 test_eq(0, tor_addr_compare(&p->addr, &tar, CMP_EXACT));
602 test_eq(16, p->maskbits);
603 test_eq(1, p->prt_min);
604 test_eq(65535, p->prt_max);
606 smartlist_add(policy, p);
608 test_assert(ADDR_POLICY_ACCEPTED ==
609 compare_addr_to_addr_policy(0x01020304u, 2, policy));
610 test_assert(ADDR_POLICY_PROBABLY_ACCEPTED ==
611 compare_addr_to_addr_policy(0, 2, policy));
612 test_assert(ADDR_POLICY_REJECTED ==
613 compare_addr_to_addr_policy(0xc0a80102, 2, policy));
615 test_assert(0 == policies_parse_exit_policy(NULL, &policy2, 1, NULL, 1));
616 test_assert(policy2);
618 policy3 = smartlist_create();
619 p = router_parse_addr_policy_item_from_string("reject *:*",-1);
620 test_assert(p != NULL);
621 smartlist_add(policy3, p);
622 p = router_parse_addr_policy_item_from_string("accept *:*",-1);
623 test_assert(p != NULL);
624 smartlist_add(policy3, p);
626 policy4 = smartlist_create();
627 p = router_parse_addr_policy_item_from_string("accept *:443",-1);
628 test_assert(p != NULL);
629 smartlist_add(policy4, p);
630 p = router_parse_addr_policy_item_from_string("accept *:443",-1);
631 test_assert(p != NULL);
632 smartlist_add(policy4, p);
634 policy5 = smartlist_create();
635 p = router_parse_addr_policy_item_from_string("reject 0.0.0.0/8:*",-1);
636 test_assert(p != NULL);
637 smartlist_add(policy5, p);
638 p = router_parse_addr_policy_item_from_string("reject 169.254.0.0/16:*",-1);
639 test_assert(p != NULL);
640 smartlist_add(policy5, p);
641 p = router_parse_addr_policy_item_from_string("reject 127.0.0.0/8:*",-1);
642 test_assert(p != NULL);
643 smartlist_add(policy5, p);
644 p = router_parse_addr_policy_item_from_string("reject 192.168.0.0/16:*",-1);
645 test_assert(p != NULL);
646 smartlist_add(policy5, p);
647 p = router_parse_addr_policy_item_from_string("reject 10.0.0.0/8:*",-1);
648 test_assert(p != NULL);
649 smartlist_add(policy5, p);
650 p = router_parse_addr_policy_item_from_string("reject 172.16.0.0/12:*",-1);
651 test_assert(p != NULL);
652 smartlist_add(policy5, p);
653 p = router_parse_addr_policy_item_from_string("reject 80.190.250.90:*",-1);
654 test_assert(p != NULL);
655 smartlist_add(policy5, p);
656 p = router_parse_addr_policy_item_from_string("reject *:1-65534",-1);
657 test_assert(p != NULL);
658 smartlist_add(policy5, p);
659 p = router_parse_addr_policy_item_from_string("reject *:65535",-1);
660 test_assert(p != NULL);
661 smartlist_add(policy5, p);
662 p = router_parse_addr_policy_item_from_string("accept *:1-65535",-1);
663 test_assert(p != NULL);
664 smartlist_add(policy5, p);
666 policy6 = smartlist_create();
667 p = router_parse_addr_policy_item_from_string("accept 43.3.0.0/9:*",-1);
668 test_assert(p != NULL);
669 smartlist_add(policy6, p);
671 policy7 = smartlist_create();
672 p = router_parse_addr_policy_item_from_string("accept 0.0.0.0/8:*",-1);
673 test_assert(p != NULL);
674 smartlist_add(policy7, p);
676 test_assert(!exit_policy_is_general_exit(policy));
677 test_assert(exit_policy_is_general_exit(policy2));
678 test_assert(!exit_policy_is_general_exit(NULL));
679 test_assert(!exit_policy_is_general_exit(policy3));
680 test_assert(!exit_policy_is_general_exit(policy4));
681 test_assert(!exit_policy_is_general_exit(policy5));
682 test_assert(!exit_policy_is_general_exit(policy6));
683 test_assert(!exit_policy_is_general_exit(policy7));
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 addr_policy_list_free(policy);
794 addr_policy_list_free(policy2);
795 addr_policy_list_free(policy3);
796 addr_policy_list_free(policy4);
797 addr_policy_list_free(policy5);
798 addr_policy_list_free(policy6);
799 addr_policy_list_free(policy7);
800 tor_free(policy_str);
801 if (sm) {
802 SMARTLIST_FOREACH(sm, char *, s, tor_free(s));
803 smartlist_free(sm);
807 /** Run AES performance benchmarks. */
808 static void
809 bench_aes(void)
811 int len, i;
812 char *b1, *b2;
813 crypto_cipher_env_t *c;
814 struct timeval start, end;
815 const int iters = 100000;
816 uint64_t nsec;
817 c = crypto_new_cipher_env();
818 crypto_cipher_generate_key(c);
819 crypto_cipher_encrypt_init_cipher(c);
820 for (len = 1; len <= 8192; len *= 2) {
821 b1 = tor_malloc_zero(len);
822 b2 = tor_malloc_zero(len);
823 tor_gettimeofday(&start);
824 for (i = 0; i < iters; ++i) {
825 crypto_cipher_encrypt(c, b1, b2, len);
827 tor_gettimeofday(&end);
828 tor_free(b1);
829 tor_free(b2);
830 nsec = (uint64_t) tv_udiff(&start,&end);
831 nsec *= 1000;
832 nsec /= (iters*len);
833 printf("%d bytes: "U64_FORMAT" nsec per byte\n", len,
834 U64_PRINTF_ARG(nsec));
836 crypto_free_cipher_env(c);
839 /** Run digestmap_t performance benchmarks. */
840 static void
841 bench_dmap(void)
843 smartlist_t *sl = smartlist_create();
844 smartlist_t *sl2 = smartlist_create();
845 struct timeval start, end, pt2, pt3, pt4;
846 const int iters = 10000;
847 const int elts = 4000;
848 const int fpostests = 1000000;
849 char d[20];
850 int i,n=0, fp = 0;
851 digestmap_t *dm = digestmap_new();
852 digestset_t *ds = digestset_new(elts);
854 for (i = 0; i < elts; ++i) {
855 crypto_rand(d, 20);
856 smartlist_add(sl, tor_memdup(d, 20));
858 for (i = 0; i < elts; ++i) {
859 crypto_rand(d, 20);
860 smartlist_add(sl2, tor_memdup(d, 20));
862 printf("nbits=%d\n", ds->mask+1);
864 tor_gettimeofday(&start);
865 for (i = 0; i < iters; ++i) {
866 SMARTLIST_FOREACH(sl, const char *, cp, digestmap_set(dm, cp, (void*)1));
868 tor_gettimeofday(&pt2);
869 for (i = 0; i < iters; ++i) {
870 SMARTLIST_FOREACH(sl, const char *, cp, digestmap_get(dm, cp));
871 SMARTLIST_FOREACH(sl2, const char *, cp, digestmap_get(dm, cp));
873 tor_gettimeofday(&pt3);
874 for (i = 0; i < iters; ++i) {
875 SMARTLIST_FOREACH(sl, const char *, cp, digestset_add(ds, cp));
877 tor_gettimeofday(&pt4);
878 for (i = 0; i < iters; ++i) {
879 SMARTLIST_FOREACH(sl, const char *, cp, n += digestset_isin(ds, cp));
880 SMARTLIST_FOREACH(sl2, const char *, cp, n += digestset_isin(ds, cp));
882 tor_gettimeofday(&end);
884 for (i = 0; i < fpostests; ++i) {
885 crypto_rand(d, 20);
886 if (digestset_isin(ds, d)) ++fp;
889 printf("%ld\n",(unsigned long)tv_udiff(&start, &pt2));
890 printf("%ld\n",(unsigned long)tv_udiff(&pt2, &pt3));
891 printf("%ld\n",(unsigned long)tv_udiff(&pt3, &pt4));
892 printf("%ld\n",(unsigned long)tv_udiff(&pt4, &end));
893 printf("-- %d\n", n);
894 printf("++ %f\n", fp/(double)fpostests);
895 digestmap_free(dm, NULL);
896 digestset_free(ds);
897 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
898 SMARTLIST_FOREACH(sl2, char *, cp, tor_free(cp));
899 smartlist_free(sl);
900 smartlist_free(sl2);
903 /** Test encoding and parsing of rendezvous service descriptors. */
904 static void
905 test_rend_fns(void)
907 rend_service_descriptor_t *generated = NULL, *parsed = NULL;
908 char service_id[DIGEST_LEN];
909 char service_id_base32[REND_SERVICE_ID_LEN_BASE32+1];
910 const char *next_desc;
911 smartlist_t *descs = smartlist_create();
912 char computed_desc_id[DIGEST_LEN];
913 char parsed_desc_id[DIGEST_LEN];
914 crypto_pk_env_t *pk1 = NULL, *pk2 = NULL;
915 time_t now;
916 char *intro_points_encrypted = NULL;
917 size_t intro_points_size;
918 size_t encoded_size;
919 int i;
920 char address1[] = "fooaddress.onion";
921 char address2[] = "aaaaaaaaaaaaaaaa.onion";
922 char address3[] = "fooaddress.exit";
923 char address4[] = "www.torproject.org";
925 test_assert(BAD_HOSTNAME == parse_extended_hostname(address1, 1));
926 test_assert(ONION_HOSTNAME == parse_extended_hostname(address2, 1));
927 test_assert(EXIT_HOSTNAME == parse_extended_hostname(address3, 1));
928 test_assert(NORMAL_HOSTNAME == parse_extended_hostname(address4, 1));
930 pk1 = pk_generate(0);
931 pk2 = pk_generate(1);
932 generated = tor_malloc_zero(sizeof(rend_service_descriptor_t));
933 generated->pk = crypto_pk_dup_key(pk1);
934 crypto_pk_get_digest(generated->pk, service_id);
935 base32_encode(service_id_base32, REND_SERVICE_ID_LEN_BASE32+1,
936 service_id, REND_SERVICE_ID_LEN);
937 now = time(NULL);
938 generated->timestamp = now;
939 generated->version = 2;
940 generated->protocols = 42;
941 generated->intro_nodes = smartlist_create();
943 for (i = 0; i < 3; i++) {
944 rend_intro_point_t *intro = tor_malloc_zero(sizeof(rend_intro_point_t));
945 crypto_pk_env_t *okey = pk_generate(2 + i);
946 intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
947 intro->extend_info->onion_key = okey;
948 crypto_pk_get_digest(intro->extend_info->onion_key,
949 intro->extend_info->identity_digest);
950 //crypto_rand(info->identity_digest, DIGEST_LEN); /* Would this work? */
951 intro->extend_info->nickname[0] = '$';
952 base16_encode(intro->extend_info->nickname + 1,
953 sizeof(intro->extend_info->nickname) - 1,
954 intro->extend_info->identity_digest, DIGEST_LEN);
955 /* Does not cover all IP addresses. */
956 tor_addr_from_ipv4h(&intro->extend_info->addr, crypto_rand_int(65536));
957 intro->extend_info->port = 1 + crypto_rand_int(65535);
958 intro->intro_key = crypto_pk_dup_key(pk2);
959 smartlist_add(generated->intro_nodes, intro);
961 test_assert(rend_encode_v2_descriptors(descs, generated, now, 0,
962 REND_NO_AUTH, NULL, NULL) > 0);
963 test_assert(rend_compute_v2_desc_id(computed_desc_id, service_id_base32,
964 NULL, now, 0) == 0);
965 test_memeq(((rend_encoded_v2_service_descriptor_t *)
966 smartlist_get(descs, 0))->desc_id, computed_desc_id, DIGEST_LEN);
967 test_assert(rend_parse_v2_service_descriptor(&parsed, parsed_desc_id,
968 &intro_points_encrypted,
969 &intro_points_size,
970 &encoded_size,
971 &next_desc,
972 ((rend_encoded_v2_service_descriptor_t *)
973 smartlist_get(descs, 0))->desc_str) == 0);
974 test_assert(parsed);
975 test_memeq(((rend_encoded_v2_service_descriptor_t *)
976 smartlist_get(descs, 0))->desc_id, parsed_desc_id, DIGEST_LEN);
977 test_eq(rend_parse_introduction_points(parsed, intro_points_encrypted,
978 intro_points_size), 3);
979 test_assert(!crypto_pk_cmp_keys(generated->pk, parsed->pk));
980 test_eq(parsed->timestamp, now);
981 test_eq(parsed->version, 2);
982 test_eq(parsed->protocols, 42);
983 test_eq(smartlist_len(parsed->intro_nodes), 3);
984 for (i = 0; i < smartlist_len(parsed->intro_nodes); i++) {
985 rend_intro_point_t *par_intro = smartlist_get(parsed->intro_nodes, i),
986 *gen_intro = smartlist_get(generated->intro_nodes, i);
987 extend_info_t *par_info = par_intro->extend_info;
988 extend_info_t *gen_info = gen_intro->extend_info;
989 test_assert(!crypto_pk_cmp_keys(gen_info->onion_key, par_info->onion_key));
990 test_memeq(gen_info->identity_digest, par_info->identity_digest,
991 DIGEST_LEN);
992 test_streq(gen_info->nickname, par_info->nickname);
993 test_assert(tor_addr_eq(&gen_info->addr, &par_info->addr));
994 test_eq(gen_info->port, par_info->port);
997 rend_service_descriptor_free(parsed);
998 rend_service_descriptor_free(generated);
999 parsed = generated = NULL;
1001 done:
1002 if (descs) {
1003 for (i = 0; i < smartlist_len(descs); i++)
1004 rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
1005 smartlist_free(descs);
1007 if (parsed)
1008 rend_service_descriptor_free(parsed);
1009 if (generated)
1010 rend_service_descriptor_free(generated);
1011 if (pk1)
1012 crypto_free_pk_env(pk1);
1013 if (pk2)
1014 crypto_free_pk_env(pk2);
1015 tor_free(intro_points_encrypted);
1018 /** Run unit tests for GeoIP code. */
1019 static void
1020 test_geoip(void)
1022 int i, j;
1023 time_t now = time(NULL);
1024 char *s = NULL;
1026 /* Populate the DB a bit. Add these in order, since we can't do the final
1027 * 'sort' step. These aren't very good IP addresses, but they're perfectly
1028 * fine uint32_t values. */
1029 test_eq(0, geoip_parse_entry("10,50,AB"));
1030 test_eq(0, geoip_parse_entry("52,90,XY"));
1031 test_eq(0, geoip_parse_entry("95,100,AB"));
1032 test_eq(0, geoip_parse_entry("\"105\",\"140\",\"ZZ\""));
1033 test_eq(0, geoip_parse_entry("\"150\",\"190\",\"XY\""));
1034 test_eq(0, geoip_parse_entry("\"200\",\"250\",\"AB\""));
1036 /* We should have 4 countries: ??, ab, xy, zz. */
1037 test_eq(4, geoip_get_n_countries());
1038 /* Make sure that country ID actually works. */
1039 #define NAMEFOR(x) geoip_get_country_name(geoip_get_country_by_ip(x))
1040 test_streq("??", NAMEFOR(3));
1041 test_eq(0, geoip_get_country_by_ip(3));
1042 test_streq("ab", NAMEFOR(32));
1043 test_streq("??", NAMEFOR(5));
1044 test_streq("??", NAMEFOR(51));
1045 test_streq("xy", NAMEFOR(150));
1046 test_streq("xy", NAMEFOR(190));
1047 test_streq("??", NAMEFOR(2000));
1048 #undef NAMEFOR
1050 get_options()->BridgeRelay = 1;
1051 get_options()->BridgeRecordUsageByCountry = 1;
1052 /* Put 9 observations in AB... */
1053 for (i=32; i < 40; ++i)
1054 geoip_note_client_seen(GEOIP_CLIENT_CONNECT, i, now-7200);
1055 geoip_note_client_seen(GEOIP_CLIENT_CONNECT, 225, now-7200);
1056 /* and 3 observations in XY, several times. */
1057 for (j=0; j < 10; ++j)
1058 for (i=52; i < 55; ++i)
1059 geoip_note_client_seen(GEOIP_CLIENT_CONNECT, i, now-3600);
1060 /* and 17 observations in ZZ... */
1061 for (i=110; i < 127; ++i)
1062 geoip_note_client_seen(GEOIP_CLIENT_CONNECT, i, now);
1063 s = geoip_get_client_history(GEOIP_CLIENT_CONNECT);
1064 test_assert(s);
1065 test_streq("zz=24,ab=16,xy=8", s);
1066 tor_free(s);
1068 /* Now clear out all the AB observations. */
1069 geoip_remove_old_clients(now-6000);
1070 s = geoip_get_client_history(GEOIP_CLIENT_CONNECT);
1071 test_assert(s);
1072 test_streq("zz=24,xy=8", s);
1074 done:
1075 tor_free(s);
1078 /** Run unit tests for stats code. */
1079 static void
1080 test_stats(void)
1082 time_t now = 1281533250; /* 2010-08-11 13:27:30 UTC */
1083 char *s = NULL;
1084 int i;
1086 /* We shouldn't collect exit stats without initializing them. */
1087 rep_hist_note_exit_stream_opened(80);
1088 rep_hist_note_exit_bytes(80, 100, 10000);
1089 s = rep_hist_format_exit_stats(now + 86400);
1090 test_assert(!s);
1092 /* Initialize stats, note some streams and bytes, and generate history
1093 * string. */
1094 rep_hist_exit_stats_init(now);
1095 rep_hist_note_exit_stream_opened(80);
1096 rep_hist_note_exit_bytes(80, 100, 10000);
1097 rep_hist_note_exit_stream_opened(443);
1098 rep_hist_note_exit_bytes(443, 100, 10000);
1099 rep_hist_note_exit_bytes(443, 100, 10000);
1100 s = rep_hist_format_exit_stats(now + 86400);
1101 test_streq("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
1102 "exit-kibibytes-written 80=1,443=1,other=0\n"
1103 "exit-kibibytes-read 80=10,443=20,other=0\n"
1104 "exit-streams-opened 80=4,443=4,other=0\n", s);
1105 tor_free(s);
1107 /* Add a few bytes on 10 more ports and ensure that only the top 10
1108 * ports are contained in the history string. */
1109 for (i = 50; i < 60; i++) {
1110 rep_hist_note_exit_bytes(i, i, i);
1111 rep_hist_note_exit_stream_opened(i);
1113 s = rep_hist_format_exit_stats(now + 86400);
1114 test_streq("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
1115 "exit-kibibytes-written 52=1,53=1,54=1,55=1,56=1,57=1,58=1,"
1116 "59=1,80=1,443=1,other=1\n"
1117 "exit-kibibytes-read 52=1,53=1,54=1,55=1,56=1,57=1,58=1,"
1118 "59=1,80=10,443=20,other=1\n"
1119 "exit-streams-opened 52=4,53=4,54=4,55=4,56=4,57=4,58=4,"
1120 "59=4,80=4,443=4,other=4\n", s);
1121 tor_free(s);
1123 /* Stop collecting stats, add some bytes, and ensure we don't generate
1124 * a history string. */
1125 rep_hist_exit_stats_term();
1126 rep_hist_note_exit_bytes(80, 100, 10000);
1127 s = rep_hist_format_exit_stats(now + 86400);
1128 test_assert(!s);
1130 /* Re-start stats, add some bytes, reset stats, and see what history we
1131 * get when observing no streams or bytes at all. */
1132 rep_hist_exit_stats_init(now);
1133 rep_hist_note_exit_stream_opened(80);
1134 rep_hist_note_exit_bytes(80, 100, 10000);
1135 rep_hist_reset_exit_stats(now);
1136 s = rep_hist_format_exit_stats(now + 86400);
1137 test_streq("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
1138 "exit-kibibytes-written other=0\n"
1139 "exit-kibibytes-read other=0\n"
1140 "exit-streams-opened other=0\n", s);
1142 done:
1143 tor_free(s);
1146 static void *
1147 legacy_test_setup(const struct testcase_t *testcase)
1149 return testcase->setup_data;
1152 void
1153 legacy_test_helper(void *data)
1155 void (*fn)(void) = data;
1156 fn();
1159 static int
1160 legacy_test_cleanup(const struct testcase_t *testcase, void *ptr)
1162 (void)ptr;
1163 (void)testcase;
1164 return 1;
1167 const struct testcase_setup_t legacy_setup = {
1168 legacy_test_setup, legacy_test_cleanup
1171 #define ENT(name) \
1172 { #name, legacy_test_helper, 0, &legacy_setup, test_ ## name }
1173 #define SUBENT(group, name) \
1174 { #group "_" #name, legacy_test_helper, 0, &legacy_setup, \
1175 test_ ## group ## _ ## name }
1176 #define DISABLED(name) \
1177 { #name, legacy_test_helper, TT_SKIP, &legacy_setup, name }
1178 #define FORK(name) \
1179 { #name, legacy_test_helper, TT_FORK, &legacy_setup, test_ ## name }
1181 static struct testcase_t test_array[] = {
1182 ENT(buffers),
1183 ENT(onion_handshake),
1184 ENT(circuit_timeout),
1185 ENT(policies),
1186 ENT(rend_fns),
1187 ENT(geoip),
1188 FORK(stats),
1190 DISABLED(bench_aes),
1191 DISABLED(bench_dmap),
1192 END_OF_TESTCASES
1195 extern struct testcase_t addr_tests[];
1196 extern struct testcase_t crypto_tests[];
1197 extern struct testcase_t container_tests[];
1198 extern struct testcase_t util_tests[];
1199 extern struct testcase_t dir_tests[];
1201 static struct testgroup_t testgroups[] = {
1202 { "", test_array },
1203 { "addr/", addr_tests },
1204 { "crypto/", crypto_tests },
1205 { "container/", container_tests },
1206 { "util/", util_tests },
1207 { "dir/", dir_tests },
1208 END_OF_GROUPS
1211 /** Main entry point for unit test code: parse the command line, and run
1212 * some unit tests. */
1214 main(int c, const char **v)
1216 or_options_t *options;
1217 char *errmsg = NULL;
1218 int i, i_out;
1219 int loglevel = LOG_ERR;
1221 #ifdef USE_DMALLOC
1223 int r = CRYPTO_set_mem_ex_functions(_tor_malloc, _tor_realloc, _tor_free);
1224 tor_assert(r);
1226 #endif
1228 update_approx_time(time(NULL));
1229 options = options_new();
1230 tor_threads_init();
1231 init_logging();
1233 for (i_out = i = 1; i < c; ++i) {
1234 if (!strcmp(v[i], "--warn")) {
1235 loglevel = LOG_WARN;
1236 } else if (!strcmp(v[i], "--notice")) {
1237 loglevel = LOG_NOTICE;
1238 } else if (!strcmp(v[i], "--info")) {
1239 loglevel = LOG_INFO;
1240 } else if (!strcmp(v[i], "--debug")) {
1241 loglevel = LOG_DEBUG;
1242 } else {
1243 v[i_out++] = v[i];
1246 c = i_out;
1249 log_severity_list_t s;
1250 memset(&s, 0, sizeof(s));
1251 set_log_severity_config(loglevel, LOG_ERR, &s);
1252 add_stream_log(&s, "", fileno(stdout));
1255 options->command = CMD_RUN_UNITTESTS;
1256 crypto_global_init(0, NULL, NULL);
1257 rep_hist_init();
1258 network_init();
1259 setup_directory();
1260 options_init(options);
1261 options->DataDirectory = tor_strdup(temp_dir);
1262 options->EntryStatistics = 1;
1263 if (set_options(options, &errmsg) < 0) {
1264 printf("Failed to set initial options: %s\n", errmsg);
1265 tor_free(errmsg);
1266 return 1;
1269 crypto_seed_rng(1);
1271 atexit(remove_directory);
1273 have_failed = (tinytest_main(c, v, testgroups) != 0);
1275 free_pregenerated_keys();
1276 #ifdef USE_DMALLOC
1277 tor_free_all(0);
1278 dmalloc_log_unfreed();
1279 #endif
1281 if (have_failed)
1282 return 1;
1283 else
1284 return 0;