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_svn_revision
[] = "";
12 * \brief Unit tests for many pieces of the lower level Tor modules.
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 CONTROL_PRIVATE
34 #define CRYPTO_PRIVATE
35 #define DIRSERV_PRIVATE
36 #define DIRVOTE_PRIVATE
38 #define MEMPOOL_PRIVATE
39 #define ROUTER_PRIVATE
49 #include <openssl/crypto.h>
52 /** Set to true if any unit test has failed. Mostly, this is set by the macros
56 /** Temporary directory (set up by setup_directory) under which we store all
57 * our files during testing. */
58 static char temp_dir
[256];
60 /** Select and create the temporary directory we'll use to run our unit tests.
61 * Store it in <b>temp_dir</b>. Exit immediately if we can't create it.
66 static int is_setup
= 0;
72 tor_snprintf(temp_dir
, sizeof(temp_dir
),
73 "c:\\windows\\temp\\tor_test_%d", (int)getpid());
76 tor_snprintf(temp_dir
, sizeof(temp_dir
), "/tmp/tor_test_%d", (int) getpid());
77 r
= mkdir(temp_dir
, 0700);
80 fprintf(stderr
, "Can't create directory %s:", temp_dir
);
87 /** Return a filename relative to our testing temporary directory */
89 get_fname(const char *name
)
91 static char buf
[1024];
93 tor_snprintf(buf
,sizeof(buf
),"%s/%s",temp_dir
,name
);
97 /** Remove all files stored under the temporary directory, and the directory
100 remove_directory(void)
102 smartlist_t
*elements
= tor_listdir(temp_dir
);
104 SMARTLIST_FOREACH(elements
, const char *, cp
,
106 size_t len
= strlen(cp
)+strlen(temp_dir
)+16;
107 char *tmp
= tor_malloc(len
);
108 tor_snprintf(tmp
, len
, "%s"PATH_SEPARATOR
"%s", temp_dir
, cp
);
112 SMARTLIST_FOREACH(elements
, char *, cp
, tor_free(cp
));
113 smartlist_free(elements
);
118 /** Define this if unit tests spend too much time generating public keys*/
119 #undef CACHE_GENERATED_KEYS
121 static crypto_pk_env_t
*pregen_keys
[5] = {NULL
, NULL
, NULL
, NULL
, NULL
};
122 #define N_PREGEN_KEYS ((int)(sizeof(pregen_keys)/sizeof(pregen_keys[0])))
124 /** Generate and return a new keypair for use in unit tests. If we're using
125 * the key cache optimization, we might reuse keys: we only guarantee that
126 * keys made with distinct values for <b>idx</b> are different. The value of
127 * <b>idx</b> must be at least 0, and less than N_PREGEN_KEYS. */
128 static crypto_pk_env_t
*
131 #ifdef CACHE_GENERATED_KEYS
132 tor_assert(idx
< N_PREGEN_KEYS
);
133 if (! pregen_keys
[idx
]) {
134 pregen_keys
[idx
] = crypto_new_pk_env();
135 tor_assert(!crypto_pk_generate_key(pregen_keys
[idx
]));
137 return crypto_pk_dup_key(pregen_keys
[idx
]);
139 crypto_pk_env_t
*result
;
141 result
= crypto_new_pk_env();
142 tor_assert(!crypto_pk_generate_key(result
));
147 /** Free all storage used for the cached key optimization. */
149 free_pregenerated_keys(void)
152 for (idx
= 0; idx
< N_PREGEN_KEYS
; ++idx
) {
153 if (pregen_keys
[idx
]) {
154 crypto_free_pk_env(pregen_keys
[idx
]);
155 pregen_keys
[idx
] = NULL
;
160 /** Run unit tests for buffers.c */
167 buf_t
*buf
= NULL
, *buf2
= NULL
;
176 if (!(buf
= buf_new()))
179 //test_eq(buf_capacity(buf), 4096);
180 test_eq(buf_datalen(buf
), 0);
183 * General pointer frobbing
185 for (j
=0;j
<256;++j
) {
188 write_to_buf(str
, 256, buf
);
189 write_to_buf(str
, 256, buf
);
190 test_eq(buf_datalen(buf
), 512);
191 fetch_from_buf(str2
, 200, buf
);
192 test_memeq(str
, str2
, 200);
193 test_eq(buf_datalen(buf
), 312);
194 memset(str2
, 0, sizeof(str2
));
196 fetch_from_buf(str2
, 256, buf
);
197 test_memeq(str
+200, str2
, 56);
198 test_memeq(str
, str2
+56, 200);
199 test_eq(buf_datalen(buf
), 56);
200 memset(str2
, 0, sizeof(str2
));
201 /* Okay, now we should be 512 bytes into the 4096-byte buffer. If we add
202 * another 3584 bytes, we hit the end. */
204 write_to_buf(str
, 256, buf
);
207 test_eq(buf_datalen(buf
), 3896);
208 fetch_from_buf(str2
, 56, buf
);
209 test_eq(buf_datalen(buf
), 3840);
210 test_memeq(str
+200, str2
, 56);
212 memset(str2
, 0, sizeof(str2
));
213 fetch_from_buf(str2
, 256, buf
);
214 test_memeq(str
, str2
, 256);
216 test_eq(buf_datalen(buf
), 0);
220 /* Okay, now make sure growing can work. */
221 buf
= buf_new_with_capacity(16);
222 //test_eq(buf_capacity(buf), 16);
223 write_to_buf(str
+1, 255, buf
);
224 //test_eq(buf_capacity(buf), 256);
225 fetch_from_buf(str2
, 254, buf
);
226 test_memeq(str
+1, str2
, 254);
227 //test_eq(buf_capacity(buf), 256);
229 write_to_buf(str
, 32, buf
);
230 //test_eq(buf_capacity(buf), 256);
232 write_to_buf(str
, 256, buf
);
234 //test_eq(buf_capacity(buf), 512);
235 test_eq(buf_datalen(buf
), 33+256);
236 fetch_from_buf(str2
, 33, buf
);
237 test_eq(*str2
, str
[255]);
239 test_memeq(str2
+1, str
, 32);
240 //test_eq(buf_capacity(buf), 512);
241 test_eq(buf_datalen(buf
), 256);
242 fetch_from_buf(str2
, 256, buf
);
243 test_memeq(str
, str2
, 256);
245 /* now try shrinking: case 1. */
247 buf
= buf_new_with_capacity(33668);
249 write_to_buf(str
,255, buf
);
251 //test_eq(buf_capacity(buf), 33668);
252 test_eq(buf_datalen(buf
), 17085);
253 for (j
=0; j
< 40; ++j
) {
254 fetch_from_buf(str2
, 255,buf
);
255 test_memeq(str2
, str
, 255);
258 /* now try shrinking: case 2. */
260 buf
= buf_new_with_capacity(33668);
262 write_to_buf(str
,255, buf
);
264 for (j
=0; j
< 20; ++j
) {
265 fetch_from_buf(str2
, 255,buf
);
266 test_memeq(str2
, str
, 255);
269 write_to_buf(str
,255, buf
);
271 //test_eq(buf_capacity(buf),33668);
272 for (j
=0; j
< 120; ++j
) {
273 fetch_from_buf(str2
, 255,buf
);
274 test_memeq(str2
, str
, 255);
277 /* Move from buf to buf. */
279 buf
= buf_new_with_capacity(4096);
280 buf2
= buf_new_with_capacity(4096);
282 write_to_buf(str
, 255, buf
);
283 test_eq(buf_datalen(buf
), 25500);
284 for (j
=0;j
<100;++j
) {
286 move_buf_to_buf(buf2
, buf
, &r
);
289 test_eq(buf_datalen(buf
), 24500);
290 test_eq(buf_datalen(buf2
), 1000);
292 fetch_from_buf(str2
, 255, buf2
);
293 test_memeq(str2
, str
, 255);
295 r
= 8192; /*big move*/
296 move_buf_to_buf(buf2
, buf
, &r
);
298 r
= 30000; /* incomplete move */
299 move_buf_to_buf(buf2
, buf
, &r
);
302 fetch_from_buf(str2
, 255, buf2
);
303 test_memeq(str2
, str
, 255);
309 buf
= buf_new_with_capacity(5);
310 cp
= "Testing. This is a moderately long Testing string.";
311 for (j
= 0; cp
[j
]; j
++)
312 write_to_buf(cp
+j
, 1, buf
);
313 test_eq(0, buf_find_string_offset(buf
, "Testing", 7));
314 test_eq(1, buf_find_string_offset(buf
, "esting", 6));
315 test_eq(1, buf_find_string_offset(buf
, "est", 3));
316 test_eq(39, buf_find_string_offset(buf
, "ing str", 7));
317 test_eq(35, buf_find_string_offset(buf
, "Testing str", 11));
318 test_eq(32, buf_find_string_offset(buf
, "ng ", 3));
319 test_eq(43, buf_find_string_offset(buf
, "string.", 7));
320 test_eq(-1, buf_find_string_offset(buf
, "shrdlu", 6));
321 test_eq(-1, buf_find_string_offset(buf
, "Testing thing", 13));
322 test_eq(-1, buf_find_string_offset(buf
, "ngx", 3));
335 s
= open(get_fname("data"), O_WRONLY
|O_CREAT
|O_TRUNC
, 0600);
339 s
= open(get_fname("data"), O_RDONLY
, 0);
341 errno
= 0; /* XXXX */
342 i
= read_to_buf(s
, 10, buf
, &eof
);
343 printf("%s\n", strerror(errno
));
346 //test_eq(buf_capacity(buf), 4096);
347 test_eq(buf_datalen(buf
), 10);
349 test_memeq(str
, (char*)_buf_peek_raw_buffer(buf
), 10);
351 /* Test reading 0 bytes. */
352 i
= read_to_buf(s
, 0, buf
, &eof
);
353 //test_eq(buf_capacity(buf), 512*1024);
354 test_eq(buf_datalen(buf
), 10);
358 /* Now test when buffer is filled exactly. */
359 buf2
= buf_new_with_capacity(6);
360 i
= read_to_buf(s
, 6, buf2
, &eof
);
361 //test_eq(buf_capacity(buf2), 6);
362 test_eq(buf_datalen(buf2
), 6);
365 test_memeq(str
+10, (char*)_buf_peek_raw_buffer(buf2
), 6);
369 /* Now test when buffer is filled with more data to read. */
370 buf2
= buf_new_with_capacity(32);
371 i
= read_to_buf(s
, 128, buf2
, &eof
);
372 //test_eq(buf_capacity(buf2), 128);
373 test_eq(buf_datalen(buf2
), 32);
379 /* Now read to eof. */
380 test_assert(buf_capacity(buf
) > 256);
381 i
= read_to_buf(s
, 1024, buf
, &eof
);
382 test_eq(i
, (256-32-10-6));
383 test_eq(buf_capacity(buf
), MAX_BUF_SIZE
);
384 test_eq(buf_datalen(buf
), 256-6-32);
385 test_memeq(str
, (char*)_buf_peek_raw_buffer(buf
), 10); /* XXX Check rest. */
388 i
= read_to_buf(s
, 1024, buf
, &eof
);
390 test_eq(buf_capacity(buf
), MAX_BUF_SIZE
);
391 test_eq(buf_datalen(buf
), 256-6-32);
403 /** Run unit tests for Diffie-Hellman functionality. */
407 crypto_dh_env_t
*dh1
= crypto_dh_new();
408 crypto_dh_env_t
*dh2
= crypto_dh_new();
413 ssize_t s1len
, s2len
;
415 test_eq(crypto_dh_get_bytes(dh1
), DH_BYTES
);
416 test_eq(crypto_dh_get_bytes(dh2
), DH_BYTES
);
418 memset(p1
, 0, DH_BYTES
);
419 memset(p2
, 0, DH_BYTES
);
420 test_memeq(p1
, p2
, DH_BYTES
);
421 test_assert(! crypto_dh_get_public(dh1
, p1
, DH_BYTES
));
422 test_memneq(p1
, p2
, DH_BYTES
);
423 test_assert(! crypto_dh_get_public(dh2
, p2
, DH_BYTES
));
424 test_memneq(p1
, p2
, DH_BYTES
);
426 memset(s1
, 0, DH_BYTES
);
427 memset(s2
, 0xFF, DH_BYTES
);
428 s1len
= crypto_dh_compute_secret(dh1
, p2
, DH_BYTES
, s1
, 50);
429 s2len
= crypto_dh_compute_secret(dh2
, p1
, DH_BYTES
, s2
, 50);
430 test_assert(s1len
> 0);
431 test_eq(s1len
, s2len
);
432 test_memeq(s1
, s2
, s1len
);
435 /* XXXX Now fabricate some bad values and make sure they get caught,
436 * Check 0, 1, N-1, >= N, etc.
445 /** Run unit tests for our random number generation function and its wrappers.
448 test_crypto_rng(void)
451 char data1
[100], data2
[100];
454 test_assert(! crypto_seed_rng(0));
455 crypto_rand(data1
, 100);
456 crypto_rand(data2
, 100);
457 test_memneq(data1
,data2
,100);
459 for (i
= 0; i
< 100; ++i
) {
462 j
= crypto_rand_int(100);
463 if (i
< 0 || i
>= 100)
465 big
= crypto_rand_uint64(U64_LITERAL(1)<<40);
466 if (big
>= (U64_LITERAL(1)<<40))
468 big
= crypto_rand_uint64(U64_LITERAL(5));
471 host
= crypto_random_hostname(3,8,"www.",".onion");
472 if (strcmpstart(host
,"www.") ||
473 strcmpend(host
,".onion") ||
484 /** Run unit tests for our AES functionality */
486 test_crypto_aes(void)
488 char *data1
= NULL
, *data2
= NULL
, *data3
= NULL
;
489 crypto_cipher_env_t
*env1
= NULL
, *env2
= NULL
;
492 data1
= tor_malloc(1024);
493 data2
= tor_malloc(1024);
494 data3
= tor_malloc(1024);
496 /* Now, test encryption and decryption with stream cipher. */
498 for (i
= 1023; i
>0; i
-= 35)
499 strncat(data1
, "Now is the time for all good onions", i
);
501 memset(data2
, 0, 1024);
502 memset(data3
, 0, 1024);
503 env1
= crypto_new_cipher_env();
505 env2
= crypto_new_cipher_env();
507 j
= crypto_cipher_generate_key(env1
);
508 crypto_cipher_set_key(env2
, crypto_cipher_get_key(env1
));
509 crypto_cipher_encrypt_init_cipher(env1
);
510 crypto_cipher_decrypt_init_cipher(env2
);
512 /* Try encrypting 512 chars. */
513 crypto_cipher_encrypt(env1
, data2
, data1
, 512);
514 crypto_cipher_decrypt(env2
, data3
, data2
, 512);
515 test_memeq(data1
, data3
, 512);
516 test_memneq(data1
, data2
, 512);
518 /* Now encrypt 1 at a time, and get 1 at a time. */
519 for (j
= 512; j
< 560; ++j
) {
520 crypto_cipher_encrypt(env1
, data2
+j
, data1
+j
, 1);
522 for (j
= 512; j
< 560; ++j
) {
523 crypto_cipher_decrypt(env2
, data3
+j
, data2
+j
, 1);
525 test_memeq(data1
, data3
, 560);
526 /* Now encrypt 3 at a time, and get 5 at a time. */
527 for (j
= 560; j
< 1024-5; j
+= 3) {
528 crypto_cipher_encrypt(env1
, data2
+j
, data1
+j
, 3);
530 for (j
= 560; j
< 1024-5; j
+= 5) {
531 crypto_cipher_decrypt(env2
, data3
+j
, data2
+j
, 5);
533 test_memeq(data1
, data3
, 1024-5);
534 /* Now make sure that when we encrypt with different chunk sizes, we get
536 crypto_free_cipher_env(env2
);
539 memset(data3
, 0, 1024);
540 env2
= crypto_new_cipher_env();
542 crypto_cipher_set_key(env2
, crypto_cipher_get_key(env1
));
543 crypto_cipher_encrypt_init_cipher(env2
);
544 for (j
= 0; j
< 1024-16; j
+= 17) {
545 crypto_cipher_encrypt(env2
, data3
+j
, data1
+j
, 17);
547 for (j
= 0; j
< 1024-16; ++j
) {
548 if (data2
[j
] != data3
[j
]) {
549 printf("%d: %d\t%d\n", j
, (int) data2
[j
], (int) data3
[j
]);
552 test_memeq(data2
, data3
, 1024-16);
553 crypto_free_cipher_env(env1
);
555 crypto_free_cipher_env(env2
);
558 /* NIST test vector for aes. */
559 env1
= crypto_new_cipher_env(); /* IV starts at 0 */
560 crypto_cipher_set_key(env1
, "\x80\x00\x00\x00\x00\x00\x00\x00"
561 "\x00\x00\x00\x00\x00\x00\x00\x00");
562 crypto_cipher_encrypt_init_cipher(env1
);
563 crypto_cipher_encrypt(env1
, data1
,
564 "\x00\x00\x00\x00\x00\x00\x00\x00"
565 "\x00\x00\x00\x00\x00\x00\x00\x00", 16);
566 test_memeq_hex(data1
, "0EDD33D3C621E546455BD8BA1418BEC8");
568 /* Now test rollover. All these values are originally from a python
570 crypto_cipher_set_iv(env1
, "\x00\x00\x00\x00\x00\x00\x00\x00"
571 "\xff\xff\xff\xff\xff\xff\xff\xff");
572 memset(data2
, 0, 1024);
573 crypto_cipher_encrypt(env1
, data1
, data2
, 32);
574 test_memeq_hex(data1
, "335fe6da56f843199066c14a00a40231"
575 "cdd0b917dbc7186908a6bfb5ffd574d3");
577 crypto_cipher_set_iv(env1
, "\x00\x00\x00\x00\xff\xff\xff\xff"
578 "\xff\xff\xff\xff\xff\xff\xff\xff");
579 memset(data2
, 0, 1024);
580 crypto_cipher_encrypt(env1
, data1
, data2
, 32);
581 test_memeq_hex(data1
, "e627c6423fa2d77832a02b2794094b73"
582 "3e63c721df790d2c6469cc1953a3ffac");
584 crypto_cipher_set_iv(env1
, "\xff\xff\xff\xff\xff\xff\xff\xff"
585 "\xff\xff\xff\xff\xff\xff\xff\xff");
586 memset(data2
, 0, 1024);
587 crypto_cipher_encrypt(env1
, data1
, data2
, 32);
588 test_memeq_hex(data1
, "2aed2bff0de54f9328efd070bf48f70a"
589 "0EDD33D3C621E546455BD8BA1418BEC8");
591 /* Now check rollover on inplace cipher. */
592 crypto_cipher_set_iv(env1
, "\xff\xff\xff\xff\xff\xff\xff\xff"
593 "\xff\xff\xff\xff\xff\xff\xff\xff");
594 crypto_cipher_crypt_inplace(env1
, data2
, 64);
595 test_memeq_hex(data2
, "2aed2bff0de54f9328efd070bf48f70a"
596 "0EDD33D3C621E546455BD8BA1418BEC8"
597 "93e2c5243d6839eac58503919192f7ae"
598 "1908e67cafa08d508816659c2e693191");
599 crypto_cipher_set_iv(env1
, "\xff\xff\xff\xff\xff\xff\xff\xff"
600 "\xff\xff\xff\xff\xff\xff\xff\xff");
601 crypto_cipher_crypt_inplace(env1
, data2
, 64);
602 test_assert(tor_mem_is_zero(data2
, 64));
606 crypto_free_cipher_env(env1
);
608 crypto_free_cipher_env(env2
);
614 /** Run unit tests for our SHA-1 functionality */
616 test_crypto_sha(void)
618 crypto_digest_env_t
*d1
= NULL
, *d2
= NULL
;
623 char d_out1
[DIGEST_LEN
], d_out2
[DIGEST_LEN
];
625 /* Test SHA-1 with a test vector from the specification. */
626 i
= crypto_digest(data
, "abc", 3);
627 test_memeq_hex(data
, "A9993E364706816ABA3E25717850C26C9CD0D89D");
629 /* Test HMAC-SHA-1 with test cases from RFC2202. */
632 memset(key
, 0x0b, 20);
633 crypto_hmac_sha1(digest
, key
, 20, "Hi There", 8);
634 test_streq(hex_str(digest
, 20),
635 "B617318655057264E28BC0B6FB378C8EF146BE00");
637 crypto_hmac_sha1(digest
, "Jefe", 4, "what do ya want for nothing?", 28);
638 test_streq(hex_str(digest
, 20),
639 "EFFCDF6AE5EB2FA2D27416D5F184DF9C259A7C79");
642 base16_decode(key
, 25,
643 "0102030405060708090a0b0c0d0e0f10111213141516171819", 50);
644 memset(data
, 0xcd, 50);
645 crypto_hmac_sha1(digest
, key
, 25, data
, 50);
646 test_streq(hex_str(digest
, 20),
647 "4C9007F4026250C6BC8414F9BF50C86C2D7235DA");
650 memset(key
, 0xaa, 80);
651 crypto_hmac_sha1(digest
, key
, 80,
652 "Test Using Larger Than Block-Size Key - Hash Key First",
654 test_streq(hex_str(digest
, 20),
655 "AA4AE5E15272D00E95705637CE8A3B55ED402112");
657 /* Incremental digest code. */
658 d1
= crypto_new_digest_env();
660 crypto_digest_add_bytes(d1
, "abcdef", 6);
661 d2
= crypto_digest_dup(d1
);
663 crypto_digest_add_bytes(d2
, "ghijkl", 6);
664 crypto_digest_get_digest(d2
, d_out1
, sizeof(d_out1
));
665 crypto_digest(d_out2
, "abcdefghijkl", 12);
666 test_memeq(d_out1
, d_out2
, DIGEST_LEN
);
667 crypto_digest_assign(d2
, d1
);
668 crypto_digest_add_bytes(d2
, "mno", 3);
669 crypto_digest_get_digest(d2
, d_out1
, sizeof(d_out1
));
670 crypto_digest(d_out2
, "abcdefmno", 9);
671 test_memeq(d_out1
, d_out2
, DIGEST_LEN
);
672 crypto_digest_get_digest(d1
, d_out1
, sizeof(d_out1
));
673 crypto_digest(d_out2
, "abcdef", 6);
674 test_memeq(d_out1
, d_out2
, DIGEST_LEN
);
678 crypto_free_digest_env(d1
);
680 crypto_free_digest_env(d2
);
683 /** Run unit tests for our public key crypto functions */
687 crypto_pk_env_t
*pk1
= NULL
, *pk2
= NULL
;
688 char *encoded
= NULL
;
689 char data1
[1024], data2
[1024], data3
[1024];
693 /* Public-key ciphers */
694 pk1
= pk_generate(0);
695 pk2
= crypto_new_pk_env();
696 test_assert(pk1
&& pk2
);
697 test_assert(! crypto_pk_write_public_key_to_string(pk1
, &encoded
, &size
));
698 test_assert(! crypto_pk_read_public_key_from_string(pk2
, encoded
, size
));
699 test_eq(0, crypto_pk_cmp_keys(pk1
, pk2
));
701 test_eq(128, crypto_pk_keysize(pk1
));
702 test_eq(128, crypto_pk_keysize(pk2
));
704 test_eq(128, crypto_pk_public_encrypt(pk2
, data1
, sizeof(data1
),
705 "Hello whirled.", 15,
706 PK_PKCS1_OAEP_PADDING
));
707 test_eq(128, crypto_pk_public_encrypt(pk1
, data2
, sizeof(data2
),
708 "Hello whirled.", 15,
709 PK_PKCS1_OAEP_PADDING
));
710 /* oaep padding should make encryption not match */
711 test_memneq(data1
, data2
, 128);
712 test_eq(15, crypto_pk_private_decrypt(pk1
, data3
, sizeof(data3
), data1
, 128,
713 PK_PKCS1_OAEP_PADDING
,1));
714 test_streq(data3
, "Hello whirled.");
715 memset(data3
, 0, 1024);
716 test_eq(15, crypto_pk_private_decrypt(pk1
, data3
, sizeof(data3
), data2
, 128,
717 PK_PKCS1_OAEP_PADDING
,1));
718 test_streq(data3
, "Hello whirled.");
719 /* Can't decrypt with public key. */
720 test_eq(-1, crypto_pk_private_decrypt(pk2
, data3
, sizeof(data3
), data2
, 128,
721 PK_PKCS1_OAEP_PADDING
,1));
722 /* Try again with bad padding */
723 memcpy(data2
+1, "XYZZY", 5); /* This has fails ~ once-in-2^40 */
724 test_eq(-1, crypto_pk_private_decrypt(pk1
, data3
, sizeof(data3
), data2
, 128,
725 PK_PKCS1_OAEP_PADDING
,1));
727 /* File operations: save and load private key */
728 test_assert(! crypto_pk_write_private_key_to_filename(pk1
,
729 get_fname("pkey1")));
730 /* failing case for read: can't read. */
731 test_assert(crypto_pk_read_private_key_from_filename(pk2
,
732 get_fname("xyzzy")) < 0);
733 write_str_to_file(get_fname("xyzzy"), "foobar", 6);
734 /* Failing case for read: no key. */
735 test_assert(crypto_pk_read_private_key_from_filename(pk2
,
736 get_fname("xyzzy")) < 0);
737 test_assert(! crypto_pk_read_private_key_from_filename(pk2
,
738 get_fname("pkey1")));
739 test_eq(15, crypto_pk_private_decrypt(pk2
, data3
, sizeof(data3
), data1
, 128,
740 PK_PKCS1_OAEP_PADDING
,1));
742 /* Now try signing. */
743 strlcpy(data1
, "Ossifrage", 1024);
744 test_eq(128, crypto_pk_private_sign(pk1
, data2
, sizeof(data2
), data1
, 10));
745 test_eq(10, crypto_pk_public_checksig(pk1
, data3
, sizeof(data3
), data2
, 128));
746 test_streq(data3
, "Ossifrage");
747 /* Try signing digests. */
748 test_eq(128, crypto_pk_private_sign_digest(pk1
, data2
, sizeof(data2
),
750 test_eq(20, crypto_pk_public_checksig(pk1
, data3
, sizeof(data1
), data2
, 128));
751 test_eq(0, crypto_pk_public_checksig_digest(pk1
, data1
,
753 test_eq(-1, crypto_pk_public_checksig_digest(pk1
, data1
,
755 /*XXXX test failed signing*/
758 crypto_free_pk_env(pk2
);
760 i
= crypto_pk_asn1_encode(pk1
, data1
, 1024);
762 pk2
= crypto_pk_asn1_decode(data1
, i
);
763 test_assert(crypto_pk_cmp_keys(pk1
,pk2
) == 0);
765 /* Try with hybrid encryption wrappers. */
766 crypto_rand(data1
, 1024);
767 for (i
= 0; i
< 3; ++i
) {
768 for (j
= 85; j
< 140; ++j
) {
769 memset(data2
,0,1024);
770 memset(data3
,0,1024);
771 if (i
== 0 && j
< 129)
773 p
= (i
==0)?PK_NO_PADDING
:
774 (i
==1)?PK_PKCS1_PADDING
:PK_PKCS1_OAEP_PADDING
;
775 len
= crypto_pk_public_hybrid_encrypt(pk1
,data2
,sizeof(data2
),
778 len
= crypto_pk_private_hybrid_decrypt(pk1
,data3
,sizeof(data3
),
781 test_memeq(data1
,data3
,j
);
786 crypto_free_pk_env(pk2
);
787 pk2
= crypto_pk_copy_full(pk1
);
788 test_assert(pk2
!= NULL
);
789 test_neq_ptr(pk1
, pk2
);
790 test_assert(crypto_pk_cmp_keys(pk1
,pk2
) == 0);
794 crypto_free_pk_env(pk1
);
796 crypto_free_pk_env(pk2
);
800 /** Run unit tests for misc crypto functionality. */
804 char *data1
= NULL
, *data2
= NULL
, *data3
= NULL
;
807 data1
= tor_malloc(1024);
808 data2
= tor_malloc(1024);
809 data3
= tor_malloc(1024);
810 test_assert(data1
&& data2
&& data3
);
813 memset(data1
, 6, 1024);
814 for (idx
= 0; idx
< 10; ++idx
) {
815 i
= base64_encode(data2
, 1024, data1
, idx
);
817 j
= base64_decode(data3
, 1024, data2
, i
);
819 test_memeq(data3
, data1
, idx
);
822 strlcpy(data1
, "Test string that contains 35 chars.", 1024);
823 strlcat(data1
, " 2nd string that contains 35 chars.", 1024);
825 i
= base64_encode(data2
, 1024, data1
, 71);
826 j
= base64_decode(data3
, 1024, data2
, i
);
828 test_streq(data3
, data1
);
829 test_assert(data2
[i
] == '\0');
831 crypto_rand(data1
, DIGEST_LEN
);
832 memset(data2
, 100, 1024);
833 digest_to_base64(data2
, data1
);
834 test_eq(BASE64_DIGEST_LEN
, strlen(data2
));
835 test_eq(100, data2
[BASE64_DIGEST_LEN
+2]);
836 memset(data3
, 99, 1024);
837 test_eq(digest_from_base64(data3
, data2
), 0);
838 test_memeq(data1
, data3
, DIGEST_LEN
);
839 test_eq(99, data3
[DIGEST_LEN
+1]);
841 test_assert(digest_from_base64(data3
, "###") < 0);
844 strlcpy(data1
, "5chrs", 1024);
845 /* bit pattern is: [35 63 68 72 73] ->
846 * [00110101 01100011 01101000 01110010 01110011]
847 * By 5s: [00110 10101 10001 10110 10000 11100 10011 10011]
849 base32_encode(data2
, 9, data1
, 5);
850 test_streq(data2
, "gvrwq4tt");
852 strlcpy(data1
, "\xFF\xF5\x6D\x44\xAE\x0D\x5C\xC9\x62\xC4", 1024);
853 base32_encode(data2
, 30, data1
, 10);
854 test_streq(data2
, "772w2rfobvomsywe");
857 strlcpy(data1
, "6chrs\xff", 1024);
858 base16_encode(data2
, 13, data1
, 6);
859 test_streq(data2
, "3663687273FF");
861 strlcpy(data1
, "f0d678affc000100", 1024);
862 i
= base16_decode(data2
, 8, data1
, 16);
864 test_memeq(data2
, "\xf0\xd6\x78\xaf\xfc\x00\x01\x00",8);
866 /* now try some failing base16 decodes */
867 test_eq(-1, base16_decode(data2
, 8, data1
, 15)); /* odd input len */
868 test_eq(-1, base16_decode(data2
, 7, data1
, 16)); /* dest too short */
869 strlcpy(data1
, "f0dz!8affc000100", 1024);
870 test_eq(-1, base16_decode(data2
, 8, data1
, 16));
876 /* Add spaces to fingerprint */
878 data1
= tor_strdup("ABCD1234ABCD56780000ABCD1234ABCD56780000");
879 test_eq(strlen(data1
), 40);
880 data2
= tor_malloc(FINGERPRINT_LEN
+1);
881 add_spaces_to_fp(data2
, FINGERPRINT_LEN
+1, data1
);
882 test_streq(data2
, "ABCD 1234 ABCD 5678 0000 ABCD 1234 ABCD 5678 0000");
887 /* Check fingerprint */
889 test_assert(crypto_pk_check_fingerprint_syntax(
890 "ABCD 1234 ABCD 5678 0000 ABCD 1234 ABCD 5678 0000"));
891 test_assert(!crypto_pk_check_fingerprint_syntax(
892 "ABCD 1234 ABCD 5678 0000 ABCD 1234 ABCD 5678 000"));
893 test_assert(!crypto_pk_check_fingerprint_syntax(
894 "ABCD 1234 ABCD 5678 0000 ABCD 1234 ABCD 5678 00000"));
895 test_assert(!crypto_pk_check_fingerprint_syntax(
896 "ABCD 1234 ABCD 5678 0000 ABCD1234 ABCD 5678 0000"));
897 test_assert(!crypto_pk_check_fingerprint_syntax(
898 "ABCD 1234 ABCD 5678 0000 ABCD1234 ABCD 5678 00000"));
899 test_assert(!crypto_pk_check_fingerprint_syntax(
900 "ACD 1234 ABCD 5678 0000 ABCD 1234 ABCD 5678 00000"));
909 /** Run unit tests for our secret-to-key passphrase hashing functionality. */
911 test_crypto_s2k(void)
918 memset(buf
, 0, sizeof(buf
));
919 memset(buf2
, 0, sizeof(buf2
));
920 buf3
= tor_malloc(65536);
921 memset(buf3
, 0, 65536);
923 secret_to_key(buf
+9, 20, "", 0, buf
);
924 crypto_digest(buf2
+9, buf3
, 1024);
925 test_memeq(buf
, buf2
, 29);
927 memcpy(buf
,"vrbacrda",8);
928 memcpy(buf2
,"vrbacrda",8);
931 secret_to_key(buf
+9, 20, "12345678", 8, buf
);
932 for (i
= 0; i
< 65536; i
+= 16) {
933 memcpy(buf3
+i
, "vrbacrda12345678", 16);
935 crypto_digest(buf2
+9, buf3
, 65536);
936 test_memeq(buf
, buf2
, 29);
942 /** Helper: return a tristate based on comparing the strings in *<b>a</b> and
945 _compare_strs(const void **a
, const void **b
)
947 const char *s1
= *a
, *s2
= *b
;
948 return strcmp(s1
, s2
);
951 /** Helper: return a tristate based on comparing the strings in *<b>a</b> and
952 * *<b>b</b>, excluding a's first character, and ignoring case. */
954 _compare_without_first_ch(const void *a
, const void **b
)
956 const char *s1
= a
, *s2
= *b
;
957 return strcasecmp(s1
+1, s2
);
960 /** Test basic utility functionality. */
964 struct timeval start
, end
;
966 char timestr
[RFC1123_TIME_LEN
+1];
976 start
.tv_usec
= 5000;
981 test_eq(0L, tv_udiff(&start
, &end
));
985 test_eq(2000L, tv_udiff(&start
, &end
));
989 test_eq(1002000L, tv_udiff(&start
, &end
));
993 test_eq(995000L, tv_udiff(&start
, &end
));
997 test_eq(-1005000L, tv_udiff(&start
, &end
));
999 end
.tv_usec
= 999990;
1001 start
.tv_usec
= 500;
1003 /* The test values here are confirmed to be correct on a platform
1004 * with a working timegm. */
1005 a_time
.tm_year
= 2003-1900;
1007 a_time
.tm_mday
= 30;
1011 test_eq((time_t) 1062224095UL, tor_timegm(&a_time
));
1012 a_time
.tm_year
= 2004-1900; /* Try a leap year, after feb. */
1013 test_eq((time_t) 1093846495UL, tor_timegm(&a_time
));
1014 a_time
.tm_mon
= 1; /* Try a leap year, in feb. */
1015 a_time
.tm_mday
= 10;
1016 test_eq((time_t) 1076393695UL, tor_timegm(&a_time
));
1018 format_rfc1123_time(timestr
, 0);
1019 test_streq("Thu, 01 Jan 1970 00:00:00 GMT", timestr
);
1020 format_rfc1123_time(timestr
, (time_t)1091580502UL);
1021 test_streq("Wed, 04 Aug 2004 00:48:22 GMT", timestr
);
1024 i
= parse_rfc1123_time(timestr
, &t_res
);
1026 test_eq(t_res
, (time_t)1091580502UL);
1027 test_eq(-1, parse_rfc1123_time("Wed, zz Aug 2004 99-99x99 GMT", &t_res
));
1028 tor_gettimeofday(&start
);
1030 /* Tests for corner cases of strl operations */
1031 test_eq(5, strlcpy(buf
, "Hello", 0));
1032 strlcpy(buf
, "Hello", sizeof(buf
));
1033 test_eq(10, strlcat(buf
, "Hello", 5));
1035 /* Test tor_strstrip() */
1036 strlcpy(buf
, "Testing 1 2 3", sizeof(buf
));
1037 tor_strstrip(buf
, ",!");
1038 test_streq(buf
, "Testing 1 2 3");
1039 strlcpy(buf
, "!Testing 1 2 3?", sizeof(buf
));
1040 tor_strstrip(buf
, "!? ");
1041 test_streq(buf
, "Testing123");
1043 /* Test parse_addr_port */
1044 cp
= NULL
; u32
= 3; u16
= 3;
1045 test_assert(!parse_addr_port(LOG_WARN
, "1.2.3.4", &cp
, &u32
, &u16
));
1046 test_streq(cp
, "1.2.3.4");
1047 test_eq(u32
, 0x01020304u
);
1050 test_assert(!parse_addr_port(LOG_WARN
, "4.3.2.1:99", &cp
, &u32
, &u16
));
1051 test_streq(cp
, "4.3.2.1");
1052 test_eq(u32
, 0x04030201u
);
1055 test_assert(!parse_addr_port(LOG_WARN
, "nonexistent.address:4040",
1057 test_streq(cp
, "nonexistent.address");
1060 test_assert(!parse_addr_port(LOG_WARN
, "localhost:9999", &cp
, &u32
, &u16
));
1061 test_streq(cp
, "localhost");
1062 test_eq(u32
, 0x7f000001u
);
1066 test_assert(!parse_addr_port(LOG_WARN
, "localhost", NULL
, &u32
, &u16
));
1068 test_eq(u32
, 0x7f000001u
);
1071 test_eq(0, addr_mask_get_bits(0x0u
));
1072 test_eq(32, addr_mask_get_bits(0xFFFFFFFFu
));
1073 test_eq(16, addr_mask_get_bits(0xFFFF0000u
));
1074 test_eq(31, addr_mask_get_bits(0xFFFFFFFEu
));
1075 test_eq(1, addr_mask_get_bits(0x80000000u
));
1077 /* Test tor_parse_long. */
1078 test_eq(10L, tor_parse_long("10",10,0,100,NULL
,NULL
));
1079 test_eq(0L, tor_parse_long("10",10,50,100,NULL
,NULL
));
1080 test_eq(-50L, tor_parse_long("-50",10,-100,100,NULL
,NULL
));
1082 /* Test tor_parse_ulong */
1083 test_eq(10UL, tor_parse_ulong("10",10,0,100,NULL
,NULL
));
1084 test_eq(0UL, tor_parse_ulong("10",10,50,100,NULL
,NULL
));
1086 /* Test tor_parse_uint64. */
1087 test_assert(U64_LITERAL(10) == tor_parse_uint64("10 x",10,0,100, &i
, &cp
));
1088 test_assert(i
== 1);
1089 test_streq(cp
, " x");
1090 test_assert(U64_LITERAL(12345678901) ==
1091 tor_parse_uint64("12345678901",10,0,UINT64_MAX
, &i
, &cp
));
1092 test_assert(i
== 1);
1094 test_assert(U64_LITERAL(0) ==
1095 tor_parse_uint64("12345678901",10,500,INT32_MAX
, &i
, &cp
));
1096 test_assert(i
== 0);
1098 /* Test failing snprintf cases */
1099 test_eq(-1, tor_snprintf(buf
, 0, "Foo"));
1100 test_eq(-1, tor_snprintf(buf
, 2, "Foo"));
1102 /* Test printf with uint64 */
1103 tor_snprintf(buf
, sizeof(buf
), "x!"U64_FORMAT
"!x",
1104 U64_PRINTF_ARG(U64_LITERAL(12345678901)));
1105 test_streq(buf
, "x!12345678901!x");
1107 /* Test parse_config_line_from_str */
1108 strlcpy(buf
, "k v\n" " key value with spaces \n" "keykey val\n"
1110 "k3 \n" "\n" " \n" "#comment\n"
1111 "k4#a\n" "k5#abc\n" "k6 val #with comment\n"
1112 "kseven \"a quoted 'string\"\n"
1113 "k8 \"a \\x71uoted\\n\\\"str\\\\ing\\t\\001\\01\\1\\\"\"\n"
1117 str
= parse_config_line_from_str(str
, &k
, &v
);
1120 tor_free(k
); tor_free(v
);
1121 test_assert(!strcmpstart(str
, "key value with"));
1123 str
= parse_config_line_from_str(str
, &k
, &v
);
1124 test_streq(k
, "key");
1125 test_streq(v
, "value with spaces");
1126 tor_free(k
); tor_free(v
);
1127 test_assert(!strcmpstart(str
, "keykey"));
1129 str
= parse_config_line_from_str(str
, &k
, &v
);
1130 test_streq(k
, "keykey");
1131 test_streq(v
, "val");
1132 tor_free(k
); tor_free(v
);
1133 test_assert(!strcmpstart(str
, "k2\n"));
1135 str
= parse_config_line_from_str(str
, &k
, &v
);
1136 test_streq(k
, "k2");
1138 tor_free(k
); tor_free(v
);
1139 test_assert(!strcmpstart(str
, "k3 \n"));
1141 str
= parse_config_line_from_str(str
, &k
, &v
);
1142 test_streq(k
, "k3");
1144 tor_free(k
); tor_free(v
);
1145 test_assert(!strcmpstart(str
, "#comment"));
1147 str
= parse_config_line_from_str(str
, &k
, &v
);
1148 test_streq(k
, "k4");
1150 tor_free(k
); tor_free(v
);
1151 test_assert(!strcmpstart(str
, "k5#abc"));
1153 str
= parse_config_line_from_str(str
, &k
, &v
);
1154 test_streq(k
, "k5");
1156 tor_free(k
); tor_free(v
);
1157 test_assert(!strcmpstart(str
, "k6"));
1159 str
= parse_config_line_from_str(str
, &k
, &v
);
1160 test_streq(k
, "k6");
1161 test_streq(v
, "val");
1162 tor_free(k
); tor_free(v
);
1163 test_assert(!strcmpstart(str
, "kseven"));
1165 str
= parse_config_line_from_str(str
, &k
, &v
);
1166 test_streq(k
, "kseven");
1167 test_streq(v
, "a quoted \'string");
1168 tor_free(k
); tor_free(v
);
1169 test_assert(!strcmpstart(str
, "k8 "));
1171 str
= parse_config_line_from_str(str
, &k
, &v
);
1172 test_streq(k
, "k8");
1173 test_streq(v
, "a quoted\n\"str\\ing\t\x01\x01\x01\"");
1174 tor_free(k
); tor_free(v
);
1175 test_streq(str
, "");
1177 /* Test for strcmpstart and strcmpend. */
1178 test_assert(strcmpstart("abcdef", "abcdef")==0);
1179 test_assert(strcmpstart("abcdef", "abc")==0);
1180 test_assert(strcmpstart("abcdef", "abd")<0);
1181 test_assert(strcmpstart("abcdef", "abb")>0);
1182 test_assert(strcmpstart("ab", "abb")<0);
1184 test_assert(strcmpend("abcdef", "abcdef")==0);
1185 test_assert(strcmpend("abcdef", "def")==0);
1186 test_assert(strcmpend("abcdef", "deg")<0);
1187 test_assert(strcmpend("abcdef", "dee")>0);
1188 test_assert(strcmpend("ab", "abb")<0);
1190 test_assert(strcasecmpend("AbcDEF", "abcdef")==0);
1191 test_assert(strcasecmpend("abcdef", "dEF")==0);
1192 test_assert(strcasecmpend("abcDEf", "deg")<0);
1193 test_assert(strcasecmpend("abcdef", "DEE")>0);
1194 test_assert(strcasecmpend("ab", "abB")<0);
1196 /* Test mem_is_zero */
1199 test_assert(tor_digest_is_zero(buf
));
1200 test_assert(tor_mem_is_zero(buf
, 10));
1201 test_assert(tor_mem_is_zero(buf
, 20));
1202 test_assert(tor_mem_is_zero(buf
, 128));
1203 test_assert(!tor_mem_is_zero(buf
, 129));
1204 buf
[60] = (char)255;
1205 test_assert(!tor_mem_is_zero(buf
, 128));
1207 test_assert(!tor_mem_is_zero(buf
, 10));
1209 /* Test inet_ntop */
1211 char tmpbuf
[TOR_ADDR_BUF_LEN
];
1212 const char *ip
= "176.192.208.224";
1214 tor_inet_pton(AF_INET
, ip
, &in
);
1215 tor_inet_ntop(AF_INET
, &in
, tmpbuf
, sizeof(tmpbuf
));
1216 test_streq(tmpbuf
, ip
);
1219 /* Test 'escaped' */
1220 test_streq("\"\"", escaped(""));
1221 test_streq("\"abcd\"", escaped("abcd"));
1222 test_streq("\"\\\\\\n\\r\\t\\\"\\'\"", escaped("\\\n\r\t\"\'"));
1223 test_streq("\"z\\001abc\\277d\"", escaped("z\001abc\277d"));
1224 test_assert(NULL
== escaped(NULL
));
1226 /* Test strndup and memdup */
1228 const char *s
= "abcdefghijklmnopqrstuvwxyz";
1229 cp
= tor_strndup(s
, 30);
1230 test_streq(cp
, s
); /* same string, */
1231 test_neq(cp
, s
); /* but different pointers. */
1234 cp
= tor_strndup(s
, 5);
1235 test_streq(cp
, "abcde");
1238 s
= "a\0b\0c\0d\0e\0";
1239 cp
= tor_memdup(s
,10);
1240 test_memeq(cp
, s
, 10); /* same ram, */
1241 test_neq(cp
, s
); /* but different pointers. */
1245 /* Test str-foo functions */
1246 cp
= tor_strdup("abcdef");
1247 test_assert(tor_strisnonupper(cp
));
1249 test_assert(!tor_strisnonupper(cp
));
1251 test_streq(cp
, "ABCDEF");
1252 test_assert(tor_strisprint(cp
));
1254 test_assert(!tor_strisprint(cp
));
1257 /* Test eat_whitespace. */
1259 const char *s
= " \n a";
1260 test_eq_ptr(eat_whitespace(s
), s
+4);
1262 test_eq_ptr(eat_whitespace(s
), s
);
1264 test_eq_ptr(eat_whitespace(s
), s
+5);
1267 /* Test memmem and memstr */
1269 const char *haystack
= "abcde";
1270 tor_assert(!tor_memmem(haystack
, 5, "ef", 2));
1271 test_eq_ptr(tor_memmem(haystack
, 5, "cd", 2), haystack
+ 2);
1272 test_eq_ptr(tor_memmem(haystack
, 5, "cde", 3), haystack
+ 2);
1273 haystack
= "ababcad";
1274 test_eq_ptr(tor_memmem(haystack
, 7, "abc", 3), haystack
+ 2);
1275 test_eq_ptr(tor_memstr(haystack
, 7, "abc"), haystack
+ 2);
1276 test_assert(!tor_memstr(haystack
, 7, "fe"));
1277 test_assert(!tor_memstr(haystack
, 7, "longerthantheoriginal"));
1280 /* Test wrap_string */
1282 smartlist_t
*sl
= smartlist_create();
1283 wrap_string(sl
, "This is a test of string wrapping functionality: woot.",
1285 cp
= smartlist_join_strings(sl
, "", 0, NULL
);
1287 "This is a\ntest of\nstring\nwrapping\nfunctional\nity: woot.\n");
1289 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1290 smartlist_clear(sl
);
1292 wrap_string(sl
, "This is a test of string wrapping functionality: woot.",
1294 cp
= smartlist_join_strings(sl
, "", 0, NULL
);
1296 "### This is a\n# test of string\n# wrapping\n# functionality:\n"
1300 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1304 tor_gettimeofday(&start
);
1305 /* now make sure time works. */
1306 tor_gettimeofday(&end
);
1307 /* We might've timewarped a little. */
1308 test_assert(tv_udiff(&start
, &end
) >= -5000);
1310 /* Test tor_log2(). */
1311 test_eq(tor_log2(64), 6);
1312 test_eq(tor_log2(65), 6);
1313 test_eq(tor_log2(63), 5);
1314 test_eq(tor_log2(1), 0);
1315 test_eq(tor_log2(2), 1);
1316 test_eq(tor_log2(3), 1);
1317 test_eq(tor_log2(4), 2);
1318 test_eq(tor_log2(5), 2);
1319 test_eq(tor_log2(U64_LITERAL(40000000000000000)), 55);
1320 test_eq(tor_log2(UINT64_MAX
), 63);
1322 /* Test round_to_power_of_2 */
1323 test_eq(round_to_power_of_2(120), 128);
1324 test_eq(round_to_power_of_2(128), 128);
1325 test_eq(round_to_power_of_2(130), 128);
1326 test_eq(round_to_power_of_2(U64_LITERAL(40000000000000000)),
1327 U64_LITERAL(1)<<55);
1328 test_eq(round_to_power_of_2(0), 2);
1334 /** Helper: assert that IPv6 addresses <b>a</b> and <b>b</b> are the same. On
1335 * failure, reports an error, describing the addresses as <b>e1</b> and
1336 * <b>e2</b>, and reporting the line number as <b>line</b>. */
1338 _test_eq_ip6(struct in6_addr
*a
, struct in6_addr
*b
, const char *e1
,
1339 const char *e2
, int line
)
1343 for (i
= 0; i
< 16; ++i
) {
1344 if (a
->s6_addr
[i
] != b
->s6_addr
[i
]) {
1350 printf("."); fflush(stdout
);
1352 char buf1
[128], *cp1
;
1353 char buf2
[128], *cp2
;
1355 cp1
= buf1
; cp2
= buf2
;
1356 for (i
=0; i
<16; ++i
) {
1357 tor_snprintf(cp1
, sizeof(buf1
)-(cp1
-buf1
), "%02x", a
->s6_addr
[i
]);
1358 tor_snprintf(cp2
, sizeof(buf2
)-(cp2
-buf2
), "%02x", b
->s6_addr
[i
]);
1360 if ((i
%2)==1 && i
!= 15) {
1366 printf("Line %d: assertion failed: (%s == %s)\n"
1367 " %s != %s\n", line
, e1
, e2
, buf1
, buf2
);
1372 /** Helper: Assert that two strings both decode as IPv6 addresses with
1373 * tor_inet_pton(), and both decode to the same address. */
1374 #define test_pton6_same(a,b) STMT_BEGIN \
1375 test_eq(tor_inet_pton(AF_INET6, a, &a1), 1); \
1376 test_eq(tor_inet_pton(AF_INET6, b, &a2), 1); \
1377 _test_eq_ip6(&a1,&a2,#a,#b,__LINE__); \
1380 /** Helper: Assert that <b>a</b> is recognized as a bad IPv6 address by
1381 * tor_inet_pton(). */
1382 #define test_pton6_bad(a) \
1383 test_eq(0, tor_inet_pton(AF_INET6, a, &a1))
1385 /** Helper: assert that <b>a</b>, when parsed by tor_inet_pton() and displayed
1386 * with tor_inet_ntop(), yields <b>b</b>. Also assert that <b>b</b> parses to
1387 * the same value as <b>a</b>. */
1388 #define test_ntop6_reduces(a,b) STMT_BEGIN \
1389 test_eq(tor_inet_pton(AF_INET6, a, &a1), 1); \
1390 test_streq(tor_inet_ntop(AF_INET6, &a1, buf, sizeof(buf)), b); \
1391 test_eq(tor_inet_pton(AF_INET6, b, &a2), 1); \
1392 _test_eq_ip6(&a1, &a2, a, b, __LINE__); \
1395 /** Helper: assert that <b>a</b> parses by tor_inet_pton() into a address that
1396 * passes tor_addr_is_internal() with <b>for_listening</b>. */
1397 #define test_internal_ip(a,for_listening) STMT_BEGIN \
1398 test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
1399 t1.family = AF_INET6; \
1400 if (!tor_addr_is_internal(&t1, for_listening)) \
1401 test_fail_msg( a "was not internal."); \
1404 /** Helper: assert that <b>a</b> parses by tor_inet_pton() into a address that
1405 * does not pass tor_addr_is_internal() with <b>for_listening</b>. */
1406 #define test_external_ip(a,for_listening) STMT_BEGIN \
1407 test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
1408 t1.family = AF_INET6; \
1409 if (tor_addr_is_internal(&t1, for_listening)) \
1410 test_fail_msg(a "was not external."); \
1413 /** Helper: Assert that <b>a</b> and <b>b</b>, when parsed by
1414 * tor_inet_pton(), give addresses that compare in the order defined by
1415 * <b>op</b> with tor_addr_compare(). */
1416 #define test_addr_compare(a, op, b) STMT_BEGIN \
1417 test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
1418 test_eq(tor_inet_pton(AF_INET6, b, &t2.addr.in6_addr), 1); \
1419 t1.family = t2.family = AF_INET6; \
1420 r = tor_addr_compare(&t1,&t2,CMP_SEMANTIC); \
1422 test_fail_msg("failed: tor_addr_compare("a","b") "#op" 0"); \
1425 /** Helper: Assert that <b>a</b> and <b>b</b>, when parsed by
1426 * tor_inet_pton(), give addresses that compare in the order defined by
1427 * <b>op</b> with tor_addr_compare_masked() with <b>m</b> masked. */
1428 #define test_addr_compare_masked(a, op, b, m) STMT_BEGIN \
1429 test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
1430 test_eq(tor_inet_pton(AF_INET6, b, &t2.addr.in6_addr), 1); \
1431 t1.family = t2.family = AF_INET6; \
1432 r = tor_addr_compare_masked(&t1,&t2,m,CMP_SEMANTIC); \
1434 test_fail_msg("failed: tor_addr_compare_masked("a","b","#m") "#op" 0"); \
1437 /** Helper: assert that <b>xx</b> is parseable as a masked IPv6 address with
1438 * ports by tor_parse_mask_addr_ports(), with family <b>f</b>, IP address
1439 * as 4 32-bit words <b>ip1...ip4</b>, mask bits as <b>mm</b>, and port range
1440 * as <b>pt1..pt2</b>. */
1441 #define test_addr_mask_ports_parse(xx, f, ip1, ip2, ip3, ip4, mm, pt1, pt2) \
1443 test_eq(tor_addr_parse_mask_ports(xx, &t1, &mask, &port1, &port2), f); \
1444 p1=tor_inet_ntop(AF_INET6, &t1.addr.in6_addr, bug, sizeof(bug)); \
1445 test_eq(htonl(ip1), tor_addr_to_in6_addr32(&t1)[0]); \
1446 test_eq(htonl(ip2), tor_addr_to_in6_addr32(&t1)[1]); \
1447 test_eq(htonl(ip3), tor_addr_to_in6_addr32(&t1)[2]); \
1448 test_eq(htonl(ip4), tor_addr_to_in6_addr32(&t1)[3]); \
1449 test_eq(mask, mm); \
1450 test_eq(port1, pt1); \
1451 test_eq(port2, pt2); \
1454 /** Run unit tests for IPv6 encoding/decoding/manipulation functions. */
1456 test_util_ip6_helpers(void)
1458 char buf
[TOR_ADDR_BUF_LEN
], bug
[TOR_ADDR_BUF_LEN
];
1459 struct in6_addr a1
, a2
;
1462 uint16_t port1
, port2
;
1465 struct sockaddr_storage sa_storage
;
1466 struct sockaddr_in
*sin
;
1467 struct sockaddr_in6
*sin6
;
1469 // struct in_addr b1, b2;
1470 /* Test tor_inet_ntop and tor_inet_pton: IPv6 */
1472 /* ==== Converting to and from sockaddr_t. */
1473 sin
= (struct sockaddr_in
*)&sa_storage
;
1474 sin
->sin_family
= AF_INET
;
1475 sin
->sin_port
= 9090;
1476 sin
->sin_addr
.s_addr
= htonl(0x7f7f0102); /*127.127.1.2*/
1477 tor_addr_from_sockaddr(&t1
, (struct sockaddr
*)sin
, NULL
);
1478 test_eq(tor_addr_family(&t1
), AF_INET
);
1479 test_eq(tor_addr_to_ipv4h(&t1
), 0x7f7f0102);
1481 memset(&sa_storage
, 0, sizeof(sa_storage
));
1482 test_eq(sizeof(struct sockaddr_in
),
1483 tor_addr_to_sockaddr(&t1
, 1234, (struct sockaddr
*)&sa_storage
,
1484 sizeof(sa_storage
)));
1485 test_eq(1234, ntohs(sin
->sin_port
));
1486 test_eq(0x7f7f0102, ntohl(sin
->sin_addr
.s_addr
));
1488 memset(&sa_storage
, 0, sizeof(sa_storage
));
1489 sin6
= (struct sockaddr_in6
*)&sa_storage
;
1490 sin6
->sin6_family
= AF_INET6
;
1491 sin6
->sin6_port
= htons(7070);
1492 sin6
->sin6_addr
.s6_addr
[0] = 128;
1493 tor_addr_from_sockaddr(&t1
, (struct sockaddr
*)sin6
, NULL
);
1494 test_eq(tor_addr_family(&t1
), AF_INET6
);
1495 p1
= tor_addr_to_str(buf
, &t1
, sizeof(buf
), 0);
1496 test_streq(p1
, "8000::");
1498 memset(&sa_storage
, 0, sizeof(sa_storage
));
1499 test_eq(sizeof(struct sockaddr_in6
),
1500 tor_addr_to_sockaddr(&t1
, 9999, (struct sockaddr
*)&sa_storage
,
1501 sizeof(sa_storage
)));
1502 test_eq(AF_INET6
, sin6
->sin6_family
);
1503 test_eq(9999, ntohs(sin6
->sin6_port
));
1504 test_eq(0x80000000, ntohl(S6_ADDR32(sin6
->sin6_addr
)[0]));
1506 /* ==== tor_addr_lookup: static cases. (Can't test dns without knowing we
1507 * have a good resolver. */
1508 test_eq(0, tor_addr_lookup("127.128.129.130", AF_UNSPEC
, &t1
));
1509 test_eq(AF_INET
, tor_addr_family(&t1
));
1510 test_eq(tor_addr_to_ipv4h(&t1
), 0x7f808182);
1512 test_eq(0, tor_addr_lookup("9000::5", AF_UNSPEC
, &t1
));
1513 test_eq(AF_INET6
, tor_addr_family(&t1
));
1514 test_eq(0x90, tor_addr_to_in6_addr8(&t1
)[0]);
1515 test_assert(tor_mem_is_zero((char*)tor_addr_to_in6_addr8(&t1
)+1, 14));
1516 test_eq(0x05, tor_addr_to_in6_addr8(&t1
)[15]);
1518 /* === Test pton: valid af_inet6 */
1519 /* Simple, valid parsing. */
1520 r
= tor_inet_pton(AF_INET6
,
1521 "0102:0304:0506:0708:090A:0B0C:0D0E:0F10", &a1
);
1523 for (i
=0;i
<16;++i
) { test_eq(i
+1, (int)a1
.s6_addr
[i
]); }
1525 test_pton6_same("0102:0304:0506:0708:090A:0B0C:0D0E:0F10",
1526 "0102:0304:0506:0708:090A:0B0C:13.14.15.16");
1527 /* shortened words. */
1528 test_pton6_same("0001:0099:BEEF:0000:0123:FFFF:0001:0001",
1529 "1:99:BEEF:0:0123:FFFF:1:1");
1530 /* zeros at the beginning */
1531 test_pton6_same("0000:0000:0000:0000:0009:C0A8:0001:0001",
1533 test_pton6_same("0000:0000:0000:0000:0009:C0A8:0001:0001",
1534 "::9:c0a8:0.1.0.1");
1535 /* zeros in the middle. */
1536 test_pton6_same("fe80:0000:0000:0000:0202:1111:0001:0001",
1537 "fe80::202:1111:1:1");
1538 /* zeros at the end. */
1539 test_pton6_same("1000:0001:0000:0007:0000:0000:0000:0000",
1542 /* === Test ntop: af_inet6 */
1543 test_ntop6_reduces("0:0:0:0:0:0:0:0", "::");
1545 test_ntop6_reduces("0001:0099:BEEF:0006:0123:FFFF:0001:0001",
1546 "1:99:beef:6:123:ffff:1:1");
1548 //test_ntop6_reduces("0:0:0:0:0:0:c0a8:0101", "::192.168.1.1");
1549 test_ntop6_reduces("0:0:0:0:0:ffff:c0a8:0101", "::ffff:192.168.1.1");
1550 test_ntop6_reduces("002:0:0000:0:3::4", "2::3:0:0:4");
1551 test_ntop6_reduces("0:0::1:0:3", "::1:0:3");
1552 test_ntop6_reduces("008:0::0", "8::");
1553 test_ntop6_reduces("0:0:0:0:0:ffff::1", "::ffff:0.0.0.1");
1554 test_ntop6_reduces("abcd:0:0:0:0:0:7f00::", "abcd::7f00:0");
1555 test_ntop6_reduces("0000:0000:0000:0000:0009:C0A8:0001:0001",
1557 test_ntop6_reduces("fe80:0000:0000:0000:0202:1111:0001:0001",
1558 "fe80::202:1111:1:1");
1559 test_ntop6_reduces("1000:0001:0000:0007:0000:0000:0000:0000",
1562 /* === Test pton: invalid in6. */
1563 test_pton6_bad("foobar.");
1564 test_pton6_bad("55555::");
1565 test_pton6_bad("9:-60::");
1566 test_pton6_bad("1:2:33333:4:0002:3::");
1567 //test_pton6_bad("1:2:3333:4:00002:3::");// BAD, but glibc doesn't say so.
1568 test_pton6_bad("1:2:3333:4:fish:3::");
1569 test_pton6_bad("1:2:3:4:5:6:7:8:9");
1570 test_pton6_bad("1:2:3:4:5:6:7");
1571 test_pton6_bad("1:2:3:4:5:6:1.2.3.4.5");
1572 test_pton6_bad("1:2:3:4:5:6:1.2.3");
1573 test_pton6_bad("::1.2.3");
1574 test_pton6_bad("::1.2.3.4.5");
1575 test_pton6_bad("99");
1577 test_pton6_bad("1::2::3:4");
1578 test_pton6_bad("a:::b:c");
1579 test_pton6_bad(":::a:b:c");
1580 test_pton6_bad("a:b:c:::");
1582 /* test internal checking */
1583 test_external_ip("fbff:ffff::2:7", 0);
1584 test_internal_ip("fc01::2:7", 0);
1585 test_internal_ip("fdff:ffff::f:f", 0);
1586 test_external_ip("fe00::3:f", 0);
1588 test_external_ip("fe7f:ffff::2:7", 0);
1589 test_internal_ip("fe80::2:7", 0);
1590 test_internal_ip("febf:ffff::f:f", 0);
1592 test_internal_ip("fec0::2:7:7", 0);
1593 test_internal_ip("feff:ffff::e:7:7", 0);
1594 test_external_ip("ff00::e:7:7", 0);
1596 test_internal_ip("::", 0);
1597 test_internal_ip("::1", 0);
1598 test_internal_ip("::1", 1);
1599 test_internal_ip("::", 0);
1600 test_external_ip("::", 1);
1601 test_external_ip("::2", 0);
1602 test_external_ip("2001::", 0);
1603 test_external_ip("ffff::", 0);
1605 test_external_ip("::ffff:0.0.0.0", 1);
1606 test_internal_ip("::ffff:0.0.0.0", 0);
1607 test_internal_ip("::ffff:0.255.255.255", 0);
1608 test_external_ip("::ffff:1.0.0.0", 0);
1610 test_external_ip("::ffff:9.255.255.255", 0);
1611 test_internal_ip("::ffff:10.0.0.0", 0);
1612 test_internal_ip("::ffff:10.255.255.255", 0);
1613 test_external_ip("::ffff:11.0.0.0", 0);
1615 test_external_ip("::ffff:126.255.255.255", 0);
1616 test_internal_ip("::ffff:127.0.0.0", 0);
1617 test_internal_ip("::ffff:127.255.255.255", 0);
1618 test_external_ip("::ffff:128.0.0.0", 0);
1620 test_external_ip("::ffff:172.15.255.255", 0);
1621 test_internal_ip("::ffff:172.16.0.0", 0);
1622 test_internal_ip("::ffff:172.31.255.255", 0);
1623 test_external_ip("::ffff:172.32.0.0", 0);
1625 test_external_ip("::ffff:192.167.255.255", 0);
1626 test_internal_ip("::ffff:192.168.0.0", 0);
1627 test_internal_ip("::ffff:192.168.255.255", 0);
1628 test_external_ip("::ffff:192.169.0.0", 0);
1630 test_external_ip("::ffff:169.253.255.255", 0);
1631 test_internal_ip("::ffff:169.254.0.0", 0);
1632 test_internal_ip("::ffff:169.254.255.255", 0);
1633 test_external_ip("::ffff:169.255.0.0", 0);
1634 test_assert(is_internal_IP(0x7f000001, 0));
1636 /* tor_addr_compare(tor_addr_t x2) */
1637 test_addr_compare("ffff::", ==, "ffff::0");
1638 test_addr_compare("0::3:2:1", <, "0::ffff:0.3.2.1");
1639 test_addr_compare("0::2:2:1", <, "0::ffff:0.3.2.1");
1640 test_addr_compare("0::ffff:0.3.2.1", >, "0::0:0:0");
1641 test_addr_compare("0::ffff:5.2.2.1", <, "::ffff:6.0.0.0"); /* XXXX wrong. */
1642 tor_addr_parse_mask_ports("[::ffff:2.3.4.5]", &t1
, NULL
, NULL
, NULL
);
1643 tor_addr_parse_mask_ports("2.3.4.5", &t2
, NULL
, NULL
, NULL
);
1644 test_assert(tor_addr_compare(&t1
, &t2
, CMP_SEMANTIC
) == 0);
1645 tor_addr_parse_mask_ports("[::ffff:2.3.4.4]", &t1
, NULL
, NULL
, NULL
);
1646 tor_addr_parse_mask_ports("2.3.4.5", &t2
, NULL
, NULL
, NULL
);
1647 test_assert(tor_addr_compare(&t1
, &t2
, CMP_SEMANTIC
) < 0);
1649 /* test compare_masked */
1650 test_addr_compare_masked("ffff::", ==, "ffff::0", 128);
1651 test_addr_compare_masked("ffff::", ==, "ffff::0", 64);
1652 test_addr_compare_masked("0::2:2:1", <, "0::8000:2:1", 81);
1653 test_addr_compare_masked("0::2:2:1", ==, "0::8000:2:1", 80);
1655 /* Test decorated addr_to_string. */
1656 test_eq(AF_INET6
, tor_addr_from_str(&t1
, "[123:45:6789::5005:11]"));
1657 p1
= tor_addr_to_str(buf
, &t1
, sizeof(buf
), 1);
1658 test_streq(p1
, "[123:45:6789::5005:11]");
1659 test_eq(AF_INET
, tor_addr_from_str(&t1
, "18.0.0.1"));
1660 p1
= tor_addr_to_str(buf
, &t1
, sizeof(buf
), 1);
1661 test_streq(p1
, "18.0.0.1");
1663 /* Test tor_addr_parse_reverse_lookup_name */
1664 i
= tor_addr_parse_reverse_lookup_name(&t1
, "Foobar.baz", AF_UNSPEC
, 0);
1666 i
= tor_addr_parse_reverse_lookup_name(&t1
, "Foobar.baz", AF_UNSPEC
, 1);
1668 i
= tor_addr_parse_reverse_lookup_name(&t1
, "1.0.168.192.in-addr.arpa",
1671 test_eq(tor_addr_family(&t1
), AF_INET
);
1672 p1
= tor_addr_to_str(buf
, &t1
, sizeof(buf
), 1);
1673 test_streq(p1
, "192.168.0.1");
1674 i
= tor_addr_parse_reverse_lookup_name(&t1
, "192.168.0.99", AF_UNSPEC
, 0);
1676 i
= tor_addr_parse_reverse_lookup_name(&t1
, "192.168.0.99", AF_UNSPEC
, 1);
1678 p1
= tor_addr_to_str(buf
, &t1
, sizeof(buf
), 1);
1679 test_streq(p1
, "192.168.0.99");
1680 memset(&t1
, 0, sizeof(t1
));
1681 i
= tor_addr_parse_reverse_lookup_name(&t1
,
1682 "0.1.2.3.4.5.6.7.8.9.a.b.c.d.e.f."
1683 "f.e.e.b.1.e.b.e.e.f.f.e.e.e.d.9."
1687 p1
= tor_addr_to_str(buf
, &t1
, sizeof(buf
), 1);
1688 test_streq(p1
, "[9dee:effe:ebe1:beef:fedc:ba98:7654:3210]");
1689 /* Failing cases. */
1690 i
= tor_addr_parse_reverse_lookup_name(&t1
,
1691 "6.7.8.9.a.b.c.d.e.f."
1692 "f.e.e.b.1.e.b.e.e.f.f.e.e.e.d.9."
1696 i
= tor_addr_parse_reverse_lookup_name(&t1
,
1697 "6.7.8.9.a.b.c.d.e.f.a.b.c.d.e.f.0."
1698 "f.e.e.b.1.e.b.e.e.f.f.e.e.e.d.9."
1702 i
= tor_addr_parse_reverse_lookup_name(&t1
,
1703 "6.7.8.9.a.b.c.d.e.f.X.0.0.0.0.9."
1704 "f.e.e.b.1.e.b.e.e.f.f.e.e.e.d.9."
1708 i
= tor_addr_parse_reverse_lookup_name(&t1
, "32.1.1.in-addr.arpa",
1711 i
= tor_addr_parse_reverse_lookup_name(&t1
, ".in-addr.arpa",
1714 i
= tor_addr_parse_reverse_lookup_name(&t1
, "1.2.3.4.5.in-addr.arpa",
1717 i
= tor_addr_parse_reverse_lookup_name(&t1
, "1.2.3.4.5.in-addr.arpa",
1720 i
= tor_addr_parse_reverse_lookup_name(&t1
,
1721 "6.7.8.9.a.b.c.d.e.f.a.b.c.d.e.0."
1722 "f.e.e.b.1.e.b.e.e.f.f.e.e.e.d.9."
1727 /* test tor_addr_parse_mask_ports */
1728 test_addr_mask_ports_parse("[::f]/17:47-95", AF_INET6
,
1729 0, 0, 0, 0x0000000f, 17, 47, 95);
1730 //test_addr_parse("[::fefe:4.1.1.7/120]:999-1000");
1731 //test_addr_parse_check("::fefe:401:107", 120, 999, 1000);
1732 test_addr_mask_ports_parse("[::ffff:4.1.1.7]/120:443", AF_INET6
,
1733 0, 0, 0x0000ffff, 0x04010107, 120, 443, 443);
1734 test_addr_mask_ports_parse("[abcd:2::44a:0]:2-65000", AF_INET6
,
1735 0xabcd0002, 0, 0, 0x044a0000, 128, 2, 65000);
1737 r
=tor_addr_parse_mask_ports("[fefef::]/112", &t1
, NULL
, NULL
, NULL
);
1738 test_assert(r
== -1);
1739 r
=tor_addr_parse_mask_ports("efef::/112", &t1
, NULL
, NULL
, NULL
);
1740 test_assert(r
== -1);
1741 r
=tor_addr_parse_mask_ports("[f:f:f:f:f:f:f:f::]", &t1
, NULL
, NULL
, NULL
);
1742 test_assert(r
== -1);
1743 r
=tor_addr_parse_mask_ports("[::f:f:f:f:f:f:f:f]", &t1
, NULL
, NULL
, NULL
);
1744 test_assert(r
== -1);
1745 r
=tor_addr_parse_mask_ports("[f:f:f:f:f:f:f:f:f]", &t1
, NULL
, NULL
, NULL
);
1746 test_assert(r
== -1);
1747 /* Test for V4-mapped address with mask < 96. (arguably not valid) */
1748 r
=tor_addr_parse_mask_ports("[::ffff:1.1.2.2/33]", &t1
, &mask
, NULL
, NULL
);
1749 test_assert(r
== -1);
1750 r
=tor_addr_parse_mask_ports("1.1.2.2/33", &t1
, &mask
, NULL
, NULL
);
1751 test_assert(r
== -1);
1752 r
=tor_addr_parse_mask_ports("1.1.2.2/31", &t1
, &mask
, NULL
, NULL
);
1753 test_assert(r
== AF_INET
);
1754 r
=tor_addr_parse_mask_ports("[efef::]/112", &t1
, &mask
, &port1
, &port2
);
1755 test_assert(r
== AF_INET6
);
1756 test_assert(port1
== 1);
1757 test_assert(port2
== 65535);
1759 /* make sure inet address lengths >= max */
1760 test_assert(INET_NTOA_BUF_LEN
>= sizeof("255.255.255.255"));
1761 test_assert(TOR_ADDR_BUF_LEN
>=
1762 sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"));
1764 test_assert(sizeof(tor_addr_t
) >= sizeof(struct in6_addr
));
1766 /* get interface addresses */
1767 r
= get_interface_address6(LOG_DEBUG
, AF_INET
, &t1
);
1768 i
= get_interface_address6(LOG_DEBUG
, AF_INET6
, &t2
);
1770 tor_inet_ntop(AF_INET
, &t1
.sa
.sin_addr
, buf
, sizeof(buf
));
1771 printf("\nv4 address: %s (family=%i)", buf
, IN_FAMILY(&t1
));
1772 tor_inet_ntop(AF_INET6
, &t2
.sa6
.sin6_addr
, buf
, sizeof(buf
));
1773 printf("\nv6 address: %s (family=%i)", buf
, IN_FAMILY(&t2
));
1780 /** Run unit tests for basic dynamic-sized array functionality. */
1782 test_util_smartlist_basic(void)
1786 /* XXXX test sort_digests, uniq_strings, uniq_digests */
1788 /* Test smartlist add, del_keeporder, insert, get. */
1789 sl
= smartlist_create();
1790 smartlist_add(sl
, (void*)1);
1791 smartlist_add(sl
, (void*)2);
1792 smartlist_add(sl
, (void*)3);
1793 smartlist_add(sl
, (void*)4);
1794 smartlist_del_keeporder(sl
, 1);
1795 smartlist_insert(sl
, 1, (void*)22);
1796 smartlist_insert(sl
, 0, (void*)0);
1797 smartlist_insert(sl
, 5, (void*)555);
1798 test_eq_ptr((void*)0, smartlist_get(sl
,0));
1799 test_eq_ptr((void*)1, smartlist_get(sl
,1));
1800 test_eq_ptr((void*)22, smartlist_get(sl
,2));
1801 test_eq_ptr((void*)3, smartlist_get(sl
,3));
1802 test_eq_ptr((void*)4, smartlist_get(sl
,4));
1803 test_eq_ptr((void*)555, smartlist_get(sl
,5));
1804 /* Try deleting in the middle. */
1805 smartlist_del(sl
, 1);
1806 test_eq_ptr((void*)555, smartlist_get(sl
, 1));
1807 /* Try deleting at the end. */
1808 smartlist_del(sl
, 4);
1809 test_eq(4, smartlist_len(sl
));
1812 test_assert(smartlist_isin(sl
, (void*)3));
1813 test_assert(!smartlist_isin(sl
, (void*)99));
1819 /** Run unit tests for smartlist-of-strings functionality. */
1821 test_util_smartlist_strings(void)
1823 smartlist_t
*sl
= smartlist_create();
1824 char *cp
=NULL
, *cp_alloc
=NULL
;
1827 /* Test split and join */
1828 test_eq(0, smartlist_len(sl
));
1829 smartlist_split_string(sl
, "abc", ":", 0, 0);
1830 test_eq(1, smartlist_len(sl
));
1831 test_streq("abc", smartlist_get(sl
, 0));
1832 smartlist_split_string(sl
, "a::bc::", "::", 0, 0);
1833 test_eq(4, smartlist_len(sl
));
1834 test_streq("a", smartlist_get(sl
, 1));
1835 test_streq("bc", smartlist_get(sl
, 2));
1836 test_streq("", smartlist_get(sl
, 3));
1837 cp_alloc
= smartlist_join_strings(sl
, "", 0, NULL
);
1838 test_streq(cp_alloc
, "abcabc");
1840 cp_alloc
= smartlist_join_strings(sl
, "!", 0, NULL
);
1841 test_streq(cp_alloc
, "abc!a!bc!");
1843 cp_alloc
= smartlist_join_strings(sl
, "XY", 0, NULL
);
1844 test_streq(cp_alloc
, "abcXYaXYbcXY");
1846 cp_alloc
= smartlist_join_strings(sl
, "XY", 1, NULL
);
1847 test_streq(cp_alloc
, "abcXYaXYbcXYXY");
1849 cp_alloc
= smartlist_join_strings(sl
, "", 1, NULL
);
1850 test_streq(cp_alloc
, "abcabc");
1853 smartlist_split_string(sl
, "/def/ /ghijk", "/", 0, 0);
1854 test_eq(8, smartlist_len(sl
));
1855 test_streq("", smartlist_get(sl
, 4));
1856 test_streq("def", smartlist_get(sl
, 5));
1857 test_streq(" ", smartlist_get(sl
, 6));
1858 test_streq("ghijk", smartlist_get(sl
, 7));
1859 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1860 smartlist_clear(sl
);
1862 smartlist_split_string(sl
, "a,bbd,cdef", ",", SPLIT_SKIP_SPACE
, 0);
1863 test_eq(3, smartlist_len(sl
));
1864 test_streq("a", smartlist_get(sl
,0));
1865 test_streq("bbd", smartlist_get(sl
,1));
1866 test_streq("cdef", smartlist_get(sl
,2));
1867 smartlist_split_string(sl
, " z <> zhasd <> <> bnud<> ", "<>",
1868 SPLIT_SKIP_SPACE
, 0);
1869 test_eq(8, smartlist_len(sl
));
1870 test_streq("z", smartlist_get(sl
,3));
1871 test_streq("zhasd", smartlist_get(sl
,4));
1872 test_streq("", smartlist_get(sl
,5));
1873 test_streq("bnud", smartlist_get(sl
,6));
1874 test_streq("", smartlist_get(sl
,7));
1876 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1877 smartlist_clear(sl
);
1879 smartlist_split_string(sl
, " ab\tc \td ef ", NULL
,
1880 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1881 test_eq(4, smartlist_len(sl
));
1882 test_streq("ab", smartlist_get(sl
,0));
1883 test_streq("c", smartlist_get(sl
,1));
1884 test_streq("d", smartlist_get(sl
,2));
1885 test_streq("ef", smartlist_get(sl
,3));
1886 smartlist_split_string(sl
, "ghi\tj", NULL
,
1887 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1888 test_eq(6, smartlist_len(sl
));
1889 test_streq("ghi", smartlist_get(sl
,4));
1890 test_streq("j", smartlist_get(sl
,5));
1892 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1893 smartlist_clear(sl
);
1895 cp_alloc
= smartlist_join_strings(sl
, "XY", 0, NULL
);
1896 test_streq(cp_alloc
, "");
1898 cp_alloc
= smartlist_join_strings(sl
, "XY", 1, NULL
);
1899 test_streq(cp_alloc
, "XY");
1902 smartlist_split_string(sl
, " z <> zhasd <> <> bnud<> ", "<>",
1903 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1904 test_eq(3, smartlist_len(sl
));
1905 test_streq("z", smartlist_get(sl
, 0));
1906 test_streq("zhasd", smartlist_get(sl
, 1));
1907 test_streq("bnud", smartlist_get(sl
, 2));
1908 smartlist_split_string(sl
, " z <> zhasd <> <> bnud<> ", "<>",
1909 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 2);
1910 test_eq(5, smartlist_len(sl
));
1911 test_streq("z", smartlist_get(sl
, 3));
1912 test_streq("zhasd <> <> bnud<>", smartlist_get(sl
, 4));
1913 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1914 smartlist_clear(sl
);
1916 smartlist_split_string(sl
, "abcd\n", "\n",
1917 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1918 test_eq(1, smartlist_len(sl
));
1919 test_streq("abcd", smartlist_get(sl
, 0));
1920 smartlist_split_string(sl
, "efgh", "\n",
1921 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1922 test_eq(2, smartlist_len(sl
));
1923 test_streq("efgh", smartlist_get(sl
, 1));
1925 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1926 smartlist_clear(sl
);
1928 /* Test swapping, shuffling, and sorting. */
1929 smartlist_split_string(sl
, "the,onion,router,by,arma,and,nickm", ",", 0, 0);
1930 test_eq(7, smartlist_len(sl
));
1931 smartlist_sort(sl
, _compare_strs
);
1932 cp_alloc
= smartlist_join_strings(sl
, ",", 0, NULL
);
1933 test_streq(cp_alloc
,"and,arma,by,nickm,onion,router,the");
1935 smartlist_swap(sl
, 1, 5);
1936 cp_alloc
= smartlist_join_strings(sl
, ",", 0, NULL
);
1937 test_streq(cp_alloc
,"and,router,by,nickm,onion,arma,the");
1939 smartlist_shuffle(sl
);
1940 test_eq(7, smartlist_len(sl
));
1941 test_assert(smartlist_string_isin(sl
, "and"));
1942 test_assert(smartlist_string_isin(sl
, "router"));
1943 test_assert(smartlist_string_isin(sl
, "by"));
1944 test_assert(smartlist_string_isin(sl
, "nickm"));
1945 test_assert(smartlist_string_isin(sl
, "onion"));
1946 test_assert(smartlist_string_isin(sl
, "arma"));
1947 test_assert(smartlist_string_isin(sl
, "the"));
1950 smartlist_sort(sl
, _compare_strs
);
1951 test_streq("nickm", smartlist_bsearch(sl
, "zNicKM",
1952 _compare_without_first_ch
));
1953 test_streq("and", smartlist_bsearch(sl
, " AND", _compare_without_first_ch
));
1954 test_eq_ptr(NULL
, smartlist_bsearch(sl
, " ANz", _compare_without_first_ch
));
1956 /* Test bsearch_idx */
1959 test_eq(0, smartlist_bsearch_idx(sl
," aaa",_compare_without_first_ch
,&f
));
1961 test_eq(0, smartlist_bsearch_idx(sl
," and",_compare_without_first_ch
,&f
));
1963 test_eq(1, smartlist_bsearch_idx(sl
," arm",_compare_without_first_ch
,&f
));
1965 test_eq(1, smartlist_bsearch_idx(sl
," arma",_compare_without_first_ch
,&f
));
1967 test_eq(2, smartlist_bsearch_idx(sl
," armb",_compare_without_first_ch
,&f
));
1969 test_eq(7, smartlist_bsearch_idx(sl
," zzzz",_compare_without_first_ch
,&f
));
1973 /* Test reverse() and pop_last() */
1974 smartlist_reverse(sl
);
1975 cp_alloc
= smartlist_join_strings(sl
, ",", 0, NULL
);
1976 test_streq(cp_alloc
,"the,router,onion,nickm,by,arma,and");
1978 cp_alloc
= smartlist_pop_last(sl
);
1979 test_streq(cp_alloc
, "and");
1981 test_eq(smartlist_len(sl
), 6);
1982 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1983 smartlist_clear(sl
);
1984 cp_alloc
= smartlist_pop_last(sl
);
1985 test_eq(cp_alloc
, NULL
);
1988 smartlist_split_string(sl
,
1989 "50,noon,radar,a,man,a,plan,a,canal,panama,radar,noon,50",
1991 smartlist_sort(sl
, _compare_strs
);
1992 smartlist_uniq(sl
, _compare_strs
, _tor_free
);
1993 cp_alloc
= smartlist_join_strings(sl
, ",", 0, NULL
);
1994 test_streq(cp_alloc
, "50,a,canal,man,noon,panama,plan,radar");
1997 /* Test string_isin and isin_case and num_isin */
1998 test_assert(smartlist_string_isin(sl
, "noon"));
1999 test_assert(!smartlist_string_isin(sl
, "noonoon"));
2000 test_assert(smartlist_string_isin_case(sl
, "nOOn"));
2001 test_assert(!smartlist_string_isin_case(sl
, "nooNooN"));
2002 test_assert(smartlist_string_num_isin(sl
, 50));
2003 test_assert(!smartlist_string_num_isin(sl
, 60));
2005 /* Test smartlist_choose */
2010 void *first
= smartlist_choose(sl
);
2011 test_assert(smartlist_isin(sl
, first
));
2012 for (i
= 0; i
< 100; ++i
) {
2013 void *second
= smartlist_choose(sl
);
2014 if (second
!= first
)
2016 if (!smartlist_isin(sl
, second
))
2019 test_assert(!allsame
);
2022 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
2023 smartlist_clear(sl
);
2025 /* Test string_remove and remove and join_strings2 */
2026 smartlist_split_string(sl
,
2027 "Some say the Earth will end in ice and some in fire",
2029 cp
= smartlist_get(sl
, 4);
2030 test_streq(cp
, "will");
2031 smartlist_add(sl
, cp
);
2032 smartlist_remove(sl
, cp
);
2034 cp_alloc
= smartlist_join_strings(sl
, ",", 0, NULL
);
2035 test_streq(cp_alloc
, "Some,say,the,Earth,fire,end,in,ice,and,some,in");
2037 smartlist_string_remove(sl
, "in");
2038 cp_alloc
= smartlist_join_strings2(sl
, "+XX", 1, 0, &sz
);
2039 test_streq(cp_alloc
, "Some+say+the+Earth+fire+end+some+ice+and");
2040 test_eq((int)sz
, 40);
2044 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
2049 /** Run unit tests for smartlist set manipulation functions. */
2051 test_util_smartlist_overlap(void)
2053 smartlist_t
*sl
= smartlist_create();
2054 smartlist_t
*ints
= smartlist_create();
2055 smartlist_t
*odds
= smartlist_create();
2056 smartlist_t
*evens
= smartlist_create();
2057 smartlist_t
*primes
= smartlist_create();
2059 for (i
=1; i
< 10; i
+= 2)
2060 smartlist_add(odds
, (void*)(uintptr_t)i
);
2061 for (i
=0; i
< 10; i
+= 2)
2062 smartlist_add(evens
, (void*)(uintptr_t)i
);
2065 smartlist_add_all(ints
, odds
);
2066 smartlist_add_all(ints
, evens
);
2067 test_eq(smartlist_len(ints
), 10);
2069 smartlist_add(primes
, (void*)2);
2070 smartlist_add(primes
, (void*)3);
2071 smartlist_add(primes
, (void*)5);
2072 smartlist_add(primes
, (void*)7);
2075 test_assert(smartlist_overlap(ints
, odds
));
2076 test_assert(smartlist_overlap(odds
, primes
));
2077 test_assert(smartlist_overlap(evens
, primes
));
2078 test_assert(!smartlist_overlap(odds
, evens
));
2081 smartlist_add_all(sl
, odds
);
2082 smartlist_intersect(sl
, primes
);
2083 test_eq(smartlist_len(sl
), 3);
2084 test_assert(smartlist_isin(sl
, (void*)3));
2085 test_assert(smartlist_isin(sl
, (void*)5));
2086 test_assert(smartlist_isin(sl
, (void*)7));
2089 smartlist_add_all(sl
, primes
);
2090 smartlist_subtract(sl
, odds
);
2091 test_eq(smartlist_len(sl
), 1);
2092 test_assert(smartlist_isin(sl
, (void*)2));
2095 smartlist_free(odds
);
2096 smartlist_free(evens
);
2097 smartlist_free(ints
);
2098 smartlist_free(primes
);
2102 /** Run unit tests for smartlist-of-digests functions. */
2104 test_util_smartlist_digests(void)
2106 smartlist_t
*sl
= smartlist_create();
2109 smartlist_add(sl
, tor_memdup("AAAAAAAAAAAAAAAAAAAA", DIGEST_LEN
));
2110 smartlist_add(sl
, tor_memdup("\00090AAB2AAAAaasdAAAAA", DIGEST_LEN
));
2111 smartlist_add(sl
, tor_memdup("\00090AAB2AAAAaasdAAAAA", DIGEST_LEN
));
2112 test_eq(0, smartlist_digest_isin(NULL
, "AAAAAAAAAAAAAAAAAAAA"));
2113 test_assert(smartlist_digest_isin(sl
, "AAAAAAAAAAAAAAAAAAAA"));
2114 test_assert(smartlist_digest_isin(sl
, "\00090AAB2AAAAaasdAAAAA"));
2115 test_eq(0, smartlist_digest_isin(sl
, "\00090AAB2AAABaasdAAAAA"));
2118 smartlist_sort_digests(sl
);
2119 test_memeq(smartlist_get(sl
, 0), "\00090AAB2AAAAaasdAAAAA", DIGEST_LEN
);
2120 test_memeq(smartlist_get(sl
, 1), "\00090AAB2AAAAaasdAAAAA", DIGEST_LEN
);
2121 test_memeq(smartlist_get(sl
, 2), "AAAAAAAAAAAAAAAAAAAA", DIGEST_LEN
);
2122 test_eq(3, smartlist_len(sl
));
2125 smartlist_uniq_digests(sl
);
2126 test_eq(2, smartlist_len(sl
));
2127 test_memeq(smartlist_get(sl
, 0), "\00090AAB2AAAAaasdAAAAA", DIGEST_LEN
);
2128 test_memeq(smartlist_get(sl
, 1), "AAAAAAAAAAAAAAAAAAAA", DIGEST_LEN
);
2131 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
2135 /** Run unit tests for concatenate-a-smartlist-of-strings functions. */
2137 test_util_smartlist_join(void)
2139 smartlist_t
*sl
= smartlist_create();
2140 smartlist_t
*sl2
= smartlist_create(), *sl3
= smartlist_create(),
2141 *sl4
= smartlist_create();
2143 /* unique, sorted. */
2144 smartlist_split_string(sl
,
2145 "Abashments Ambush Anchorman Bacon Banks Borscht "
2146 "Bunks Inhumane Insurance Knish Know Manners "
2147 "Maraschinos Stamina Sunbonnets Unicorns Wombats",
2149 /* non-unique, sorted. */
2150 smartlist_split_string(sl2
,
2151 "Ambush Anchorman Anchorman Anemias Anemias Bacon "
2152 "Crossbowmen Inhumane Insurance Knish Know Manners "
2153 "Manners Maraschinos Wombats Wombats Work",
2155 SMARTLIST_FOREACH_JOIN(sl
, char *, cp1
,
2158 smartlist_add(sl3
, cp2
)) {
2159 test_streq(cp1
, cp2
);
2160 smartlist_add(sl4
, cp1
);
2161 } SMARTLIST_FOREACH_JOIN_END(cp1
, cp2
);
2163 SMARTLIST_FOREACH(sl3
, const char *, cp
,
2164 test_assert(smartlist_isin(sl2
, cp
) &&
2165 !smartlist_string_isin(sl
, cp
)));
2166 SMARTLIST_FOREACH(sl4
, const char *, cp
,
2167 test_assert(smartlist_isin(sl
, cp
) &&
2168 smartlist_string_isin(sl2
, cp
)));
2169 joined
= smartlist_join_strings(sl3
, ",", 0, NULL
);
2170 test_streq(joined
, "Anemias,Anemias,Crossbowmen,Work");
2172 joined
= smartlist_join_strings(sl4
, ",", 0, NULL
);
2173 test_streq(joined
, "Ambush,Anchorman,Anchorman,Bacon,Inhumane,Insurance,"
2174 "Knish,Know,Manners,Manners,Maraschinos,Wombats,Wombats");
2178 smartlist_free(sl4
);
2179 smartlist_free(sl3
);
2180 SMARTLIST_FOREACH(sl2
, char *, cp
, tor_free(cp
));
2181 smartlist_free(sl2
);
2182 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
2187 /** Run unit tests for bitarray code */
2189 test_util_bitarray(void)
2191 bitarray_t
*ba
= NULL
;
2194 ba
= bitarray_init_zero(1);
2196 test_assert(! bitarray_is_set(ba
, 0));
2197 bitarray_set(ba
, 0);
2198 test_assert(bitarray_is_set(ba
, 0));
2199 bitarray_clear(ba
, 0);
2200 test_assert(! bitarray_is_set(ba
, 0));
2203 ba
= bitarray_init_zero(1023);
2204 for (i
= 1; i
< 64; ) {
2205 for (j
= 0; j
< 1023; ++j
) {
2207 bitarray_set(ba
, j
);
2209 bitarray_clear(ba
, j
);
2211 for (j
= 0; j
< 1023; ++j
) {
2212 if (!bool_eq(bitarray_is_set(ba
, j
), j
%i
))
2229 /** Run unit tests for digest set code (implemented as a hashtable or as a
2232 test_util_digestset(void)
2234 smartlist_t
*included
= smartlist_create();
2238 int false_positives
= 0;
2239 digestset_t
*set
= NULL
;
2241 for (i
= 0; i
< 1000; ++i
) {
2242 crypto_rand(d
, DIGEST_LEN
);
2243 smartlist_add(included
, tor_memdup(d
, DIGEST_LEN
));
2245 set
= digestset_new(1000);
2246 SMARTLIST_FOREACH(included
, const char *, cp
,
2247 if (digestset_isin(set
, cp
))
2250 SMARTLIST_FOREACH(included
, const char *, cp
,
2251 digestset_add(set
, cp
));
2252 SMARTLIST_FOREACH(included
, const char *, cp
,
2253 if (!digestset_isin(set
, cp
))
2256 for (i
= 0; i
< 1000; ++i
) {
2257 crypto_rand(d
, DIGEST_LEN
);
2258 if (digestset_isin(set
, d
))
2261 test_assert(false_positives
< 50); /* Should be far lower. */
2265 digestset_free(set
);
2266 SMARTLIST_FOREACH(included
, char *, cp
, tor_free(cp
));
2267 smartlist_free(included
);
2270 /** mutex for thread test to stop the threads hitting data at the same time. */
2271 static tor_mutex_t
*_thread_test_mutex
= NULL
;
2272 /** mutexes for the thread test to make sure that the threads have to
2273 * interleave somewhat. */
2274 static tor_mutex_t
*_thread_test_start1
= NULL
,
2275 *_thread_test_start2
= NULL
;
2276 /** Shared strmap for the thread test. */
2277 static strmap_t
*_thread_test_strmap
= NULL
;
2278 /** The name of thread1 for the thread test */
2279 static char *_thread1_name
= NULL
;
2280 /** The name of thread2 for the thread test */
2281 static char *_thread2_name
= NULL
;
2283 static void _thread_test_func(void* _s
) ATTR_NORETURN
;
2285 /** How many iterations have the threads in the unit test run? */
2286 static int t1_count
= 0, t2_count
= 0;
2288 /** Helper function for threading unit tests: This function runs in a
2289 * subthread. It grabs its own mutex (start1 or start2) to make sure that it
2290 * should start, then it repeatedly alters _test_thread_strmap protected by
2291 * _thread_test_mutex. */
2293 _thread_test_func(void* _s
)
2300 if (!strcmp(s
, "thread 1")) {
2301 m
= _thread_test_start1
;
2302 cp
= &_thread1_name
;
2305 m
= _thread_test_start2
;
2306 cp
= &_thread2_name
;
2309 tor_mutex_acquire(m
);
2311 tor_snprintf(buf
, sizeof(buf
), "%lu", tor_get_thread_id());
2312 *cp
= tor_strdup(buf
);
2314 for (i
=0; i
<10000; ++i
) {
2315 tor_mutex_acquire(_thread_test_mutex
);
2316 strmap_set(_thread_test_strmap
, "last to run", *cp
);
2318 tor_mutex_release(_thread_test_mutex
);
2320 tor_mutex_acquire(_thread_test_mutex
);
2321 strmap_set(_thread_test_strmap
, s
, *cp
);
2322 tor_mutex_release(_thread_test_mutex
);
2324 tor_mutex_release(m
);
2329 /** Run unit tests for threading logic. */
2331 test_util_threads(void)
2333 char *s1
= NULL
, *s2
= NULL
;
2334 int done
= 0, timedout
= 0;
2341 #ifndef TOR_IS_MULTITHREADED
2342 /* Skip this test if we aren't threading. We should be threading most
2343 * everywhere by now. */
2347 _thread_test_mutex
= tor_mutex_new();
2348 _thread_test_start1
= tor_mutex_new();
2349 _thread_test_start2
= tor_mutex_new();
2350 _thread_test_strmap
= strmap_new();
2351 s1
= tor_strdup("thread 1");
2352 s2
= tor_strdup("thread 2");
2353 tor_mutex_acquire(_thread_test_start1
);
2354 tor_mutex_acquire(_thread_test_start2
);
2355 spawn_func(_thread_test_func
, s1
);
2356 spawn_func(_thread_test_func
, s2
);
2357 tor_mutex_release(_thread_test_start2
);
2358 tor_mutex_release(_thread_test_start1
);
2359 started
= time(NULL
);
2361 tor_mutex_acquire(_thread_test_mutex
);
2362 strmap_assert_ok(_thread_test_strmap
);
2363 if (strmap_get(_thread_test_strmap
, "thread 1") &&
2364 strmap_get(_thread_test_strmap
, "thread 2")) {
2366 } else if (time(NULL
) > started
+ 25) {
2367 timedout
= done
= 1;
2369 tor_mutex_release(_thread_test_mutex
);
2371 /* Prevent the main thread from starving the worker threads. */
2372 select(0, NULL
, NULL
, NULL
, &tv
);
2376 tor_mutex_acquire(_thread_test_start1
);
2377 tor_mutex_release(_thread_test_start1
);
2378 tor_mutex_acquire(_thread_test_start2
);
2379 tor_mutex_release(_thread_test_start2
);
2381 tor_mutex_free(_thread_test_mutex
);
2384 printf("\nTimed out: %d %d", t1_count
, t2_count
);
2385 test_assert(strmap_get(_thread_test_strmap
, "thread 1"));
2386 test_assert(strmap_get(_thread_test_strmap
, "thread 2"));
2387 test_assert(!timedout
);
2390 /* different thread IDs. */
2391 test_assert(strcmp(strmap_get(_thread_test_strmap
, "thread 1"),
2392 strmap_get(_thread_test_strmap
, "thread 2")));
2393 test_assert(!strcmp(strmap_get(_thread_test_strmap
, "thread 1"),
2394 strmap_get(_thread_test_strmap
, "last to run")) ||
2395 !strcmp(strmap_get(_thread_test_strmap
, "thread 2"),
2396 strmap_get(_thread_test_strmap
, "last to run")));
2401 tor_free(_thread1_name
);
2402 tor_free(_thread2_name
);
2403 if (_thread_test_strmap
)
2404 strmap_free(_thread_test_strmap
, NULL
);
2405 if (_thread_test_start1
)
2406 tor_mutex_free(_thread_test_start1
);
2407 if (_thread_test_start2
)
2408 tor_mutex_free(_thread_test_start2
);
2411 /** Helper: return a tristate based on comparing two strings. */
2413 _compare_strings_for_pqueue(const void *s1
, const void *s2
)
2415 return strcmp((const char*)s1
, (const char*)s2
);
2418 /** Run unit tests for heap-based priority queue functions. */
2420 test_util_pqueue(void)
2422 smartlist_t
*sl
= smartlist_create();
2423 int (*cmp
)(const void *, const void*);
2424 #define OK() smartlist_pqueue_assert_ok(sl, cmp)
2426 cmp
= _compare_strings_for_pqueue
;
2428 smartlist_pqueue_add(sl
, cmp
, (char*)"cows");
2429 smartlist_pqueue_add(sl
, cmp
, (char*)"zebras");
2430 smartlist_pqueue_add(sl
, cmp
, (char*)"fish");
2431 smartlist_pqueue_add(sl
, cmp
, (char*)"frogs");
2432 smartlist_pqueue_add(sl
, cmp
, (char*)"apples");
2433 smartlist_pqueue_add(sl
, cmp
, (char*)"squid");
2434 smartlist_pqueue_add(sl
, cmp
, (char*)"daschunds");
2435 smartlist_pqueue_add(sl
, cmp
, (char*)"eggplants");
2436 smartlist_pqueue_add(sl
, cmp
, (char*)"weissbier");
2437 smartlist_pqueue_add(sl
, cmp
, (char*)"lobsters");
2438 smartlist_pqueue_add(sl
, cmp
, (char*)"roquefort");
2442 test_eq(smartlist_len(sl
), 11);
2443 test_streq(smartlist_get(sl
, 0), "apples");
2444 test_streq(smartlist_pqueue_pop(sl
, cmp
), "apples");
2445 test_eq(smartlist_len(sl
), 10);
2447 test_streq(smartlist_pqueue_pop(sl
, cmp
), "cows");
2448 test_streq(smartlist_pqueue_pop(sl
, cmp
), "daschunds");
2449 smartlist_pqueue_add(sl
, cmp
, (char*)"chinchillas");
2451 smartlist_pqueue_add(sl
, cmp
, (char*)"fireflies");
2453 test_streq(smartlist_pqueue_pop(sl
, cmp
), "chinchillas");
2454 test_streq(smartlist_pqueue_pop(sl
, cmp
), "eggplants");
2455 test_streq(smartlist_pqueue_pop(sl
, cmp
), "fireflies");
2457 test_streq(smartlist_pqueue_pop(sl
, cmp
), "fish");
2458 test_streq(smartlist_pqueue_pop(sl
, cmp
), "frogs");
2459 test_streq(smartlist_pqueue_pop(sl
, cmp
), "lobsters");
2460 test_streq(smartlist_pqueue_pop(sl
, cmp
), "roquefort");
2462 test_eq(smartlist_len(sl
), 3);
2463 test_streq(smartlist_pqueue_pop(sl
, cmp
), "squid");
2464 test_streq(smartlist_pqueue_pop(sl
, cmp
), "weissbier");
2465 test_streq(smartlist_pqueue_pop(sl
, cmp
), "zebras");
2466 test_eq(smartlist_len(sl
), 0);
2475 /** Run unit tests for compression functions */
2477 test_util_gzip(void)
2479 char *buf1
=NULL
, *buf2
=NULL
, *buf3
=NULL
, *cp1
, *cp2
;
2482 tor_zlib_state_t
*state
= NULL
;
2484 buf1
= tor_strdup("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ");
2485 test_assert(detect_compression_method(buf1
, strlen(buf1
)) == UNKNOWN_METHOD
);
2486 if (is_gzip_supported()) {
2487 test_assert(!tor_gzip_compress(&buf2
, &len1
, buf1
, strlen(buf1
)+1,
2490 test_assert(!memcmp(buf2
, "\037\213", 2)); /* Gzip magic. */
2491 test_assert(detect_compression_method(buf2
, len1
) == GZIP_METHOD
);
2493 test_assert(!tor_gzip_uncompress(&buf3
, &len2
, buf2
, len1
,
2494 GZIP_METHOD
, 1, LOG_INFO
));
2496 test_streq(buf1
,buf3
);
2502 test_assert(!tor_gzip_compress(&buf2
, &len1
, buf1
, strlen(buf1
)+1,
2505 test_assert(!memcmp(buf2
, "\x78\xDA", 2)); /* deflate magic. */
2506 test_assert(detect_compression_method(buf2
, len1
) == ZLIB_METHOD
);
2508 test_assert(!tor_gzip_uncompress(&buf3
, &len2
, buf2
, len1
,
2509 ZLIB_METHOD
, 1, LOG_INFO
));
2511 test_streq(buf1
,buf3
);
2513 /* Check whether we can uncompress concatenated, compressed strings. */
2515 buf2
= tor_realloc(buf2
, len1
*2);
2516 memcpy(buf2
+len1
, buf2
, len1
);
2517 test_assert(!tor_gzip_uncompress(&buf3
, &len2
, buf2
, len1
*2,
2518 ZLIB_METHOD
, 1, LOG_INFO
));
2519 test_eq(len2
, (strlen(buf1
)+1)*2);
2521 "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ\0"
2522 "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ\0",
2523 (strlen(buf1
)+1)*2);
2529 /* Check whether we can uncompress partial strings. */
2531 tor_strdup("String with low redundancy that won't be compressed much.");
2532 test_assert(!tor_gzip_compress(&buf2
, &len1
, buf1
, strlen(buf1
)+1,
2534 tor_assert(len1
>16);
2535 /* when we allow an incomplete string, we should succeed.*/
2536 tor_assert(!tor_gzip_uncompress(&buf3
, &len2
, buf2
, len1
-16,
2537 ZLIB_METHOD
, 0, LOG_INFO
));
2539 tor_assert(len2
> 5);
2540 tor_assert(!strcmpstart(buf1
, buf3
));
2542 /* when we demand a complete string, this must fail. */
2544 tor_assert(tor_gzip_uncompress(&buf3
, &len2
, buf2
, len1
-16,
2545 ZLIB_METHOD
, 1, LOG_INFO
));
2548 /* Now, try streaming compression. */
2552 state
= tor_zlib_new(1, ZLIB_METHOD
);
2554 cp1
= buf1
= tor_malloc(1024);
2556 ccp2
= "ABCDEFGHIJABCDEFGHIJ";
2558 test_assert(tor_zlib_process(state
, &cp1
, &len1
, &ccp2
, &len2
, 0)
2560 test_eq(len2
, 0); /* Make sure we compressed it all. */
2561 test_assert(cp1
> buf1
);
2565 test_assert(tor_zlib_process(state
, &cp1
, &len1
, &ccp2
, &len2
, 1)
2568 test_assert(cp1
> cp2
); /* Make sure we really added something. */
2570 tor_assert(!tor_gzip_uncompress(&buf3
, &len2
, buf1
, 1024-len1
,
2571 ZLIB_METHOD
, 1, LOG_WARN
));
2572 test_streq(buf3
, "ABCDEFGHIJABCDEFGHIJ"); /*Make sure it compressed right.*/
2576 tor_zlib_free(state
);
2582 /** Run unit tests for string-to-void* map functions */
2584 test_util_strmap(void)
2587 strmap_iter_t
*iter
;
2590 char *visited
= NULL
;
2591 smartlist_t
*found_keys
= NULL
;
2595 test_eq(strmap_size(map
), 0);
2596 test_assert(strmap_isempty(map
));
2597 v
= strmap_set(map
, "K1", (void*)99);
2599 test_assert(!strmap_isempty(map
));
2600 v
= strmap_set(map
, "K2", (void*)101);
2602 v
= strmap_set(map
, "K1", (void*)100);
2603 test_eq(v
, (void*)99);
2604 test_eq_ptr(strmap_get(map
,"K1"), (void*)100);
2605 test_eq_ptr(strmap_get(map
,"K2"), (void*)101);
2606 test_eq_ptr(strmap_get(map
,"K-not-there"), NULL
);
2607 strmap_assert_ok(map
);
2609 v
= strmap_remove(map
,"K2");
2610 strmap_assert_ok(map
);
2611 test_eq_ptr(v
, (void*)101);
2612 test_eq_ptr(strmap_get(map
,"K2"), NULL
);
2613 test_eq_ptr(strmap_remove(map
,"K2"), NULL
);
2615 strmap_set(map
, "K2", (void*)101);
2616 strmap_set(map
, "K3", (void*)102);
2617 strmap_set(map
, "K4", (void*)103);
2618 test_eq(strmap_size(map
), 4);
2619 strmap_assert_ok(map
);
2620 strmap_set(map
, "K5", (void*)104);
2621 strmap_set(map
, "K6", (void*)105);
2622 strmap_assert_ok(map
);
2624 /* Test iterator. */
2625 iter
= strmap_iter_init(map
);
2626 found_keys
= smartlist_create();
2627 while (!strmap_iter_done(iter
)) {
2628 strmap_iter_get(iter
,&k
,&v
);
2629 smartlist_add(found_keys
, tor_strdup(k
));
2630 test_eq_ptr(v
, strmap_get(map
, k
));
2632 if (!strcmp(k
, "K2")) {
2633 iter
= strmap_iter_next_rmv(map
,iter
);
2635 iter
= strmap_iter_next(map
,iter
);
2639 /* Make sure we removed K2, but not the others. */
2640 test_eq_ptr(strmap_get(map
, "K2"), NULL
);
2641 test_eq_ptr(strmap_get(map
, "K5"), (void*)104);
2642 /* Make sure we visited everyone once */
2643 smartlist_sort_strings(found_keys
);
2644 visited
= smartlist_join_strings(found_keys
, ":", 0, NULL
);
2645 test_streq(visited
, "K1:K2:K3:K4:K5:K6");
2647 strmap_assert_ok(map
);
2648 /* Clean up after ourselves. */
2649 strmap_free(map
, NULL
);
2652 /* Now try some lc functions. */
2654 strmap_set_lc(map
,"Ab.C", (void*)1);
2655 test_eq_ptr(strmap_get(map
,"ab.c"), (void*)1);
2656 strmap_assert_ok(map
);
2657 test_eq_ptr(strmap_get_lc(map
,"AB.C"), (void*)1);
2658 test_eq_ptr(strmap_get(map
,"AB.C"), NULL
);
2659 test_eq_ptr(strmap_remove_lc(map
,"aB.C"), (void*)1);
2660 strmap_assert_ok(map
);
2661 test_eq_ptr(strmap_get_lc(map
,"AB.C"), NULL
);
2665 strmap_free(map
,NULL
);
2667 SMARTLIST_FOREACH(found_keys
, char *, cp
, tor_free(cp
));
2668 smartlist_free(found_keys
);
2673 /** Run unit tests for mmap() wrapper functionality. */
2675 test_util_mmap(void)
2677 char *fname1
= tor_strdup(get_fname("mapped_1"));
2678 char *fname2
= tor_strdup(get_fname("mapped_2"));
2679 char *fname3
= tor_strdup(get_fname("mapped_3"));
2680 const size_t buflen
= 17000;
2681 char *buf
= tor_malloc(17000);
2682 tor_mmap_t
*mapping
= NULL
;
2684 crypto_rand(buf
, buflen
);
2686 mapping
= tor_mmap_file(fname1
);
2687 test_assert(! mapping
);
2689 write_str_to_file(fname1
, "Short file.", 1);
2690 write_bytes_to_file(fname2
, buf
, buflen
, 1);
2691 write_bytes_to_file(fname3
, buf
, 16384, 1);
2693 mapping
= tor_mmap_file(fname1
);
2694 test_assert(mapping
);
2695 test_eq(mapping
->size
, strlen("Short file."));
2696 test_streq(mapping
->data
, "Short file.");
2698 tor_munmap_file(mapping
);
2700 test_assert(unlink(fname1
) == 0);
2702 /* make sure we can unlink. */
2703 test_assert(unlink(fname1
) == 0);
2704 test_streq(mapping
->data
, "Short file.");
2705 tor_munmap_file(mapping
);
2709 /* Now a zero-length file. */
2710 write_str_to_file(fname1
, "", 1);
2711 mapping
= tor_mmap_file(fname1
);
2712 test_eq(mapping
, NULL
);
2713 test_eq(ERANGE
, errno
);
2716 /* Make sure that we fail to map a no-longer-existent file. */
2717 mapping
= tor_mmap_file(fname1
);
2718 test_assert(mapping
== NULL
);
2720 /* Now try a big file that stretches across a few pages and isn't aligned */
2721 mapping
= tor_mmap_file(fname2
);
2722 test_assert(mapping
);
2723 test_eq(mapping
->size
, buflen
);
2724 test_memeq(mapping
->data
, buf
, buflen
);
2725 tor_munmap_file(mapping
);
2728 /* Now try a big aligned file. */
2729 mapping
= tor_mmap_file(fname3
);
2730 test_assert(mapping
);
2731 test_eq(mapping
->size
, 16384);
2732 test_memeq(mapping
->data
, buf
, 16384);
2733 tor_munmap_file(mapping
);
2747 tor_munmap_file(mapping
);
2750 /** Run unit tests for escaping/unescaping data for use by controllers. */
2752 test_util_control_formats(void)
2756 "..This is a test\r\nof the emergency \nbroadcast\r\n..system.\r\nZ.\r\n";
2759 sz
= read_escaped_data(inp
, strlen(inp
), &out
);
2761 ".This is a test\nof the emergency \nbroadcast\n.system.\nZ.\n");
2762 test_eq(sz
, strlen(out
));
2769 test_util_sscanf(void)
2771 unsigned u1
, u2
, u3
;
2772 char s1
[10], s2
[10], s3
[10], ch
;
2775 r
= tor_sscanf("hello world", "hello world"); /* String match: success */
2777 r
= tor_sscanf("hello world 3", "hello worlb %u", &u1
); /* String fail */
2779 r
= tor_sscanf("12345", "%u", &u1
); /* Simple number */
2781 test_eq(u1
, 12345u);
2782 r
= tor_sscanf("", "%u", &u1
); /* absent number */
2784 r
= tor_sscanf("A", "%u", &u1
); /* bogus number */
2786 r
= tor_sscanf("4294967295", "%u", &u1
); /* UINT32_MAX should work. */
2788 test_eq(u1
, 4294967295u);
2789 r
= tor_sscanf("4294967296", "%u", &u1
); /* Always say -1 at 32 bits. */
2791 r
= tor_sscanf("123456", "%2u%u", &u1
, &u2
); /* Width */
2795 r
= tor_sscanf("!12:3:456", "!%2u:%2u:%3u", &u1
, &u2
, &u3
); /* separators */
2800 r
= tor_sscanf("12:3:045", "%2u:%2u:%3u", &u1
, &u2
, &u3
); /* 0s */
2805 /* %u does not match space.*/
2806 r
= tor_sscanf("12:3: 45", "%2u:%2u:%3u", &u1
, &u2
, &u3
);
2808 /* %u does not match negative numbers. */
2809 r
= tor_sscanf("12:3:-4", "%2u:%2u:%3u", &u1
, &u2
, &u3
);
2811 /* Arbitrary amounts of 0-padding are okay */
2812 r
= tor_sscanf("12:03:000000000000000099", "%2u:%2u:%u", &u1
, &u2
, &u3
);
2818 r
= tor_sscanf("99% fresh", "%3u%% fresh", &u1
); /* percents are scannable.*/
2822 r
= tor_sscanf("hello", "%s", s1
); /* %s needs a number. */
2825 r
= tor_sscanf("hello", "%3s%7s", s1
, s2
); /* %s matches characters. */
2827 test_streq(s1
, "hel");
2828 test_streq(s2
, "lo");
2829 r
= tor_sscanf("WD40", "%2s%u", s3
, &u1
); /* %s%u */
2831 test_streq(s3
, "WD");
2833 r
= tor_sscanf("76trombones", "%6u%9s", &u1
, s1
); /* %u%s */
2836 test_streq(s1
, "trombones");
2837 r
= tor_sscanf("hello world", "%9s %9s", s1
, s2
); /* %s doesn't eat space. */
2839 test_streq(s1
, "hello");
2840 test_streq(s2
, "world");
2841 r
= tor_sscanf("hi", "%9s%9s%3s", s1
, s2
, s3
); /* %s can be empty. */
2843 test_streq(s1
, "hi");
2847 r
= tor_sscanf("1.2.3", "%u.%u.%u%c", &u1
, &u2
, &u3
, &ch
);
2849 r
= tor_sscanf("1.2.3 foobar", "%u.%u.%u%c", &u1
, &u2
, &u3
, &ch
);
2856 /** Run unit tests for the onion handshake code. */
2858 test_onion_handshake(void)
2861 crypto_dh_env_t
*c_dh
= NULL
;
2862 char c_buf
[ONIONSKIN_CHALLENGE_LEN
];
2866 char s_buf
[ONIONSKIN_REPLY_LEN
];
2870 crypto_pk_env_t
*pk
= NULL
;
2872 pk
= pk_generate(0);
2874 /* client handshake 1. */
2875 memset(c_buf
, 0, ONIONSKIN_CHALLENGE_LEN
);
2876 test_assert(! onion_skin_create(pk
, &c_dh
, c_buf
));
2878 /* server handshake */
2879 memset(s_buf
, 0, ONIONSKIN_REPLY_LEN
);
2880 memset(s_keys
, 0, 40);
2881 test_assert(! onion_skin_server_handshake(c_buf
, pk
, NULL
,
2882 s_buf
, s_keys
, 40));
2884 /* client handshake 2 */
2885 memset(c_keys
, 0, 40);
2886 test_assert(! onion_skin_client_handshake(c_dh
, s_buf
, c_keys
, 40));
2888 if (memcmp(c_keys
, s_keys
, 40)) {
2892 test_memeq(c_keys
, s_keys
, 40);
2893 memset(s_buf
, 0, 40);
2894 test_memneq(c_keys
, s_buf
, 40);
2898 crypto_dh_free(c_dh
);
2900 crypto_free_pk_env(pk
);
2903 /** Run unit tests for router descriptor generation logic. */
2905 test_dir_format(void)
2907 char buf
[8192], buf2
[8192];
2909 char fingerprint
[FINGERPRINT_LEN
+1];
2910 char *pk1_str
= NULL
, *pk2_str
= NULL
, *pk3_str
= NULL
, *cp
;
2911 size_t pk1_str_len
, pk2_str_len
, pk3_str_len
;
2912 routerinfo_t
*r1
=NULL
, *r2
=NULL
;
2913 crypto_pk_env_t
*pk1
= NULL
, *pk2
= NULL
, *pk3
= NULL
;
2914 routerinfo_t
*rp1
= NULL
;
2915 addr_policy_t
*ex1
, *ex2
;
2916 routerlist_t
*dir1
= NULL
, *dir2
= NULL
;
2919 pk1
= pk_generate(0);
2920 pk2
= pk_generate(1);
2921 pk3
= pk_generate(2);
2923 test_assert( is_legal_nickname("a"));
2924 test_assert(!is_legal_nickname(""));
2925 test_assert(!is_legal_nickname("abcdefghijklmnopqrst")); /* 20 chars */
2926 test_assert(!is_legal_nickname("hyphen-")); /* bad char */
2927 test_assert( is_legal_nickname("abcdefghijklmnopqrs")); /* 19 chars */
2928 test_assert(!is_legal_nickname("$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2930 test_assert( is_legal_nickname_or_hexdigest(
2931 "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2932 test_assert( is_legal_nickname_or_hexdigest(
2933 "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA=fred"));
2934 test_assert( is_legal_nickname_or_hexdigest(
2935 "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA~fred"));
2937 test_assert(!is_legal_nickname_or_hexdigest(
2938 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2940 test_assert(!is_legal_nickname_or_hexdigest(
2941 "$AAAAAAzAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2942 /* hex part too long */
2943 test_assert(!is_legal_nickname_or_hexdigest(
2944 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2945 test_assert(!is_legal_nickname_or_hexdigest(
2946 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=fred"));
2948 test_assert(!is_legal_nickname_or_hexdigest(
2949 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="));
2950 test_assert(!is_legal_nickname_or_hexdigest(
2951 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~"));
2952 test_assert(!is_legal_nickname_or_hexdigest(
2953 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~hyphen-"));
2954 test_assert(!is_legal_nickname_or_hexdigest(
2955 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~"
2956 "abcdefghijklmnoppqrst"));
2957 /* Bad extra char. */
2958 test_assert(!is_legal_nickname_or_hexdigest(
2959 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA!"));
2960 test_assert(is_legal_nickname_or_hexdigest("xyzzy"));
2961 test_assert(is_legal_nickname_or_hexdigest("abcdefghijklmnopqrs"));
2962 test_assert(!is_legal_nickname_or_hexdigest("abcdefghijklmnopqrst"));
2964 get_platform_str(platform
, sizeof(platform
));
2965 r1
= tor_malloc_zero(sizeof(routerinfo_t
));
2966 r1
->address
= tor_strdup("18.244.0.1");
2967 r1
->addr
= 0xc0a80001u
; /* 192.168.0.1 */
2968 r1
->cache_info
.published_on
= 0;
2970 r1
->dir_port
= 9003;
2971 r1
->onion_pkey
= crypto_pk_dup_key(pk1
);
2972 r1
->identity_pkey
= crypto_pk_dup_key(pk2
);
2973 r1
->bandwidthrate
= 1000;
2974 r1
->bandwidthburst
= 5000;
2975 r1
->bandwidthcapacity
= 10000;
2976 r1
->exit_policy
= NULL
;
2977 r1
->nickname
= tor_strdup("Magri");
2978 r1
->platform
= tor_strdup(platform
);
2980 ex1
= tor_malloc_zero(sizeof(addr_policy_t
));
2981 ex2
= tor_malloc_zero(sizeof(addr_policy_t
));
2982 ex1
->policy_type
= ADDR_POLICY_ACCEPT
;
2983 tor_addr_from_ipv4h(&ex1
->addr
, 0);
2985 ex1
->prt_min
= ex1
->prt_max
= 80;
2986 ex2
->policy_type
= ADDR_POLICY_REJECT
;
2987 tor_addr_from_ipv4h(&ex2
->addr
, 18<<24);
2989 ex2
->prt_min
= ex2
->prt_max
= 24;
2990 r2
= tor_malloc_zero(sizeof(routerinfo_t
));
2991 r2
->address
= tor_strdup("1.1.1.1");
2992 r2
->addr
= 0x0a030201u
; /* 10.3.2.1 */
2993 r2
->platform
= tor_strdup(platform
);
2994 r2
->cache_info
.published_on
= 5;
2997 r2
->onion_pkey
= crypto_pk_dup_key(pk2
);
2998 r2
->identity_pkey
= crypto_pk_dup_key(pk1
);
2999 r2
->bandwidthrate
= r2
->bandwidthburst
= r2
->bandwidthcapacity
= 3000;
3000 r2
->exit_policy
= smartlist_create();
3001 smartlist_add(r2
->exit_policy
, ex2
);
3002 smartlist_add(r2
->exit_policy
, ex1
);
3003 r2
->nickname
= tor_strdup("Fred");
3005 test_assert(!crypto_pk_write_public_key_to_string(pk1
, &pk1_str
,
3007 test_assert(!crypto_pk_write_public_key_to_string(pk2
, &pk2_str
,
3009 test_assert(!crypto_pk_write_public_key_to_string(pk3
, &pk3_str
,
3012 memset(buf
, 0, 2048);
3013 test_assert(router_dump_router_to_string(buf
, 2048, r1
, pk2
)>0);
3015 strlcpy(buf2
, "router Magri 18.244.0.1 9000 0 9003\n"
3016 "platform Tor "VERSION
" on ", sizeof(buf2
));
3017 strlcat(buf2
, get_uname(), sizeof(buf2
));
3019 "opt protocols Link 1 2 Circuit 1\n"
3020 "published 1970-01-01 00:00:00\n"
3021 "opt fingerprint ", sizeof(buf2
));
3022 test_assert(!crypto_pk_get_fingerprint(pk2
, fingerprint
, 1));
3023 strlcat(buf2
, fingerprint
, sizeof(buf2
));
3024 strlcat(buf2
, "\nuptime 0\n"
3025 /* XXX the "0" above is hard-coded, but even if we made it reflect
3026 * uptime, that still wouldn't make it right, because the two
3027 * descriptors might be made on different seconds... hm. */
3028 "bandwidth 1000 5000 10000\n"
3029 "opt extra-info-digest 0000000000000000000000000000000000000000\n"
3030 "onion-key\n", sizeof(buf2
));
3031 strlcat(buf2
, pk1_str
, sizeof(buf2
));
3032 strlcat(buf2
, "signing-key\n", sizeof(buf2
));
3033 strlcat(buf2
, pk2_str
, sizeof(buf2
));
3034 strlcat(buf2
, "opt hidden-service-dir\n", sizeof(buf2
));
3035 strlcat(buf2
, "reject *:*\nrouter-signature\n", sizeof(buf2
));
3036 buf
[strlen(buf2
)] = '\0'; /* Don't compare the sig; it's never the same
3039 test_streq(buf
, buf2
);
3041 test_assert(router_dump_router_to_string(buf
, 2048, r1
, pk2
)>0);
3043 rp1
= router_parse_entry_from_string((const char*)cp
,NULL
,1,0,NULL
);
3045 test_streq(rp1
->address
, r1
->address
);
3046 test_eq(rp1
->or_port
, r1
->or_port
);
3047 //test_eq(rp1->dir_port, r1->dir_port);
3048 test_eq(rp1
->bandwidthrate
, r1
->bandwidthrate
);
3049 test_eq(rp1
->bandwidthburst
, r1
->bandwidthburst
);
3050 test_eq(rp1
->bandwidthcapacity
, r1
->bandwidthcapacity
);
3051 test_assert(crypto_pk_cmp_keys(rp1
->onion_pkey
, pk1
) == 0);
3052 test_assert(crypto_pk_cmp_keys(rp1
->identity_pkey
, pk2
) == 0);
3053 //test_assert(rp1->exit_policy == NULL);
3056 /* XXX Once we have exit policies, test this again. XXX */
3057 strlcpy(buf2
, "router tor.tor.tor 9005 0 0 3000\n", sizeof(buf2
));
3058 strlcat(buf2
, pk2_str
, sizeof(buf2
));
3059 strlcat(buf2
, "signing-key\n", sizeof(buf2
));
3060 strlcat(buf2
, pk1_str
, sizeof(buf2
));
3061 strlcat(buf2
, "accept *:80\nreject 18.*:24\n\n", sizeof(buf2
));
3062 test_assert(router_dump_router_to_string(buf
, 2048, &r2
, pk2
)>0);
3063 test_streq(buf
, buf2
);
3066 rp2
= router_parse_entry_from_string(&cp
,1);
3068 test_streq(rp2
->address
, r2
.address
);
3069 test_eq(rp2
->or_port
, r2
.or_port
);
3070 test_eq(rp2
->dir_port
, r2
.dir_port
);
3071 test_eq(rp2
->bandwidth
, r2
.bandwidth
);
3072 test_assert(crypto_pk_cmp_keys(rp2
->onion_pkey
, pk2
) == 0);
3073 test_assert(crypto_pk_cmp_keys(rp2
->identity_pkey
, pk1
) == 0);
3074 test_eq(rp2
->exit_policy
->policy_type
, EXIT_POLICY_ACCEPT
);
3075 test_streq(rp2
->exit_policy
->string
, "accept *:80");
3076 test_streq(rp2
->exit_policy
->address
, "*");
3077 test_streq(rp2
->exit_policy
->port
, "80");
3078 test_eq(rp2
->exit_policy
->next
->policy_type
, EXIT_POLICY_REJECT
);
3079 test_streq(rp2
->exit_policy
->next
->string
, "reject 18.*:24");
3080 test_streq(rp2
->exit_policy
->next
->address
, "18.*");
3081 test_streq(rp2
->exit_policy
->next
->port
, "24");
3082 test_assert(rp2
->exit_policy
->next
->next
== NULL
);
3084 /* Okay, now for the directories. */
3086 fingerprint_list
= smartlist_create();
3087 crypto_pk_get_fingerprint(pk2
, buf
, 1);
3088 add_fingerprint_to_dir("Magri", buf
, fingerprint_list
);
3089 crypto_pk_get_fingerprint(pk1
, buf
, 1);
3090 add_fingerprint_to_dir("Fred", buf
, fingerprint_list
);
3096 /* XXXX NM re-enable. */
3097 /* Make sure routers aren't too far in the past any more. */
3098 r1
->cache_info
.published_on
= time(NULL
);
3099 r2
->cache_info
.published_on
= time(NULL
)-3*60*60;
3100 test_assert(router_dump_router_to_string(buf
, 2048, r1
, pk2
)>0);
3101 test_eq(dirserv_add_descriptor(buf
,&m
,""), ROUTER_ADDED_NOTIFY_GENERATOR
);
3102 test_assert(router_dump_router_to_string(buf
, 2048, r2
, pk1
)>0);
3103 test_eq(dirserv_add_descriptor(buf
,&m
,""), ROUTER_ADDED_NOTIFY_GENERATOR
);
3104 get_options()->Nickname
= tor_strdup("DirServer");
3105 test_assert(!dirserv_dump_directory_to_string(&cp
,pk3
, 0));
3106 crypto_pk_get_digest(pk3
, d
);
3107 test_assert(!router_parse_directory(cp
));
3108 test_eq(2, smartlist_len(dir1
->routers
));
3112 dirserv_free_fingerprint_list();
3114 /* Try out version parsing functionality */
3115 test_eq(0, tor_version_parse("0.3.4pre2-cvs", &ver1
));
3116 test_eq(0, ver1
.major
);
3117 test_eq(3, ver1
.minor
);
3118 test_eq(4, ver1
.micro
);
3119 test_eq(VER_PRE
, ver1
.status
);
3120 test_eq(2, ver1
.patchlevel
);
3121 test_eq(0, tor_version_parse("0.3.4rc1", &ver1
));
3122 test_eq(0, ver1
.major
);
3123 test_eq(3, ver1
.minor
);
3124 test_eq(4, ver1
.micro
);
3125 test_eq(VER_RC
, ver1
.status
);
3126 test_eq(1, ver1
.patchlevel
);
3127 test_eq(0, tor_version_parse("1.3.4", &ver1
));
3128 test_eq(1, ver1
.major
);
3129 test_eq(3, ver1
.minor
);
3130 test_eq(4, ver1
.micro
);
3131 test_eq(VER_RELEASE
, ver1
.status
);
3132 test_eq(0, ver1
.patchlevel
);
3133 test_eq(0, tor_version_parse("1.3.4.999", &ver1
));
3134 test_eq(1, ver1
.major
);
3135 test_eq(3, ver1
.minor
);
3136 test_eq(4, ver1
.micro
);
3137 test_eq(VER_RELEASE
, ver1
.status
);
3138 test_eq(999, ver1
.patchlevel
);
3139 test_eq(0, tor_version_parse("0.1.2.4-alpha", &ver1
));
3140 test_eq(0, ver1
.major
);
3141 test_eq(1, ver1
.minor
);
3142 test_eq(2, ver1
.micro
);
3143 test_eq(4, ver1
.patchlevel
);
3144 test_eq(VER_RELEASE
, ver1
.status
);
3145 test_streq("alpha", ver1
.status_tag
);
3146 test_eq(0, tor_version_parse("0.1.2.4", &ver1
));
3147 test_eq(0, ver1
.major
);
3148 test_eq(1, ver1
.minor
);
3149 test_eq(2, ver1
.micro
);
3150 test_eq(4, ver1
.patchlevel
);
3151 test_eq(VER_RELEASE
, ver1
.status
);
3152 test_streq("", ver1
.status_tag
);
3154 #define test_eq_vs(vs1, vs2) test_eq_type(version_status_t, "%d", (vs1), (vs2))
3155 #define test_v_i_o(val, ver, lst) \
3156 test_eq_vs(val, tor_version_is_obsolete(ver, lst))
3158 /* make sure tor_version_is_obsolete() works */
3159 test_v_i_o(VS_OLD
, "0.0.1", "Tor 0.0.2");
3160 test_v_i_o(VS_OLD
, "0.0.1", "0.0.2, Tor 0.0.3");
3161 test_v_i_o(VS_OLD
, "0.0.1", "0.0.2,Tor 0.0.3");
3162 test_v_i_o(VS_OLD
, "0.0.1","0.0.3,BetterTor 0.0.1");
3163 test_v_i_o(VS_RECOMMENDED
, "0.0.2", "Tor 0.0.2,Tor 0.0.3");
3164 test_v_i_o(VS_NEW_IN_SERIES
, "0.0.2", "Tor 0.0.2pre1,Tor 0.0.3");
3165 test_v_i_o(VS_OLD
, "0.0.2", "Tor 0.0.2.1,Tor 0.0.3");
3166 test_v_i_o(VS_NEW
, "0.1.0", "Tor 0.0.2,Tor 0.0.3");
3167 test_v_i_o(VS_RECOMMENDED
, "0.0.7rc2", "0.0.7,Tor 0.0.7rc2,Tor 0.0.8");
3168 test_v_i_o(VS_OLD
, "0.0.5.0", "0.0.5.1-cvs");
3169 test_v_i_o(VS_NEW_IN_SERIES
, "0.0.5.1-cvs", "0.0.5, 0.0.6");
3170 /* Not on list, but newer than any in same series. */
3171 test_v_i_o(VS_NEW_IN_SERIES
, "0.1.0.3",
3172 "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
3173 /* Series newer than any on list. */
3174 test_v_i_o(VS_NEW
, "0.1.2.3", "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
3175 /* Series older than any on list. */
3176 test_v_i_o(VS_OLD
, "0.0.1.3", "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
3177 /* Not on list, not newer than any on same series. */
3178 test_v_i_o(VS_UNRECOMMENDED
, "0.1.0.1",
3179 "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
3180 /* On list, not newer than any on same series. */
3181 test_v_i_o(VS_UNRECOMMENDED
,
3182 "0.1.0.1", "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
3183 test_eq(0, tor_version_as_new_as("Tor 0.0.5", "0.0.9pre1-cvs"));
3184 test_eq(1, tor_version_as_new_as(
3185 "Tor 0.0.8 on Darwin 64-121-192-100.c3-0."
3186 "sfpo-ubr1.sfrn-sfpo.ca.cable.rcn.com Power Macintosh",
3188 test_eq(0, tor_version_as_new_as(
3189 "Tor 0.0.8 on Darwin 64-121-192-100.c3-0."
3190 "sfpo-ubr1.sfrn-sfpo.ca.cable.rcn.com Power Macintosh", "0.0.8.2"));
3192 /* Now try svn revisions. */
3193 test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100)",
3194 "Tor 0.2.1.0-dev (r99)"));
3195 test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100) on Banana Jr",
3196 "Tor 0.2.1.0-dev (r99) on Hal 9000"));
3197 test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100)",
3198 "Tor 0.2.1.0-dev on Colossus"));
3199 test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev (r99)",
3200 "Tor 0.2.1.0-dev (r100)"));
3201 test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev (r99) on MCP",
3202 "Tor 0.2.1.0-dev (r100) on AM"));
3203 test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev",
3204 "Tor 0.2.1.0-dev (r99)"));
3205 test_eq(1, tor_version_as_new_as("Tor 0.2.1.1",
3206 "Tor 0.2.1.0-dev (r99)"));
3209 routerinfo_free(r1
);
3211 routerinfo_free(r2
);
3216 if (pk1
) crypto_free_pk_env(pk1
);
3217 if (pk2
) crypto_free_pk_env(pk2
);
3218 if (pk3
) crypto_free_pk_env(pk3
);
3219 if (rp1
) routerinfo_free(rp1
);
3220 tor_free(dir1
); /* XXXX And more !*/
3221 tor_free(dir2
); /* And more !*/
3224 /** Run unit tests for misc directory functions. */
3228 smartlist_t
*sl
= smartlist_create();
3231 dir_split_resource_into_fingerprint_pairs(
3232 /* Two pairs, out of order, with one duplicate. */
3233 "73656372657420646174612E0000000000FFFFFF-"
3234 "557365204145532d32353620696e73746561642e+"
3235 "73656372657420646174612E0000000000FFFFFF-"
3236 "557365204145532d32353620696e73746561642e+"
3237 "48657861646563696d616c2069736e277420736f-"
3238 "676f6f6420666f7220686964696e6720796f7572.z", sl
);
3240 test_eq(smartlist_len(sl
), 2);
3241 pair
= smartlist_get(sl
, 0);
3242 test_memeq(pair
->first
, "Hexadecimal isn't so", DIGEST_LEN
);
3243 test_memeq(pair
->second
, "good for hiding your", DIGEST_LEN
);
3244 pair
= smartlist_get(sl
, 1);
3245 test_memeq(pair
->first
, "secret data.\0\0\0\0\0\xff\xff\xff", DIGEST_LEN
);
3246 test_memeq(pair
->second
, "Use AES-256 instead.", DIGEST_LEN
);
3249 SMARTLIST_FOREACH(sl
, fp_pair_t
*, pair
, tor_free(pair
));
3253 extern const char AUTHORITY_CERT_1
[];
3254 extern const char AUTHORITY_SIGNKEY_1
[];
3255 extern const char AUTHORITY_CERT_2
[];
3256 extern const char AUTHORITY_SIGNKEY_2
[];
3257 extern const char AUTHORITY_CERT_3
[];
3258 extern const char AUTHORITY_SIGNKEY_3
[];
3260 /** Helper: Test that two networkstatus_voter_info_t do in fact represent the
3261 * same voting authority, and that they do in fact have all the same
3264 test_same_voter(networkstatus_voter_info_t
*v1
,
3265 networkstatus_voter_info_t
*v2
)
3267 test_streq(v1
->nickname
, v2
->nickname
);
3268 test_memeq(v1
->identity_digest
, v2
->identity_digest
, DIGEST_LEN
);
3269 test_streq(v1
->address
, v2
->address
);
3270 test_eq(v1
->addr
, v2
->addr
);
3271 test_eq(v1
->dir_port
, v2
->dir_port
);
3272 test_eq(v1
->or_port
, v2
->or_port
);
3273 test_streq(v1
->contact
, v2
->contact
);
3274 test_memeq(v1
->vote_digest
, v2
->vote_digest
, DIGEST_LEN
);
3279 /** Run unit tests for getting the median of a list. */
3281 test_util_order_functions(void)
3284 // int a=12,b=24,c=25,d=60,e=77;
3286 #define median() median_int(lst, n)
3289 test_eq(12, median()); /* 12 */
3291 //smartlist_shuffle(sl);
3292 test_eq(12, median()); /* 12, 77 */
3294 //smartlist_shuffle(sl);
3295 test_eq(77, median()); /* 12, 77, 77 */
3297 test_eq(24, median()); /* 12,24,77,77 */
3301 //smartlist_shuffle(sl);
3302 test_eq(25, median()); /* 12,12,24,25,60,77,77 */
3309 /** Helper: Make a new routerinfo containing the right information for a
3310 * given vote_routerstatus_t. */
3311 static routerinfo_t
*
3312 generate_ri_from_rs(const vote_routerstatus_t
*vrs
)
3315 const routerstatus_t
*rs
= &vrs
->status
;
3316 static time_t published
= 0;
3318 r
= tor_malloc_zero(sizeof(routerinfo_t
));
3319 memcpy(r
->cache_info
.identity_digest
, rs
->identity_digest
, DIGEST_LEN
);
3320 memcpy(r
->cache_info
.signed_descriptor_digest
, rs
->descriptor_digest
,
3322 r
->cache_info
.do_not_cache
= 1;
3323 r
->cache_info
.routerlist_index
= -1;
3324 r
->cache_info
.signed_descriptor_body
=
3325 tor_strdup("123456789012345678901234567890123");
3326 r
->cache_info
.signed_descriptor_len
=
3327 strlen(r
->cache_info
.signed_descriptor_body
);
3328 r
->exit_policy
= smartlist_create();
3329 r
->cache_info
.published_on
= ++published
+ time(NULL
);
3333 /** Run unit tests for generating and parsing V3 consensus networkstatus
3336 test_v3_networkstatus(void)
3338 authority_cert_t
*cert1
=NULL
, *cert2
=NULL
, *cert3
=NULL
;
3339 crypto_pk_env_t
*sign_skey_1
=NULL
, *sign_skey_2
=NULL
, *sign_skey_3
=NULL
;
3340 crypto_pk_env_t
*sign_skey_leg1
=NULL
;
3341 const char *msg
=NULL
;
3343 time_t now
= time(NULL
);
3344 networkstatus_voter_info_t
*voter
;
3345 networkstatus_t
*vote
=NULL
, *v1
=NULL
, *v2
=NULL
, *v3
=NULL
, *con
=NULL
;
3346 vote_routerstatus_t
*vrs
;
3348 char *v1_text
=NULL
, *v2_text
=NULL
, *v3_text
=NULL
, *consensus_text
=NULL
, *cp
;
3349 smartlist_t
*votes
= smartlist_create();
3351 /* For generating the two other consensuses. */
3352 char *detached_text1
=NULL
, *detached_text2
=NULL
;
3353 char *consensus_text2
=NULL
, *consensus_text3
=NULL
;
3354 networkstatus_t
*con2
=NULL
, *con3
=NULL
;
3355 ns_detached_signatures_t
*dsig1
=NULL
, *dsig2
=NULL
;
3357 /* Parse certificates and keys. */
3358 cert1
= authority_cert_parse_from_string(AUTHORITY_CERT_1
, NULL
);
3360 test_assert(cert1
->is_cross_certified
);
3361 cert2
= authority_cert_parse_from_string(AUTHORITY_CERT_2
, NULL
);
3363 cert3
= authority_cert_parse_from_string(AUTHORITY_CERT_3
, NULL
);
3365 sign_skey_1
= crypto_new_pk_env();
3366 sign_skey_2
= crypto_new_pk_env();
3367 sign_skey_3
= crypto_new_pk_env();
3368 sign_skey_leg1
= pk_generate(4);
3370 test_assert(!crypto_pk_read_private_key_from_string(sign_skey_1
,
3371 AUTHORITY_SIGNKEY_1
));
3372 test_assert(!crypto_pk_read_private_key_from_string(sign_skey_2
,
3373 AUTHORITY_SIGNKEY_2
));
3374 test_assert(!crypto_pk_read_private_key_from_string(sign_skey_3
,
3375 AUTHORITY_SIGNKEY_3
));
3377 test_assert(!crypto_pk_cmp_keys(sign_skey_1
, cert1
->signing_key
));
3378 test_assert(!crypto_pk_cmp_keys(sign_skey_2
, cert2
->signing_key
));
3381 * Set up a vote; generate it; try to parse it.
3383 vote
= tor_malloc_zero(sizeof(networkstatus_t
));
3384 vote
->type
= NS_TYPE_VOTE
;
3385 vote
->published
= now
;
3386 vote
->valid_after
= now
+1000;
3387 vote
->fresh_until
= now
+2000;
3388 vote
->valid_until
= now
+3000;
3389 vote
->vote_seconds
= 100;
3390 vote
->dist_seconds
= 200;
3391 vote
->supported_methods
= smartlist_create();
3392 smartlist_split_string(vote
->supported_methods
, "1 2 3", NULL
, 0, -1);
3393 vote
->client_versions
= tor_strdup("0.1.2.14,0.1.2.15");
3394 vote
->server_versions
= tor_strdup("0.1.2.14,0.1.2.15,0.1.2.16");
3395 vote
->known_flags
= smartlist_create();
3396 smartlist_split_string(vote
->known_flags
,
3397 "Authority Exit Fast Guard Running Stable V2Dir Valid",
3398 0, SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
3399 vote
->voters
= smartlist_create();
3400 voter
= tor_malloc_zero(sizeof(networkstatus_voter_info_t
));
3401 voter
->nickname
= tor_strdup("Voter1");
3402 voter
->address
= tor_strdup("1.2.3.4");
3403 voter
->addr
= 0x01020304;
3404 voter
->dir_port
= 80;
3405 voter
->or_port
= 9000;
3406 voter
->contact
= tor_strdup("voter@example.com");
3407 crypto_pk_get_digest(cert1
->identity_key
, voter
->identity_digest
);
3408 smartlist_add(vote
->voters
, voter
);
3409 vote
->cert
= authority_cert_dup(cert1
);
3410 vote
->routerstatus_list
= smartlist_create();
3411 /* add the first routerstatus. */
3412 vrs
= tor_malloc_zero(sizeof(vote_routerstatus_t
));
3414 vrs
->version
= tor_strdup("0.1.2.14");
3415 rs
->published_on
= now
-1500;
3416 strlcpy(rs
->nickname
, "router2", sizeof(rs
->nickname
));
3417 memset(rs
->identity_digest
, 3, DIGEST_LEN
);
3418 memset(rs
->descriptor_digest
, 78, DIGEST_LEN
);
3419 rs
->addr
= 0x99008801;
3421 rs
->dir_port
= 8000;
3422 /* all flags but running cleared */
3424 smartlist_add(vote
->routerstatus_list
, vrs
);
3425 test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs
), &msg
,0,0)>=0);
3427 /* add the second routerstatus. */
3428 vrs
= tor_malloc_zero(sizeof(vote_routerstatus_t
));
3430 vrs
->version
= tor_strdup("0.2.0.5");
3431 rs
->published_on
= now
-1000;
3432 strlcpy(rs
->nickname
, "router1", sizeof(rs
->nickname
));
3433 memset(rs
->identity_digest
, 5, DIGEST_LEN
);
3434 memset(rs
->descriptor_digest
, 77, DIGEST_LEN
);
3435 rs
->addr
= 0x99009901;
3438 rs
->is_exit
= rs
->is_stable
= rs
->is_fast
= rs
->is_running
=
3439 rs
->is_valid
= rs
->is_v2_dir
= rs
->is_possible_guard
= 1;
3440 smartlist_add(vote
->routerstatus_list
, vrs
);
3441 test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs
), &msg
,0,0)>=0);
3443 /* add the third routerstatus. */
3444 vrs
= tor_malloc_zero(sizeof(vote_routerstatus_t
));
3446 vrs
->version
= tor_strdup("0.1.0.3");
3447 rs
->published_on
= now
-1000;
3448 strlcpy(rs
->nickname
, "router3", sizeof(rs
->nickname
));
3449 memset(rs
->identity_digest
, 33, DIGEST_LEN
);
3450 memset(rs
->descriptor_digest
, 79, DIGEST_LEN
);
3451 rs
->addr
= 0xAA009901;
3453 rs
->dir_port
= 9999;
3454 rs
->is_authority
= rs
->is_exit
= rs
->is_stable
= rs
->is_fast
=
3455 rs
->is_running
= rs
->is_valid
= rs
->is_v2_dir
= rs
->is_possible_guard
= 1;
3456 smartlist_add(vote
->routerstatus_list
, vrs
);
3457 test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs
), &msg
,0,0)>=0);
3459 /* add a fourth routerstatus that is not running. */
3460 vrs
= tor_malloc_zero(sizeof(vote_routerstatus_t
));
3462 vrs
->version
= tor_strdup("0.1.6.3");
3463 rs
->published_on
= now
-1000;
3464 strlcpy(rs
->nickname
, "router4", sizeof(rs
->nickname
));
3465 memset(rs
->identity_digest
, 34, DIGEST_LEN
);
3466 memset(rs
->descriptor_digest
, 48, DIGEST_LEN
);
3467 rs
->addr
= 0xC0000203;
3469 rs
->dir_port
= 1999;
3470 /* Running flag (and others) cleared */
3471 smartlist_add(vote
->routerstatus_list
, vrs
);
3472 test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs
), &msg
,0,0)>=0);
3474 /* dump the vote and try to parse it. */
3475 v1_text
= format_networkstatus_vote(sign_skey_1
, vote
);
3476 test_assert(v1_text
);
3477 v1
= networkstatus_parse_vote_from_string(v1_text
, NULL
, NS_TYPE_VOTE
);
3480 /* Make sure the parsed thing was right. */
3481 test_eq(v1
->type
, NS_TYPE_VOTE
);
3482 test_eq(v1
->published
, vote
->published
);
3483 test_eq(v1
->valid_after
, vote
->valid_after
);
3484 test_eq(v1
->fresh_until
, vote
->fresh_until
);
3485 test_eq(v1
->valid_until
, vote
->valid_until
);
3486 test_eq(v1
->vote_seconds
, vote
->vote_seconds
);
3487 test_eq(v1
->dist_seconds
, vote
->dist_seconds
);
3488 test_streq(v1
->client_versions
, vote
->client_versions
);
3489 test_streq(v1
->server_versions
, vote
->server_versions
);
3490 test_assert(v1
->voters
&& smartlist_len(v1
->voters
));
3491 voter
= smartlist_get(v1
->voters
, 0);
3492 test_streq(voter
->nickname
, "Voter1");
3493 test_streq(voter
->address
, "1.2.3.4");
3494 test_eq(voter
->addr
, 0x01020304);
3495 test_eq(voter
->dir_port
, 80);
3496 test_eq(voter
->or_port
, 9000);
3497 test_streq(voter
->contact
, "voter@example.com");
3498 test_assert(v1
->cert
);
3499 test_assert(!crypto_pk_cmp_keys(sign_skey_1
, v1
->cert
->signing_key
));
3500 cp
= smartlist_join_strings(v1
->known_flags
, ":", 0, NULL
);
3501 test_streq(cp
, "Authority:Exit:Fast:Guard:Running:Stable:V2Dir:Valid");
3503 test_eq(smartlist_len(v1
->routerstatus_list
), 4);
3504 /* Check the first routerstatus. */
3505 vrs
= smartlist_get(v1
->routerstatus_list
, 0);
3507 test_streq(vrs
->version
, "0.1.2.14");
3508 test_eq(rs
->published_on
, now
-1500);
3509 test_streq(rs
->nickname
, "router2");
3510 test_memeq(rs
->identity_digest
,
3511 "\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3",
3513 test_memeq(rs
->descriptor_digest
, "NNNNNNNNNNNNNNNNNNNN", DIGEST_LEN
);
3514 test_eq(rs
->addr
, 0x99008801);
3515 test_eq(rs
->or_port
, 443);
3516 test_eq(rs
->dir_port
, 8000);
3517 test_eq(vrs
->flags
, U64_LITERAL(16)); // no flags except "running"
3518 /* Check the second routerstatus. */
3519 vrs
= smartlist_get(v1
->routerstatus_list
, 1);
3521 test_streq(vrs
->version
, "0.2.0.5");
3522 test_eq(rs
->published_on
, now
-1000);
3523 test_streq(rs
->nickname
, "router1");
3524 test_memeq(rs
->identity_digest
,
3525 "\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5",
3527 test_memeq(rs
->descriptor_digest
, "MMMMMMMMMMMMMMMMMMMM", DIGEST_LEN
);
3528 test_eq(rs
->addr
, 0x99009901);
3529 test_eq(rs
->or_port
, 443);
3530 test_eq(rs
->dir_port
, 0);
3531 test_eq(vrs
->flags
, U64_LITERAL(254)); // all flags except "authority."
3533 /* Generate second vote. It disagrees on some of the times,
3534 * and doesn't list versions, and knows some crazy flags */
3535 vote
->published
= now
+1;
3536 vote
->fresh_until
= now
+3005;
3537 vote
->dist_seconds
= 300;
3538 authority_cert_free(vote
->cert
);
3539 vote
->cert
= authority_cert_dup(cert2
);
3540 tor_free(vote
->client_versions
);
3541 tor_free(vote
->server_versions
);
3542 voter
= smartlist_get(vote
->voters
, 0);
3543 tor_free(voter
->nickname
);
3544 tor_free(voter
->address
);
3545 voter
->nickname
= tor_strdup("Voter2");
3546 voter
->address
= tor_strdup("2.3.4.5");
3547 voter
->addr
= 0x02030405;
3548 crypto_pk_get_digest(cert2
->identity_key
, voter
->identity_digest
);
3549 smartlist_add(vote
->known_flags
, tor_strdup("MadeOfCheese"));
3550 smartlist_add(vote
->known_flags
, tor_strdup("MadeOfTin"));
3551 smartlist_sort_strings(vote
->known_flags
);
3552 vrs
= smartlist_get(vote
->routerstatus_list
, 2);
3553 smartlist_del_keeporder(vote
->routerstatus_list
, 2);
3554 tor_free(vrs
->version
);
3556 vrs
= smartlist_get(vote
->routerstatus_list
, 0);
3557 vrs
->status
.is_fast
= 1;
3558 /* generate and parse. */
3559 v2_text
= format_networkstatus_vote(sign_skey_2
, vote
);
3560 test_assert(v2_text
);
3561 v2
= networkstatus_parse_vote_from_string(v2_text
, NULL
, NS_TYPE_VOTE
);
3563 /* Check that flags come out right.*/
3564 cp
= smartlist_join_strings(v2
->known_flags
, ":", 0, NULL
);
3565 test_streq(cp
, "Authority:Exit:Fast:Guard:MadeOfCheese:MadeOfTin:"
3566 "Running:Stable:V2Dir:Valid");
3568 vrs
= smartlist_get(v2
->routerstatus_list
, 1);
3569 /* 1023 - authority(1) - madeofcheese(16) - madeoftin(32) */
3570 test_eq(vrs
->flags
, U64_LITERAL(974));
3572 /* Generate the third vote. */
3573 vote
->published
= now
;
3574 vote
->fresh_until
= now
+2003;
3575 vote
->dist_seconds
= 250;
3576 authority_cert_free(vote
->cert
);
3577 vote
->cert
= authority_cert_dup(cert3
);
3578 smartlist_add(vote
->supported_methods
, tor_strdup("4"));
3579 vote
->client_versions
= tor_strdup("0.1.2.14,0.1.2.17");
3580 vote
->server_versions
= tor_strdup("0.1.2.10,0.1.2.15,0.1.2.16");
3581 voter
= smartlist_get(vote
->voters
, 0);
3582 tor_free(voter
->nickname
);
3583 tor_free(voter
->address
);
3584 voter
->nickname
= tor_strdup("Voter3");
3585 voter
->address
= tor_strdup("3.4.5.6");
3586 voter
->addr
= 0x03040506;
3587 crypto_pk_get_digest(cert3
->identity_key
, voter
->identity_digest
);
3588 /* This one has a legacy id. */
3589 memset(voter
->legacy_id_digest
, (int)'A', DIGEST_LEN
);
3590 vrs
= smartlist_get(vote
->routerstatus_list
, 0);
3591 smartlist_del_keeporder(vote
->routerstatus_list
, 0);
3592 tor_free(vrs
->version
);
3594 vrs
= smartlist_get(vote
->routerstatus_list
, 0);
3595 memset(vrs
->status
.descriptor_digest
, (int)'Z', DIGEST_LEN
);
3596 test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs
), &msg
,0,0)>=0);
3598 v3_text
= format_networkstatus_vote(sign_skey_3
, vote
);
3599 test_assert(v3_text
);
3601 v3
= networkstatus_parse_vote_from_string(v3_text
, NULL
, NS_TYPE_VOTE
);
3604 /* Compute a consensus as voter 3. */
3605 smartlist_add(votes
, v3
);
3606 smartlist_add(votes
, v1
);
3607 smartlist_add(votes
, v2
);
3608 consensus_text
= networkstatus_compute_consensus(votes
, 3,
3609 cert3
->identity_key
,
3611 "AAAAAAAAAAAAAAAAAAAA",
3613 test_assert(consensus_text
);
3614 con
= networkstatus_parse_vote_from_string(consensus_text
, NULL
,
3617 //log_notice(LD_GENERAL, "<<%s>>\n<<%s>>\n<<%s>>\n",
3618 // v1_text, v2_text, v3_text);
3620 /* Check consensus contents. */
3621 test_assert(con
->type
== NS_TYPE_CONSENSUS
);
3622 test_eq(con
->published
, 0); /* this field only appears in votes. */
3623 test_eq(con
->valid_after
, now
+1000);
3624 test_eq(con
->fresh_until
, now
+2003); /* median */
3625 test_eq(con
->valid_until
, now
+3000);
3626 test_eq(con
->vote_seconds
, 100);
3627 test_eq(con
->dist_seconds
, 250); /* median */
3628 test_streq(con
->client_versions
, "0.1.2.14");
3629 test_streq(con
->server_versions
, "0.1.2.15,0.1.2.16");
3630 cp
= smartlist_join_strings(v2
->known_flags
, ":", 0, NULL
);
3631 test_streq(cp
, "Authority:Exit:Fast:Guard:MadeOfCheese:MadeOfTin:"
3632 "Running:Stable:V2Dir:Valid");
3634 test_eq(4, smartlist_len(con
->voters
)); /*3 voters, 1 legacy key.*/
3635 /* The voter id digests should be in this order. */
3636 test_assert(memcmp(cert2
->cache_info
.identity_digest
,
3637 cert1
->cache_info
.identity_digest
,DIGEST_LEN
)<0);
3638 test_assert(memcmp(cert1
->cache_info
.identity_digest
,
3639 cert3
->cache_info
.identity_digest
,DIGEST_LEN
)<0);
3640 test_same_voter(smartlist_get(con
->voters
, 1),
3641 smartlist_get(v2
->voters
, 0));
3642 test_same_voter(smartlist_get(con
->voters
, 2),
3643 smartlist_get(v1
->voters
, 0));
3644 test_same_voter(smartlist_get(con
->voters
, 3),
3645 smartlist_get(v3
->voters
, 0));
3647 test_assert(!con
->cert
);
3648 test_eq(2, smartlist_len(con
->routerstatus_list
));
3649 /* There should be two listed routers: one with identity 3, one with
3651 /* This one showed up in 2 digests. */
3652 rs
= smartlist_get(con
->routerstatus_list
, 0);
3653 test_memeq(rs
->identity_digest
,
3654 "\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3",
3656 test_memeq(rs
->descriptor_digest
, "NNNNNNNNNNNNNNNNNNNN", DIGEST_LEN
);
3657 test_assert(!rs
->is_authority
);
3658 test_assert(!rs
->is_exit
);
3659 test_assert(!rs
->is_fast
);
3660 test_assert(!rs
->is_possible_guard
);
3661 test_assert(!rs
->is_stable
);
3662 test_assert(rs
->is_running
); /* If it wasn't running it wouldn't be here */
3663 test_assert(!rs
->is_v2_dir
);
3664 test_assert(!rs
->is_valid
);
3665 test_assert(!rs
->is_named
);
3666 /* XXXX check version */
3668 rs
= smartlist_get(con
->routerstatus_list
, 1);
3669 /* This one showed up in 3 digests. Twice with ID 'M', once with 'Z'. */
3670 test_memeq(rs
->identity_digest
,
3671 "\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5",
3673 test_streq(rs
->nickname
, "router1");
3674 test_memeq(rs
->descriptor_digest
, "MMMMMMMMMMMMMMMMMMMM", DIGEST_LEN
);
3675 test_eq(rs
->published_on
, now
-1000);
3676 test_eq(rs
->addr
, 0x99009901);
3677 test_eq(rs
->or_port
, 443);
3678 test_eq(rs
->dir_port
, 0);
3679 test_assert(!rs
->is_authority
);
3680 test_assert(rs
->is_exit
);
3681 test_assert(rs
->is_fast
);
3682 test_assert(rs
->is_possible_guard
);
3683 test_assert(rs
->is_stable
);
3684 test_assert(rs
->is_running
);
3685 test_assert(rs
->is_v2_dir
);
3686 test_assert(rs
->is_valid
);
3687 test_assert(!rs
->is_named
);
3688 /* XXXX check version */
3692 /* Check signatures. the first voter is a pseudo-entry with a legacy key.
3693 * The second one hasn't signed. The fourth one has signed: validate it. */
3694 voter
= smartlist_get(con
->voters
, 1);
3695 test_assert(!voter
->signature
);
3696 test_assert(!voter
->good_signature
);
3697 test_assert(!voter
->bad_signature
);
3699 voter
= smartlist_get(con
->voters
, 3);
3700 test_assert(voter
->signature
);
3701 test_assert(!voter
->good_signature
);
3702 test_assert(!voter
->bad_signature
);
3703 test_assert(!networkstatus_check_voter_signature(con
,
3704 smartlist_get(con
->voters
, 3),
3706 test_assert(voter
->signature
);
3707 test_assert(voter
->good_signature
);
3708 test_assert(!voter
->bad_signature
);
3711 const char *msg
=NULL
;
3712 /* Compute the other two signed consensuses. */
3713 smartlist_shuffle(votes
);
3714 consensus_text2
= networkstatus_compute_consensus(votes
, 3,
3715 cert2
->identity_key
,
3716 sign_skey_2
, NULL
,NULL
);
3717 smartlist_shuffle(votes
);
3718 consensus_text3
= networkstatus_compute_consensus(votes
, 3,
3719 cert1
->identity_key
,
3720 sign_skey_1
, NULL
,NULL
);
3721 test_assert(consensus_text2
);
3722 test_assert(consensus_text3
);
3723 con2
= networkstatus_parse_vote_from_string(consensus_text2
, NULL
,
3725 con3
= networkstatus_parse_vote_from_string(consensus_text3
, NULL
,
3730 /* All three should have the same digest. */
3731 test_memeq(con
->networkstatus_digest
, con2
->networkstatus_digest
,
3733 test_memeq(con
->networkstatus_digest
, con3
->networkstatus_digest
,
3736 /* Extract a detached signature from con3. */
3737 detached_text1
= networkstatus_get_detached_signatures(con3
);
3738 tor_assert(detached_text1
);
3739 /* Try to parse it. */
3740 dsig1
= networkstatus_parse_detached_signatures(detached_text1
, NULL
);
3743 /* Are parsed values as expected? */
3744 test_eq(dsig1
->valid_after
, con3
->valid_after
);
3745 test_eq(dsig1
->fresh_until
, con3
->fresh_until
);
3746 test_eq(dsig1
->valid_until
, con3
->valid_until
);
3747 test_memeq(dsig1
->networkstatus_digest
, con3
->networkstatus_digest
,
3749 test_eq(1, smartlist_len(dsig1
->signatures
));
3750 voter
= smartlist_get(dsig1
->signatures
, 0);
3751 test_memeq(voter
->identity_digest
, cert1
->cache_info
.identity_digest
,
3754 /* Try adding it to con2. */
3755 detached_text2
= networkstatus_get_detached_signatures(con2
);
3756 test_eq(1, networkstatus_add_detached_signatures(con2
, dsig1
, &msg
));
3757 tor_free(detached_text2
);
3758 detached_text2
= networkstatus_get_detached_signatures(con2
);
3759 //printf("\n<%s>\n", detached_text2);
3760 dsig2
= networkstatus_parse_detached_signatures(detached_text2
, NULL
);
3764 SMARTLIST_FOREACH(dsig2->signatures, networkstatus_voter_info_t *, vi, {
3766 base16_encode(hd, sizeof(hd), vi->identity_digest, DIGEST_LEN);
3770 test_eq(2, smartlist_len(dsig2
->signatures
));
3772 /* Try adding to con2 twice; verify that nothing changes. */
3773 test_eq(0, networkstatus_add_detached_signatures(con2
, dsig1
, &msg
));
3776 test_eq(2, networkstatus_add_detached_signatures(con
, dsig2
, &msg
));
3777 /* Check signatures */
3778 test_assert(!networkstatus_check_voter_signature(con
,
3779 smartlist_get(con
->voters
, 1),
3781 test_assert(!networkstatus_check_voter_signature(con
,
3782 smartlist_get(con
->voters
, 2),
3788 smartlist_free(votes
);
3792 tor_free(consensus_text
);
3795 networkstatus_vote_free(vote
);
3797 networkstatus_vote_free(v1
);
3799 networkstatus_vote_free(v2
);
3801 networkstatus_vote_free(v3
);
3803 networkstatus_vote_free(con
);
3805 crypto_free_pk_env(sign_skey_1
);
3807 crypto_free_pk_env(sign_skey_2
);
3809 crypto_free_pk_env(sign_skey_3
);
3811 crypto_free_pk_env(sign_skey_leg1
);
3813 authority_cert_free(cert1
);
3815 authority_cert_free(cert2
);
3817 authority_cert_free(cert3
);
3819 tor_free(consensus_text2
);
3820 tor_free(consensus_text3
);
3821 tor_free(detached_text1
);
3822 tor_free(detached_text2
);
3824 networkstatus_vote_free(con2
);
3826 networkstatus_vote_free(con3
);
3828 ns_detached_signatures_free(dsig1
);
3830 ns_detached_signatures_free(dsig2
);
3833 /** Helper: Parse the exit policy string in <b>policy_str</b>, and make sure
3834 * that policies_summarize() produces the string <b>expected_summary</b> from
3837 test_policy_summary_helper(const char *policy_str
,
3838 const char *expected_summary
)
3841 smartlist_t
*policy
= smartlist_create();
3842 char *summary
= NULL
;
3845 line
.key
= (char*)"foo";
3846 line
.value
= (char *)policy_str
;
3849 r
= policies_parse_exit_policy(&line
, &policy
, 0, NULL
);
3851 summary
= policy_summarize(policy
);
3853 test_assert(summary
!= NULL
);
3854 test_streq(summary
, expected_summary
);
3859 addr_policy_list_free(policy
);
3862 /** Run unit tests for generating summary lines of exit policies */
3867 smartlist_t
*policy
= NULL
, *policy2
= NULL
;
3871 smartlist_t
*sm
= NULL
;
3872 char *policy_str
= NULL
;
3874 policy
= smartlist_create();
3876 p
= router_parse_addr_policy_item_from_string("reject 192.168.0.0/16:*",-1);
3877 test_assert(p
!= NULL
);
3878 test_eq(ADDR_POLICY_REJECT
, p
->policy_type
);
3879 tor_addr_from_ipv4h(&tar
, 0xc0a80000u
);
3880 test_eq(0, tor_addr_compare(&p
->addr
, &tar
, CMP_EXACT
));
3881 test_eq(16, p
->maskbits
);
3882 test_eq(1, p
->prt_min
);
3883 test_eq(65535, p
->prt_max
);
3885 smartlist_add(policy
, p
);
3887 test_assert(ADDR_POLICY_ACCEPTED
==
3888 compare_addr_to_addr_policy(0x01020304u
, 2, policy
));
3889 test_assert(ADDR_POLICY_PROBABLY_ACCEPTED
==
3890 compare_addr_to_addr_policy(0, 2, policy
));
3891 test_assert(ADDR_POLICY_REJECTED
==
3892 compare_addr_to_addr_policy(0xc0a80102, 2, policy
));
3895 test_assert(0 == policies_parse_exit_policy(NULL
, &policy2
, 1, NULL
));
3896 test_assert(policy2
);
3898 test_assert(!exit_policy_is_general_exit(policy
));
3899 test_assert(exit_policy_is_general_exit(policy2
));
3900 test_assert(!exit_policy_is_general_exit(NULL
));
3902 test_assert(cmp_addr_policies(policy
, policy2
));
3903 test_assert(cmp_addr_policies(policy
, NULL
));
3904 test_assert(!cmp_addr_policies(policy2
, policy2
));
3905 test_assert(!cmp_addr_policies(NULL
, NULL
));
3907 test_assert(!policy_is_reject_star(policy2
));
3908 test_assert(policy_is_reject_star(policy
));
3909 test_assert(policy_is_reject_star(NULL
));
3911 addr_policy_list_free(policy
);
3914 /* make sure compacting logic works. */
3916 line
.key
= (char*)"foo";
3917 line
.value
= (char*)"accept *:80,reject private:*,reject *:*";
3919 test_assert(0 == policies_parse_exit_policy(&line
, &policy
, 0, NULL
));
3920 test_assert(policy
);
3921 //test_streq(policy->string, "accept *:80");
3922 //test_streq(policy->next->string, "reject *:*");
3923 test_eq(smartlist_len(policy
), 2);
3925 /* test policy summaries */
3926 /* check if we properly ignore private IP addresses */
3927 test_policy_summary_helper("reject 192.168.0.0/16:*,"
3928 "reject 0.0.0.0/8:*,"
3929 "reject 10.0.0.0/8:*,"
3934 /* check all accept policies, and proper counting of rejects */
3935 test_policy_summary_helper("reject 11.0.0.0/9:80,"
3936 "reject 12.0.0.0/9:80,"
3937 "reject 13.0.0.0/9:80,"
3938 "reject 14.0.0.0/9:80,"
3939 "accept *:*", "accept 1-65535");
3940 test_policy_summary_helper("reject 11.0.0.0/9:80,"
3941 "reject 12.0.0.0/9:80,"
3942 "reject 13.0.0.0/9:80,"
3943 "reject 14.0.0.0/9:80,"
3944 "reject 15.0.0.0:81,"
3945 "accept *:*", "accept 1-65535");
3946 test_policy_summary_helper("reject 11.0.0.0/9:80,"
3947 "reject 12.0.0.0/9:80,"
3948 "reject 13.0.0.0/9:80,"
3949 "reject 14.0.0.0/9:80,"
3950 "reject 15.0.0.0:80,"
3954 test_policy_summary_helper("accept 11.0.0.0/9:80,"
3958 test_policy_summary_helper("accept *:80,"
3963 "accept 80-81,100-111");
3965 test_policy_summary_helper("accept *:1,"
3969 "accept 1,3,65535");
3971 test_policy_summary_helper("accept *:1,"
3977 test_policy_summary_helper("reject *:1,"
3984 /* truncation ports */
3985 sm
= smartlist_create();
3986 for (i
=1; i
<2000; i
+=2) {
3987 char buf
[POLICY_BUF_LEN
];
3988 tor_snprintf(buf
, sizeof(buf
), "reject *:%d", i
);
3989 smartlist_add(sm
, tor_strdup(buf
));
3991 smartlist_add(sm
, tor_strdup("accept *:*"));
3992 policy_str
= smartlist_join_strings(sm
, ",", 0, NULL
);
3993 test_policy_summary_helper( policy_str
,
3994 "accept 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,"
3995 "46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,"
3996 "92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,"
3997 "130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,"
3998 "166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198,200,"
3999 "202,204,206,208,210,212,214,216,218,220,222,224,226,228,230,232,234,236,"
4000 "238,240,242,244,246,248,250,252,254,256,258,260,262,264,266,268,270,272,"
4001 "274,276,278,280,282,284,286,288,290,292,294,296,298,300,302,304,306,308,"
4002 "310,312,314,316,318,320,322,324,326,328,330,332,334,336,338,340,342,344,"
4003 "346,348,350,352,354,356,358,360,362,364,366,368,370,372,374,376,378,380,"
4004 "382,384,386,388,390,392,394,396,398,400,402,404,406,408,410,412,414,416,"
4005 "418,420,422,424,426,428,430,432,434,436,438,440,442,444,446,448,450,452,"
4006 "454,456,458,460,462,464,466,468,470,472,474,476,478,480,482,484,486,488,"
4007 "490,492,494,496,498,500,502,504,506,508,510,512,514,516,518,520,522");
4011 addr_policy_list_free(policy
);
4013 addr_policy_list_free(policy2
);
4014 tor_free(policy_str
);
4016 SMARTLIST_FOREACH(sm
, char *, s
, tor_free(s
));
4021 /** Run unit tests for basic rendezvous functions. */
4025 char address1
[] = "fooaddress.onion";
4026 char address2
[] = "aaaaaaaaaaaaaaaa.onion";
4027 char address3
[] = "fooaddress.exit";
4028 char address4
[] = "www.torproject.org";
4029 rend_service_descriptor_t
*d1
=
4030 tor_malloc_zero(sizeof(rend_service_descriptor_t
));
4031 rend_service_descriptor_t
*d2
= NULL
;
4032 char *encoded
= NULL
;
4036 crypto_pk_env_t
*pk1
= pk_generate(0), *pk2
= pk_generate(1);
4038 /* Test unversioned (v0) descriptor */
4039 d1
->pk
= crypto_pk_dup_key(pk1
);
4041 d1
->timestamp
= now
;
4043 d1
->intro_nodes
= smartlist_create();
4044 for (i
= 0; i
< 3; i
++) {
4045 rend_intro_point_t
*intro
= tor_malloc_zero(sizeof(rend_intro_point_t
));
4046 intro
->extend_info
= tor_malloc_zero(sizeof(extend_info_t
));
4047 crypto_rand(intro
->extend_info
->identity_digest
, DIGEST_LEN
);
4048 intro
->extend_info
->nickname
[0] = '$';
4049 base16_encode(intro
->extend_info
->nickname
+1, HEX_DIGEST_LEN
+1,
4050 intro
->extend_info
->identity_digest
, DIGEST_LEN
);
4051 smartlist_add(d1
->intro_nodes
, intro
);
4053 test_assert(! rend_encode_service_descriptor(d1
, pk1
, &encoded
, &len
));
4054 d2
= rend_parse_service_descriptor(encoded
, len
);
4057 test_assert(!crypto_pk_cmp_keys(d1
->pk
, d2
->pk
));
4058 test_eq(d2
->timestamp
, now
);
4059 test_eq(d2
->version
, 0);
4060 test_eq(d2
->protocols
, 1<<2);
4061 test_eq(smartlist_len(d2
->intro_nodes
), 3);
4062 for (i
= 0; i
< 3; i
++) {
4063 rend_intro_point_t
*intro1
= smartlist_get(d1
->intro_nodes
, i
);
4064 rend_intro_point_t
*intro2
= smartlist_get(d2
->intro_nodes
, i
);
4065 test_streq(intro1
->extend_info
->nickname
,
4066 intro2
->extend_info
->nickname
);
4069 test_assert(BAD_HOSTNAME
== parse_extended_hostname(address1
));
4070 test_assert(ONION_HOSTNAME
== parse_extended_hostname(address2
));
4071 test_assert(EXIT_HOSTNAME
== parse_extended_hostname(address3
));
4072 test_assert(NORMAL_HOSTNAME
== parse_extended_hostname(address4
));
4074 crypto_free_pk_env(pk1
);
4075 crypto_free_pk_env(pk2
);
4077 rend_service_descriptor_free(d1
);
4078 rend_service_descriptor_free(d2
);
4083 crypto_free_pk_env(pk1
);
4085 crypto_free_pk_env(pk2
);
4087 rend_service_descriptor_free(d1
);
4089 rend_service_descriptor_free(d2
);
4093 /** Run AES performance benchmarks. */
4099 crypto_cipher_env_t
*c
;
4100 struct timeval start
, end
;
4101 const int iters
= 100000;
4103 c
= crypto_new_cipher_env();
4104 crypto_cipher_generate_key(c
);
4105 crypto_cipher_encrypt_init_cipher(c
);
4106 for (len
= 1; len
<= 8192; len
*= 2) {
4107 b1
= tor_malloc_zero(len
);
4108 b2
= tor_malloc_zero(len
);
4109 tor_gettimeofday(&start
);
4110 for (i
= 0; i
< iters
; ++i
) {
4111 crypto_cipher_encrypt(c
, b1
, b2
, len
);
4113 tor_gettimeofday(&end
);
4116 nsec
= (uint64_t) tv_udiff(&start
,&end
);
4118 nsec
/= (iters
*len
);
4119 printf("%d bytes: "U64_FORMAT
" nsec per byte\n", len
,
4120 U64_PRINTF_ARG(nsec
));
4122 crypto_free_cipher_env(c
);
4125 /** Run digestmap_t performance benchmarks. */
4129 smartlist_t
*sl
= smartlist_create();
4130 smartlist_t
*sl2
= smartlist_create();
4131 struct timeval start
, end
, pt2
, pt3
, pt4
;
4132 const int iters
= 10000;
4133 const int elts
= 4000;
4134 const int fpostests
= 1000000;
4137 digestmap_t
*dm
= digestmap_new();
4138 digestset_t
*ds
= digestset_new(elts
);
4140 for (i
= 0; i
< elts
; ++i
) {
4142 smartlist_add(sl
, tor_memdup(d
, 20));
4144 for (i
= 0; i
< elts
; ++i
) {
4146 smartlist_add(sl2
, tor_memdup(d
, 20));
4148 printf("nbits=%d\n", ds
->mask
+1);
4150 tor_gettimeofday(&start
);
4151 for (i
= 0; i
< iters
; ++i
) {
4152 SMARTLIST_FOREACH(sl
, const char *, cp
, digestmap_set(dm
, cp
, (void*)1));
4154 tor_gettimeofday(&pt2
);
4155 for (i
= 0; i
< iters
; ++i
) {
4156 SMARTLIST_FOREACH(sl
, const char *, cp
, digestmap_get(dm
, cp
));
4157 SMARTLIST_FOREACH(sl2
, const char *, cp
, digestmap_get(dm
, cp
));
4159 tor_gettimeofday(&pt3
);
4160 for (i
= 0; i
< iters
; ++i
) {
4161 SMARTLIST_FOREACH(sl
, const char *, cp
, digestset_add(ds
, cp
));
4163 tor_gettimeofday(&pt4
);
4164 for (i
= 0; i
< iters
; ++i
) {
4165 SMARTLIST_FOREACH(sl
, const char *, cp
, n
+= digestset_isin(ds
, cp
));
4166 SMARTLIST_FOREACH(sl2
, const char *, cp
, n
+= digestset_isin(ds
, cp
));
4168 tor_gettimeofday(&end
);
4170 for (i
= 0; i
< fpostests
; ++i
) {
4172 if (digestset_isin(ds
, d
)) ++fp
;
4175 printf("%ld\n",(unsigned long)tv_udiff(&start
, &pt2
));
4176 printf("%ld\n",(unsigned long)tv_udiff(&pt2
, &pt3
));
4177 printf("%ld\n",(unsigned long)tv_udiff(&pt3
, &pt4
));
4178 printf("%ld\n",(unsigned long)tv_udiff(&pt4
, &end
));
4179 printf("-- %d\n", n
);
4180 printf("++ %f\n", fp
/(double)fpostests
);
4181 digestmap_free(dm
, NULL
);
4183 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
4184 SMARTLIST_FOREACH(sl2
, char *, cp
, tor_free(cp
));
4186 smartlist_free(sl2
);
4189 /** Run unittests for memory pool allocator */
4191 test_util_mempool(void)
4193 mp_pool_t
*pool
= NULL
;
4194 smartlist_t
*allocated
= NULL
;
4197 pool
= mp_pool_new(1, 100);
4199 test_assert(pool
->new_chunk_capacity
>= 100);
4200 test_assert(pool
->item_alloc_size
>= sizeof(void*)+1);
4201 mp_pool_destroy(pool
);
4204 pool
= mp_pool_new(241, 2500);
4206 test_assert(pool
->new_chunk_capacity
>= 10);
4207 test_assert(pool
->item_alloc_size
>= sizeof(void*)+241);
4208 test_eq(pool
->item_alloc_size
& 0x03, 0);
4209 test_assert(pool
->new_chunk_capacity
< 60);
4211 allocated
= smartlist_create();
4212 for (i
= 0; i
< 20000; ++i
) {
4213 if (smartlist_len(allocated
) < 20 || crypto_rand_int(2)) {
4214 void *m
= mp_pool_get(pool
);
4215 memset(m
, 0x09, 241);
4216 smartlist_add(allocated
, m
);
4217 //printf("%d: %p\n", i, m);
4218 //mp_pool_assert_ok(pool);
4220 int idx
= crypto_rand_int(smartlist_len(allocated
));
4221 void *m
= smartlist_get(allocated
, idx
);
4222 //printf("%d: free %p\n", i, m);
4223 smartlist_del(allocated
, idx
);
4225 //mp_pool_assert_ok(pool);
4227 if (crypto_rand_int(777)==0)
4228 mp_pool_clean(pool
, 1, 1);
4231 mp_pool_assert_ok(pool
);
4236 SMARTLIST_FOREACH(allocated
, void *, m
, mp_pool_release(m
));
4237 mp_pool_assert_ok(pool
);
4238 mp_pool_clean(pool
, 0, 0);
4239 mp_pool_assert_ok(pool
);
4240 smartlist_free(allocated
);
4244 mp_pool_destroy(pool
);
4247 /** Run unittests for memory area allocator */
4249 test_util_memarea(void)
4251 memarea_t
*area
= memarea_new();
4252 char *p1
, *p2
, *p3
, *p1_orig
;
4253 void *malloced_ptr
= NULL
;
4258 p1_orig
= p1
= memarea_alloc(area
,64);
4259 p2
= memarea_alloc_zero(area
,52);
4260 p3
= memarea_alloc(area
,11);
4262 test_assert(memarea_owns_ptr(area
, p1
));
4263 test_assert(memarea_owns_ptr(area
, p2
));
4264 test_assert(memarea_owns_ptr(area
, p3
));
4265 /* Make sure we left enough space. */
4266 test_assert(p1
+64 <= p2
);
4267 test_assert(p2
+52 <= p3
);
4268 /* Make sure we aligned. */
4269 test_eq(((uintptr_t)p1
) % sizeof(void*), 0);
4270 test_eq(((uintptr_t)p2
) % sizeof(void*), 0);
4271 test_eq(((uintptr_t)p3
) % sizeof(void*), 0);
4272 test_assert(!memarea_owns_ptr(area
, p3
+8192));
4273 test_assert(!memarea_owns_ptr(area
, p3
+30));
4274 test_assert(tor_mem_is_zero(p2
, 52));
4275 /* Make sure we don't overalign. */
4276 p1
= memarea_alloc(area
, 1);
4277 p2
= memarea_alloc(area
, 1);
4278 test_eq(p1
+sizeof(void*), p2
);
4280 malloced_ptr
= tor_malloc(64);
4281 test_assert(!memarea_owns_ptr(area
, malloced_ptr
));
4282 tor_free(malloced_ptr
);
4285 /* memarea_memdup */
4287 malloced_ptr
= tor_malloc(64);
4288 crypto_rand((char*)malloced_ptr
, 64);
4289 p1
= memarea_memdup(area
, malloced_ptr
, 64);
4290 test_assert(p1
!= malloced_ptr
);
4291 test_memeq(p1
, malloced_ptr
, 64);
4292 tor_free(malloced_ptr
);
4295 /* memarea_strdup. */
4296 p1
= memarea_strdup(area
,"");
4297 p2
= memarea_strdup(area
, "abcd");
4301 test_streq(p2
, "abcd");
4303 /* memarea_strndup. */
4305 const char *s
= "Ad ogni porta batte la morte e grida: il nome!";
4306 /* (From Turandot, act 3.) */
4307 size_t len
= strlen(s
);
4308 p1
= memarea_strndup(area
, s
, 1000);
4309 p2
= memarea_strndup(area
, s
, 10);
4311 test_assert(p2
>= p1
+ len
+ 1);
4312 test_memeq(s
, p2
, 10);
4313 test_eq(p2
[10], '\0');
4314 p3
= memarea_strndup(area
, s
, len
);
4316 p3
= memarea_strndup(area
, s
, len
-1);
4317 test_memeq(s
, p3
, len
-1);
4318 test_eq(p3
[len
-1], '\0');
4321 memarea_clear(area
);
4322 p1
= memarea_alloc(area
, 1);
4323 test_eq(p1
, p1_orig
);
4324 memarea_clear(area
);
4326 /* Check for running over an area's size. */
4327 for (i
= 0; i
< 512; ++i
) {
4328 p1
= memarea_alloc(area
, crypto_rand_int(5)+1);
4329 test_assert(memarea_owns_ptr(area
, p1
));
4331 memarea_assert_ok(area
);
4332 /* Make sure we can allocate a too-big object. */
4333 p1
= memarea_alloc_zero(area
, 9000);
4334 p2
= memarea_alloc_zero(area
, 16);
4335 test_assert(memarea_owns_ptr(area
, p1
));
4336 test_assert(memarea_owns_ptr(area
, p2
));
4339 memarea_drop_all(area
);
4340 tor_free(malloced_ptr
);
4343 /** Run unit tests for utility functions to get file names relative to
4344 * the data directory. */
4346 test_util_datadir(void)
4351 f
= get_datadir_fname(NULL
);
4352 test_streq(f
, temp_dir
);
4354 f
= get_datadir_fname("state");
4355 tor_snprintf(buf
, sizeof(buf
), "%s"PATH_SEPARATOR
"state", temp_dir
);
4358 f
= get_datadir_fname2("cache", "thingy");
4359 tor_snprintf(buf
, sizeof(buf
),
4360 "%s"PATH_SEPARATOR
"cache"PATH_SEPARATOR
"thingy", temp_dir
);
4363 f
= get_datadir_fname2_suffix("cache", "thingy", ".foo");
4364 tor_snprintf(buf
, sizeof(buf
),
4365 "%s"PATH_SEPARATOR
"cache"PATH_SEPARATOR
"thingy.foo", temp_dir
);
4368 f
= get_datadir_fname_suffix("cache", ".foo");
4369 tor_snprintf(buf
, sizeof(buf
), "%s"PATH_SEPARATOR
"cache.foo",
4377 /** Test AES-CTR encryption and decryption with IV. */
4379 test_crypto_aes_iv(void)
4381 crypto_cipher_env_t
*cipher
;
4382 char *plain
, *encrypted1
, *encrypted2
, *decrypted1
, *decrypted2
;
4383 char plain_1
[1], plain_15
[15], plain_16
[16], plain_17
[17];
4384 char key1
[16], key2
[16];
4385 ssize_t encrypted_size
, decrypted_size
;
4387 plain
= tor_malloc(4095);
4388 encrypted1
= tor_malloc(4095 + 1 + 16);
4389 encrypted2
= tor_malloc(4095 + 1 + 16);
4390 decrypted1
= tor_malloc(4095 + 1);
4391 decrypted2
= tor_malloc(4095 + 1);
4393 crypto_rand(plain
, 4095);
4394 crypto_rand(key1
, 16);
4395 crypto_rand(key2
, 16);
4396 crypto_rand(plain_1
, 1);
4397 crypto_rand(plain_15
, 15);
4398 crypto_rand(plain_16
, 16);
4399 crypto_rand(plain_17
, 17);
4400 key1
[0] = key2
[0] + 128; /* Make sure that contents are different. */
4401 /* Encrypt and decrypt with the same key. */
4402 cipher
= crypto_create_init_cipher(key1
, 1);
4403 encrypted_size
= crypto_cipher_encrypt_with_iv(cipher
, encrypted1
, 16 + 4095,
4405 crypto_free_cipher_env(cipher
);
4407 test_eq(encrypted_size
, 16 + 4095);
4408 tor_assert(encrypted_size
> 0); /* This is obviously true, since 4111 is
4409 * greater than 0, but its truth is not
4410 * obvious to all analysis tools. */
4411 cipher
= crypto_create_init_cipher(key1
, 0);
4412 decrypted_size
= crypto_cipher_decrypt_with_iv(cipher
, decrypted1
, 4095,
4413 encrypted1
, encrypted_size
);
4414 crypto_free_cipher_env(cipher
);
4416 test_eq(decrypted_size
, 4095);
4417 tor_assert(decrypted_size
> 0);
4418 test_memeq(plain
, decrypted1
, 4095);
4419 /* Encrypt a second time (with a new random initialization vector). */
4420 cipher
= crypto_create_init_cipher(key1
, 1);
4421 encrypted_size
= crypto_cipher_encrypt_with_iv(cipher
, encrypted2
, 16 + 4095,
4423 crypto_free_cipher_env(cipher
);
4425 test_eq(encrypted_size
, 16 + 4095);
4426 tor_assert(encrypted_size
> 0);
4427 cipher
= crypto_create_init_cipher(key1
, 0);
4428 decrypted_size
= crypto_cipher_decrypt_with_iv(cipher
, decrypted2
, 4095,
4429 encrypted2
, encrypted_size
);
4430 crypto_free_cipher_env(cipher
);
4432 test_eq(decrypted_size
, 4095);
4433 tor_assert(decrypted_size
> 0);
4434 test_memeq(plain
, decrypted2
, 4095);
4435 test_memneq(encrypted1
, encrypted2
, encrypted_size
);
4436 /* Decrypt with the wrong key. */
4437 cipher
= crypto_create_init_cipher(key2
, 0);
4438 decrypted_size
= crypto_cipher_decrypt_with_iv(cipher
, decrypted2
, 4095,
4439 encrypted1
, encrypted_size
);
4440 crypto_free_cipher_env(cipher
);
4442 test_memneq(plain
, decrypted2
, encrypted_size
);
4443 /* Alter the initialization vector. */
4444 encrypted1
[0] += 42;
4445 cipher
= crypto_create_init_cipher(key1
, 0);
4446 decrypted_size
= crypto_cipher_decrypt_with_iv(cipher
, decrypted1
, 4095,
4447 encrypted1
, encrypted_size
);
4448 crypto_free_cipher_env(cipher
);
4450 test_memneq(plain
, decrypted2
, 4095);
4451 /* Special length case: 1. */
4452 cipher
= crypto_create_init_cipher(key1
, 1);
4453 encrypted_size
= crypto_cipher_encrypt_with_iv(cipher
, encrypted1
, 16 + 1,
4455 crypto_free_cipher_env(cipher
);
4457 test_eq(encrypted_size
, 16 + 1);
4458 tor_assert(encrypted_size
> 0);
4459 cipher
= crypto_create_init_cipher(key1
, 0);
4460 decrypted_size
= crypto_cipher_decrypt_with_iv(cipher
, decrypted1
, 1,
4461 encrypted1
, encrypted_size
);
4462 crypto_free_cipher_env(cipher
);
4464 test_eq(decrypted_size
, 1);
4465 tor_assert(decrypted_size
> 0);
4466 test_memeq(plain_1
, decrypted1
, 1);
4467 /* Special length case: 15. */
4468 cipher
= crypto_create_init_cipher(key1
, 1);
4469 encrypted_size
= crypto_cipher_encrypt_with_iv(cipher
, encrypted1
, 16 + 15,
4471 crypto_free_cipher_env(cipher
);
4473 test_eq(encrypted_size
, 16 + 15);
4474 tor_assert(encrypted_size
> 0);
4475 cipher
= crypto_create_init_cipher(key1
, 0);
4476 decrypted_size
= crypto_cipher_decrypt_with_iv(cipher
, decrypted1
, 15,
4477 encrypted1
, encrypted_size
);
4478 crypto_free_cipher_env(cipher
);
4480 test_eq(decrypted_size
, 15);
4481 tor_assert(decrypted_size
> 0);
4482 test_memeq(plain_15
, decrypted1
, 15);
4483 /* Special length case: 16. */
4484 cipher
= crypto_create_init_cipher(key1
, 1);
4485 encrypted_size
= crypto_cipher_encrypt_with_iv(cipher
, encrypted1
, 16 + 16,
4487 crypto_free_cipher_env(cipher
);
4489 test_eq(encrypted_size
, 16 + 16);
4490 tor_assert(encrypted_size
> 0);
4491 cipher
= crypto_create_init_cipher(key1
, 0);
4492 decrypted_size
= crypto_cipher_decrypt_with_iv(cipher
, decrypted1
, 16,
4493 encrypted1
, encrypted_size
);
4494 crypto_free_cipher_env(cipher
);
4496 test_eq(decrypted_size
, 16);
4497 tor_assert(decrypted_size
> 0);
4498 test_memeq(plain_16
, decrypted1
, 16);
4499 /* Special length case: 17. */
4500 cipher
= crypto_create_init_cipher(key1
, 1);
4501 encrypted_size
= crypto_cipher_encrypt_with_iv(cipher
, encrypted1
, 16 + 17,
4503 crypto_free_cipher_env(cipher
);
4505 test_eq(encrypted_size
, 16 + 17);
4506 tor_assert(encrypted_size
> 0);
4507 cipher
= crypto_create_init_cipher(key1
, 0);
4508 decrypted_size
= crypto_cipher_decrypt_with_iv(cipher
, decrypted1
, 17,
4509 encrypted1
, encrypted_size
);
4510 test_eq(decrypted_size
, 17);
4511 tor_assert(decrypted_size
> 0);
4512 test_memeq(plain_17
, decrypted1
, 17);
4517 tor_free(encrypted1
);
4518 tor_free(encrypted2
);
4519 tor_free(decrypted1
);
4520 tor_free(decrypted2
);
4522 crypto_free_cipher_env(cipher
);
4525 /** Test base32 decoding. */
4527 test_crypto_base32_decode(void)
4529 char plain
[60], encoded
[96 + 1], decoded
[60];
4531 crypto_rand(plain
, 60);
4532 /* Encode and decode a random string. */
4533 base32_encode(encoded
, 96 + 1, plain
, 60);
4534 res
= base32_decode(decoded
, 60, encoded
, 96);
4536 test_memeq(plain
, decoded
, 60);
4537 /* Encode, uppercase, and decode a random string. */
4538 base32_encode(encoded
, 96 + 1, plain
, 60);
4539 tor_strupper(encoded
);
4540 res
= base32_decode(decoded
, 60, encoded
, 96);
4542 test_memeq(plain
, decoded
, 60);
4543 /* Change encoded string and decode. */
4544 if (encoded
[0] == 'A' || encoded
[0] == 'a')
4548 res
= base32_decode(decoded
, 60, encoded
, 96);
4550 test_memneq(plain
, decoded
, 60);
4551 /* Bad encodings. */
4553 res
= base32_decode(decoded
, 60, encoded
, 96);
4554 test_assert(res
< 0);
4560 /** Test encoding and parsing of v2 rendezvous service descriptors. */
4562 test_rend_fns_v2(void)
4564 rend_service_descriptor_t
*generated
= NULL
, *parsed
= NULL
;
4565 char service_id
[DIGEST_LEN
];
4566 char service_id_base32
[REND_SERVICE_ID_LEN_BASE32
+1];
4567 const char *next_desc
;
4568 smartlist_t
*descs
= smartlist_create();
4569 char computed_desc_id
[DIGEST_LEN
];
4570 char parsed_desc_id
[DIGEST_LEN
];
4571 crypto_pk_env_t
*pk1
= NULL
, *pk2
= NULL
;
4573 char *intro_points_encrypted
= NULL
;
4574 size_t intro_points_size
;
4575 size_t encoded_size
;
4577 pk1
= pk_generate(0);
4578 pk2
= pk_generate(1);
4579 generated
= tor_malloc_zero(sizeof(rend_service_descriptor_t
));
4580 generated
->pk
= crypto_pk_dup_key(pk1
);
4581 crypto_pk_get_digest(generated
->pk
, service_id
);
4582 base32_encode(service_id_base32
, REND_SERVICE_ID_LEN_BASE32
+1,
4583 service_id
, REND_SERVICE_ID_LEN
);
4585 generated
->timestamp
= now
;
4586 generated
->version
= 2;
4587 generated
->protocols
= 42;
4588 generated
->intro_nodes
= smartlist_create();
4590 for (i
= 0; i
< 3; i
++) {
4591 rend_intro_point_t
*intro
= tor_malloc_zero(sizeof(rend_intro_point_t
));
4592 crypto_pk_env_t
*okey
= pk_generate(2 + i
);
4593 intro
->extend_info
= tor_malloc_zero(sizeof(extend_info_t
));
4594 intro
->extend_info
->onion_key
= okey
;
4595 crypto_pk_get_digest(intro
->extend_info
->onion_key
,
4596 intro
->extend_info
->identity_digest
);
4597 //crypto_rand(info->identity_digest, DIGEST_LEN); /* Would this work? */
4598 intro
->extend_info
->nickname
[0] = '$';
4599 base16_encode(intro
->extend_info
->nickname
+ 1,
4600 sizeof(intro
->extend_info
->nickname
) - 1,
4601 intro
->extend_info
->identity_digest
, DIGEST_LEN
);
4602 /* Does not cover all IP addresses. */
4603 tor_addr_from_ipv4h(&intro
->extend_info
->addr
, crypto_rand_int(65536));
4604 intro
->extend_info
->port
= crypto_rand_int(65536);
4605 intro
->intro_key
= crypto_pk_dup_key(pk2
);
4606 smartlist_add(generated
->intro_nodes
, intro
);
4608 test_assert(rend_encode_v2_descriptors(descs
, generated
, now
, 0,
4609 REND_NO_AUTH
, NULL
, NULL
) > 0);
4610 test_assert(rend_compute_v2_desc_id(computed_desc_id
, service_id_base32
,
4611 NULL
, now
, 0) == 0);
4612 test_memeq(((rend_encoded_v2_service_descriptor_t
*)
4613 smartlist_get(descs
, 0))->desc_id
, computed_desc_id
, DIGEST_LEN
);
4614 test_assert(rend_parse_v2_service_descriptor(&parsed
, parsed_desc_id
,
4615 &intro_points_encrypted
,
4619 ((rend_encoded_v2_service_descriptor_t
*)
4620 smartlist_get(descs
, 0))->desc_str
) == 0);
4621 test_assert(parsed
);
4622 test_memeq(((rend_encoded_v2_service_descriptor_t
*)
4623 smartlist_get(descs
, 0))->desc_id
, parsed_desc_id
, DIGEST_LEN
);
4624 test_eq(rend_parse_introduction_points(parsed
, intro_points_encrypted
,
4625 intro_points_size
), 3);
4626 test_assert(!crypto_pk_cmp_keys(generated
->pk
, parsed
->pk
));
4627 test_eq(parsed
->timestamp
, now
);
4628 test_eq(parsed
->version
, 2);
4629 test_eq(parsed
->protocols
, 42);
4630 test_eq(smartlist_len(parsed
->intro_nodes
), 3);
4631 for (i
= 0; i
< smartlist_len(parsed
->intro_nodes
); i
++) {
4632 rend_intro_point_t
*par_intro
= smartlist_get(parsed
->intro_nodes
, i
),
4633 *gen_intro
= smartlist_get(generated
->intro_nodes
, i
);
4634 extend_info_t
*par_info
= par_intro
->extend_info
;
4635 extend_info_t
*gen_info
= gen_intro
->extend_info
;
4636 test_assert(!crypto_pk_cmp_keys(gen_info
->onion_key
, par_info
->onion_key
));
4637 test_memeq(gen_info
->identity_digest
, par_info
->identity_digest
,
4639 test_streq(gen_info
->nickname
, par_info
->nickname
);
4640 test_assert(tor_addr_eq(&gen_info
->addr
, &par_info
->addr
));
4641 test_eq(gen_info
->port
, par_info
->port
);
4644 rend_service_descriptor_free(parsed
);
4645 rend_service_descriptor_free(generated
);
4646 parsed
= generated
= NULL
;
4650 for (i
= 0; i
< smartlist_len(descs
); i
++)
4651 rend_encoded_v2_service_descriptor_free(smartlist_get(descs
, i
));
4652 smartlist_free(descs
);
4655 rend_service_descriptor_free(parsed
);
4657 rend_service_descriptor_free(generated
);
4659 crypto_free_pk_env(pk1
);
4661 crypto_free_pk_env(pk2
);
4662 tor_free(intro_points_encrypted
);
4665 /** Run unit tests for GeoIP code. */
4670 time_t now
= time(NULL
);
4673 /* Populate the DB a bit. Add these in order, since we can't do the final
4674 * 'sort' step. These aren't very good IP addresses, but they're perfectly
4675 * fine uint32_t values. */
4676 test_eq(0, geoip_parse_entry("10,50,AB"));
4677 test_eq(0, geoip_parse_entry("52,90,XY"));
4678 test_eq(0, geoip_parse_entry("95,100,AB"));
4679 test_eq(0, geoip_parse_entry("\"105\",\"140\",\"ZZ\""));
4680 test_eq(0, geoip_parse_entry("\"150\",\"190\",\"XY\""));
4681 test_eq(0, geoip_parse_entry("\"200\",\"250\",\"AB\""));
4683 /* We should have 3 countries: ab, xy, zz. */
4684 test_eq(3, geoip_get_n_countries());
4685 /* Make sure that country ID actually works. */
4686 #define NAMEFOR(x) geoip_get_country_name(geoip_get_country_by_ip(x))
4687 test_streq("ab", NAMEFOR(32));
4688 test_streq("??", NAMEFOR(5));
4689 test_streq("??", NAMEFOR(51));
4690 test_streq("xy", NAMEFOR(150));
4691 test_streq("xy", NAMEFOR(190));
4692 test_streq("??", NAMEFOR(2000));
4695 get_options()->BridgeRelay
= 1;
4696 get_options()->BridgeRecordUsageByCountry
= 1;
4697 /* Put 9 observations in AB... */
4698 for (i
=32; i
< 40; ++i
)
4699 geoip_note_client_seen(GEOIP_CLIENT_CONNECT
, i
, now
-7200);
4700 geoip_note_client_seen(GEOIP_CLIENT_CONNECT
, 225, now
-7200);
4701 /* and 3 observations in XY, several times. */
4702 for (j
=0; j
< 10; ++j
)
4703 for (i
=52; i
< 55; ++i
)
4704 geoip_note_client_seen(GEOIP_CLIENT_CONNECT
, i
, now
-3600);
4705 /* and 17 observations in ZZ... */
4706 for (i
=110; i
< 127; ++i
)
4707 geoip_note_client_seen(GEOIP_CLIENT_CONNECT
, i
, now
);
4708 s
= geoip_get_client_history(now
+5*24*60*60, GEOIP_CLIENT_CONNECT
);
4710 test_streq("zz=24,ab=16,xy=8", s
);
4713 /* Now clear out all the AB observations. */
4714 geoip_remove_old_clients(now
-6000);
4715 s
= geoip_get_client_history(now
+5*24*60*60, GEOIP_CLIENT_CONNECT
);
4717 test_streq("zz=24,xy=8", s
);
4723 /** For test_array. Declare an CLI-invocable off-by-default function in the
4724 * unit tests, with function name and user-visible name <b>x</b>*/
4725 #define DISABLED(x) { #x, x, 0, 0, 0 }
4726 /** For test_array. Declare an CLI-invocable unit test function, with function
4727 * name test_<b>x</b>(), and user-visible name <b>x</b> */
4728 #define ENT(x) { #x, test_ ## x, 0, 0, 1 }
4729 /** For test_array. Declare an CLI-invocable unit test function, with function
4730 * name test_<b>x</b>_<b>y</b>(), and user-visible name
4731 * <b>x</b>/<b>y</b>. This function will be treated as a subentry of <b>x</b>,
4732 * so that invoking <b>x</b> from the CLI invokes this test too. */
4733 #define SUBENT(x,y) { #x "/" #y, test_ ## x ## _ ## y, 1, 0, 1 }
4735 /** An array of functions and information for all the unit tests we can run. */
4737 const char *test_name
; /**< How does the user refer to this test from the
4739 void (*test_fn
)(void); /**< What function is called to run this test? */
4740 int is_subent
; /**< Is this a subentry of a bigger set of related tests? */
4741 int selected
; /**< Are we planning to run this one? */
4742 int is_default
; /**< If the user doesn't say what tests they want, do they
4743 * get this function by default? */
4747 SUBENT(crypto
, rng
),
4748 SUBENT(crypto
, aes
),
4749 SUBENT(crypto
, sha
),
4752 SUBENT(crypto
, s2k
),
4753 SUBENT(crypto
, aes_iv
),
4754 SUBENT(crypto
, base32_decode
),
4756 SUBENT(util
, ip6_helpers
),
4758 SUBENT(util
, datadir
),
4759 SUBENT(util
, smartlist_basic
),
4760 SUBENT(util
, smartlist_strings
),
4761 SUBENT(util
, smartlist_overlap
),
4762 SUBENT(util
, smartlist_digests
),
4763 SUBENT(util
, smartlist_join
),
4764 SUBENT(util
, bitarray
),
4765 SUBENT(util
, digestset
),
4766 SUBENT(util
, mempool
),
4767 SUBENT(util
, memarea
),
4768 SUBENT(util
, strmap
),
4769 SUBENT(util
, control_formats
),
4770 SUBENT(util
, pqueue
),
4772 SUBENT(util
, threads
),
4773 SUBENT(util
, order_functions
),
4774 SUBENT(util
, sscanf
),
4775 ENT(onion_handshake
),
4778 ENT(v3_networkstatus
),
4781 SUBENT(rend_fns
, v2
),
4784 DISABLED(bench_aes
),
4785 DISABLED(bench_dmap
),
4786 { NULL
, NULL
, 0, 0, 0 },
4789 static void syntax(void) ATTR_NORETURN
;
4791 /** Print a syntax usage message, and exit.*/
4797 " test [-v|--verbose] [--warn|--notice|--info|--debug]\n"
4799 "Recognized tests are:\n");
4800 for (i
= 0; test_array
[i
].test_name
; ++i
) {
4801 printf(" %s\n", test_array
[i
].test_name
);
4807 /** Main entry point for unit test code: parse the command line, and run
4808 * some unit tests. */
4810 main(int c
, char**v
)
4812 or_options_t
*options
;
4813 char *errmsg
= NULL
;
4815 int verbose
= 0, any_selected
= 0;
4816 int loglevel
= LOG_ERR
;
4820 int r
= CRYPTO_set_mem_ex_functions(_tor_malloc
, _tor_realloc
, _tor_free
);
4825 update_approx_time(time(NULL
));
4826 options
= options_new();
4830 for (i
= 1; i
< c
; ++i
) {
4831 if (!strcmp(v
[i
], "-v") || !strcmp(v
[i
], "--verbose"))
4833 else if (!strcmp(v
[i
], "--warn"))
4834 loglevel
= LOG_WARN
;
4835 else if (!strcmp(v
[i
], "--notice"))
4836 loglevel
= LOG_NOTICE
;
4837 else if (!strcmp(v
[i
], "--info"))
4838 loglevel
= LOG_INFO
;
4839 else if (!strcmp(v
[i
], "--debug"))
4840 loglevel
= LOG_DEBUG
;
4841 else if (!strcmp(v
[i
], "--help") || !strcmp(v
[i
], "-h") || v
[i
][0] == '-')
4845 for (j
= 0; test_array
[j
].test_name
; ++j
) {
4846 if (!strcmp(v
[i
], test_array
[j
].test_name
) ||
4847 (test_array
[j
].is_subent
&&
4848 !strcmpstart(test_array
[j
].test_name
, v
[i
]) &&
4849 test_array
[j
].test_name
[strlen(v
[i
])] == '/') ||
4850 (v
[i
][0] == '=' && !strcmp(v
[i
]+1, test_array
[j
].test_name
))) {
4851 test_array
[j
].selected
= 1;
4857 printf("Unknown test: %s\n", v
[i
]);
4863 if (!any_selected
) {
4864 for (i
= 0; test_array
[i
].test_name
; ++i
) {
4865 test_array
[i
].selected
= test_array
[i
].is_default
;
4870 log_severity_list_t s
;
4871 memset(&s
, 0, sizeof(s
));
4872 set_log_severity_config(loglevel
, LOG_ERR
, &s
);
4873 add_stream_log(&s
, "", fileno(stdout
));
4876 options
->command
= CMD_RUN_UNITTESTS
;
4877 crypto_global_init(0);
4881 options_init(options
);
4882 options
->DataDirectory
= tor_strdup(temp_dir
);
4883 if (set_options(options
, &errmsg
) < 0) {
4884 printf("Failed to set initial options: %s\n", errmsg
);
4891 atexit(remove_directory
);
4893 printf("Running Tor unit tests on %s\n", get_uname());
4895 for (i
= 0; test_array
[i
].test_name
; ++i
) {
4896 if (!test_array
[i
].selected
)
4898 if (!test_array
[i
].is_subent
) {
4899 printf("\n============================== %s\n",test_array
[i
].test_name
);
4900 } else if (test_array
[i
].is_subent
&& verbose
) {
4901 printf("\n%s", test_array
[i
].test_name
);
4903 test_array
[i
].test_fn();
4907 free_pregenerated_keys();
4910 dmalloc_log_unfreed();