1 /* Copyright (c) 2001-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2010, 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
, "Hello whirled.", 15,
705 PK_PKCS1_OAEP_PADDING
));
706 test_eq(128, crypto_pk_public_encrypt(pk1
, data2
, "Hello whirled.", 15,
707 PK_PKCS1_OAEP_PADDING
));
708 /* oaep padding should make encryption not match */
709 test_memneq(data1
, data2
, 128);
710 test_eq(15, crypto_pk_private_decrypt(pk1
, data3
, data1
, 128,
711 PK_PKCS1_OAEP_PADDING
,1));
712 test_streq(data3
, "Hello whirled.");
713 memset(data3
, 0, 1024);
714 test_eq(15, crypto_pk_private_decrypt(pk1
, data3
, data2
, 128,
715 PK_PKCS1_OAEP_PADDING
,1));
716 test_streq(data3
, "Hello whirled.");
717 /* Can't decrypt with public key. */
718 test_eq(-1, crypto_pk_private_decrypt(pk2
, data3
, data2
, 128,
719 PK_PKCS1_OAEP_PADDING
,1));
720 /* Try again with bad padding */
721 memcpy(data2
+1, "XYZZY", 5); /* This has fails ~ once-in-2^40 */
722 test_eq(-1, crypto_pk_private_decrypt(pk1
, data3
, data2
, 128,
723 PK_PKCS1_OAEP_PADDING
,1));
725 /* File operations: save and load private key */
726 test_assert(! crypto_pk_write_private_key_to_filename(pk1
,
727 get_fname("pkey1")));
728 /* failing case for read: can't read. */
729 test_assert(crypto_pk_read_private_key_from_filename(pk2
,
730 get_fname("xyzzy")) < 0);
731 write_str_to_file(get_fname("xyzzy"), "foobar", 6);
732 /* Failing case for read: no key. */
733 test_assert(crypto_pk_read_private_key_from_filename(pk2
,
734 get_fname("xyzzy")) < 0);
735 test_assert(! crypto_pk_read_private_key_from_filename(pk2
,
736 get_fname("pkey1")));
737 test_eq(15, crypto_pk_private_decrypt(pk2
, data3
, data1
, 128,
738 PK_PKCS1_OAEP_PADDING
,1));
740 /* Now try signing. */
741 strlcpy(data1
, "Ossifrage", 1024);
742 test_eq(128, crypto_pk_private_sign(pk1
, data2
, data1
, 10));
743 test_eq(10, crypto_pk_public_checksig(pk1
, data3
, data2
, 128));
744 test_streq(data3
, "Ossifrage");
745 /* Try signing digests. */
746 test_eq(128, crypto_pk_private_sign_digest(pk1
, data2
, data1
, 10));
747 test_eq(20, crypto_pk_public_checksig(pk1
, data3
, data2
, 128));
748 test_eq(0, crypto_pk_public_checksig_digest(pk1
, data1
, 10, data2
, 128));
749 test_eq(-1, crypto_pk_public_checksig_digest(pk1
, data1
, 11, data2
, 128));
750 /*XXXX test failed signing*/
753 crypto_free_pk_env(pk2
);
755 i
= crypto_pk_asn1_encode(pk1
, data1
, 1024);
757 pk2
= crypto_pk_asn1_decode(data1
, i
);
758 test_assert(crypto_pk_cmp_keys(pk1
,pk2
) == 0);
760 /* Try with hybrid encryption wrappers. */
761 crypto_rand(data1
, 1024);
762 for (i
= 0; i
< 3; ++i
) {
763 for (j
= 85; j
< 140; ++j
) {
764 memset(data2
,0,1024);
765 memset(data3
,0,1024);
766 if (i
== 0 && j
< 129)
768 p
= (i
==0)?PK_NO_PADDING
:
769 (i
==1)?PK_PKCS1_PADDING
:PK_PKCS1_OAEP_PADDING
;
770 len
= crypto_pk_public_hybrid_encrypt(pk1
,data2
,data1
,j
,p
,0);
772 len
= crypto_pk_private_hybrid_decrypt(pk1
,data3
,data2
,len
,p
,1);
774 test_memeq(data1
,data3
,j
);
779 crypto_free_pk_env(pk2
);
780 pk2
= crypto_pk_copy_full(pk1
);
781 test_assert(pk2
!= NULL
);
782 test_neq_ptr(pk1
, pk2
);
783 test_assert(crypto_pk_cmp_keys(pk1
,pk2
) == 0);
787 crypto_free_pk_env(pk1
);
789 crypto_free_pk_env(pk2
);
793 /** Run unit tests for misc crypto functionality. */
797 char *data1
= NULL
, *data2
= NULL
, *data3
= NULL
;
800 data1
= tor_malloc(1024);
801 data2
= tor_malloc(1024);
802 data3
= tor_malloc(1024);
803 test_assert(data1
&& data2
&& data3
);
806 memset(data1
, 6, 1024);
807 for (idx
= 0; idx
< 10; ++idx
) {
808 i
= base64_encode(data2
, 1024, data1
, idx
);
810 j
= base64_decode(data3
, 1024, data2
, i
);
812 test_memeq(data3
, data1
, idx
);
815 strlcpy(data1
, "Test string that contains 35 chars.", 1024);
816 strlcat(data1
, " 2nd string that contains 35 chars.", 1024);
818 i
= base64_encode(data2
, 1024, data1
, 71);
819 j
= base64_decode(data3
, 1024, data2
, i
);
821 test_streq(data3
, data1
);
822 test_assert(data2
[i
] == '\0');
824 crypto_rand(data1
, DIGEST_LEN
);
825 memset(data2
, 100, 1024);
826 digest_to_base64(data2
, data1
);
827 test_eq(BASE64_DIGEST_LEN
, strlen(data2
));
828 test_eq(100, data2
[BASE64_DIGEST_LEN
+2]);
829 memset(data3
, 99, 1024);
830 test_eq(digest_from_base64(data3
, data2
), 0);
831 test_memeq(data1
, data3
, DIGEST_LEN
);
832 test_eq(99, data3
[DIGEST_LEN
+1]);
834 test_assert(digest_from_base64(data3
, "###") < 0);
837 strlcpy(data1
, "5chrs", 1024);
838 /* bit pattern is: [35 63 68 72 73] ->
839 * [00110101 01100011 01101000 01110010 01110011]
840 * By 5s: [00110 10101 10001 10110 10000 11100 10011 10011]
842 base32_encode(data2
, 9, data1
, 5);
843 test_streq(data2
, "gvrwq4tt");
845 strlcpy(data1
, "\xFF\xF5\x6D\x44\xAE\x0D\x5C\xC9\x62\xC4", 1024);
846 base32_encode(data2
, 30, data1
, 10);
847 test_streq(data2
, "772w2rfobvomsywe");
850 strlcpy(data1
, "6chrs\xff", 1024);
851 base16_encode(data2
, 13, data1
, 6);
852 test_streq(data2
, "3663687273FF");
854 strlcpy(data1
, "f0d678affc000100", 1024);
855 i
= base16_decode(data2
, 8, data1
, 16);
857 test_memeq(data2
, "\xf0\xd6\x78\xaf\xfc\x00\x01\x00",8);
859 /* now try some failing base16 decodes */
860 test_eq(-1, base16_decode(data2
, 8, data1
, 15)); /* odd input len */
861 test_eq(-1, base16_decode(data2
, 7, data1
, 16)); /* dest too short */
862 strlcpy(data1
, "f0dz!8affc000100", 1024);
863 test_eq(-1, base16_decode(data2
, 8, data1
, 16));
869 /* Add spaces to fingerprint */
871 data1
= tor_strdup("ABCD1234ABCD56780000ABCD1234ABCD56780000");
872 test_eq(strlen(data1
), 40);
873 data2
= tor_malloc(FINGERPRINT_LEN
+1);
874 add_spaces_to_fp(data2
, FINGERPRINT_LEN
+1, data1
);
875 test_streq(data2
, "ABCD 1234 ABCD 5678 0000 ABCD 1234 ABCD 5678 0000");
880 /* Check fingerprint */
882 test_assert(crypto_pk_check_fingerprint_syntax(
883 "ABCD 1234 ABCD 5678 0000 ABCD 1234 ABCD 5678 0000"));
884 test_assert(!crypto_pk_check_fingerprint_syntax(
885 "ABCD 1234 ABCD 5678 0000 ABCD 1234 ABCD 5678 000"));
886 test_assert(!crypto_pk_check_fingerprint_syntax(
887 "ABCD 1234 ABCD 5678 0000 ABCD 1234 ABCD 5678 00000"));
888 test_assert(!crypto_pk_check_fingerprint_syntax(
889 "ABCD 1234 ABCD 5678 0000 ABCD1234 ABCD 5678 0000"));
890 test_assert(!crypto_pk_check_fingerprint_syntax(
891 "ABCD 1234 ABCD 5678 0000 ABCD1234 ABCD 5678 00000"));
892 test_assert(!crypto_pk_check_fingerprint_syntax(
893 "ACD 1234 ABCD 5678 0000 ABCD 1234 ABCD 5678 00000"));
902 /** Run unit tests for our secret-to-key passphrase hashing functionality. */
904 test_crypto_s2k(void)
911 memset(buf
, 0, sizeof(buf
));
912 memset(buf2
, 0, sizeof(buf2
));
913 buf3
= tor_malloc(65536);
914 memset(buf3
, 0, 65536);
916 secret_to_key(buf
+9, 20, "", 0, buf
);
917 crypto_digest(buf2
+9, buf3
, 1024);
918 test_memeq(buf
, buf2
, 29);
920 memcpy(buf
,"vrbacrda",8);
921 memcpy(buf2
,"vrbacrda",8);
924 secret_to_key(buf
+9, 20, "12345678", 8, buf
);
925 for (i
= 0; i
< 65536; i
+= 16) {
926 memcpy(buf3
+i
, "vrbacrda12345678", 16);
928 crypto_digest(buf2
+9, buf3
, 65536);
929 test_memeq(buf
, buf2
, 29);
935 /** Helper: return a tristate based on comparing the strings in *<b>a</b> and
938 _compare_strs(const void **a
, const void **b
)
940 const char *s1
= *a
, *s2
= *b
;
941 return strcmp(s1
, s2
);
944 /** Helper: return a tristate based on comparing the strings in *<b>a</b> and
945 * *<b>b</b>, excluding a's first character, and ignoring case. */
947 _compare_without_first_ch(const void *a
, const void **b
)
949 const char *s1
= a
, *s2
= *b
;
950 return strcasecmp(s1
+1, s2
);
953 /** Test basic utility functionality. */
957 struct timeval start
, end
;
959 char timestr
[RFC1123_TIME_LEN
+1];
969 start
.tv_usec
= 5000;
974 test_eq(0L, tv_udiff(&start
, &end
));
978 test_eq(2000L, tv_udiff(&start
, &end
));
982 test_eq(1002000L, tv_udiff(&start
, &end
));
986 test_eq(995000L, tv_udiff(&start
, &end
));
990 test_eq(-1005000L, tv_udiff(&start
, &end
));
992 end
.tv_usec
= 999990;
996 /* The test values here are confirmed to be correct on a platform
997 * with a working timegm. */
998 a_time
.tm_year
= 2003-1900;
1000 a_time
.tm_mday
= 30;
1004 test_eq((time_t) 1062224095UL, tor_timegm(&a_time
));
1005 a_time
.tm_year
= 2004-1900; /* Try a leap year, after feb. */
1006 test_eq((time_t) 1093846495UL, tor_timegm(&a_time
));
1007 a_time
.tm_mon
= 1; /* Try a leap year, in feb. */
1008 a_time
.tm_mday
= 10;
1009 test_eq((time_t) 1076393695UL, tor_timegm(&a_time
));
1011 format_rfc1123_time(timestr
, 0);
1012 test_streq("Thu, 01 Jan 1970 00:00:00 GMT", timestr
);
1013 format_rfc1123_time(timestr
, (time_t)1091580502UL);
1014 test_streq("Wed, 04 Aug 2004 00:48:22 GMT", timestr
);
1017 i
= parse_rfc1123_time(timestr
, &t_res
);
1019 test_eq(t_res
, (time_t)1091580502UL);
1020 test_eq(-1, parse_rfc1123_time("Wed, zz Aug 2004 99-99x99 GMT", &t_res
));
1021 tor_gettimeofday(&start
);
1023 /* Tests for corner cases of strl operations */
1024 test_eq(5, strlcpy(buf
, "Hello", 0));
1025 strlcpy(buf
, "Hello", sizeof(buf
));
1026 test_eq(10, strlcat(buf
, "Hello", 5));
1028 /* Test tor_strstrip() */
1029 strlcpy(buf
, "Testing 1 2 3", sizeof(buf
));
1030 tor_strstrip(buf
, ",!");
1031 test_streq(buf
, "Testing 1 2 3");
1032 strlcpy(buf
, "!Testing 1 2 3?", sizeof(buf
));
1033 tor_strstrip(buf
, "!? ");
1034 test_streq(buf
, "Testing123");
1036 /* Test parse_addr_port */
1037 cp
= NULL
; u32
= 3; u16
= 3;
1038 test_assert(!parse_addr_port(LOG_WARN
, "1.2.3.4", &cp
, &u32
, &u16
));
1039 test_streq(cp
, "1.2.3.4");
1040 test_eq(u32
, 0x01020304u
);
1043 test_assert(!parse_addr_port(LOG_WARN
, "4.3.2.1:99", &cp
, &u32
, &u16
));
1044 test_streq(cp
, "4.3.2.1");
1045 test_eq(u32
, 0x04030201u
);
1048 test_assert(!parse_addr_port(LOG_WARN
, "nonexistent.address:4040",
1050 test_streq(cp
, "nonexistent.address");
1053 test_assert(!parse_addr_port(LOG_WARN
, "localhost:9999", &cp
, &u32
, &u16
));
1054 test_streq(cp
, "localhost");
1055 test_eq(u32
, 0x7f000001u
);
1059 test_assert(!parse_addr_port(LOG_WARN
, "localhost", NULL
, &u32
, &u16
));
1061 test_eq(u32
, 0x7f000001u
);
1064 test_eq(0, addr_mask_get_bits(0x0u
));
1065 test_eq(32, addr_mask_get_bits(0xFFFFFFFFu
));
1066 test_eq(16, addr_mask_get_bits(0xFFFF0000u
));
1067 test_eq(31, addr_mask_get_bits(0xFFFFFFFEu
));
1068 test_eq(1, addr_mask_get_bits(0x80000000u
));
1070 /* Test tor_parse_long. */
1071 test_eq(10L, tor_parse_long("10",10,0,100,NULL
,NULL
));
1072 test_eq(0L, tor_parse_long("10",10,50,100,NULL
,NULL
));
1073 test_eq(-50L, tor_parse_long("-50",10,-100,100,NULL
,NULL
));
1075 /* Test tor_parse_ulong */
1076 test_eq(10UL, tor_parse_ulong("10",10,0,100,NULL
,NULL
));
1077 test_eq(0UL, tor_parse_ulong("10",10,50,100,NULL
,NULL
));
1079 /* Test tor_parse_uint64. */
1080 test_assert(U64_LITERAL(10) == tor_parse_uint64("10 x",10,0,100, &i
, &cp
));
1081 test_assert(i
== 1);
1082 test_streq(cp
, " x");
1083 test_assert(U64_LITERAL(12345678901) ==
1084 tor_parse_uint64("12345678901",10,0,UINT64_MAX
, &i
, &cp
));
1085 test_assert(i
== 1);
1087 test_assert(U64_LITERAL(0) ==
1088 tor_parse_uint64("12345678901",10,500,INT32_MAX
, &i
, &cp
));
1089 test_assert(i
== 0);
1091 /* Test failing snprintf cases */
1092 test_eq(-1, tor_snprintf(buf
, 0, "Foo"));
1093 test_eq(-1, tor_snprintf(buf
, 2, "Foo"));
1095 /* Test printf with uint64 */
1096 tor_snprintf(buf
, sizeof(buf
), "x!"U64_FORMAT
"!x",
1097 U64_PRINTF_ARG(U64_LITERAL(12345678901)));
1098 test_streq(buf
, "x!12345678901!x");
1100 /* Test parse_config_line_from_str */
1101 strlcpy(buf
, "k v\n" " key value with spaces \n" "keykey val\n"
1103 "k3 \n" "\n" " \n" "#comment\n"
1104 "k4#a\n" "k5#abc\n" "k6 val #with comment\n"
1105 "kseven \"a quoted 'string\"\n"
1106 "k8 \"a \\x71uoted\\n\\\"str\\\\ing\\t\\001\\01\\1\\\"\"\n"
1110 str
= parse_config_line_from_str(str
, &k
, &v
);
1113 tor_free(k
); tor_free(v
);
1114 test_assert(!strcmpstart(str
, "key value with"));
1116 str
= parse_config_line_from_str(str
, &k
, &v
);
1117 test_streq(k
, "key");
1118 test_streq(v
, "value with spaces");
1119 tor_free(k
); tor_free(v
);
1120 test_assert(!strcmpstart(str
, "keykey"));
1122 str
= parse_config_line_from_str(str
, &k
, &v
);
1123 test_streq(k
, "keykey");
1124 test_streq(v
, "val");
1125 tor_free(k
); tor_free(v
);
1126 test_assert(!strcmpstart(str
, "k2\n"));
1128 str
= parse_config_line_from_str(str
, &k
, &v
);
1129 test_streq(k
, "k2");
1131 tor_free(k
); tor_free(v
);
1132 test_assert(!strcmpstart(str
, "k3 \n"));
1134 str
= parse_config_line_from_str(str
, &k
, &v
);
1135 test_streq(k
, "k3");
1137 tor_free(k
); tor_free(v
);
1138 test_assert(!strcmpstart(str
, "#comment"));
1140 str
= parse_config_line_from_str(str
, &k
, &v
);
1141 test_streq(k
, "k4");
1143 tor_free(k
); tor_free(v
);
1144 test_assert(!strcmpstart(str
, "k5#abc"));
1146 str
= parse_config_line_from_str(str
, &k
, &v
);
1147 test_streq(k
, "k5");
1149 tor_free(k
); tor_free(v
);
1150 test_assert(!strcmpstart(str
, "k6"));
1152 str
= parse_config_line_from_str(str
, &k
, &v
);
1153 test_streq(k
, "k6");
1154 test_streq(v
, "val");
1155 tor_free(k
); tor_free(v
);
1156 test_assert(!strcmpstart(str
, "kseven"));
1158 str
= parse_config_line_from_str(str
, &k
, &v
);
1159 test_streq(k
, "kseven");
1160 test_streq(v
, "a quoted \'string");
1161 tor_free(k
); tor_free(v
);
1162 test_assert(!strcmpstart(str
, "k8 "));
1164 str
= parse_config_line_from_str(str
, &k
, &v
);
1165 test_streq(k
, "k8");
1166 test_streq(v
, "a quoted\n\"str\\ing\t\x01\x01\x01\"");
1167 tor_free(k
); tor_free(v
);
1168 test_streq(str
, "");
1170 /* Test for strcmpstart and strcmpend. */
1171 test_assert(strcmpstart("abcdef", "abcdef")==0);
1172 test_assert(strcmpstart("abcdef", "abc")==0);
1173 test_assert(strcmpstart("abcdef", "abd")<0);
1174 test_assert(strcmpstart("abcdef", "abb")>0);
1175 test_assert(strcmpstart("ab", "abb")<0);
1177 test_assert(strcmpend("abcdef", "abcdef")==0);
1178 test_assert(strcmpend("abcdef", "def")==0);
1179 test_assert(strcmpend("abcdef", "deg")<0);
1180 test_assert(strcmpend("abcdef", "dee")>0);
1181 test_assert(strcmpend("ab", "abb")<0);
1183 test_assert(strcasecmpend("AbcDEF", "abcdef")==0);
1184 test_assert(strcasecmpend("abcdef", "dEF")==0);
1185 test_assert(strcasecmpend("abcDEf", "deg")<0);
1186 test_assert(strcasecmpend("abcdef", "DEE")>0);
1187 test_assert(strcasecmpend("ab", "abB")<0);
1189 /* Test mem_is_zero */
1192 test_assert(tor_digest_is_zero(buf
));
1193 test_assert(tor_mem_is_zero(buf
, 10));
1194 test_assert(tor_mem_is_zero(buf
, 20));
1195 test_assert(tor_mem_is_zero(buf
, 128));
1196 test_assert(!tor_mem_is_zero(buf
, 129));
1197 buf
[60] = (char)255;
1198 test_assert(!tor_mem_is_zero(buf
, 128));
1200 test_assert(!tor_mem_is_zero(buf
, 10));
1202 /* Test inet_ntop */
1204 char tmpbuf
[TOR_ADDR_BUF_LEN
];
1205 const char *ip
= "176.192.208.224";
1207 tor_inet_pton(AF_INET
, ip
, &in
);
1208 tor_inet_ntop(AF_INET
, &in
, tmpbuf
, sizeof(tmpbuf
));
1209 test_streq(tmpbuf
, ip
);
1212 /* Test 'escaped' */
1213 test_streq("\"\"", escaped(""));
1214 test_streq("\"abcd\"", escaped("abcd"));
1215 test_streq("\"\\\\\\n\\r\\t\\\"\\'\"", escaped("\\\n\r\t\"\'"));
1216 test_streq("\"z\\001abc\\277d\"", escaped("z\001abc\277d"));
1217 test_assert(NULL
== escaped(NULL
));
1219 /* Test strndup and memdup */
1221 const char *s
= "abcdefghijklmnopqrstuvwxyz";
1222 cp
= tor_strndup(s
, 30);
1223 test_streq(cp
, s
); /* same string, */
1224 test_neq(cp
, s
); /* but different pointers. */
1227 cp
= tor_strndup(s
, 5);
1228 test_streq(cp
, "abcde");
1231 s
= "a\0b\0c\0d\0e\0";
1232 cp
= tor_memdup(s
,10);
1233 test_memeq(cp
, s
, 10); /* same ram, */
1234 test_neq(cp
, s
); /* but different pointers. */
1238 /* Test str-foo functions */
1239 cp
= tor_strdup("abcdef");
1240 test_assert(tor_strisnonupper(cp
));
1242 test_assert(!tor_strisnonupper(cp
));
1244 test_streq(cp
, "ABCDEF");
1245 test_assert(tor_strisprint(cp
));
1247 test_assert(!tor_strisprint(cp
));
1250 /* Test eat_whitespace. */
1252 const char *s
= " \n a";
1253 test_eq_ptr(eat_whitespace(s
), s
+4);
1255 test_eq_ptr(eat_whitespace(s
), s
);
1257 test_eq_ptr(eat_whitespace(s
), s
+5);
1260 /* Test memmem and memstr */
1262 const char *haystack
= "abcde";
1263 tor_assert(!tor_memmem(haystack
, 5, "ef", 2));
1264 test_eq_ptr(tor_memmem(haystack
, 5, "cd", 2), haystack
+ 2);
1265 test_eq_ptr(tor_memmem(haystack
, 5, "cde", 3), haystack
+ 2);
1266 haystack
= "ababcad";
1267 test_eq_ptr(tor_memmem(haystack
, 7, "abc", 3), haystack
+ 2);
1268 test_eq_ptr(tor_memstr(haystack
, 7, "abc"), haystack
+ 2);
1269 test_assert(!tor_memstr(haystack
, 7, "fe"));
1270 test_assert(!tor_memstr(haystack
, 7, "longerthantheoriginal"));
1273 /* Test wrap_string */
1275 smartlist_t
*sl
= smartlist_create();
1276 wrap_string(sl
, "This is a test of string wrapping functionality: woot.",
1278 cp
= smartlist_join_strings(sl
, "", 0, NULL
);
1280 "This is a\ntest of\nstring\nwrapping\nfunctional\nity: woot.\n");
1282 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1283 smartlist_clear(sl
);
1285 wrap_string(sl
, "This is a test of string wrapping functionality: woot.",
1287 cp
= smartlist_join_strings(sl
, "", 0, NULL
);
1289 "### This is a\n# test of string\n# wrapping\n# functionality:\n"
1293 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1297 tor_gettimeofday(&start
);
1298 /* now make sure time works. */
1299 tor_gettimeofday(&end
);
1300 /* We might've timewarped a little. */
1301 test_assert(tv_udiff(&start
, &end
) >= -5000);
1303 /* Test tor_log2(). */
1304 test_eq(tor_log2(64), 6);
1305 test_eq(tor_log2(65), 6);
1306 test_eq(tor_log2(63), 5);
1307 test_eq(tor_log2(1), 0);
1308 test_eq(tor_log2(2), 1);
1309 test_eq(tor_log2(3), 1);
1310 test_eq(tor_log2(4), 2);
1311 test_eq(tor_log2(5), 2);
1312 test_eq(tor_log2(U64_LITERAL(40000000000000000)), 55);
1313 test_eq(tor_log2(UINT64_MAX
), 63);
1315 /* Test round_to_power_of_2 */
1316 test_eq(round_to_power_of_2(120), 128);
1317 test_eq(round_to_power_of_2(128), 128);
1318 test_eq(round_to_power_of_2(130), 128);
1319 test_eq(round_to_power_of_2(U64_LITERAL(40000000000000000)),
1320 U64_LITERAL(1)<<55);
1321 test_eq(round_to_power_of_2(0), 2);
1327 /** Helper: assert that IPv6 addresses <b>a</b> and <b>b</b> are the same. On
1328 * failure, reports an error, describing the addresses as <b>e1</b> and
1329 * <b>e2</b>, and reporting the line number as <b>line</b>. */
1331 _test_eq_ip6(struct in6_addr
*a
, struct in6_addr
*b
, const char *e1
,
1332 const char *e2
, int line
)
1336 for (i
= 0; i
< 16; ++i
) {
1337 if (a
->s6_addr
[i
] != b
->s6_addr
[i
]) {
1343 printf("."); fflush(stdout
);
1345 char buf1
[128], *cp1
;
1346 char buf2
[128], *cp2
;
1348 cp1
= buf1
; cp2
= buf2
;
1349 for (i
=0; i
<16; ++i
) {
1350 tor_snprintf(cp1
, sizeof(buf1
)-(cp1
-buf1
), "%02x", a
->s6_addr
[i
]);
1351 tor_snprintf(cp2
, sizeof(buf2
)-(cp2
-buf2
), "%02x", b
->s6_addr
[i
]);
1353 if ((i
%2)==1 && i
!= 15) {
1359 printf("Line %d: assertion failed: (%s == %s)\n"
1360 " %s != %s\n", line
, e1
, e2
, buf1
, buf2
);
1365 /** Helper: Assert that two strings both decode as IPv6 addresses with
1366 * tor_inet_pton(), and both decode to the same address. */
1367 #define test_pton6_same(a,b) STMT_BEGIN \
1368 test_eq(tor_inet_pton(AF_INET6, a, &a1), 1); \
1369 test_eq(tor_inet_pton(AF_INET6, b, &a2), 1); \
1370 _test_eq_ip6(&a1,&a2,#a,#b,__LINE__); \
1373 /** Helper: Assert that <b>a</b> is recognized as a bad IPv6 address by
1374 * tor_inet_pton(). */
1375 #define test_pton6_bad(a) \
1376 test_eq(0, tor_inet_pton(AF_INET6, a, &a1))
1378 /** Helper: assert that <b>a</b>, when parsed by tor_inet_pton() and displayed
1379 * with tor_inet_ntop(), yields <b>b</b>. Also assert that <b>b</b> parses to
1380 * the same value as <b>a</b>. */
1381 #define test_ntop6_reduces(a,b) STMT_BEGIN \
1382 test_eq(tor_inet_pton(AF_INET6, a, &a1), 1); \
1383 test_streq(tor_inet_ntop(AF_INET6, &a1, buf, sizeof(buf)), b); \
1384 test_eq(tor_inet_pton(AF_INET6, b, &a2), 1); \
1385 _test_eq_ip6(&a1, &a2, a, b, __LINE__); \
1388 /** Helper: assert that <b>a</b> parses by tor_inet_pton() into a address that
1389 * passes tor_addr_is_internal() with <b>for_listening</b>. */
1390 #define test_internal_ip(a,for_listening) STMT_BEGIN \
1391 test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
1392 t1.family = AF_INET6; \
1393 if (!tor_addr_is_internal(&t1, for_listening)) \
1394 test_fail_msg( a "was not internal."); \
1397 /** Helper: assert that <b>a</b> parses by tor_inet_pton() into a address that
1398 * does not pass tor_addr_is_internal() with <b>for_listening</b>. */
1399 #define test_external_ip(a,for_listening) STMT_BEGIN \
1400 test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
1401 t1.family = AF_INET6; \
1402 if (tor_addr_is_internal(&t1, for_listening)) \
1403 test_fail_msg(a "was not external."); \
1406 /** Helper: Assert that <b>a</b> and <b>b</b>, when parsed by
1407 * tor_inet_pton(), give addresses that compare in the order defined by
1408 * <b>op</b> with tor_addr_compare(). */
1409 #define test_addr_compare(a, op, b) STMT_BEGIN \
1410 test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
1411 test_eq(tor_inet_pton(AF_INET6, b, &t2.addr.in6_addr), 1); \
1412 t1.family = t2.family = AF_INET6; \
1413 r = tor_addr_compare(&t1,&t2,CMP_SEMANTIC); \
1415 test_fail_msg("failed: tor_addr_compare("a","b") "#op" 0"); \
1418 /** Helper: Assert that <b>a</b> and <b>b</b>, when parsed by
1419 * tor_inet_pton(), give addresses that compare in the order defined by
1420 * <b>op</b> with tor_addr_compare_masked() with <b>m</b> masked. */
1421 #define test_addr_compare_masked(a, op, b, m) STMT_BEGIN \
1422 test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
1423 test_eq(tor_inet_pton(AF_INET6, b, &t2.addr.in6_addr), 1); \
1424 t1.family = t2.family = AF_INET6; \
1425 r = tor_addr_compare_masked(&t1,&t2,m,CMP_SEMANTIC); \
1427 test_fail_msg("failed: tor_addr_compare_masked("a","b","#m") "#op" 0"); \
1430 /** Helper: assert that <b>xx</b> is parseable as a masked IPv6 address with
1431 * ports by tor_parse_mask_addr_ports(), with family <b>f</b>, IP address
1432 * as 4 32-bit words <b>ip1...ip4</b>, mask bits as <b>mm</b>, and port range
1433 * as <b>pt1..pt2</b>. */
1434 #define test_addr_mask_ports_parse(xx, f, ip1, ip2, ip3, ip4, mm, pt1, pt2) \
1436 test_eq(tor_addr_parse_mask_ports(xx, &t1, &mask, &port1, &port2), f); \
1437 p1=tor_inet_ntop(AF_INET6, &t1.addr.in6_addr, bug, sizeof(bug)); \
1438 test_eq(htonl(ip1), tor_addr_to_in6_addr32(&t1)[0]); \
1439 test_eq(htonl(ip2), tor_addr_to_in6_addr32(&t1)[1]); \
1440 test_eq(htonl(ip3), tor_addr_to_in6_addr32(&t1)[2]); \
1441 test_eq(htonl(ip4), tor_addr_to_in6_addr32(&t1)[3]); \
1442 test_eq(mask, mm); \
1443 test_eq(port1, pt1); \
1444 test_eq(port2, pt2); \
1447 /** Run unit tests for IPv6 encoding/decoding/manipulation functions. */
1449 test_util_ip6_helpers(void)
1451 char buf
[TOR_ADDR_BUF_LEN
], bug
[TOR_ADDR_BUF_LEN
];
1452 struct in6_addr a1
, a2
;
1455 uint16_t port1
, port2
;
1458 struct sockaddr_storage sa_storage
;
1459 struct sockaddr_in
*sin
;
1460 struct sockaddr_in6
*sin6
;
1462 // struct in_addr b1, b2;
1463 /* Test tor_inet_ntop and tor_inet_pton: IPv6 */
1465 /* ==== Converting to and from sockaddr_t. */
1466 sin
= (struct sockaddr_in
*)&sa_storage
;
1467 sin
->sin_family
= AF_INET
;
1468 sin
->sin_port
= 9090;
1469 sin
->sin_addr
.s_addr
= htonl(0x7f7f0102); /*127.127.1.2*/
1470 tor_addr_from_sockaddr(&t1
, (struct sockaddr
*)sin
, NULL
);
1471 test_eq(tor_addr_family(&t1
), AF_INET
);
1472 test_eq(tor_addr_to_ipv4h(&t1
), 0x7f7f0102);
1474 memset(&sa_storage
, 0, sizeof(sa_storage
));
1475 test_eq(sizeof(struct sockaddr_in
),
1476 tor_addr_to_sockaddr(&t1
, 1234, (struct sockaddr
*)&sa_storage
,
1477 sizeof(sa_storage
)));
1478 test_eq(1234, ntohs(sin
->sin_port
));
1479 test_eq(0x7f7f0102, ntohl(sin
->sin_addr
.s_addr
));
1481 memset(&sa_storage
, 0, sizeof(sa_storage
));
1482 sin6
= (struct sockaddr_in6
*)&sa_storage
;
1483 sin6
->sin6_family
= AF_INET6
;
1484 sin6
->sin6_port
= htons(7070);
1485 sin6
->sin6_addr
.s6_addr
[0] = 128;
1486 tor_addr_from_sockaddr(&t1
, (struct sockaddr
*)sin6
, NULL
);
1487 test_eq(tor_addr_family(&t1
), AF_INET6
);
1488 p1
= tor_addr_to_str(buf
, &t1
, sizeof(buf
), 0);
1489 test_streq(p1
, "8000::");
1491 memset(&sa_storage
, 0, sizeof(sa_storage
));
1492 test_eq(sizeof(struct sockaddr_in6
),
1493 tor_addr_to_sockaddr(&t1
, 9999, (struct sockaddr
*)&sa_storage
,
1494 sizeof(sa_storage
)));
1495 test_eq(AF_INET6
, sin6
->sin6_family
);
1496 test_eq(9999, ntohs(sin6
->sin6_port
));
1497 test_eq(0x80000000, ntohl(S6_ADDR32(sin6
->sin6_addr
)[0]));
1499 /* ==== tor_addr_lookup: static cases. (Can't test dns without knowing we
1500 * have a good resolver. */
1501 test_eq(0, tor_addr_lookup("127.128.129.130", AF_UNSPEC
, &t1
));
1502 test_eq(AF_INET
, tor_addr_family(&t1
));
1503 test_eq(tor_addr_to_ipv4h(&t1
), 0x7f808182);
1505 test_eq(0, tor_addr_lookup("9000::5", AF_UNSPEC
, &t1
));
1506 test_eq(AF_INET6
, tor_addr_family(&t1
));
1507 test_eq(0x90, tor_addr_to_in6_addr8(&t1
)[0]);
1508 test_assert(tor_mem_is_zero((char*)tor_addr_to_in6_addr8(&t1
)+1, 14));
1509 test_eq(0x05, tor_addr_to_in6_addr8(&t1
)[15]);
1511 /* === Test pton: valid af_inet6 */
1512 /* Simple, valid parsing. */
1513 r
= tor_inet_pton(AF_INET6
,
1514 "0102:0304:0506:0708:090A:0B0C:0D0E:0F10", &a1
);
1516 for (i
=0;i
<16;++i
) { test_eq(i
+1, (int)a1
.s6_addr
[i
]); }
1518 test_pton6_same("0102:0304:0506:0708:090A:0B0C:0D0E:0F10",
1519 "0102:0304:0506:0708:090A:0B0C:13.14.15.16");
1520 /* shortened words. */
1521 test_pton6_same("0001:0099:BEEF:0000:0123:FFFF:0001:0001",
1522 "1:99:BEEF:0:0123:FFFF:1:1");
1523 /* zeros at the beginning */
1524 test_pton6_same("0000:0000:0000:0000:0009:C0A8:0001:0001",
1526 test_pton6_same("0000:0000:0000:0000:0009:C0A8:0001:0001",
1527 "::9:c0a8:0.1.0.1");
1528 /* zeros in the middle. */
1529 test_pton6_same("fe80:0000:0000:0000:0202:1111:0001:0001",
1530 "fe80::202:1111:1:1");
1531 /* zeros at the end. */
1532 test_pton6_same("1000:0001:0000:0007:0000:0000:0000:0000",
1535 /* === Test ntop: af_inet6 */
1536 test_ntop6_reduces("0:0:0:0:0:0:0:0", "::");
1538 test_ntop6_reduces("0001:0099:BEEF:0006:0123:FFFF:0001:0001",
1539 "1:99:beef:6:123:ffff:1:1");
1541 //test_ntop6_reduces("0:0:0:0:0:0:c0a8:0101", "::192.168.1.1");
1542 test_ntop6_reduces("0:0:0:0:0:ffff:c0a8:0101", "::ffff:192.168.1.1");
1543 test_ntop6_reduces("002:0:0000:0:3::4", "2::3:0:0:4");
1544 test_ntop6_reduces("0:0::1:0:3", "::1:0:3");
1545 test_ntop6_reduces("008:0::0", "8::");
1546 test_ntop6_reduces("0:0:0:0:0:ffff::1", "::ffff:0.0.0.1");
1547 test_ntop6_reduces("abcd:0:0:0:0:0:7f00::", "abcd::7f00:0");
1548 test_ntop6_reduces("0000:0000:0000:0000:0009:C0A8:0001:0001",
1550 test_ntop6_reduces("fe80:0000:0000:0000:0202:1111:0001:0001",
1551 "fe80::202:1111:1:1");
1552 test_ntop6_reduces("1000:0001:0000:0007:0000:0000:0000:0000",
1555 /* === Test pton: invalid in6. */
1556 test_pton6_bad("foobar.");
1557 test_pton6_bad("55555::");
1558 test_pton6_bad("9:-60::");
1559 test_pton6_bad("1:2:33333:4:0002:3::");
1560 //test_pton6_bad("1:2:3333:4:00002:3::");// BAD, but glibc doesn't say so.
1561 test_pton6_bad("1:2:3333:4:fish:3::");
1562 test_pton6_bad("1:2:3:4:5:6:7:8:9");
1563 test_pton6_bad("1:2:3:4:5:6:7");
1564 test_pton6_bad("1:2:3:4:5:6:1.2.3.4.5");
1565 test_pton6_bad("1:2:3:4:5:6:1.2.3");
1566 test_pton6_bad("::1.2.3");
1567 test_pton6_bad("::1.2.3.4.5");
1568 test_pton6_bad("99");
1570 test_pton6_bad("1::2::3:4");
1571 test_pton6_bad("a:::b:c");
1572 test_pton6_bad(":::a:b:c");
1573 test_pton6_bad("a:b:c:::");
1575 /* test internal checking */
1576 test_external_ip("fbff:ffff::2:7", 0);
1577 test_internal_ip("fc01::2:7", 0);
1578 test_internal_ip("fdff:ffff::f:f", 0);
1579 test_external_ip("fe00::3:f", 0);
1581 test_external_ip("fe7f:ffff::2:7", 0);
1582 test_internal_ip("fe80::2:7", 0);
1583 test_internal_ip("febf:ffff::f:f", 0);
1585 test_internal_ip("fec0::2:7:7", 0);
1586 test_internal_ip("feff:ffff::e:7:7", 0);
1587 test_external_ip("ff00::e:7:7", 0);
1589 test_internal_ip("::", 0);
1590 test_internal_ip("::1", 0);
1591 test_internal_ip("::1", 1);
1592 test_internal_ip("::", 0);
1593 test_external_ip("::", 1);
1594 test_external_ip("::2", 0);
1595 test_external_ip("2001::", 0);
1596 test_external_ip("ffff::", 0);
1598 test_external_ip("::ffff:0.0.0.0", 1);
1599 test_internal_ip("::ffff:0.0.0.0", 0);
1600 test_internal_ip("::ffff:0.255.255.255", 0);
1601 test_external_ip("::ffff:1.0.0.0", 0);
1603 test_external_ip("::ffff:9.255.255.255", 0);
1604 test_internal_ip("::ffff:10.0.0.0", 0);
1605 test_internal_ip("::ffff:10.255.255.255", 0);
1606 test_external_ip("::ffff:11.0.0.0", 0);
1608 test_external_ip("::ffff:126.255.255.255", 0);
1609 test_internal_ip("::ffff:127.0.0.0", 0);
1610 test_internal_ip("::ffff:127.255.255.255", 0);
1611 test_external_ip("::ffff:128.0.0.0", 0);
1613 test_external_ip("::ffff:172.15.255.255", 0);
1614 test_internal_ip("::ffff:172.16.0.0", 0);
1615 test_internal_ip("::ffff:172.31.255.255", 0);
1616 test_external_ip("::ffff:172.32.0.0", 0);
1618 test_external_ip("::ffff:192.167.255.255", 0);
1619 test_internal_ip("::ffff:192.168.0.0", 0);
1620 test_internal_ip("::ffff:192.168.255.255", 0);
1621 test_external_ip("::ffff:192.169.0.0", 0);
1623 test_external_ip("::ffff:169.253.255.255", 0);
1624 test_internal_ip("::ffff:169.254.0.0", 0);
1625 test_internal_ip("::ffff:169.254.255.255", 0);
1626 test_external_ip("::ffff:169.255.0.0", 0);
1627 test_assert(is_internal_IP(0x7f000001, 0));
1629 /* tor_addr_compare(tor_addr_t x2) */
1630 test_addr_compare("ffff::", ==, "ffff::0");
1631 test_addr_compare("0::3:2:1", <, "0::ffff:0.3.2.1");
1632 test_addr_compare("0::2:2:1", <, "0::ffff:0.3.2.1");
1633 test_addr_compare("0::ffff:0.3.2.1", >, "0::0:0:0");
1634 test_addr_compare("0::ffff:5.2.2.1", <, "::ffff:6.0.0.0"); /* XXXX wrong. */
1635 tor_addr_parse_mask_ports("[::ffff:2.3.4.5]", &t1
, NULL
, NULL
, NULL
);
1636 tor_addr_parse_mask_ports("2.3.4.5", &t2
, NULL
, NULL
, NULL
);
1637 test_assert(tor_addr_compare(&t1
, &t2
, CMP_SEMANTIC
) == 0);
1638 tor_addr_parse_mask_ports("[::ffff:2.3.4.4]", &t1
, NULL
, NULL
, NULL
);
1639 tor_addr_parse_mask_ports("2.3.4.5", &t2
, NULL
, NULL
, NULL
);
1640 test_assert(tor_addr_compare(&t1
, &t2
, CMP_SEMANTIC
) < 0);
1642 /* test compare_masked */
1643 test_addr_compare_masked("ffff::", ==, "ffff::0", 128);
1644 test_addr_compare_masked("ffff::", ==, "ffff::0", 64);
1645 test_addr_compare_masked("0::2:2:1", <, "0::8000:2:1", 81);
1646 test_addr_compare_masked("0::2:2:1", ==, "0::8000:2:1", 80);
1648 /* Test decorated addr_to_string. */
1649 test_eq(AF_INET6
, tor_addr_from_str(&t1
, "[123:45:6789::5005:11]"));
1650 p1
= tor_addr_to_str(buf
, &t1
, sizeof(buf
), 1);
1651 test_streq(p1
, "[123:45:6789::5005:11]");
1652 test_eq(AF_INET
, tor_addr_from_str(&t1
, "18.0.0.1"));
1653 p1
= tor_addr_to_str(buf
, &t1
, sizeof(buf
), 1);
1654 test_streq(p1
, "18.0.0.1");
1656 /* Test tor_addr_parse_reverse_lookup_name */
1657 i
= tor_addr_parse_reverse_lookup_name(&t1
, "Foobar.baz", AF_UNSPEC
, 0);
1659 i
= tor_addr_parse_reverse_lookup_name(&t1
, "Foobar.baz", AF_UNSPEC
, 1);
1661 i
= tor_addr_parse_reverse_lookup_name(&t1
, "1.0.168.192.in-addr.arpa",
1664 test_eq(tor_addr_family(&t1
), AF_INET
);
1665 p1
= tor_addr_to_str(buf
, &t1
, sizeof(buf
), 1);
1666 test_streq(p1
, "192.168.0.1");
1667 i
= tor_addr_parse_reverse_lookup_name(&t1
, "192.168.0.99", AF_UNSPEC
, 0);
1669 i
= tor_addr_parse_reverse_lookup_name(&t1
, "192.168.0.99", AF_UNSPEC
, 1);
1671 p1
= tor_addr_to_str(buf
, &t1
, sizeof(buf
), 1);
1672 test_streq(p1
, "192.168.0.99");
1673 memset(&t1
, 0, sizeof(t1
));
1674 i
= tor_addr_parse_reverse_lookup_name(&t1
,
1675 "0.1.2.3.4.5.6.7.8.9.a.b.c.d.e.f."
1676 "f.e.e.b.1.e.b.e.e.f.f.e.e.e.d.9."
1680 p1
= tor_addr_to_str(buf
, &t1
, sizeof(buf
), 1);
1681 test_streq(p1
, "[9dee:effe:ebe1:beef:fedc:ba98:7654:3210]");
1682 /* Failing cases. */
1683 i
= tor_addr_parse_reverse_lookup_name(&t1
,
1684 "6.7.8.9.a.b.c.d.e.f."
1685 "f.e.e.b.1.e.b.e.e.f.f.e.e.e.d.9."
1689 i
= tor_addr_parse_reverse_lookup_name(&t1
,
1690 "6.7.8.9.a.b.c.d.e.f.a.b.c.d.e.f.0."
1691 "f.e.e.b.1.e.b.e.e.f.f.e.e.e.d.9."
1695 i
= tor_addr_parse_reverse_lookup_name(&t1
,
1696 "6.7.8.9.a.b.c.d.e.f.X.0.0.0.0.9."
1697 "f.e.e.b.1.e.b.e.e.f.f.e.e.e.d.9."
1701 i
= tor_addr_parse_reverse_lookup_name(&t1
, "32.1.1.in-addr.arpa",
1704 i
= tor_addr_parse_reverse_lookup_name(&t1
, ".in-addr.arpa",
1707 i
= tor_addr_parse_reverse_lookup_name(&t1
, "1.2.3.4.5.in-addr.arpa",
1710 i
= tor_addr_parse_reverse_lookup_name(&t1
, "1.2.3.4.5.in-addr.arpa",
1713 i
= tor_addr_parse_reverse_lookup_name(&t1
,
1714 "6.7.8.9.a.b.c.d.e.f.a.b.c.d.e.0."
1715 "f.e.e.b.1.e.b.e.e.f.f.e.e.e.d.9."
1720 /* test tor_addr_parse_mask_ports */
1721 test_addr_mask_ports_parse("[::f]/17:47-95", AF_INET6
,
1722 0, 0, 0, 0x0000000f, 17, 47, 95);
1723 //test_addr_parse("[::fefe:4.1.1.7/120]:999-1000");
1724 //test_addr_parse_check("::fefe:401:107", 120, 999, 1000);
1725 test_addr_mask_ports_parse("[::ffff:4.1.1.7]/120:443", AF_INET6
,
1726 0, 0, 0x0000ffff, 0x04010107, 120, 443, 443);
1727 test_addr_mask_ports_parse("[abcd:2::44a:0]:2-65000", AF_INET6
,
1728 0xabcd0002, 0, 0, 0x044a0000, 128, 2, 65000);
1730 r
=tor_addr_parse_mask_ports("[fefef::]/112", &t1
, NULL
, NULL
, NULL
);
1731 test_assert(r
== -1);
1732 r
=tor_addr_parse_mask_ports("efef::/112", &t1
, NULL
, NULL
, NULL
);
1733 test_assert(r
== -1);
1734 r
=tor_addr_parse_mask_ports("[f:f:f:f:f:f:f:f::]", &t1
, NULL
, NULL
, NULL
);
1735 test_assert(r
== -1);
1736 r
=tor_addr_parse_mask_ports("[::f:f:f:f:f:f:f:f]", &t1
, NULL
, NULL
, NULL
);
1737 test_assert(r
== -1);
1738 r
=tor_addr_parse_mask_ports("[f:f:f:f:f:f:f:f:f]", &t1
, NULL
, NULL
, NULL
);
1739 test_assert(r
== -1);
1740 /* Test for V4-mapped address with mask < 96. (arguably not valid) */
1741 r
=tor_addr_parse_mask_ports("[::ffff:1.1.2.2/33]", &t1
, &mask
, NULL
, NULL
);
1742 test_assert(r
== -1);
1743 r
=tor_addr_parse_mask_ports("1.1.2.2/33", &t1
, &mask
, NULL
, NULL
);
1744 test_assert(r
== -1);
1745 r
=tor_addr_parse_mask_ports("1.1.2.2/31", &t1
, &mask
, NULL
, NULL
);
1746 test_assert(r
== AF_INET
);
1747 r
=tor_addr_parse_mask_ports("[efef::]/112", &t1
, &mask
, &port1
, &port2
);
1748 test_assert(r
== AF_INET6
);
1749 test_assert(port1
== 1);
1750 test_assert(port2
== 65535);
1752 /* make sure inet address lengths >= max */
1753 test_assert(INET_NTOA_BUF_LEN
>= sizeof("255.255.255.255"));
1754 test_assert(TOR_ADDR_BUF_LEN
>=
1755 sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"));
1757 test_assert(sizeof(tor_addr_t
) >= sizeof(struct in6_addr
));
1759 /* get interface addresses */
1760 r
= get_interface_address6(LOG_DEBUG
, AF_INET
, &t1
);
1761 i
= get_interface_address6(LOG_DEBUG
, AF_INET6
, &t2
);
1763 tor_inet_ntop(AF_INET
, &t1
.sa
.sin_addr
, buf
, sizeof(buf
));
1764 printf("\nv4 address: %s (family=%i)", buf
, IN_FAMILY(&t1
));
1765 tor_inet_ntop(AF_INET6
, &t2
.sa6
.sin6_addr
, buf
, sizeof(buf
));
1766 printf("\nv6 address: %s (family=%i)", buf
, IN_FAMILY(&t2
));
1773 /** Run unit tests for basic dynamic-sized array functionality. */
1775 test_util_smartlist_basic(void)
1779 /* XXXX test sort_digests, uniq_strings, uniq_digests */
1781 /* Test smartlist add, del_keeporder, insert, get. */
1782 sl
= smartlist_create();
1783 smartlist_add(sl
, (void*)1);
1784 smartlist_add(sl
, (void*)2);
1785 smartlist_add(sl
, (void*)3);
1786 smartlist_add(sl
, (void*)4);
1787 smartlist_del_keeporder(sl
, 1);
1788 smartlist_insert(sl
, 1, (void*)22);
1789 smartlist_insert(sl
, 0, (void*)0);
1790 smartlist_insert(sl
, 5, (void*)555);
1791 test_eq_ptr((void*)0, smartlist_get(sl
,0));
1792 test_eq_ptr((void*)1, smartlist_get(sl
,1));
1793 test_eq_ptr((void*)22, smartlist_get(sl
,2));
1794 test_eq_ptr((void*)3, smartlist_get(sl
,3));
1795 test_eq_ptr((void*)4, smartlist_get(sl
,4));
1796 test_eq_ptr((void*)555, smartlist_get(sl
,5));
1797 /* Try deleting in the middle. */
1798 smartlist_del(sl
, 1);
1799 test_eq_ptr((void*)555, smartlist_get(sl
, 1));
1800 /* Try deleting at the end. */
1801 smartlist_del(sl
, 4);
1802 test_eq(4, smartlist_len(sl
));
1805 test_assert(smartlist_isin(sl
, (void*)3));
1806 test_assert(!smartlist_isin(sl
, (void*)99));
1812 /** Run unit tests for smartlist-of-strings functionality. */
1814 test_util_smartlist_strings(void)
1816 smartlist_t
*sl
= smartlist_create();
1817 char *cp
=NULL
, *cp_alloc
=NULL
;
1820 /* Test split and join */
1821 test_eq(0, smartlist_len(sl
));
1822 smartlist_split_string(sl
, "abc", ":", 0, 0);
1823 test_eq(1, smartlist_len(sl
));
1824 test_streq("abc", smartlist_get(sl
, 0));
1825 smartlist_split_string(sl
, "a::bc::", "::", 0, 0);
1826 test_eq(4, smartlist_len(sl
));
1827 test_streq("a", smartlist_get(sl
, 1));
1828 test_streq("bc", smartlist_get(sl
, 2));
1829 test_streq("", smartlist_get(sl
, 3));
1830 cp_alloc
= smartlist_join_strings(sl
, "", 0, NULL
);
1831 test_streq(cp_alloc
, "abcabc");
1833 cp_alloc
= smartlist_join_strings(sl
, "!", 0, NULL
);
1834 test_streq(cp_alloc
, "abc!a!bc!");
1836 cp_alloc
= smartlist_join_strings(sl
, "XY", 0, NULL
);
1837 test_streq(cp_alloc
, "abcXYaXYbcXY");
1839 cp_alloc
= smartlist_join_strings(sl
, "XY", 1, NULL
);
1840 test_streq(cp_alloc
, "abcXYaXYbcXYXY");
1842 cp_alloc
= smartlist_join_strings(sl
, "", 1, NULL
);
1843 test_streq(cp_alloc
, "abcabc");
1846 smartlist_split_string(sl
, "/def/ /ghijk", "/", 0, 0);
1847 test_eq(8, smartlist_len(sl
));
1848 test_streq("", smartlist_get(sl
, 4));
1849 test_streq("def", smartlist_get(sl
, 5));
1850 test_streq(" ", smartlist_get(sl
, 6));
1851 test_streq("ghijk", smartlist_get(sl
, 7));
1852 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1853 smartlist_clear(sl
);
1855 smartlist_split_string(sl
, "a,bbd,cdef", ",", SPLIT_SKIP_SPACE
, 0);
1856 test_eq(3, smartlist_len(sl
));
1857 test_streq("a", smartlist_get(sl
,0));
1858 test_streq("bbd", smartlist_get(sl
,1));
1859 test_streq("cdef", smartlist_get(sl
,2));
1860 smartlist_split_string(sl
, " z <> zhasd <> <> bnud<> ", "<>",
1861 SPLIT_SKIP_SPACE
, 0);
1862 test_eq(8, smartlist_len(sl
));
1863 test_streq("z", smartlist_get(sl
,3));
1864 test_streq("zhasd", smartlist_get(sl
,4));
1865 test_streq("", smartlist_get(sl
,5));
1866 test_streq("bnud", smartlist_get(sl
,6));
1867 test_streq("", smartlist_get(sl
,7));
1869 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1870 smartlist_clear(sl
);
1872 smartlist_split_string(sl
, " ab\tc \td ef ", NULL
,
1873 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1874 test_eq(4, smartlist_len(sl
));
1875 test_streq("ab", smartlist_get(sl
,0));
1876 test_streq("c", smartlist_get(sl
,1));
1877 test_streq("d", smartlist_get(sl
,2));
1878 test_streq("ef", smartlist_get(sl
,3));
1879 smartlist_split_string(sl
, "ghi\tj", NULL
,
1880 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1881 test_eq(6, smartlist_len(sl
));
1882 test_streq("ghi", smartlist_get(sl
,4));
1883 test_streq("j", smartlist_get(sl
,5));
1885 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1886 smartlist_clear(sl
);
1888 cp_alloc
= smartlist_join_strings(sl
, "XY", 0, NULL
);
1889 test_streq(cp_alloc
, "");
1891 cp_alloc
= smartlist_join_strings(sl
, "XY", 1, NULL
);
1892 test_streq(cp_alloc
, "XY");
1895 smartlist_split_string(sl
, " z <> zhasd <> <> bnud<> ", "<>",
1896 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1897 test_eq(3, smartlist_len(sl
));
1898 test_streq("z", smartlist_get(sl
, 0));
1899 test_streq("zhasd", smartlist_get(sl
, 1));
1900 test_streq("bnud", smartlist_get(sl
, 2));
1901 smartlist_split_string(sl
, " z <> zhasd <> <> bnud<> ", "<>",
1902 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 2);
1903 test_eq(5, smartlist_len(sl
));
1904 test_streq("z", smartlist_get(sl
, 3));
1905 test_streq("zhasd <> <> bnud<>", smartlist_get(sl
, 4));
1906 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1907 smartlist_clear(sl
);
1909 smartlist_split_string(sl
, "abcd\n", "\n",
1910 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1911 test_eq(1, smartlist_len(sl
));
1912 test_streq("abcd", smartlist_get(sl
, 0));
1913 smartlist_split_string(sl
, "efgh", "\n",
1914 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1915 test_eq(2, smartlist_len(sl
));
1916 test_streq("efgh", smartlist_get(sl
, 1));
1918 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1919 smartlist_clear(sl
);
1921 /* Test swapping, shuffling, and sorting. */
1922 smartlist_split_string(sl
, "the,onion,router,by,arma,and,nickm", ",", 0, 0);
1923 test_eq(7, smartlist_len(sl
));
1924 smartlist_sort(sl
, _compare_strs
);
1925 cp_alloc
= smartlist_join_strings(sl
, ",", 0, NULL
);
1926 test_streq(cp_alloc
,"and,arma,by,nickm,onion,router,the");
1928 smartlist_swap(sl
, 1, 5);
1929 cp_alloc
= smartlist_join_strings(sl
, ",", 0, NULL
);
1930 test_streq(cp_alloc
,"and,router,by,nickm,onion,arma,the");
1932 smartlist_shuffle(sl
);
1933 test_eq(7, smartlist_len(sl
));
1934 test_assert(smartlist_string_isin(sl
, "and"));
1935 test_assert(smartlist_string_isin(sl
, "router"));
1936 test_assert(smartlist_string_isin(sl
, "by"));
1937 test_assert(smartlist_string_isin(sl
, "nickm"));
1938 test_assert(smartlist_string_isin(sl
, "onion"));
1939 test_assert(smartlist_string_isin(sl
, "arma"));
1940 test_assert(smartlist_string_isin(sl
, "the"));
1943 smartlist_sort(sl
, _compare_strs
);
1944 test_streq("nickm", smartlist_bsearch(sl
, "zNicKM",
1945 _compare_without_first_ch
));
1946 test_streq("and", smartlist_bsearch(sl
, " AND", _compare_without_first_ch
));
1947 test_eq_ptr(NULL
, smartlist_bsearch(sl
, " ANz", _compare_without_first_ch
));
1949 /* Test bsearch_idx */
1952 test_eq(0, smartlist_bsearch_idx(sl
," aaa",_compare_without_first_ch
,&f
));
1954 test_eq(0, smartlist_bsearch_idx(sl
," and",_compare_without_first_ch
,&f
));
1956 test_eq(1, smartlist_bsearch_idx(sl
," arm",_compare_without_first_ch
,&f
));
1958 test_eq(1, smartlist_bsearch_idx(sl
," arma",_compare_without_first_ch
,&f
));
1960 test_eq(2, smartlist_bsearch_idx(sl
," armb",_compare_without_first_ch
,&f
));
1962 test_eq(7, smartlist_bsearch_idx(sl
," zzzz",_compare_without_first_ch
,&f
));
1966 /* Test reverse() and pop_last() */
1967 smartlist_reverse(sl
);
1968 cp_alloc
= smartlist_join_strings(sl
, ",", 0, NULL
);
1969 test_streq(cp_alloc
,"the,router,onion,nickm,by,arma,and");
1971 cp_alloc
= smartlist_pop_last(sl
);
1972 test_streq(cp_alloc
, "and");
1974 test_eq(smartlist_len(sl
), 6);
1975 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1976 smartlist_clear(sl
);
1977 cp_alloc
= smartlist_pop_last(sl
);
1978 test_eq(cp_alloc
, NULL
);
1981 smartlist_split_string(sl
,
1982 "50,noon,radar,a,man,a,plan,a,canal,panama,radar,noon,50",
1984 smartlist_sort(sl
, _compare_strs
);
1985 smartlist_uniq(sl
, _compare_strs
, _tor_free
);
1986 cp_alloc
= smartlist_join_strings(sl
, ",", 0, NULL
);
1987 test_streq(cp_alloc
, "50,a,canal,man,noon,panama,plan,radar");
1990 /* Test string_isin and isin_case and num_isin */
1991 test_assert(smartlist_string_isin(sl
, "noon"));
1992 test_assert(!smartlist_string_isin(sl
, "noonoon"));
1993 test_assert(smartlist_string_isin_case(sl
, "nOOn"));
1994 test_assert(!smartlist_string_isin_case(sl
, "nooNooN"));
1995 test_assert(smartlist_string_num_isin(sl
, 50));
1996 test_assert(!smartlist_string_num_isin(sl
, 60));
1998 /* Test smartlist_choose */
2003 void *first
= smartlist_choose(sl
);
2004 test_assert(smartlist_isin(sl
, first
));
2005 for (i
= 0; i
< 100; ++i
) {
2006 void *second
= smartlist_choose(sl
);
2007 if (second
!= first
)
2009 if (!smartlist_isin(sl
, second
))
2012 test_assert(!allsame
);
2015 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
2016 smartlist_clear(sl
);
2018 /* Test string_remove and remove and join_strings2 */
2019 smartlist_split_string(sl
,
2020 "Some say the Earth will end in ice and some in fire",
2022 cp
= smartlist_get(sl
, 4);
2023 test_streq(cp
, "will");
2024 smartlist_add(sl
, cp
);
2025 smartlist_remove(sl
, cp
);
2027 cp_alloc
= smartlist_join_strings(sl
, ",", 0, NULL
);
2028 test_streq(cp_alloc
, "Some,say,the,Earth,fire,end,in,ice,and,some,in");
2030 smartlist_string_remove(sl
, "in");
2031 cp_alloc
= smartlist_join_strings2(sl
, "+XX", 1, 0, &sz
);
2032 test_streq(cp_alloc
, "Some+say+the+Earth+fire+end+some+ice+and");
2033 test_eq((int)sz
, 40);
2037 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
2042 /** Run unit tests for smartlist set manipulation functions. */
2044 test_util_smartlist_overlap(void)
2046 smartlist_t
*sl
= smartlist_create();
2047 smartlist_t
*ints
= smartlist_create();
2048 smartlist_t
*odds
= smartlist_create();
2049 smartlist_t
*evens
= smartlist_create();
2050 smartlist_t
*primes
= smartlist_create();
2052 for (i
=1; i
< 10; i
+= 2)
2053 smartlist_add(odds
, (void*)(uintptr_t)i
);
2054 for (i
=0; i
< 10; i
+= 2)
2055 smartlist_add(evens
, (void*)(uintptr_t)i
);
2058 smartlist_add_all(ints
, odds
);
2059 smartlist_add_all(ints
, evens
);
2060 test_eq(smartlist_len(ints
), 10);
2062 smartlist_add(primes
, (void*)2);
2063 smartlist_add(primes
, (void*)3);
2064 smartlist_add(primes
, (void*)5);
2065 smartlist_add(primes
, (void*)7);
2068 test_assert(smartlist_overlap(ints
, odds
));
2069 test_assert(smartlist_overlap(odds
, primes
));
2070 test_assert(smartlist_overlap(evens
, primes
));
2071 test_assert(!smartlist_overlap(odds
, evens
));
2074 smartlist_add_all(sl
, odds
);
2075 smartlist_intersect(sl
, primes
);
2076 test_eq(smartlist_len(sl
), 3);
2077 test_assert(smartlist_isin(sl
, (void*)3));
2078 test_assert(smartlist_isin(sl
, (void*)5));
2079 test_assert(smartlist_isin(sl
, (void*)7));
2082 smartlist_add_all(sl
, primes
);
2083 smartlist_subtract(sl
, odds
);
2084 test_eq(smartlist_len(sl
), 1);
2085 test_assert(smartlist_isin(sl
, (void*)2));
2088 smartlist_free(odds
);
2089 smartlist_free(evens
);
2090 smartlist_free(ints
);
2091 smartlist_free(primes
);
2095 /** Run unit tests for smartlist-of-digests functions. */
2097 test_util_smartlist_digests(void)
2099 smartlist_t
*sl
= smartlist_create();
2102 smartlist_add(sl
, tor_memdup("AAAAAAAAAAAAAAAAAAAA", DIGEST_LEN
));
2103 smartlist_add(sl
, tor_memdup("\00090AAB2AAAAaasdAAAAA", DIGEST_LEN
));
2104 smartlist_add(sl
, tor_memdup("\00090AAB2AAAAaasdAAAAA", DIGEST_LEN
));
2105 test_eq(0, smartlist_digest_isin(NULL
, "AAAAAAAAAAAAAAAAAAAA"));
2106 test_assert(smartlist_digest_isin(sl
, "AAAAAAAAAAAAAAAAAAAA"));
2107 test_assert(smartlist_digest_isin(sl
, "\00090AAB2AAAAaasdAAAAA"));
2108 test_eq(0, smartlist_digest_isin(sl
, "\00090AAB2AAABaasdAAAAA"));
2111 smartlist_sort_digests(sl
);
2112 test_memeq(smartlist_get(sl
, 0), "\00090AAB2AAAAaasdAAAAA", DIGEST_LEN
);
2113 test_memeq(smartlist_get(sl
, 1), "\00090AAB2AAAAaasdAAAAA", DIGEST_LEN
);
2114 test_memeq(smartlist_get(sl
, 2), "AAAAAAAAAAAAAAAAAAAA", DIGEST_LEN
);
2115 test_eq(3, smartlist_len(sl
));
2118 smartlist_uniq_digests(sl
);
2119 test_eq(2, smartlist_len(sl
));
2120 test_memeq(smartlist_get(sl
, 0), "\00090AAB2AAAAaasdAAAAA", DIGEST_LEN
);
2121 test_memeq(smartlist_get(sl
, 1), "AAAAAAAAAAAAAAAAAAAA", DIGEST_LEN
);
2124 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
2128 /** Run unit tests for concatenate-a-smartlist-of-strings functions. */
2130 test_util_smartlist_join(void)
2132 smartlist_t
*sl
= smartlist_create();
2133 smartlist_t
*sl2
= smartlist_create(), *sl3
= smartlist_create(),
2134 *sl4
= smartlist_create();
2136 /* unique, sorted. */
2137 smartlist_split_string(sl
,
2138 "Abashments Ambush Anchorman Bacon Banks Borscht "
2139 "Bunks Inhumane Insurance Knish Know Manners "
2140 "Maraschinos Stamina Sunbonnets Unicorns Wombats",
2142 /* non-unique, sorted. */
2143 smartlist_split_string(sl2
,
2144 "Ambush Anchorman Anchorman Anemias Anemias Bacon "
2145 "Crossbowmen Inhumane Insurance Knish Know Manners "
2146 "Manners Maraschinos Wombats Wombats Work",
2148 SMARTLIST_FOREACH_JOIN(sl
, char *, cp1
,
2151 smartlist_add(sl3
, cp2
)) {
2152 test_streq(cp1
, cp2
);
2153 smartlist_add(sl4
, cp1
);
2154 } SMARTLIST_FOREACH_JOIN_END(cp1
, cp2
);
2156 SMARTLIST_FOREACH(sl3
, const char *, cp
,
2157 test_assert(smartlist_isin(sl2
, cp
) &&
2158 !smartlist_string_isin(sl
, cp
)));
2159 SMARTLIST_FOREACH(sl4
, const char *, cp
,
2160 test_assert(smartlist_isin(sl
, cp
) &&
2161 smartlist_string_isin(sl2
, cp
)));
2162 joined
= smartlist_join_strings(sl3
, ",", 0, NULL
);
2163 test_streq(joined
, "Anemias,Anemias,Crossbowmen,Work");
2165 joined
= smartlist_join_strings(sl4
, ",", 0, NULL
);
2166 test_streq(joined
, "Ambush,Anchorman,Anchorman,Bacon,Inhumane,Insurance,"
2167 "Knish,Know,Manners,Manners,Maraschinos,Wombats,Wombats");
2171 smartlist_free(sl4
);
2172 smartlist_free(sl3
);
2173 SMARTLIST_FOREACH(sl2
, char *, cp
, tor_free(cp
));
2174 smartlist_free(sl2
);
2175 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
2180 /** Run unit tests for bitarray code */
2182 test_util_bitarray(void)
2184 bitarray_t
*ba
= NULL
;
2187 ba
= bitarray_init_zero(1);
2189 test_assert(! bitarray_is_set(ba
, 0));
2190 bitarray_set(ba
, 0);
2191 test_assert(bitarray_is_set(ba
, 0));
2192 bitarray_clear(ba
, 0);
2193 test_assert(! bitarray_is_set(ba
, 0));
2196 ba
= bitarray_init_zero(1023);
2197 for (i
= 1; i
< 64; ) {
2198 for (j
= 0; j
< 1023; ++j
) {
2200 bitarray_set(ba
, j
);
2202 bitarray_clear(ba
, j
);
2204 for (j
= 0; j
< 1023; ++j
) {
2205 if (!bool_eq(bitarray_is_set(ba
, j
), j
%i
))
2222 /** Run unit tests for digest set code (implemented as a hashtable or as a
2225 test_util_digestset(void)
2227 smartlist_t
*included
= smartlist_create();
2231 int false_positives
= 0;
2232 digestset_t
*set
= NULL
;
2234 for (i
= 0; i
< 1000; ++i
) {
2235 crypto_rand(d
, DIGEST_LEN
);
2236 smartlist_add(included
, tor_memdup(d
, DIGEST_LEN
));
2238 set
= digestset_new(1000);
2239 SMARTLIST_FOREACH(included
, const char *, cp
,
2240 if (digestset_isin(set
, cp
))
2243 SMARTLIST_FOREACH(included
, const char *, cp
,
2244 digestset_add(set
, cp
));
2245 SMARTLIST_FOREACH(included
, const char *, cp
,
2246 if (!digestset_isin(set
, cp
))
2249 for (i
= 0; i
< 1000; ++i
) {
2250 crypto_rand(d
, DIGEST_LEN
);
2251 if (digestset_isin(set
, d
))
2254 test_assert(false_positives
< 50); /* Should be far lower. */
2258 digestset_free(set
);
2259 SMARTLIST_FOREACH(included
, char *, cp
, tor_free(cp
));
2260 smartlist_free(included
);
2263 /** mutex for thread test to stop the threads hitting data at the same time. */
2264 static tor_mutex_t
*_thread_test_mutex
= NULL
;
2265 /** mutexes for the thread test to make sure that the threads have to
2266 * interleave somewhat. */
2267 static tor_mutex_t
*_thread_test_start1
= NULL
,
2268 *_thread_test_start2
= NULL
;
2269 /** Shared strmap for the thread test. */
2270 static strmap_t
*_thread_test_strmap
= NULL
;
2271 /** The name of thread1 for the thread test */
2272 static char *_thread1_name
= NULL
;
2273 /** The name of thread2 for the thread test */
2274 static char *_thread2_name
= NULL
;
2276 static void _thread_test_func(void* _s
) ATTR_NORETURN
;
2278 /** How many iterations have the threads in the unit test run? */
2279 static int t1_count
= 0, t2_count
= 0;
2281 /** Helper function for threading unit tests: This function runs in a
2282 * subthread. It grabs its own mutex (start1 or start2) to make sure that it
2283 * should start, then it repeatedly alters _test_thread_strmap protected by
2284 * _thread_test_mutex. */
2286 _thread_test_func(void* _s
)
2293 if (!strcmp(s
, "thread 1")) {
2294 m
= _thread_test_start1
;
2295 cp
= &_thread1_name
;
2298 m
= _thread_test_start2
;
2299 cp
= &_thread2_name
;
2302 tor_mutex_acquire(m
);
2304 tor_snprintf(buf
, sizeof(buf
), "%lu", tor_get_thread_id());
2305 *cp
= tor_strdup(buf
);
2307 for (i
=0; i
<10000; ++i
) {
2308 tor_mutex_acquire(_thread_test_mutex
);
2309 strmap_set(_thread_test_strmap
, "last to run", *cp
);
2311 tor_mutex_release(_thread_test_mutex
);
2313 tor_mutex_acquire(_thread_test_mutex
);
2314 strmap_set(_thread_test_strmap
, s
, *cp
);
2315 tor_mutex_release(_thread_test_mutex
);
2317 tor_mutex_release(m
);
2322 /** Run unit tests for threading logic. */
2324 test_util_threads(void)
2326 char *s1
= NULL
, *s2
= NULL
;
2327 int done
= 0, timedout
= 0;
2329 #ifndef TOR_IS_MULTITHREADED
2330 /* Skip this test if we aren't threading. We should be threading most
2331 * everywhere by now. */
2335 _thread_test_mutex
= tor_mutex_new();
2336 _thread_test_start1
= tor_mutex_new();
2337 _thread_test_start2
= tor_mutex_new();
2338 _thread_test_strmap
= strmap_new();
2339 s1
= tor_strdup("thread 1");
2340 s2
= tor_strdup("thread 2");
2341 tor_mutex_acquire(_thread_test_start1
);
2342 tor_mutex_acquire(_thread_test_start2
);
2343 spawn_func(_thread_test_func
, s1
);
2344 spawn_func(_thread_test_func
, s2
);
2345 tor_mutex_release(_thread_test_start2
);
2346 tor_mutex_release(_thread_test_start1
);
2347 started
= time(NULL
);
2349 tor_mutex_acquire(_thread_test_mutex
);
2350 strmap_assert_ok(_thread_test_strmap
);
2351 if (strmap_get(_thread_test_strmap
, "thread 1") &&
2352 strmap_get(_thread_test_strmap
, "thread 2")) {
2354 } else if (time(NULL
) > started
+ 25) {
2355 timedout
= done
= 1;
2357 tor_mutex_release(_thread_test_mutex
);
2359 tor_mutex_free(_thread_test_mutex
);
2361 tor_mutex_acquire(_thread_test_start1
);
2362 tor_mutex_release(_thread_test_start1
);
2363 tor_mutex_acquire(_thread_test_start2
);
2364 tor_mutex_release(_thread_test_start2
);
2367 printf("\nTimed out: %d %d", t1_count
, t2_count
);
2368 test_assert(strmap_get(_thread_test_strmap
, "thread 1"));
2369 test_assert(strmap_get(_thread_test_strmap
, "thread 2"));
2370 test_assert(!timedout
);
2373 /* different thread IDs. */
2374 test_assert(strcmp(strmap_get(_thread_test_strmap
, "thread 1"),
2375 strmap_get(_thread_test_strmap
, "thread 2")));
2376 test_assert(!strcmp(strmap_get(_thread_test_strmap
, "thread 1"),
2377 strmap_get(_thread_test_strmap
, "last to run")) ||
2378 !strcmp(strmap_get(_thread_test_strmap
, "thread 2"),
2379 strmap_get(_thread_test_strmap
, "last to run")));
2384 tor_free(_thread1_name
);
2385 tor_free(_thread2_name
);
2386 if (_thread_test_strmap
)
2387 strmap_free(_thread_test_strmap
, NULL
);
2388 if (_thread_test_start1
)
2389 tor_mutex_free(_thread_test_start1
);
2390 if (_thread_test_start2
)
2391 tor_mutex_free(_thread_test_start2
);
2394 /** Helper: return a tristate based on comparing two strings. */
2396 _compare_strings_for_pqueue(const void *s1
, const void *s2
)
2398 return strcmp((const char*)s1
, (const char*)s2
);
2401 /** Run unit tests for heap-based priority queue functions. */
2403 test_util_pqueue(void)
2405 smartlist_t
*sl
= smartlist_create();
2406 int (*cmp
)(const void *, const void*);
2407 #define OK() smartlist_pqueue_assert_ok(sl, cmp)
2409 cmp
= _compare_strings_for_pqueue
;
2411 smartlist_pqueue_add(sl
, cmp
, (char*)"cows");
2412 smartlist_pqueue_add(sl
, cmp
, (char*)"zebras");
2413 smartlist_pqueue_add(sl
, cmp
, (char*)"fish");
2414 smartlist_pqueue_add(sl
, cmp
, (char*)"frogs");
2415 smartlist_pqueue_add(sl
, cmp
, (char*)"apples");
2416 smartlist_pqueue_add(sl
, cmp
, (char*)"squid");
2417 smartlist_pqueue_add(sl
, cmp
, (char*)"daschunds");
2418 smartlist_pqueue_add(sl
, cmp
, (char*)"eggplants");
2419 smartlist_pqueue_add(sl
, cmp
, (char*)"weissbier");
2420 smartlist_pqueue_add(sl
, cmp
, (char*)"lobsters");
2421 smartlist_pqueue_add(sl
, cmp
, (char*)"roquefort");
2425 test_eq(smartlist_len(sl
), 11);
2426 test_streq(smartlist_get(sl
, 0), "apples");
2427 test_streq(smartlist_pqueue_pop(sl
, cmp
), "apples");
2428 test_eq(smartlist_len(sl
), 10);
2430 test_streq(smartlist_pqueue_pop(sl
, cmp
), "cows");
2431 test_streq(smartlist_pqueue_pop(sl
, cmp
), "daschunds");
2432 smartlist_pqueue_add(sl
, cmp
, (char*)"chinchillas");
2434 smartlist_pqueue_add(sl
, cmp
, (char*)"fireflies");
2436 test_streq(smartlist_pqueue_pop(sl
, cmp
), "chinchillas");
2437 test_streq(smartlist_pqueue_pop(sl
, cmp
), "eggplants");
2438 test_streq(smartlist_pqueue_pop(sl
, cmp
), "fireflies");
2440 test_streq(smartlist_pqueue_pop(sl
, cmp
), "fish");
2441 test_streq(smartlist_pqueue_pop(sl
, cmp
), "frogs");
2442 test_streq(smartlist_pqueue_pop(sl
, cmp
), "lobsters");
2443 test_streq(smartlist_pqueue_pop(sl
, cmp
), "roquefort");
2445 test_eq(smartlist_len(sl
), 3);
2446 test_streq(smartlist_pqueue_pop(sl
, cmp
), "squid");
2447 test_streq(smartlist_pqueue_pop(sl
, cmp
), "weissbier");
2448 test_streq(smartlist_pqueue_pop(sl
, cmp
), "zebras");
2449 test_eq(smartlist_len(sl
), 0);
2458 /** Run unit tests for compression functions */
2460 test_util_gzip(void)
2462 char *buf1
=NULL
, *buf2
=NULL
, *buf3
=NULL
, *cp1
, *cp2
;
2465 tor_zlib_state_t
*state
= NULL
;
2467 buf1
= tor_strdup("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ");
2468 test_assert(detect_compression_method(buf1
, strlen(buf1
)) == UNKNOWN_METHOD
);
2469 if (is_gzip_supported()) {
2470 test_assert(!tor_gzip_compress(&buf2
, &len1
, buf1
, strlen(buf1
)+1,
2473 test_assert(!memcmp(buf2
, "\037\213", 2)); /* Gzip magic. */
2474 test_assert(detect_compression_method(buf2
, len1
) == GZIP_METHOD
);
2476 test_assert(!tor_gzip_uncompress(&buf3
, &len2
, buf2
, len1
,
2477 GZIP_METHOD
, 1, LOG_INFO
));
2479 test_streq(buf1
,buf3
);
2485 test_assert(!tor_gzip_compress(&buf2
, &len1
, buf1
, strlen(buf1
)+1,
2488 test_assert(!memcmp(buf2
, "\x78\xDA", 2)); /* deflate magic. */
2489 test_assert(detect_compression_method(buf2
, len1
) == ZLIB_METHOD
);
2491 test_assert(!tor_gzip_uncompress(&buf3
, &len2
, buf2
, len1
,
2492 ZLIB_METHOD
, 1, LOG_INFO
));
2494 test_streq(buf1
,buf3
);
2496 /* Check whether we can uncompress concatenated, compressed strings. */
2498 buf2
= tor_realloc(buf2
, len1
*2);
2499 memcpy(buf2
+len1
, buf2
, len1
);
2500 test_assert(!tor_gzip_uncompress(&buf3
, &len2
, buf2
, len1
*2,
2501 ZLIB_METHOD
, 1, LOG_INFO
));
2502 test_eq(len2
, (strlen(buf1
)+1)*2);
2504 "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ\0"
2505 "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ\0",
2506 (strlen(buf1
)+1)*2);
2512 /* Check whether we can uncompress partial strings. */
2514 tor_strdup("String with low redundancy that won't be compressed much.");
2515 test_assert(!tor_gzip_compress(&buf2
, &len1
, buf1
, strlen(buf1
)+1,
2517 tor_assert(len1
>16);
2518 /* when we allow an incomplete string, we should succeed.*/
2519 tor_assert(!tor_gzip_uncompress(&buf3
, &len2
, buf2
, len1
-16,
2520 ZLIB_METHOD
, 0, LOG_INFO
));
2522 tor_assert(len2
> 5);
2523 tor_assert(!strcmpstart(buf1
, buf3
));
2525 /* when we demand a complete string, this must fail. */
2527 tor_assert(tor_gzip_uncompress(&buf3
, &len2
, buf2
, len1
-16,
2528 ZLIB_METHOD
, 1, LOG_INFO
));
2531 /* Now, try streaming compression. */
2535 state
= tor_zlib_new(1, ZLIB_METHOD
);
2537 cp1
= buf1
= tor_malloc(1024);
2539 ccp2
= "ABCDEFGHIJABCDEFGHIJ";
2541 test_assert(tor_zlib_process(state
, &cp1
, &len1
, &ccp2
, &len2
, 0)
2543 test_eq(len2
, 0); /* Make sure we compressed it all. */
2544 test_assert(cp1
> buf1
);
2548 test_assert(tor_zlib_process(state
, &cp1
, &len1
, &ccp2
, &len2
, 1)
2551 test_assert(cp1
> cp2
); /* Make sure we really added something. */
2553 tor_assert(!tor_gzip_uncompress(&buf3
, &len2
, buf1
, 1024-len1
,
2554 ZLIB_METHOD
, 1, LOG_WARN
));
2555 test_streq(buf3
, "ABCDEFGHIJABCDEFGHIJ"); /*Make sure it compressed right.*/
2559 tor_zlib_free(state
);
2565 /** Run unit tests for string-to-void* map functions */
2567 test_util_strmap(void)
2570 strmap_iter_t
*iter
;
2573 char *visited
= NULL
;
2574 smartlist_t
*found_keys
= NULL
;
2578 test_eq(strmap_size(map
), 0);
2579 test_assert(strmap_isempty(map
));
2580 v
= strmap_set(map
, "K1", (void*)99);
2582 test_assert(!strmap_isempty(map
));
2583 v
= strmap_set(map
, "K2", (void*)101);
2585 v
= strmap_set(map
, "K1", (void*)100);
2586 test_eq(v
, (void*)99);
2587 test_eq_ptr(strmap_get(map
,"K1"), (void*)100);
2588 test_eq_ptr(strmap_get(map
,"K2"), (void*)101);
2589 test_eq_ptr(strmap_get(map
,"K-not-there"), NULL
);
2590 strmap_assert_ok(map
);
2592 v
= strmap_remove(map
,"K2");
2593 strmap_assert_ok(map
);
2594 test_eq_ptr(v
, (void*)101);
2595 test_eq_ptr(strmap_get(map
,"K2"), NULL
);
2596 test_eq_ptr(strmap_remove(map
,"K2"), NULL
);
2598 strmap_set(map
, "K2", (void*)101);
2599 strmap_set(map
, "K3", (void*)102);
2600 strmap_set(map
, "K4", (void*)103);
2601 test_eq(strmap_size(map
), 4);
2602 strmap_assert_ok(map
);
2603 strmap_set(map
, "K5", (void*)104);
2604 strmap_set(map
, "K6", (void*)105);
2605 strmap_assert_ok(map
);
2607 /* Test iterator. */
2608 iter
= strmap_iter_init(map
);
2609 found_keys
= smartlist_create();
2610 while (!strmap_iter_done(iter
)) {
2611 strmap_iter_get(iter
,&k
,&v
);
2612 smartlist_add(found_keys
, tor_strdup(k
));
2613 test_eq_ptr(v
, strmap_get(map
, k
));
2615 if (!strcmp(k
, "K2")) {
2616 iter
= strmap_iter_next_rmv(map
,iter
);
2618 iter
= strmap_iter_next(map
,iter
);
2622 /* Make sure we removed K2, but not the others. */
2623 test_eq_ptr(strmap_get(map
, "K2"), NULL
);
2624 test_eq_ptr(strmap_get(map
, "K5"), (void*)104);
2625 /* Make sure we visited everyone once */
2626 smartlist_sort_strings(found_keys
);
2627 visited
= smartlist_join_strings(found_keys
, ":", 0, NULL
);
2628 test_streq(visited
, "K1:K2:K3:K4:K5:K6");
2630 strmap_assert_ok(map
);
2631 /* Clean up after ourselves. */
2632 strmap_free(map
, NULL
);
2635 /* Now try some lc functions. */
2637 strmap_set_lc(map
,"Ab.C", (void*)1);
2638 test_eq_ptr(strmap_get(map
,"ab.c"), (void*)1);
2639 strmap_assert_ok(map
);
2640 test_eq_ptr(strmap_get_lc(map
,"AB.C"), (void*)1);
2641 test_eq_ptr(strmap_get(map
,"AB.C"), NULL
);
2642 test_eq_ptr(strmap_remove_lc(map
,"aB.C"), (void*)1);
2643 strmap_assert_ok(map
);
2644 test_eq_ptr(strmap_get_lc(map
,"AB.C"), NULL
);
2648 strmap_free(map
,NULL
);
2650 SMARTLIST_FOREACH(found_keys
, char *, cp
, tor_free(cp
));
2651 smartlist_free(found_keys
);
2656 /** Run unit tests for mmap() wrapper functionality. */
2658 test_util_mmap(void)
2660 char *fname1
= tor_strdup(get_fname("mapped_1"));
2661 char *fname2
= tor_strdup(get_fname("mapped_2"));
2662 char *fname3
= tor_strdup(get_fname("mapped_3"));
2663 const size_t buflen
= 17000;
2664 char *buf
= tor_malloc(17000);
2665 tor_mmap_t
*mapping
= NULL
;
2667 crypto_rand(buf
, buflen
);
2669 mapping
= tor_mmap_file(fname1
);
2670 test_assert(! mapping
);
2672 write_str_to_file(fname1
, "Short file.", 1);
2673 write_bytes_to_file(fname2
, buf
, buflen
, 1);
2674 write_bytes_to_file(fname3
, buf
, 16384, 1);
2676 mapping
= tor_mmap_file(fname1
);
2677 test_assert(mapping
);
2678 test_eq(mapping
->size
, strlen("Short file."));
2679 test_streq(mapping
->data
, "Short file.");
2681 tor_munmap_file(mapping
);
2683 test_assert(unlink(fname1
) == 0);
2685 /* make sure we can unlink. */
2686 test_assert(unlink(fname1
) == 0);
2687 test_streq(mapping
->data
, "Short file.");
2688 tor_munmap_file(mapping
);
2692 /* Now a zero-length file. */
2693 write_str_to_file(fname1
, "", 1);
2694 mapping
= tor_mmap_file(fname1
);
2695 test_eq(mapping
, NULL
);
2696 test_eq(ERANGE
, errno
);
2699 /* Make sure that we fail to map a no-longer-existent file. */
2700 mapping
= tor_mmap_file(fname1
);
2701 test_assert(mapping
== NULL
);
2703 /* Now try a big file that stretches across a few pages and isn't aligned */
2704 mapping
= tor_mmap_file(fname2
);
2705 test_assert(mapping
);
2706 test_eq(mapping
->size
, buflen
);
2707 test_memeq(mapping
->data
, buf
, buflen
);
2708 tor_munmap_file(mapping
);
2711 /* Now try a big aligned file. */
2712 mapping
= tor_mmap_file(fname3
);
2713 test_assert(mapping
);
2714 test_eq(mapping
->size
, 16384);
2715 test_memeq(mapping
->data
, buf
, 16384);
2716 tor_munmap_file(mapping
);
2730 tor_munmap_file(mapping
);
2733 /** Run unit tests for escaping/unescaping data for use by controllers. */
2735 test_util_control_formats(void)
2739 "..This is a test\r\nof the emergency \nbroadcast\r\n..system.\r\nZ.\r\n";
2742 sz
= read_escaped_data(inp
, strlen(inp
), &out
);
2744 ".This is a test\nof the emergency \nbroadcast\n.system.\nZ.\n");
2745 test_eq(sz
, strlen(out
));
2752 test_util_sscanf(void)
2754 unsigned u1
, u2
, u3
;
2755 char s1
[10], s2
[10], s3
[10], ch
;
2758 r
= tor_sscanf("hello world", "hello world"); /* String match: success */
2760 r
= tor_sscanf("hello world 3", "hello worlb %u", &u1
); /* String fail */
2762 r
= tor_sscanf("12345", "%u", &u1
); /* Simple number */
2764 test_eq(u1
, 12345u);
2765 r
= tor_sscanf("", "%u", &u1
); /* absent number */
2767 r
= tor_sscanf("A", "%u", &u1
); /* bogus number */
2769 r
= tor_sscanf("4294967295", "%u", &u1
); /* UINT32_MAX should work. */
2771 test_eq(u1
, 4294967295u);
2772 r
= tor_sscanf("4294967296", "%u", &u1
); /* Always say -1 at 32 bits. */
2774 r
= tor_sscanf("123456", "%2u%u", &u1
, &u2
); /* Width */
2778 r
= tor_sscanf("!12:3:456", "!%2u:%2u:%3u", &u1
, &u2
, &u3
); /* separators */
2783 r
= tor_sscanf("12:3:045", "%2u:%2u:%3u", &u1
, &u2
, &u3
); /* 0s */
2788 /* %u does not match space.*/
2789 r
= tor_sscanf("12:3: 45", "%2u:%2u:%3u", &u1
, &u2
, &u3
);
2791 /* %u does not match negative numbers. */
2792 r
= tor_sscanf("12:3:-4", "%2u:%2u:%3u", &u1
, &u2
, &u3
);
2794 /* Arbitrary amounts of 0-padding are okay */
2795 r
= tor_sscanf("12:03:000000000000000099", "%2u:%2u:%u", &u1
, &u2
, &u3
);
2801 r
= tor_sscanf("99% fresh", "%3u%% fresh", &u1
); /* percents are scannable.*/
2805 r
= tor_sscanf("hello", "%s", s1
); /* %s needs a number. */
2808 r
= tor_sscanf("hello", "%3s%7s", s1
, s2
); /* %s matches characters. */
2810 test_streq(s1
, "hel");
2811 test_streq(s2
, "lo");
2812 r
= tor_sscanf("WD40", "%2s%u", s3
, &u1
); /* %s%u */
2814 test_streq(s3
, "WD");
2816 r
= tor_sscanf("76trombones", "%6u%9s", &u1
, s1
); /* %u%s */
2819 test_streq(s1
, "trombones");
2820 r
= tor_sscanf("hello world", "%9s %9s", s1
, s2
); /* %s doesn't eat space. */
2822 test_streq(s1
, "hello");
2823 test_streq(s2
, "world");
2824 r
= tor_sscanf("hi", "%9s%9s%3s", s1
, s2
, s3
); /* %s can be empty. */
2826 test_streq(s1
, "hi");
2830 r
= tor_sscanf("1.2.3", "%u.%u.%u%c", &u1
, &u2
, &u3
, &ch
);
2832 r
= tor_sscanf("1.2.3 foobar", "%u.%u.%u%c", &u1
, &u2
, &u3
, &ch
);
2839 /** Run unit tests for the onion handshake code. */
2841 test_onion_handshake(void)
2844 crypto_dh_env_t
*c_dh
= NULL
;
2845 char c_buf
[ONIONSKIN_CHALLENGE_LEN
];
2849 char s_buf
[ONIONSKIN_REPLY_LEN
];
2853 crypto_pk_env_t
*pk
= NULL
;
2855 pk
= pk_generate(0);
2857 /* client handshake 1. */
2858 memset(c_buf
, 0, ONIONSKIN_CHALLENGE_LEN
);
2859 test_assert(! onion_skin_create(pk
, &c_dh
, c_buf
));
2861 /* server handshake */
2862 memset(s_buf
, 0, ONIONSKIN_REPLY_LEN
);
2863 memset(s_keys
, 0, 40);
2864 test_assert(! onion_skin_server_handshake(c_buf
, pk
, NULL
,
2865 s_buf
, s_keys
, 40));
2867 /* client handshake 2 */
2868 memset(c_keys
, 0, 40);
2869 test_assert(! onion_skin_client_handshake(c_dh
, s_buf
, c_keys
, 40));
2871 if (memcmp(c_keys
, s_keys
, 40)) {
2875 test_memeq(c_keys
, s_keys
, 40);
2876 memset(s_buf
, 0, 40);
2877 test_memneq(c_keys
, s_buf
, 40);
2881 crypto_dh_free(c_dh
);
2883 crypto_free_pk_env(pk
);
2886 /** Run unit tests for router descriptor generation logic. */
2888 test_dir_format(void)
2890 char buf
[8192], buf2
[8192];
2892 char fingerprint
[FINGERPRINT_LEN
+1];
2893 char *pk1_str
= NULL
, *pk2_str
= NULL
, *pk3_str
= NULL
, *cp
;
2894 size_t pk1_str_len
, pk2_str_len
, pk3_str_len
;
2895 routerinfo_t
*r1
=NULL
, *r2
=NULL
;
2896 crypto_pk_env_t
*pk1
= NULL
, *pk2
= NULL
, *pk3
= NULL
;
2897 routerinfo_t
*rp1
= NULL
;
2898 addr_policy_t
*ex1
, *ex2
;
2899 routerlist_t
*dir1
= NULL
, *dir2
= NULL
;
2902 pk1
= pk_generate(0);
2903 pk2
= pk_generate(1);
2904 pk3
= pk_generate(2);
2906 test_assert( is_legal_nickname("a"));
2907 test_assert(!is_legal_nickname(""));
2908 test_assert(!is_legal_nickname("abcdefghijklmnopqrst")); /* 20 chars */
2909 test_assert(!is_legal_nickname("hyphen-")); /* bad char */
2910 test_assert( is_legal_nickname("abcdefghijklmnopqrs")); /* 19 chars */
2911 test_assert(!is_legal_nickname("$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2913 test_assert( is_legal_nickname_or_hexdigest(
2914 "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2915 test_assert( is_legal_nickname_or_hexdigest(
2916 "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA=fred"));
2917 test_assert( is_legal_nickname_or_hexdigest(
2918 "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA~fred"));
2920 test_assert(!is_legal_nickname_or_hexdigest(
2921 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2923 test_assert(!is_legal_nickname_or_hexdigest(
2924 "$AAAAAAzAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2925 /* hex part too long */
2926 test_assert(!is_legal_nickname_or_hexdigest(
2927 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2928 test_assert(!is_legal_nickname_or_hexdigest(
2929 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=fred"));
2931 test_assert(!is_legal_nickname_or_hexdigest(
2932 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="));
2933 test_assert(!is_legal_nickname_or_hexdigest(
2934 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~"));
2935 test_assert(!is_legal_nickname_or_hexdigest(
2936 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~hyphen-"));
2937 test_assert(!is_legal_nickname_or_hexdigest(
2938 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~"
2939 "abcdefghijklmnoppqrst"));
2940 /* Bad extra char. */
2941 test_assert(!is_legal_nickname_or_hexdigest(
2942 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA!"));
2943 test_assert(is_legal_nickname_or_hexdigest("xyzzy"));
2944 test_assert(is_legal_nickname_or_hexdigest("abcdefghijklmnopqrs"));
2945 test_assert(!is_legal_nickname_or_hexdigest("abcdefghijklmnopqrst"));
2947 get_platform_str(platform
, sizeof(platform
));
2948 r1
= tor_malloc_zero(sizeof(routerinfo_t
));
2949 r1
->address
= tor_strdup("18.244.0.1");
2950 r1
->addr
= 0xc0a80001u
; /* 192.168.0.1 */
2951 r1
->cache_info
.published_on
= 0;
2953 r1
->dir_port
= 9003;
2954 r1
->onion_pkey
= crypto_pk_dup_key(pk1
);
2955 r1
->identity_pkey
= crypto_pk_dup_key(pk2
);
2956 r1
->bandwidthrate
= 1000;
2957 r1
->bandwidthburst
= 5000;
2958 r1
->bandwidthcapacity
= 10000;
2959 r1
->exit_policy
= NULL
;
2960 r1
->nickname
= tor_strdup("Magri");
2961 r1
->platform
= tor_strdup(platform
);
2963 ex1
= tor_malloc_zero(sizeof(addr_policy_t
));
2964 ex2
= tor_malloc_zero(sizeof(addr_policy_t
));
2965 ex1
->policy_type
= ADDR_POLICY_ACCEPT
;
2966 tor_addr_from_ipv4h(&ex1
->addr
, 0);
2968 ex1
->prt_min
= ex1
->prt_max
= 80;
2969 ex2
->policy_type
= ADDR_POLICY_REJECT
;
2970 tor_addr_from_ipv4h(&ex2
->addr
, 18<<24);
2972 ex2
->prt_min
= ex2
->prt_max
= 24;
2973 r2
= tor_malloc_zero(sizeof(routerinfo_t
));
2974 r2
->address
= tor_strdup("1.1.1.1");
2975 r2
->addr
= 0x0a030201u
; /* 10.3.2.1 */
2976 r2
->platform
= tor_strdup(platform
);
2977 r2
->cache_info
.published_on
= 5;
2980 r2
->onion_pkey
= crypto_pk_dup_key(pk2
);
2981 r2
->identity_pkey
= crypto_pk_dup_key(pk1
);
2982 r2
->bandwidthrate
= r2
->bandwidthburst
= r2
->bandwidthcapacity
= 3000;
2983 r2
->exit_policy
= smartlist_create();
2984 smartlist_add(r2
->exit_policy
, ex2
);
2985 smartlist_add(r2
->exit_policy
, ex1
);
2986 r2
->nickname
= tor_strdup("Fred");
2988 test_assert(!crypto_pk_write_public_key_to_string(pk1
, &pk1_str
,
2990 test_assert(!crypto_pk_write_public_key_to_string(pk2
, &pk2_str
,
2992 test_assert(!crypto_pk_write_public_key_to_string(pk3
, &pk3_str
,
2995 memset(buf
, 0, 2048);
2996 test_assert(router_dump_router_to_string(buf
, 2048, r1
, pk2
)>0);
2998 strlcpy(buf2
, "router Magri 18.244.0.1 9000 0 9003\n"
2999 "platform Tor "VERSION
" on ", sizeof(buf2
));
3000 strlcat(buf2
, get_uname(), sizeof(buf2
));
3002 "opt protocols Link 1 2 Circuit 1\n"
3003 "published 1970-01-01 00:00:00\n"
3004 "opt fingerprint ", sizeof(buf2
));
3005 test_assert(!crypto_pk_get_fingerprint(pk2
, fingerprint
, 1));
3006 strlcat(buf2
, fingerprint
, sizeof(buf2
));
3007 strlcat(buf2
, "\nuptime 0\n"
3008 /* XXX the "0" above is hard-coded, but even if we made it reflect
3009 * uptime, that still wouldn't make it right, because the two
3010 * descriptors might be made on different seconds... hm. */
3011 "bandwidth 1000 5000 10000\n"
3012 "opt extra-info-digest 0000000000000000000000000000000000000000\n"
3013 "onion-key\n", sizeof(buf2
));
3014 strlcat(buf2
, pk1_str
, sizeof(buf2
));
3015 strlcat(buf2
, "signing-key\n", sizeof(buf2
));
3016 strlcat(buf2
, pk2_str
, sizeof(buf2
));
3017 strlcat(buf2
, "opt hidden-service-dir\n", sizeof(buf2
));
3018 strlcat(buf2
, "reject *:*\nrouter-signature\n", sizeof(buf2
));
3019 buf
[strlen(buf2
)] = '\0'; /* Don't compare the sig; it's never the same
3022 test_streq(buf
, buf2
);
3024 test_assert(router_dump_router_to_string(buf
, 2048, r1
, pk2
)>0);
3026 rp1
= router_parse_entry_from_string((const char*)cp
,NULL
,1,0,NULL
);
3028 test_streq(rp1
->address
, r1
->address
);
3029 test_eq(rp1
->or_port
, r1
->or_port
);
3030 //test_eq(rp1->dir_port, r1->dir_port);
3031 test_eq(rp1
->bandwidthrate
, r1
->bandwidthrate
);
3032 test_eq(rp1
->bandwidthburst
, r1
->bandwidthburst
);
3033 test_eq(rp1
->bandwidthcapacity
, r1
->bandwidthcapacity
);
3034 test_assert(crypto_pk_cmp_keys(rp1
->onion_pkey
, pk1
) == 0);
3035 test_assert(crypto_pk_cmp_keys(rp1
->identity_pkey
, pk2
) == 0);
3036 //test_assert(rp1->exit_policy == NULL);
3039 /* XXX Once we have exit policies, test this again. XXX */
3040 strlcpy(buf2
, "router tor.tor.tor 9005 0 0 3000\n", sizeof(buf2
));
3041 strlcat(buf2
, pk2_str
, sizeof(buf2
));
3042 strlcat(buf2
, "signing-key\n", sizeof(buf2
));
3043 strlcat(buf2
, pk1_str
, sizeof(buf2
));
3044 strlcat(buf2
, "accept *:80\nreject 18.*:24\n\n", sizeof(buf2
));
3045 test_assert(router_dump_router_to_string(buf
, 2048, &r2
, pk2
)>0);
3046 test_streq(buf
, buf2
);
3049 rp2
= router_parse_entry_from_string(&cp
,1);
3051 test_streq(rp2
->address
, r2
.address
);
3052 test_eq(rp2
->or_port
, r2
.or_port
);
3053 test_eq(rp2
->dir_port
, r2
.dir_port
);
3054 test_eq(rp2
->bandwidth
, r2
.bandwidth
);
3055 test_assert(crypto_pk_cmp_keys(rp2
->onion_pkey
, pk2
) == 0);
3056 test_assert(crypto_pk_cmp_keys(rp2
->identity_pkey
, pk1
) == 0);
3057 test_eq(rp2
->exit_policy
->policy_type
, EXIT_POLICY_ACCEPT
);
3058 test_streq(rp2
->exit_policy
->string
, "accept *:80");
3059 test_streq(rp2
->exit_policy
->address
, "*");
3060 test_streq(rp2
->exit_policy
->port
, "80");
3061 test_eq(rp2
->exit_policy
->next
->policy_type
, EXIT_POLICY_REJECT
);
3062 test_streq(rp2
->exit_policy
->next
->string
, "reject 18.*:24");
3063 test_streq(rp2
->exit_policy
->next
->address
, "18.*");
3064 test_streq(rp2
->exit_policy
->next
->port
, "24");
3065 test_assert(rp2
->exit_policy
->next
->next
== NULL
);
3067 /* Okay, now for the directories. */
3069 fingerprint_list
= smartlist_create();
3070 crypto_pk_get_fingerprint(pk2
, buf
, 1);
3071 add_fingerprint_to_dir("Magri", buf
, fingerprint_list
);
3072 crypto_pk_get_fingerprint(pk1
, buf
, 1);
3073 add_fingerprint_to_dir("Fred", buf
, fingerprint_list
);
3079 /* XXXX NM re-enable. */
3080 /* Make sure routers aren't too far in the past any more. */
3081 r1
->cache_info
.published_on
= time(NULL
);
3082 r2
->cache_info
.published_on
= time(NULL
)-3*60*60;
3083 test_assert(router_dump_router_to_string(buf
, 2048, r1
, pk2
)>0);
3084 test_eq(dirserv_add_descriptor(buf
,&m
,""), ROUTER_ADDED_NOTIFY_GENERATOR
);
3085 test_assert(router_dump_router_to_string(buf
, 2048, r2
, pk1
)>0);
3086 test_eq(dirserv_add_descriptor(buf
,&m
,""), ROUTER_ADDED_NOTIFY_GENERATOR
);
3087 get_options()->Nickname
= tor_strdup("DirServer");
3088 test_assert(!dirserv_dump_directory_to_string(&cp
,pk3
, 0));
3089 crypto_pk_get_digest(pk3
, d
);
3090 test_assert(!router_parse_directory(cp
));
3091 test_eq(2, smartlist_len(dir1
->routers
));
3095 dirserv_free_fingerprint_list();
3097 /* Try out version parsing functionality */
3098 test_eq(0, tor_version_parse("0.3.4pre2-cvs", &ver1
));
3099 test_eq(0, ver1
.major
);
3100 test_eq(3, ver1
.minor
);
3101 test_eq(4, ver1
.micro
);
3102 test_eq(VER_PRE
, ver1
.status
);
3103 test_eq(2, ver1
.patchlevel
);
3104 test_eq(0, tor_version_parse("0.3.4rc1", &ver1
));
3105 test_eq(0, ver1
.major
);
3106 test_eq(3, ver1
.minor
);
3107 test_eq(4, ver1
.micro
);
3108 test_eq(VER_RC
, ver1
.status
);
3109 test_eq(1, ver1
.patchlevel
);
3110 test_eq(0, tor_version_parse("1.3.4", &ver1
));
3111 test_eq(1, ver1
.major
);
3112 test_eq(3, ver1
.minor
);
3113 test_eq(4, ver1
.micro
);
3114 test_eq(VER_RELEASE
, ver1
.status
);
3115 test_eq(0, ver1
.patchlevel
);
3116 test_eq(0, tor_version_parse("1.3.4.999", &ver1
));
3117 test_eq(1, ver1
.major
);
3118 test_eq(3, ver1
.minor
);
3119 test_eq(4, ver1
.micro
);
3120 test_eq(VER_RELEASE
, ver1
.status
);
3121 test_eq(999, ver1
.patchlevel
);
3122 test_eq(0, tor_version_parse("0.1.2.4-alpha", &ver1
));
3123 test_eq(0, ver1
.major
);
3124 test_eq(1, ver1
.minor
);
3125 test_eq(2, ver1
.micro
);
3126 test_eq(4, ver1
.patchlevel
);
3127 test_eq(VER_RELEASE
, ver1
.status
);
3128 test_streq("alpha", ver1
.status_tag
);
3129 test_eq(0, tor_version_parse("0.1.2.4", &ver1
));
3130 test_eq(0, ver1
.major
);
3131 test_eq(1, ver1
.minor
);
3132 test_eq(2, ver1
.micro
);
3133 test_eq(4, ver1
.patchlevel
);
3134 test_eq(VER_RELEASE
, ver1
.status
);
3135 test_streq("", ver1
.status_tag
);
3137 #define test_eq_vs(vs1, vs2) test_eq_type(version_status_t, "%d", (vs1), (vs2))
3138 #define test_v_i_o(val, ver, lst) \
3139 test_eq_vs(val, tor_version_is_obsolete(ver, lst))
3141 /* make sure tor_version_is_obsolete() works */
3142 test_v_i_o(VS_OLD
, "0.0.1", "Tor 0.0.2");
3143 test_v_i_o(VS_OLD
, "0.0.1", "0.0.2, Tor 0.0.3");
3144 test_v_i_o(VS_OLD
, "0.0.1", "0.0.2,Tor 0.0.3");
3145 test_v_i_o(VS_OLD
, "0.0.1","0.0.3,BetterTor 0.0.1");
3146 test_v_i_o(VS_RECOMMENDED
, "0.0.2", "Tor 0.0.2,Tor 0.0.3");
3147 test_v_i_o(VS_NEW_IN_SERIES
, "0.0.2", "Tor 0.0.2pre1,Tor 0.0.3");
3148 test_v_i_o(VS_OLD
, "0.0.2", "Tor 0.0.2.1,Tor 0.0.3");
3149 test_v_i_o(VS_NEW
, "0.1.0", "Tor 0.0.2,Tor 0.0.3");
3150 test_v_i_o(VS_RECOMMENDED
, "0.0.7rc2", "0.0.7,Tor 0.0.7rc2,Tor 0.0.8");
3151 test_v_i_o(VS_OLD
, "0.0.5.0", "0.0.5.1-cvs");
3152 test_v_i_o(VS_NEW_IN_SERIES
, "0.0.5.1-cvs", "0.0.5, 0.0.6");
3153 /* Not on list, but newer than any in same series. */
3154 test_v_i_o(VS_NEW_IN_SERIES
, "0.1.0.3",
3155 "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
3156 /* Series newer than any on list. */
3157 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");
3158 /* Series older than any on list. */
3159 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");
3160 /* Not on list, not newer than any on same series. */
3161 test_v_i_o(VS_UNRECOMMENDED
, "0.1.0.1",
3162 "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
3163 /* On list, not newer than any on same series. */
3164 test_v_i_o(VS_UNRECOMMENDED
,
3165 "0.1.0.1", "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
3166 test_eq(0, tor_version_as_new_as("Tor 0.0.5", "0.0.9pre1-cvs"));
3167 test_eq(1, tor_version_as_new_as(
3168 "Tor 0.0.8 on Darwin 64-121-192-100.c3-0."
3169 "sfpo-ubr1.sfrn-sfpo.ca.cable.rcn.com Power Macintosh",
3171 test_eq(0, tor_version_as_new_as(
3172 "Tor 0.0.8 on Darwin 64-121-192-100.c3-0."
3173 "sfpo-ubr1.sfrn-sfpo.ca.cable.rcn.com Power Macintosh", "0.0.8.2"));
3175 /* Now try svn revisions. */
3176 test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100)",
3177 "Tor 0.2.1.0-dev (r99)"));
3178 test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100) on Banana Jr",
3179 "Tor 0.2.1.0-dev (r99) on Hal 9000"));
3180 test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100)",
3181 "Tor 0.2.1.0-dev on Colossus"));
3182 test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev (r99)",
3183 "Tor 0.2.1.0-dev (r100)"));
3184 test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev (r99) on MCP",
3185 "Tor 0.2.1.0-dev (r100) on AM"));
3186 test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev",
3187 "Tor 0.2.1.0-dev (r99)"));
3188 test_eq(1, tor_version_as_new_as("Tor 0.2.1.1",
3189 "Tor 0.2.1.0-dev (r99)"));
3192 routerinfo_free(r1
);
3194 routerinfo_free(r2
);
3199 if (pk1
) crypto_free_pk_env(pk1
);
3200 if (pk2
) crypto_free_pk_env(pk2
);
3201 if (pk3
) crypto_free_pk_env(pk3
);
3202 if (rp1
) routerinfo_free(rp1
);
3203 tor_free(dir1
); /* XXXX And more !*/
3204 tor_free(dir2
); /* And more !*/
3207 /** Run unit tests for misc directory functions. */
3211 smartlist_t
*sl
= smartlist_create();
3214 dir_split_resource_into_fingerprint_pairs(
3215 /* Two pairs, out of order, with one duplicate. */
3216 "73656372657420646174612E0000000000FFFFFF-"
3217 "557365204145532d32353620696e73746561642e+"
3218 "73656372657420646174612E0000000000FFFFFF-"
3219 "557365204145532d32353620696e73746561642e+"
3220 "48657861646563696d616c2069736e277420736f-"
3221 "676f6f6420666f7220686964696e6720796f7572.z", sl
);
3223 test_eq(smartlist_len(sl
), 2);
3224 pair
= smartlist_get(sl
, 0);
3225 test_memeq(pair
->first
, "Hexadecimal isn't so", DIGEST_LEN
);
3226 test_memeq(pair
->second
, "good for hiding your", DIGEST_LEN
);
3227 pair
= smartlist_get(sl
, 1);
3228 test_memeq(pair
->first
, "secret data.\0\0\0\0\0\xff\xff\xff", DIGEST_LEN
);
3229 test_memeq(pair
->second
, "Use AES-256 instead.", DIGEST_LEN
);
3232 SMARTLIST_FOREACH(sl
, fp_pair_t
*, pair
, tor_free(pair
));
3236 extern const char AUTHORITY_CERT_1
[];
3237 extern const char AUTHORITY_SIGNKEY_1
[];
3238 extern const char AUTHORITY_CERT_2
[];
3239 extern const char AUTHORITY_SIGNKEY_2
[];
3240 extern const char AUTHORITY_CERT_3
[];
3241 extern const char AUTHORITY_SIGNKEY_3
[];
3243 /** Helper: Test that two networkstatus_voter_info_t do in fact represent the
3244 * same voting authority, and that they do in fact have all the same
3247 test_same_voter(networkstatus_voter_info_t
*v1
,
3248 networkstatus_voter_info_t
*v2
)
3250 test_streq(v1
->nickname
, v2
->nickname
);
3251 test_memeq(v1
->identity_digest
, v2
->identity_digest
, DIGEST_LEN
);
3252 test_streq(v1
->address
, v2
->address
);
3253 test_eq(v1
->addr
, v2
->addr
);
3254 test_eq(v1
->dir_port
, v2
->dir_port
);
3255 test_eq(v1
->or_port
, v2
->or_port
);
3256 test_streq(v1
->contact
, v2
->contact
);
3257 test_memeq(v1
->vote_digest
, v2
->vote_digest
, DIGEST_LEN
);
3262 /** Run unit tests for getting the median of a list. */
3264 test_util_order_functions(void)
3267 // int a=12,b=24,c=25,d=60,e=77;
3269 #define median() median_int(lst, n)
3272 test_eq(12, median()); /* 12 */
3274 //smartlist_shuffle(sl);
3275 test_eq(12, median()); /* 12, 77 */
3277 //smartlist_shuffle(sl);
3278 test_eq(77, median()); /* 12, 77, 77 */
3280 test_eq(24, median()); /* 12,24,77,77 */
3284 //smartlist_shuffle(sl);
3285 test_eq(25, median()); /* 12,12,24,25,60,77,77 */
3292 /** Helper: Make a new routerinfo containing the right information for a
3293 * given vote_routerstatus_t. */
3294 static routerinfo_t
*
3295 generate_ri_from_rs(const vote_routerstatus_t
*vrs
)
3298 const routerstatus_t
*rs
= &vrs
->status
;
3299 static time_t published
= 0;
3301 r
= tor_malloc_zero(sizeof(routerinfo_t
));
3302 memcpy(r
->cache_info
.identity_digest
, rs
->identity_digest
, DIGEST_LEN
);
3303 memcpy(r
->cache_info
.signed_descriptor_digest
, rs
->descriptor_digest
,
3305 r
->cache_info
.do_not_cache
= 1;
3306 r
->cache_info
.routerlist_index
= -1;
3307 r
->cache_info
.signed_descriptor_body
=
3308 tor_strdup("123456789012345678901234567890123");
3309 r
->cache_info
.signed_descriptor_len
=
3310 strlen(r
->cache_info
.signed_descriptor_body
);
3311 r
->exit_policy
= smartlist_create();
3312 r
->cache_info
.published_on
= ++published
+ time(NULL
);
3316 /** Run unit tests for generating and parsing V3 consensus networkstatus
3319 test_v3_networkstatus(void)
3321 authority_cert_t
*cert1
=NULL
, *cert2
=NULL
, *cert3
=NULL
;
3322 crypto_pk_env_t
*sign_skey_1
=NULL
, *sign_skey_2
=NULL
, *sign_skey_3
=NULL
;
3323 crypto_pk_env_t
*sign_skey_leg1
=NULL
;
3324 const char *msg
=NULL
;
3326 time_t now
= time(NULL
);
3327 networkstatus_voter_info_t
*voter
;
3328 networkstatus_t
*vote
=NULL
, *v1
=NULL
, *v2
=NULL
, *v3
=NULL
, *con
=NULL
;
3329 vote_routerstatus_t
*vrs
;
3331 char *v1_text
=NULL
, *v2_text
=NULL
, *v3_text
=NULL
, *consensus_text
=NULL
, *cp
;
3332 smartlist_t
*votes
= smartlist_create();
3334 /* For generating the two other consensuses. */
3335 char *detached_text1
=NULL
, *detached_text2
=NULL
;
3336 char *consensus_text2
=NULL
, *consensus_text3
=NULL
;
3337 networkstatus_t
*con2
=NULL
, *con3
=NULL
;
3338 ns_detached_signatures_t
*dsig1
=NULL
, *dsig2
=NULL
;
3340 /* Parse certificates and keys. */
3341 cert1
= authority_cert_parse_from_string(AUTHORITY_CERT_1
, NULL
);
3343 test_assert(cert1
->is_cross_certified
);
3344 cert2
= authority_cert_parse_from_string(AUTHORITY_CERT_2
, NULL
);
3346 cert3
= authority_cert_parse_from_string(AUTHORITY_CERT_3
, NULL
);
3348 sign_skey_1
= crypto_new_pk_env();
3349 sign_skey_2
= crypto_new_pk_env();
3350 sign_skey_3
= crypto_new_pk_env();
3351 sign_skey_leg1
= pk_generate(4);
3353 test_assert(!crypto_pk_read_private_key_from_string(sign_skey_1
,
3354 AUTHORITY_SIGNKEY_1
));
3355 test_assert(!crypto_pk_read_private_key_from_string(sign_skey_2
,
3356 AUTHORITY_SIGNKEY_2
));
3357 test_assert(!crypto_pk_read_private_key_from_string(sign_skey_3
,
3358 AUTHORITY_SIGNKEY_3
));
3360 test_assert(!crypto_pk_cmp_keys(sign_skey_1
, cert1
->signing_key
));
3361 test_assert(!crypto_pk_cmp_keys(sign_skey_2
, cert2
->signing_key
));
3364 * Set up a vote; generate it; try to parse it.
3366 vote
= tor_malloc_zero(sizeof(networkstatus_t
));
3367 vote
->type
= NS_TYPE_VOTE
;
3368 vote
->published
= now
;
3369 vote
->valid_after
= now
+1000;
3370 vote
->fresh_until
= now
+2000;
3371 vote
->valid_until
= now
+3000;
3372 vote
->vote_seconds
= 100;
3373 vote
->dist_seconds
= 200;
3374 vote
->supported_methods
= smartlist_create();
3375 smartlist_split_string(vote
->supported_methods
, "1 2 3", NULL
, 0, -1);
3376 vote
->client_versions
= tor_strdup("0.1.2.14,0.1.2.15");
3377 vote
->server_versions
= tor_strdup("0.1.2.14,0.1.2.15,0.1.2.16");
3378 vote
->known_flags
= smartlist_create();
3379 smartlist_split_string(vote
->known_flags
,
3380 "Authority Exit Fast Guard Running Stable V2Dir Valid",
3381 0, SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
3382 vote
->voters
= smartlist_create();
3383 voter
= tor_malloc_zero(sizeof(networkstatus_voter_info_t
));
3384 voter
->nickname
= tor_strdup("Voter1");
3385 voter
->address
= tor_strdup("1.2.3.4");
3386 voter
->addr
= 0x01020304;
3387 voter
->dir_port
= 80;
3388 voter
->or_port
= 9000;
3389 voter
->contact
= tor_strdup("voter@example.com");
3390 crypto_pk_get_digest(cert1
->identity_key
, voter
->identity_digest
);
3391 smartlist_add(vote
->voters
, voter
);
3392 vote
->cert
= authority_cert_dup(cert1
);
3393 vote
->routerstatus_list
= smartlist_create();
3394 /* add the first routerstatus. */
3395 vrs
= tor_malloc_zero(sizeof(vote_routerstatus_t
));
3397 vrs
->version
= tor_strdup("0.1.2.14");
3398 rs
->published_on
= now
-1500;
3399 strlcpy(rs
->nickname
, "router2", sizeof(rs
->nickname
));
3400 memset(rs
->identity_digest
, 3, DIGEST_LEN
);
3401 memset(rs
->descriptor_digest
, 78, DIGEST_LEN
);
3402 rs
->addr
= 0x99008801;
3404 rs
->dir_port
= 8000;
3405 /* all flags but running cleared */
3407 smartlist_add(vote
->routerstatus_list
, vrs
);
3408 test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs
), &msg
,0,0)>=0);
3410 /* add the second routerstatus. */
3411 vrs
= tor_malloc_zero(sizeof(vote_routerstatus_t
));
3413 vrs
->version
= tor_strdup("0.2.0.5");
3414 rs
->published_on
= now
-1000;
3415 strlcpy(rs
->nickname
, "router1", sizeof(rs
->nickname
));
3416 memset(rs
->identity_digest
, 5, DIGEST_LEN
);
3417 memset(rs
->descriptor_digest
, 77, DIGEST_LEN
);
3418 rs
->addr
= 0x99009901;
3421 rs
->is_exit
= rs
->is_stable
= rs
->is_fast
= rs
->is_running
=
3422 rs
->is_valid
= rs
->is_v2_dir
= rs
->is_possible_guard
= 1;
3423 smartlist_add(vote
->routerstatus_list
, vrs
);
3424 test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs
), &msg
,0,0)>=0);
3426 /* add the third routerstatus. */
3427 vrs
= tor_malloc_zero(sizeof(vote_routerstatus_t
));
3429 vrs
->version
= tor_strdup("0.1.0.3");
3430 rs
->published_on
= now
-1000;
3431 strlcpy(rs
->nickname
, "router3", sizeof(rs
->nickname
));
3432 memset(rs
->identity_digest
, 33, DIGEST_LEN
);
3433 memset(rs
->descriptor_digest
, 79, DIGEST_LEN
);
3434 rs
->addr
= 0xAA009901;
3436 rs
->dir_port
= 9999;
3437 rs
->is_authority
= rs
->is_exit
= rs
->is_stable
= rs
->is_fast
=
3438 rs
->is_running
= rs
->is_valid
= rs
->is_v2_dir
= rs
->is_possible_guard
= 1;
3439 smartlist_add(vote
->routerstatus_list
, vrs
);
3440 test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs
), &msg
,0,0)>=0);
3442 /* add a fourth routerstatus that is not running. */
3443 vrs
= tor_malloc_zero(sizeof(vote_routerstatus_t
));
3445 vrs
->version
= tor_strdup("0.1.6.3");
3446 rs
->published_on
= now
-1000;
3447 strlcpy(rs
->nickname
, "router4", sizeof(rs
->nickname
));
3448 memset(rs
->identity_digest
, 34, DIGEST_LEN
);
3449 memset(rs
->descriptor_digest
, 48, DIGEST_LEN
);
3450 rs
->addr
= 0xC0000203;
3452 rs
->dir_port
= 1999;
3453 /* Running flag (and others) cleared */
3454 smartlist_add(vote
->routerstatus_list
, vrs
);
3455 test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs
), &msg
,0,0)>=0);
3457 /* dump the vote and try to parse it. */
3458 v1_text
= format_networkstatus_vote(sign_skey_1
, vote
);
3459 test_assert(v1_text
);
3460 v1
= networkstatus_parse_vote_from_string(v1_text
, NULL
, NS_TYPE_VOTE
);
3463 /* Make sure the parsed thing was right. */
3464 test_eq(v1
->type
, NS_TYPE_VOTE
);
3465 test_eq(v1
->published
, vote
->published
);
3466 test_eq(v1
->valid_after
, vote
->valid_after
);
3467 test_eq(v1
->fresh_until
, vote
->fresh_until
);
3468 test_eq(v1
->valid_until
, vote
->valid_until
);
3469 test_eq(v1
->vote_seconds
, vote
->vote_seconds
);
3470 test_eq(v1
->dist_seconds
, vote
->dist_seconds
);
3471 test_streq(v1
->client_versions
, vote
->client_versions
);
3472 test_streq(v1
->server_versions
, vote
->server_versions
);
3473 test_assert(v1
->voters
&& smartlist_len(v1
->voters
));
3474 voter
= smartlist_get(v1
->voters
, 0);
3475 test_streq(voter
->nickname
, "Voter1");
3476 test_streq(voter
->address
, "1.2.3.4");
3477 test_eq(voter
->addr
, 0x01020304);
3478 test_eq(voter
->dir_port
, 80);
3479 test_eq(voter
->or_port
, 9000);
3480 test_streq(voter
->contact
, "voter@example.com");
3481 test_assert(v1
->cert
);
3482 test_assert(!crypto_pk_cmp_keys(sign_skey_1
, v1
->cert
->signing_key
));
3483 cp
= smartlist_join_strings(v1
->known_flags
, ":", 0, NULL
);
3484 test_streq(cp
, "Authority:Exit:Fast:Guard:Running:Stable:V2Dir:Valid");
3486 test_eq(smartlist_len(v1
->routerstatus_list
), 4);
3487 /* Check the first routerstatus. */
3488 vrs
= smartlist_get(v1
->routerstatus_list
, 0);
3490 test_streq(vrs
->version
, "0.1.2.14");
3491 test_eq(rs
->published_on
, now
-1500);
3492 test_streq(rs
->nickname
, "router2");
3493 test_memeq(rs
->identity_digest
,
3494 "\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3",
3496 test_memeq(rs
->descriptor_digest
, "NNNNNNNNNNNNNNNNNNNN", DIGEST_LEN
);
3497 test_eq(rs
->addr
, 0x99008801);
3498 test_eq(rs
->or_port
, 443);
3499 test_eq(rs
->dir_port
, 8000);
3500 test_eq(vrs
->flags
, U64_LITERAL(16)); // no flags except "running"
3501 /* Check the second routerstatus. */
3502 vrs
= smartlist_get(v1
->routerstatus_list
, 1);
3504 test_streq(vrs
->version
, "0.2.0.5");
3505 test_eq(rs
->published_on
, now
-1000);
3506 test_streq(rs
->nickname
, "router1");
3507 test_memeq(rs
->identity_digest
,
3508 "\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5",
3510 test_memeq(rs
->descriptor_digest
, "MMMMMMMMMMMMMMMMMMMM", DIGEST_LEN
);
3511 test_eq(rs
->addr
, 0x99009901);
3512 test_eq(rs
->or_port
, 443);
3513 test_eq(rs
->dir_port
, 0);
3514 test_eq(vrs
->flags
, U64_LITERAL(254)); // all flags except "authority."
3516 /* Generate second vote. It disagrees on some of the times,
3517 * and doesn't list versions, and knows some crazy flags */
3518 vote
->published
= now
+1;
3519 vote
->fresh_until
= now
+3005;
3520 vote
->dist_seconds
= 300;
3521 authority_cert_free(vote
->cert
);
3522 vote
->cert
= authority_cert_dup(cert2
);
3523 tor_free(vote
->client_versions
);
3524 tor_free(vote
->server_versions
);
3525 voter
= smartlist_get(vote
->voters
, 0);
3526 tor_free(voter
->nickname
);
3527 tor_free(voter
->address
);
3528 voter
->nickname
= tor_strdup("Voter2");
3529 voter
->address
= tor_strdup("2.3.4.5");
3530 voter
->addr
= 0x02030405;
3531 crypto_pk_get_digest(cert2
->identity_key
, voter
->identity_digest
);
3532 smartlist_add(vote
->known_flags
, tor_strdup("MadeOfCheese"));
3533 smartlist_add(vote
->known_flags
, tor_strdup("MadeOfTin"));
3534 smartlist_sort_strings(vote
->known_flags
);
3535 vrs
= smartlist_get(vote
->routerstatus_list
, 2);
3536 smartlist_del_keeporder(vote
->routerstatus_list
, 2);
3537 tor_free(vrs
->version
);
3539 vrs
= smartlist_get(vote
->routerstatus_list
, 0);
3540 vrs
->status
.is_fast
= 1;
3541 /* generate and parse. */
3542 v2_text
= format_networkstatus_vote(sign_skey_2
, vote
);
3543 test_assert(v2_text
);
3544 v2
= networkstatus_parse_vote_from_string(v2_text
, NULL
, NS_TYPE_VOTE
);
3546 /* Check that flags come out right.*/
3547 cp
= smartlist_join_strings(v2
->known_flags
, ":", 0, NULL
);
3548 test_streq(cp
, "Authority:Exit:Fast:Guard:MadeOfCheese:MadeOfTin:"
3549 "Running:Stable:V2Dir:Valid");
3551 vrs
= smartlist_get(v2
->routerstatus_list
, 1);
3552 /* 1023 - authority(1) - madeofcheese(16) - madeoftin(32) */
3553 test_eq(vrs
->flags
, U64_LITERAL(974));
3555 /* Generate the third vote. */
3556 vote
->published
= now
;
3557 vote
->fresh_until
= now
+2003;
3558 vote
->dist_seconds
= 250;
3559 authority_cert_free(vote
->cert
);
3560 vote
->cert
= authority_cert_dup(cert3
);
3561 smartlist_add(vote
->supported_methods
, tor_strdup("4"));
3562 vote
->client_versions
= tor_strdup("0.1.2.14,0.1.2.17");
3563 vote
->server_versions
= tor_strdup("0.1.2.10,0.1.2.15,0.1.2.16");
3564 voter
= smartlist_get(vote
->voters
, 0);
3565 tor_free(voter
->nickname
);
3566 tor_free(voter
->address
);
3567 voter
->nickname
= tor_strdup("Voter3");
3568 voter
->address
= tor_strdup("3.4.5.6");
3569 voter
->addr
= 0x03040506;
3570 crypto_pk_get_digest(cert3
->identity_key
, voter
->identity_digest
);
3571 /* This one has a legacy id. */
3572 memset(voter
->legacy_id_digest
, (int)'A', DIGEST_LEN
);
3573 vrs
= smartlist_get(vote
->routerstatus_list
, 0);
3574 smartlist_del_keeporder(vote
->routerstatus_list
, 0);
3575 tor_free(vrs
->version
);
3577 vrs
= smartlist_get(vote
->routerstatus_list
, 0);
3578 memset(vrs
->status
.descriptor_digest
, (int)'Z', DIGEST_LEN
);
3579 test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs
), &msg
,0,0)>=0);
3581 v3_text
= format_networkstatus_vote(sign_skey_3
, vote
);
3582 test_assert(v3_text
);
3584 v3
= networkstatus_parse_vote_from_string(v3_text
, NULL
, NS_TYPE_VOTE
);
3587 /* Compute a consensus as voter 3. */
3588 smartlist_add(votes
, v3
);
3589 smartlist_add(votes
, v1
);
3590 smartlist_add(votes
, v2
);
3591 consensus_text
= networkstatus_compute_consensus(votes
, 3,
3592 cert3
->identity_key
,
3594 "AAAAAAAAAAAAAAAAAAAA",
3596 test_assert(consensus_text
);
3597 con
= networkstatus_parse_vote_from_string(consensus_text
, NULL
,
3600 //log_notice(LD_GENERAL, "<<%s>>\n<<%s>>\n<<%s>>\n",
3601 // v1_text, v2_text, v3_text);
3603 /* Check consensus contents. */
3604 test_assert(con
->type
== NS_TYPE_CONSENSUS
);
3605 test_eq(con
->published
, 0); /* this field only appears in votes. */
3606 test_eq(con
->valid_after
, now
+1000);
3607 test_eq(con
->fresh_until
, now
+2003); /* median */
3608 test_eq(con
->valid_until
, now
+3000);
3609 test_eq(con
->vote_seconds
, 100);
3610 test_eq(con
->dist_seconds
, 250); /* median */
3611 test_streq(con
->client_versions
, "0.1.2.14");
3612 test_streq(con
->server_versions
, "0.1.2.15,0.1.2.16");
3613 cp
= smartlist_join_strings(v2
->known_flags
, ":", 0, NULL
);
3614 test_streq(cp
, "Authority:Exit:Fast:Guard:MadeOfCheese:MadeOfTin:"
3615 "Running:Stable:V2Dir:Valid");
3617 test_eq(4, smartlist_len(con
->voters
)); /*3 voters, 1 legacy key.*/
3618 /* The voter id digests should be in this order. */
3619 test_assert(memcmp(cert2
->cache_info
.identity_digest
,
3620 cert1
->cache_info
.identity_digest
,DIGEST_LEN
)<0);
3621 test_assert(memcmp(cert1
->cache_info
.identity_digest
,
3622 cert3
->cache_info
.identity_digest
,DIGEST_LEN
)<0);
3623 test_same_voter(smartlist_get(con
->voters
, 1),
3624 smartlist_get(v2
->voters
, 0));
3625 test_same_voter(smartlist_get(con
->voters
, 2),
3626 smartlist_get(v1
->voters
, 0));
3627 test_same_voter(smartlist_get(con
->voters
, 3),
3628 smartlist_get(v3
->voters
, 0));
3630 test_assert(!con
->cert
);
3631 test_eq(2, smartlist_len(con
->routerstatus_list
));
3632 /* There should be two listed routers: one with identity 3, one with
3634 /* This one showed up in 2 digests. */
3635 rs
= smartlist_get(con
->routerstatus_list
, 0);
3636 test_memeq(rs
->identity_digest
,
3637 "\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3",
3639 test_memeq(rs
->descriptor_digest
, "NNNNNNNNNNNNNNNNNNNN", DIGEST_LEN
);
3640 test_assert(!rs
->is_authority
);
3641 test_assert(!rs
->is_exit
);
3642 test_assert(!rs
->is_fast
);
3643 test_assert(!rs
->is_possible_guard
);
3644 test_assert(!rs
->is_stable
);
3645 test_assert(rs
->is_running
); /* If it wasn't running it wouldn't be here */
3646 test_assert(!rs
->is_v2_dir
);
3647 test_assert(!rs
->is_valid
);
3648 test_assert(!rs
->is_named
);
3649 /* XXXX check version */
3651 rs
= smartlist_get(con
->routerstatus_list
, 1);
3652 /* This one showed up in 3 digests. Twice with ID 'M', once with 'Z'. */
3653 test_memeq(rs
->identity_digest
,
3654 "\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5",
3656 test_streq(rs
->nickname
, "router1");
3657 test_memeq(rs
->descriptor_digest
, "MMMMMMMMMMMMMMMMMMMM", DIGEST_LEN
);
3658 test_eq(rs
->published_on
, now
-1000);
3659 test_eq(rs
->addr
, 0x99009901);
3660 test_eq(rs
->or_port
, 443);
3661 test_eq(rs
->dir_port
, 0);
3662 test_assert(!rs
->is_authority
);
3663 test_assert(rs
->is_exit
);
3664 test_assert(rs
->is_fast
);
3665 test_assert(rs
->is_possible_guard
);
3666 test_assert(rs
->is_stable
);
3667 test_assert(rs
->is_running
);
3668 test_assert(rs
->is_v2_dir
);
3669 test_assert(rs
->is_valid
);
3670 test_assert(!rs
->is_named
);
3671 /* XXXX check version */
3675 /* Check signatures. the first voter is a pseudo-entry with a legacy key.
3676 * The second one hasn't signed. The fourth one has signed: validate it. */
3677 voter
= smartlist_get(con
->voters
, 1);
3678 test_assert(!voter
->signature
);
3679 test_assert(!voter
->good_signature
);
3680 test_assert(!voter
->bad_signature
);
3682 voter
= smartlist_get(con
->voters
, 3);
3683 test_assert(voter
->signature
);
3684 test_assert(!voter
->good_signature
);
3685 test_assert(!voter
->bad_signature
);
3686 test_assert(!networkstatus_check_voter_signature(con
,
3687 smartlist_get(con
->voters
, 3),
3689 test_assert(voter
->signature
);
3690 test_assert(voter
->good_signature
);
3691 test_assert(!voter
->bad_signature
);
3694 const char *msg
=NULL
;
3695 /* Compute the other two signed consensuses. */
3696 smartlist_shuffle(votes
);
3697 consensus_text2
= networkstatus_compute_consensus(votes
, 3,
3698 cert2
->identity_key
,
3699 sign_skey_2
, NULL
,NULL
);
3700 smartlist_shuffle(votes
);
3701 consensus_text3
= networkstatus_compute_consensus(votes
, 3,
3702 cert1
->identity_key
,
3703 sign_skey_1
, NULL
,NULL
);
3704 test_assert(consensus_text2
);
3705 test_assert(consensus_text3
);
3706 con2
= networkstatus_parse_vote_from_string(consensus_text2
, NULL
,
3708 con3
= networkstatus_parse_vote_from_string(consensus_text3
, NULL
,
3713 /* All three should have the same digest. */
3714 test_memeq(con
->networkstatus_digest
, con2
->networkstatus_digest
,
3716 test_memeq(con
->networkstatus_digest
, con3
->networkstatus_digest
,
3719 /* Extract a detached signature from con3. */
3720 detached_text1
= networkstatus_get_detached_signatures(con3
);
3721 tor_assert(detached_text1
);
3722 /* Try to parse it. */
3723 dsig1
= networkstatus_parse_detached_signatures(detached_text1
, NULL
);
3726 /* Are parsed values as expected? */
3727 test_eq(dsig1
->valid_after
, con3
->valid_after
);
3728 test_eq(dsig1
->fresh_until
, con3
->fresh_until
);
3729 test_eq(dsig1
->valid_until
, con3
->valid_until
);
3730 test_memeq(dsig1
->networkstatus_digest
, con3
->networkstatus_digest
,
3732 test_eq(1, smartlist_len(dsig1
->signatures
));
3733 voter
= smartlist_get(dsig1
->signatures
, 0);
3734 test_memeq(voter
->identity_digest
, cert1
->cache_info
.identity_digest
,
3737 /* Try adding it to con2. */
3738 detached_text2
= networkstatus_get_detached_signatures(con2
);
3739 test_eq(1, networkstatus_add_detached_signatures(con2
, dsig1
, &msg
));
3740 tor_free(detached_text2
);
3741 detached_text2
= networkstatus_get_detached_signatures(con2
);
3742 //printf("\n<%s>\n", detached_text2);
3743 dsig2
= networkstatus_parse_detached_signatures(detached_text2
, NULL
);
3747 SMARTLIST_FOREACH(dsig2->signatures, networkstatus_voter_info_t *, vi, {
3749 base16_encode(hd, sizeof(hd), vi->identity_digest, DIGEST_LEN);
3753 test_eq(2, smartlist_len(dsig2
->signatures
));
3755 /* Try adding to con2 twice; verify that nothing changes. */
3756 test_eq(0, networkstatus_add_detached_signatures(con2
, dsig1
, &msg
));
3759 test_eq(2, networkstatus_add_detached_signatures(con
, dsig2
, &msg
));
3760 /* Check signatures */
3761 test_assert(!networkstatus_check_voter_signature(con
,
3762 smartlist_get(con
->voters
, 1),
3764 test_assert(!networkstatus_check_voter_signature(con
,
3765 smartlist_get(con
->voters
, 2),
3771 smartlist_free(votes
);
3775 tor_free(consensus_text
);
3778 networkstatus_vote_free(vote
);
3780 networkstatus_vote_free(v1
);
3782 networkstatus_vote_free(v2
);
3784 networkstatus_vote_free(v3
);
3786 networkstatus_vote_free(con
);
3788 crypto_free_pk_env(sign_skey_1
);
3790 crypto_free_pk_env(sign_skey_2
);
3792 crypto_free_pk_env(sign_skey_3
);
3794 crypto_free_pk_env(sign_skey_leg1
);
3796 authority_cert_free(cert1
);
3798 authority_cert_free(cert2
);
3800 authority_cert_free(cert3
);
3802 tor_free(consensus_text2
);
3803 tor_free(consensus_text3
);
3804 tor_free(detached_text1
);
3805 tor_free(detached_text2
);
3807 networkstatus_vote_free(con2
);
3809 networkstatus_vote_free(con3
);
3811 ns_detached_signatures_free(dsig1
);
3813 ns_detached_signatures_free(dsig2
);
3816 /** Helper: Parse the exit policy string in <b>policy_str</b>, and make sure
3817 * that policies_summarize() produces the string <b>expected_summary</b> from
3820 test_policy_summary_helper(const char *policy_str
,
3821 const char *expected_summary
)
3824 smartlist_t
*policy
= smartlist_create();
3825 char *summary
= NULL
;
3828 line
.key
= (char*)"foo";
3829 line
.value
= (char *)policy_str
;
3832 r
= policies_parse_exit_policy(&line
, &policy
, 0, NULL
);
3834 summary
= policy_summarize(policy
);
3836 test_assert(summary
!= NULL
);
3837 test_streq(summary
, expected_summary
);
3842 addr_policy_list_free(policy
);
3845 /** Run unit tests for generating summary lines of exit policies */
3850 smartlist_t
*policy
= NULL
, *policy2
= NULL
;
3854 smartlist_t
*sm
= NULL
;
3855 char *policy_str
= NULL
;
3857 policy
= smartlist_create();
3859 p
= router_parse_addr_policy_item_from_string("reject 192.168.0.0/16:*",-1);
3860 test_assert(p
!= NULL
);
3861 test_eq(ADDR_POLICY_REJECT
, p
->policy_type
);
3862 tor_addr_from_ipv4h(&tar
, 0xc0a80000u
);
3863 test_eq(0, tor_addr_compare(&p
->addr
, &tar
, CMP_EXACT
));
3864 test_eq(16, p
->maskbits
);
3865 test_eq(1, p
->prt_min
);
3866 test_eq(65535, p
->prt_max
);
3868 smartlist_add(policy
, p
);
3870 test_assert(ADDR_POLICY_ACCEPTED
==
3871 compare_addr_to_addr_policy(0x01020304u
, 2, policy
));
3872 test_assert(ADDR_POLICY_PROBABLY_ACCEPTED
==
3873 compare_addr_to_addr_policy(0, 2, policy
));
3874 test_assert(ADDR_POLICY_REJECTED
==
3875 compare_addr_to_addr_policy(0xc0a80102, 2, policy
));
3878 test_assert(0 == policies_parse_exit_policy(NULL
, &policy2
, 1, NULL
));
3879 test_assert(policy2
);
3881 test_assert(!exit_policy_is_general_exit(policy
));
3882 test_assert(exit_policy_is_general_exit(policy2
));
3883 test_assert(!exit_policy_is_general_exit(NULL
));
3885 test_assert(cmp_addr_policies(policy
, policy2
));
3886 test_assert(cmp_addr_policies(policy
, NULL
));
3887 test_assert(!cmp_addr_policies(policy2
, policy2
));
3888 test_assert(!cmp_addr_policies(NULL
, NULL
));
3890 test_assert(!policy_is_reject_star(policy2
));
3891 test_assert(policy_is_reject_star(policy
));
3892 test_assert(policy_is_reject_star(NULL
));
3894 addr_policy_list_free(policy
);
3897 /* make sure compacting logic works. */
3899 line
.key
= (char*)"foo";
3900 line
.value
= (char*)"accept *:80,reject private:*,reject *:*";
3902 test_assert(0 == policies_parse_exit_policy(&line
, &policy
, 0, NULL
));
3903 test_assert(policy
);
3904 //test_streq(policy->string, "accept *:80");
3905 //test_streq(policy->next->string, "reject *:*");
3906 test_eq(smartlist_len(policy
), 2);
3908 /* test policy summaries */
3909 /* check if we properly ignore private IP addresses */
3910 test_policy_summary_helper("reject 192.168.0.0/16:*,"
3911 "reject 0.0.0.0/8:*,"
3912 "reject 10.0.0.0/8:*,"
3917 /* check all accept policies, and proper counting of rejects */
3918 test_policy_summary_helper("reject 11.0.0.0/9:80,"
3919 "reject 12.0.0.0/9:80,"
3920 "reject 13.0.0.0/9:80,"
3921 "reject 14.0.0.0/9:80,"
3922 "accept *:*", "accept 1-65535");
3923 test_policy_summary_helper("reject 11.0.0.0/9:80,"
3924 "reject 12.0.0.0/9:80,"
3925 "reject 13.0.0.0/9:80,"
3926 "reject 14.0.0.0/9:80,"
3927 "reject 15.0.0.0:81,"
3928 "accept *:*", "accept 1-65535");
3929 test_policy_summary_helper("reject 11.0.0.0/9:80,"
3930 "reject 12.0.0.0/9:80,"
3931 "reject 13.0.0.0/9:80,"
3932 "reject 14.0.0.0/9:80,"
3933 "reject 15.0.0.0:80,"
3937 test_policy_summary_helper("accept 11.0.0.0/9:80,"
3941 test_policy_summary_helper("accept *:80,"
3946 "accept 80-81,100-111");
3948 test_policy_summary_helper("accept *:1,"
3952 "accept 1,3,65535");
3954 test_policy_summary_helper("accept *:1,"
3960 test_policy_summary_helper("reject *:1,"
3967 /* truncation ports */
3968 sm
= smartlist_create();
3969 for (i
=1; i
<2000; i
+=2) {
3970 char buf
[POLICY_BUF_LEN
];
3971 tor_snprintf(buf
, sizeof(buf
), "reject *:%d", i
);
3972 smartlist_add(sm
, tor_strdup(buf
));
3974 smartlist_add(sm
, tor_strdup("accept *:*"));
3975 policy_str
= smartlist_join_strings(sm
, ",", 0, NULL
);
3976 test_policy_summary_helper( policy_str
,
3977 "accept 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,"
3978 "46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,"
3979 "92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,"
3980 "130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,"
3981 "166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198,200,"
3982 "202,204,206,208,210,212,214,216,218,220,222,224,226,228,230,232,234,236,"
3983 "238,240,242,244,246,248,250,252,254,256,258,260,262,264,266,268,270,272,"
3984 "274,276,278,280,282,284,286,288,290,292,294,296,298,300,302,304,306,308,"
3985 "310,312,314,316,318,320,322,324,326,328,330,332,334,336,338,340,342,344,"
3986 "346,348,350,352,354,356,358,360,362,364,366,368,370,372,374,376,378,380,"
3987 "382,384,386,388,390,392,394,396,398,400,402,404,406,408,410,412,414,416,"
3988 "418,420,422,424,426,428,430,432,434,436,438,440,442,444,446,448,450,452,"
3989 "454,456,458,460,462,464,466,468,470,472,474,476,478,480,482,484,486,488,"
3990 "490,492,494,496,498,500,502,504,506,508,510,512,514,516,518,520,522");
3994 addr_policy_list_free(policy
);
3996 addr_policy_list_free(policy2
);
3997 tor_free(policy_str
);
3999 SMARTLIST_FOREACH(sm
, char *, s
, tor_free(s
));
4004 /** Run unit tests for basic rendezvous functions. */
4008 char address1
[] = "fooaddress.onion";
4009 char address2
[] = "aaaaaaaaaaaaaaaa.onion";
4010 char address3
[] = "fooaddress.exit";
4011 char address4
[] = "www.torproject.org";
4012 rend_service_descriptor_t
*d1
=
4013 tor_malloc_zero(sizeof(rend_service_descriptor_t
));
4014 rend_service_descriptor_t
*d2
= NULL
;
4015 char *encoded
= NULL
;
4019 crypto_pk_env_t
*pk1
= pk_generate(0), *pk2
= pk_generate(1);
4021 /* Test unversioned (v0) descriptor */
4022 d1
->pk
= crypto_pk_dup_key(pk1
);
4024 d1
->timestamp
= now
;
4026 d1
->intro_nodes
= smartlist_create();
4027 for (i
= 0; i
< 3; i
++) {
4028 rend_intro_point_t
*intro
= tor_malloc_zero(sizeof(rend_intro_point_t
));
4029 intro
->extend_info
= tor_malloc_zero(sizeof(extend_info_t
));
4030 crypto_rand(intro
->extend_info
->identity_digest
, DIGEST_LEN
);
4031 intro
->extend_info
->nickname
[0] = '$';
4032 base16_encode(intro
->extend_info
->nickname
+1, HEX_DIGEST_LEN
+1,
4033 intro
->extend_info
->identity_digest
, DIGEST_LEN
);
4034 smartlist_add(d1
->intro_nodes
, intro
);
4036 test_assert(! rend_encode_service_descriptor(d1
, pk1
, &encoded
, &len
));
4037 d2
= rend_parse_service_descriptor(encoded
, len
);
4040 test_assert(!crypto_pk_cmp_keys(d1
->pk
, d2
->pk
));
4041 test_eq(d2
->timestamp
, now
);
4042 test_eq(d2
->version
, 0);
4043 test_eq(d2
->protocols
, 1<<2);
4044 test_eq(smartlist_len(d2
->intro_nodes
), 3);
4045 for (i
= 0; i
< 3; i
++) {
4046 rend_intro_point_t
*intro1
= smartlist_get(d1
->intro_nodes
, i
);
4047 rend_intro_point_t
*intro2
= smartlist_get(d2
->intro_nodes
, i
);
4048 test_streq(intro1
->extend_info
->nickname
,
4049 intro2
->extend_info
->nickname
);
4052 test_assert(BAD_HOSTNAME
== parse_extended_hostname(address1
));
4053 test_assert(ONION_HOSTNAME
== parse_extended_hostname(address2
));
4054 test_assert(EXIT_HOSTNAME
== parse_extended_hostname(address3
));
4055 test_assert(NORMAL_HOSTNAME
== parse_extended_hostname(address4
));
4057 crypto_free_pk_env(pk1
);
4058 crypto_free_pk_env(pk2
);
4060 rend_service_descriptor_free(d1
);
4061 rend_service_descriptor_free(d2
);
4066 crypto_free_pk_env(pk1
);
4068 crypto_free_pk_env(pk2
);
4070 rend_service_descriptor_free(d1
);
4072 rend_service_descriptor_free(d2
);
4076 /** Run AES performance benchmarks. */
4082 crypto_cipher_env_t
*c
;
4083 struct timeval start
, end
;
4084 const int iters
= 100000;
4086 c
= crypto_new_cipher_env();
4087 crypto_cipher_generate_key(c
);
4088 crypto_cipher_encrypt_init_cipher(c
);
4089 for (len
= 1; len
<= 8192; len
*= 2) {
4090 b1
= tor_malloc_zero(len
);
4091 b2
= tor_malloc_zero(len
);
4092 tor_gettimeofday(&start
);
4093 for (i
= 0; i
< iters
; ++i
) {
4094 crypto_cipher_encrypt(c
, b1
, b2
, len
);
4096 tor_gettimeofday(&end
);
4099 nsec
= (uint64_t) tv_udiff(&start
,&end
);
4101 nsec
/= (iters
*len
);
4102 printf("%d bytes: "U64_FORMAT
" nsec per byte\n", len
,
4103 U64_PRINTF_ARG(nsec
));
4105 crypto_free_cipher_env(c
);
4108 /** Run digestmap_t performance benchmarks. */
4112 smartlist_t
*sl
= smartlist_create();
4113 smartlist_t
*sl2
= smartlist_create();
4114 struct timeval start
, end
, pt2
, pt3
, pt4
;
4115 const int iters
= 10000;
4116 const int elts
= 4000;
4117 const int fpostests
= 1000000;
4120 digestmap_t
*dm
= digestmap_new();
4121 digestset_t
*ds
= digestset_new(elts
);
4123 for (i
= 0; i
< elts
; ++i
) {
4125 smartlist_add(sl
, tor_memdup(d
, 20));
4127 for (i
= 0; i
< elts
; ++i
) {
4129 smartlist_add(sl2
, tor_memdup(d
, 20));
4131 printf("nbits=%d\n", ds
->mask
+1);
4133 tor_gettimeofday(&start
);
4134 for (i
= 0; i
< iters
; ++i
) {
4135 SMARTLIST_FOREACH(sl
, const char *, cp
, digestmap_set(dm
, cp
, (void*)1));
4137 tor_gettimeofday(&pt2
);
4138 for (i
= 0; i
< iters
; ++i
) {
4139 SMARTLIST_FOREACH(sl
, const char *, cp
, digestmap_get(dm
, cp
));
4140 SMARTLIST_FOREACH(sl2
, const char *, cp
, digestmap_get(dm
, cp
));
4142 tor_gettimeofday(&pt3
);
4143 for (i
= 0; i
< iters
; ++i
) {
4144 SMARTLIST_FOREACH(sl
, const char *, cp
, digestset_add(ds
, cp
));
4146 tor_gettimeofday(&pt4
);
4147 for (i
= 0; i
< iters
; ++i
) {
4148 SMARTLIST_FOREACH(sl
, const char *, cp
, n
+= digestset_isin(ds
, cp
));
4149 SMARTLIST_FOREACH(sl2
, const char *, cp
, n
+= digestset_isin(ds
, cp
));
4151 tor_gettimeofday(&end
);
4153 for (i
= 0; i
< fpostests
; ++i
) {
4155 if (digestset_isin(ds
, d
)) ++fp
;
4158 printf("%ld\n",(unsigned long)tv_udiff(&start
, &pt2
));
4159 printf("%ld\n",(unsigned long)tv_udiff(&pt2
, &pt3
));
4160 printf("%ld\n",(unsigned long)tv_udiff(&pt3
, &pt4
));
4161 printf("%ld\n",(unsigned long)tv_udiff(&pt4
, &end
));
4162 printf("-- %d\n", n
);
4163 printf("++ %f\n", fp
/(double)fpostests
);
4164 digestmap_free(dm
, NULL
);
4166 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
4167 SMARTLIST_FOREACH(sl2
, char *, cp
, tor_free(cp
));
4169 smartlist_free(sl2
);
4172 /** Run unittests for memory pool allocator */
4174 test_util_mempool(void)
4176 mp_pool_t
*pool
= NULL
;
4177 smartlist_t
*allocated
= NULL
;
4180 pool
= mp_pool_new(1, 100);
4182 test_assert(pool
->new_chunk_capacity
>= 100);
4183 test_assert(pool
->item_alloc_size
>= sizeof(void*)+1);
4184 mp_pool_destroy(pool
);
4187 pool
= mp_pool_new(241, 2500);
4189 test_assert(pool
->new_chunk_capacity
>= 10);
4190 test_assert(pool
->item_alloc_size
>= sizeof(void*)+241);
4191 test_eq(pool
->item_alloc_size
& 0x03, 0);
4192 test_assert(pool
->new_chunk_capacity
< 60);
4194 allocated
= smartlist_create();
4195 for (i
= 0; i
< 20000; ++i
) {
4196 if (smartlist_len(allocated
) < 20 || crypto_rand_int(2)) {
4197 void *m
= mp_pool_get(pool
);
4198 memset(m
, 0x09, 241);
4199 smartlist_add(allocated
, m
);
4200 //printf("%d: %p\n", i, m);
4201 //mp_pool_assert_ok(pool);
4203 int idx
= crypto_rand_int(smartlist_len(allocated
));
4204 void *m
= smartlist_get(allocated
, idx
);
4205 //printf("%d: free %p\n", i, m);
4206 smartlist_del(allocated
, idx
);
4208 //mp_pool_assert_ok(pool);
4210 if (crypto_rand_int(777)==0)
4211 mp_pool_clean(pool
, 1, 1);
4214 mp_pool_assert_ok(pool
);
4219 SMARTLIST_FOREACH(allocated
, void *, m
, mp_pool_release(m
));
4220 mp_pool_assert_ok(pool
);
4221 mp_pool_clean(pool
, 0, 0);
4222 mp_pool_assert_ok(pool
);
4223 smartlist_free(allocated
);
4227 mp_pool_destroy(pool
);
4230 /** Run unittests for memory area allocator */
4232 test_util_memarea(void)
4234 memarea_t
*area
= memarea_new();
4235 char *p1
, *p2
, *p3
, *p1_orig
;
4236 void *malloced_ptr
= NULL
;
4241 p1_orig
= p1
= memarea_alloc(area
,64);
4242 p2
= memarea_alloc_zero(area
,52);
4243 p3
= memarea_alloc(area
,11);
4245 test_assert(memarea_owns_ptr(area
, p1
));
4246 test_assert(memarea_owns_ptr(area
, p2
));
4247 test_assert(memarea_owns_ptr(area
, p3
));
4248 /* Make sure we left enough space. */
4249 test_assert(p1
+64 <= p2
);
4250 test_assert(p2
+52 <= p3
);
4251 /* Make sure we aligned. */
4252 test_eq(((uintptr_t)p1
) % sizeof(void*), 0);
4253 test_eq(((uintptr_t)p2
) % sizeof(void*), 0);
4254 test_eq(((uintptr_t)p3
) % sizeof(void*), 0);
4255 test_assert(!memarea_owns_ptr(area
, p3
+8192));
4256 test_assert(!memarea_owns_ptr(area
, p3
+30));
4257 test_assert(tor_mem_is_zero(p2
, 52));
4258 /* Make sure we don't overalign. */
4259 p1
= memarea_alloc(area
, 1);
4260 p2
= memarea_alloc(area
, 1);
4261 test_eq(p1
+sizeof(void*), p2
);
4263 malloced_ptr
= tor_malloc(64);
4264 test_assert(!memarea_owns_ptr(area
, malloced_ptr
));
4265 tor_free(malloced_ptr
);
4268 /* memarea_memdup */
4270 malloced_ptr
= tor_malloc(64);
4271 crypto_rand((char*)malloced_ptr
, 64);
4272 p1
= memarea_memdup(area
, malloced_ptr
, 64);
4273 test_assert(p1
!= malloced_ptr
);
4274 test_memeq(p1
, malloced_ptr
, 64);
4275 tor_free(malloced_ptr
);
4278 /* memarea_strdup. */
4279 p1
= memarea_strdup(area
,"");
4280 p2
= memarea_strdup(area
, "abcd");
4284 test_streq(p2
, "abcd");
4286 /* memarea_strndup. */
4288 const char *s
= "Ad ogni porta batte la morte e grida: il nome!";
4289 /* (From Turandot, act 3.) */
4290 size_t len
= strlen(s
);
4291 p1
= memarea_strndup(area
, s
, 1000);
4292 p2
= memarea_strndup(area
, s
, 10);
4294 test_assert(p2
>= p1
+ len
+ 1);
4295 test_memeq(s
, p2
, 10);
4296 test_eq(p2
[10], '\0');
4297 p3
= memarea_strndup(area
, s
, len
);
4299 p3
= memarea_strndup(area
, s
, len
-1);
4300 test_memeq(s
, p3
, len
-1);
4301 test_eq(p3
[len
-1], '\0');
4304 memarea_clear(area
);
4305 p1
= memarea_alloc(area
, 1);
4306 test_eq(p1
, p1_orig
);
4307 memarea_clear(area
);
4309 /* Check for running over an area's size. */
4310 for (i
= 0; i
< 512; ++i
) {
4311 p1
= memarea_alloc(area
, crypto_rand_int(5)+1);
4312 test_assert(memarea_owns_ptr(area
, p1
));
4314 memarea_assert_ok(area
);
4315 /* Make sure we can allocate a too-big object. */
4316 p1
= memarea_alloc_zero(area
, 9000);
4317 p2
= memarea_alloc_zero(area
, 16);
4318 test_assert(memarea_owns_ptr(area
, p1
));
4319 test_assert(memarea_owns_ptr(area
, p2
));
4322 memarea_drop_all(area
);
4323 tor_free(malloced_ptr
);
4326 /** Run unit tests for utility functions to get file names relative to
4327 * the data directory. */
4329 test_util_datadir(void)
4334 f
= get_datadir_fname(NULL
);
4335 test_streq(f
, temp_dir
);
4337 f
= get_datadir_fname("state");
4338 tor_snprintf(buf
, sizeof(buf
), "%s"PATH_SEPARATOR
"state", temp_dir
);
4341 f
= get_datadir_fname2("cache", "thingy");
4342 tor_snprintf(buf
, sizeof(buf
),
4343 "%s"PATH_SEPARATOR
"cache"PATH_SEPARATOR
"thingy", temp_dir
);
4346 f
= get_datadir_fname2_suffix("cache", "thingy", ".foo");
4347 tor_snprintf(buf
, sizeof(buf
),
4348 "%s"PATH_SEPARATOR
"cache"PATH_SEPARATOR
"thingy.foo", temp_dir
);
4351 f
= get_datadir_fname_suffix("cache", ".foo");
4352 tor_snprintf(buf
, sizeof(buf
), "%s"PATH_SEPARATOR
"cache.foo",
4360 /** Test AES-CTR encryption and decryption with IV. */
4362 test_crypto_aes_iv(void)
4364 crypto_cipher_env_t
*cipher
;
4365 char *plain
, *encrypted1
, *encrypted2
, *decrypted1
, *decrypted2
;
4366 char plain_1
[1], plain_15
[15], plain_16
[16], plain_17
[17];
4367 char key1
[16], key2
[16];
4368 ssize_t encrypted_size
, decrypted_size
;
4370 plain
= tor_malloc(4095);
4371 encrypted1
= tor_malloc(4095 + 1 + 16);
4372 encrypted2
= tor_malloc(4095 + 1 + 16);
4373 decrypted1
= tor_malloc(4095 + 1);
4374 decrypted2
= tor_malloc(4095 + 1);
4376 crypto_rand(plain
, 4095);
4377 crypto_rand(key1
, 16);
4378 crypto_rand(key2
, 16);
4379 crypto_rand(plain_1
, 1);
4380 crypto_rand(plain_15
, 15);
4381 crypto_rand(plain_16
, 16);
4382 crypto_rand(plain_17
, 17);
4383 key1
[0] = key2
[0] + 128; /* Make sure that contents are different. */
4384 /* Encrypt and decrypt with the same key. */
4385 cipher
= crypto_create_init_cipher(key1
, 1);
4386 encrypted_size
= crypto_cipher_encrypt_with_iv(cipher
, encrypted1
, 16 + 4095,
4388 crypto_free_cipher_env(cipher
);
4390 test_eq(encrypted_size
, 16 + 4095);
4391 tor_assert(encrypted_size
> 0); /* This is obviously true, since 4111 is
4392 * greater than 0, but its truth is not
4393 * obvious to all analysis tools. */
4394 cipher
= crypto_create_init_cipher(key1
, 0);
4395 decrypted_size
= crypto_cipher_decrypt_with_iv(cipher
, decrypted1
, 4095,
4396 encrypted1
, encrypted_size
);
4397 crypto_free_cipher_env(cipher
);
4399 test_eq(decrypted_size
, 4095);
4400 tor_assert(decrypted_size
> 0);
4401 test_memeq(plain
, decrypted1
, 4095);
4402 /* Encrypt a second time (with a new random initialization vector). */
4403 cipher
= crypto_create_init_cipher(key1
, 1);
4404 encrypted_size
= crypto_cipher_encrypt_with_iv(cipher
, encrypted2
, 16 + 4095,
4406 crypto_free_cipher_env(cipher
);
4408 test_eq(encrypted_size
, 16 + 4095);
4409 tor_assert(encrypted_size
> 0);
4410 cipher
= crypto_create_init_cipher(key1
, 0);
4411 decrypted_size
= crypto_cipher_decrypt_with_iv(cipher
, decrypted2
, 4095,
4412 encrypted2
, encrypted_size
);
4413 crypto_free_cipher_env(cipher
);
4415 test_eq(decrypted_size
, 4095);
4416 tor_assert(decrypted_size
> 0);
4417 test_memeq(plain
, decrypted2
, 4095);
4418 test_memneq(encrypted1
, encrypted2
, encrypted_size
);
4419 /* Decrypt with the wrong key. */
4420 cipher
= crypto_create_init_cipher(key2
, 0);
4421 decrypted_size
= crypto_cipher_decrypt_with_iv(cipher
, decrypted2
, 4095,
4422 encrypted1
, encrypted_size
);
4423 crypto_free_cipher_env(cipher
);
4425 test_memneq(plain
, decrypted2
, encrypted_size
);
4426 /* Alter the initialization vector. */
4427 encrypted1
[0] += 42;
4428 cipher
= crypto_create_init_cipher(key1
, 0);
4429 decrypted_size
= crypto_cipher_decrypt_with_iv(cipher
, decrypted1
, 4095,
4430 encrypted1
, encrypted_size
);
4431 crypto_free_cipher_env(cipher
);
4433 test_memneq(plain
, decrypted2
, 4095);
4434 /* Special length case: 1. */
4435 cipher
= crypto_create_init_cipher(key1
, 1);
4436 encrypted_size
= crypto_cipher_encrypt_with_iv(cipher
, encrypted1
, 16 + 1,
4438 crypto_free_cipher_env(cipher
);
4440 test_eq(encrypted_size
, 16 + 1);
4441 tor_assert(encrypted_size
> 0);
4442 cipher
= crypto_create_init_cipher(key1
, 0);
4443 decrypted_size
= crypto_cipher_decrypt_with_iv(cipher
, decrypted1
, 1,
4444 encrypted1
, encrypted_size
);
4445 crypto_free_cipher_env(cipher
);
4447 test_eq(decrypted_size
, 1);
4448 tor_assert(decrypted_size
> 0);
4449 test_memeq(plain_1
, decrypted1
, 1);
4450 /* Special length case: 15. */
4451 cipher
= crypto_create_init_cipher(key1
, 1);
4452 encrypted_size
= crypto_cipher_encrypt_with_iv(cipher
, encrypted1
, 16 + 15,
4454 crypto_free_cipher_env(cipher
);
4456 test_eq(encrypted_size
, 16 + 15);
4457 tor_assert(encrypted_size
> 0);
4458 cipher
= crypto_create_init_cipher(key1
, 0);
4459 decrypted_size
= crypto_cipher_decrypt_with_iv(cipher
, decrypted1
, 15,
4460 encrypted1
, encrypted_size
);
4461 crypto_free_cipher_env(cipher
);
4463 test_eq(decrypted_size
, 15);
4464 tor_assert(decrypted_size
> 0);
4465 test_memeq(plain_15
, decrypted1
, 15);
4466 /* Special length case: 16. */
4467 cipher
= crypto_create_init_cipher(key1
, 1);
4468 encrypted_size
= crypto_cipher_encrypt_with_iv(cipher
, encrypted1
, 16 + 16,
4470 crypto_free_cipher_env(cipher
);
4472 test_eq(encrypted_size
, 16 + 16);
4473 tor_assert(encrypted_size
> 0);
4474 cipher
= crypto_create_init_cipher(key1
, 0);
4475 decrypted_size
= crypto_cipher_decrypt_with_iv(cipher
, decrypted1
, 16,
4476 encrypted1
, encrypted_size
);
4477 crypto_free_cipher_env(cipher
);
4479 test_eq(decrypted_size
, 16);
4480 tor_assert(decrypted_size
> 0);
4481 test_memeq(plain_16
, decrypted1
, 16);
4482 /* Special length case: 17. */
4483 cipher
= crypto_create_init_cipher(key1
, 1);
4484 encrypted_size
= crypto_cipher_encrypt_with_iv(cipher
, encrypted1
, 16 + 17,
4486 crypto_free_cipher_env(cipher
);
4488 test_eq(encrypted_size
, 16 + 17);
4489 tor_assert(encrypted_size
> 0);
4490 cipher
= crypto_create_init_cipher(key1
, 0);
4491 decrypted_size
= crypto_cipher_decrypt_with_iv(cipher
, decrypted1
, 17,
4492 encrypted1
, encrypted_size
);
4493 test_eq(decrypted_size
, 17);
4494 tor_assert(decrypted_size
> 0);
4495 test_memeq(plain_17
, decrypted1
, 17);
4500 tor_free(encrypted1
);
4501 tor_free(encrypted2
);
4502 tor_free(decrypted1
);
4503 tor_free(decrypted2
);
4505 crypto_free_cipher_env(cipher
);
4508 /** Test base32 decoding. */
4510 test_crypto_base32_decode(void)
4512 char plain
[60], encoded
[96 + 1], decoded
[60];
4514 crypto_rand(plain
, 60);
4515 /* Encode and decode a random string. */
4516 base32_encode(encoded
, 96 + 1, plain
, 60);
4517 res
= base32_decode(decoded
, 60, encoded
, 96);
4519 test_memeq(plain
, decoded
, 60);
4520 /* Encode, uppercase, and decode a random string. */
4521 base32_encode(encoded
, 96 + 1, plain
, 60);
4522 tor_strupper(encoded
);
4523 res
= base32_decode(decoded
, 60, encoded
, 96);
4525 test_memeq(plain
, decoded
, 60);
4526 /* Change encoded string and decode. */
4527 if (encoded
[0] == 'A' || encoded
[0] == 'a')
4531 res
= base32_decode(decoded
, 60, encoded
, 96);
4533 test_memneq(plain
, decoded
, 60);
4534 /* Bad encodings. */
4536 res
= base32_decode(decoded
, 60, encoded
, 96);
4537 test_assert(res
< 0);
4543 /** Test encoding and parsing of v2 rendezvous service descriptors. */
4545 test_rend_fns_v2(void)
4547 rend_service_descriptor_t
*generated
= NULL
, *parsed
= NULL
;
4548 char service_id
[DIGEST_LEN
];
4549 char service_id_base32
[REND_SERVICE_ID_LEN_BASE32
+1];
4550 const char *next_desc
;
4551 smartlist_t
*descs
= smartlist_create();
4552 char computed_desc_id
[DIGEST_LEN
];
4553 char parsed_desc_id
[DIGEST_LEN
];
4554 crypto_pk_env_t
*pk1
= NULL
, *pk2
= NULL
;
4556 char *intro_points_encrypted
= NULL
;
4557 size_t intro_points_size
;
4558 size_t encoded_size
;
4560 pk1
= pk_generate(0);
4561 pk2
= pk_generate(1);
4562 generated
= tor_malloc_zero(sizeof(rend_service_descriptor_t
));
4563 generated
->pk
= crypto_pk_dup_key(pk1
);
4564 crypto_pk_get_digest(generated
->pk
, service_id
);
4565 base32_encode(service_id_base32
, REND_SERVICE_ID_LEN_BASE32
+1,
4566 service_id
, REND_SERVICE_ID_LEN
);
4568 generated
->timestamp
= now
;
4569 generated
->version
= 2;
4570 generated
->protocols
= 42;
4571 generated
->intro_nodes
= smartlist_create();
4573 for (i
= 0; i
< 3; i
++) {
4574 rend_intro_point_t
*intro
= tor_malloc_zero(sizeof(rend_intro_point_t
));
4575 crypto_pk_env_t
*okey
= pk_generate(2 + i
);
4576 intro
->extend_info
= tor_malloc_zero(sizeof(extend_info_t
));
4577 intro
->extend_info
->onion_key
= okey
;
4578 crypto_pk_get_digest(intro
->extend_info
->onion_key
,
4579 intro
->extend_info
->identity_digest
);
4580 //crypto_rand(info->identity_digest, DIGEST_LEN); /* Would this work? */
4581 intro
->extend_info
->nickname
[0] = '$';
4582 base16_encode(intro
->extend_info
->nickname
+ 1,
4583 sizeof(intro
->extend_info
->nickname
) - 1,
4584 intro
->extend_info
->identity_digest
, DIGEST_LEN
);
4585 /* Does not cover all IP addresses. */
4586 tor_addr_from_ipv4h(&intro
->extend_info
->addr
, crypto_rand_int(65536));
4587 intro
->extend_info
->port
= crypto_rand_int(65536);
4588 intro
->intro_key
= crypto_pk_dup_key(pk2
);
4589 smartlist_add(generated
->intro_nodes
, intro
);
4591 test_assert(rend_encode_v2_descriptors(descs
, generated
, now
, 0,
4592 REND_NO_AUTH
, NULL
, NULL
) > 0);
4593 test_assert(rend_compute_v2_desc_id(computed_desc_id
, service_id_base32
,
4594 NULL
, now
, 0) == 0);
4595 test_memeq(((rend_encoded_v2_service_descriptor_t
*)
4596 smartlist_get(descs
, 0))->desc_id
, computed_desc_id
, DIGEST_LEN
);
4597 test_assert(rend_parse_v2_service_descriptor(&parsed
, parsed_desc_id
,
4598 &intro_points_encrypted
,
4602 ((rend_encoded_v2_service_descriptor_t
*)
4603 smartlist_get(descs
, 0))->desc_str
) == 0);
4604 test_assert(parsed
);
4605 test_memeq(((rend_encoded_v2_service_descriptor_t
*)
4606 smartlist_get(descs
, 0))->desc_id
, parsed_desc_id
, DIGEST_LEN
);
4607 test_eq(rend_parse_introduction_points(parsed
, intro_points_encrypted
,
4608 intro_points_size
), 3);
4609 test_assert(!crypto_pk_cmp_keys(generated
->pk
, parsed
->pk
));
4610 test_eq(parsed
->timestamp
, now
);
4611 test_eq(parsed
->version
, 2);
4612 test_eq(parsed
->protocols
, 42);
4613 test_eq(smartlist_len(parsed
->intro_nodes
), 3);
4614 for (i
= 0; i
< smartlist_len(parsed
->intro_nodes
); i
++) {
4615 rend_intro_point_t
*par_intro
= smartlist_get(parsed
->intro_nodes
, i
),
4616 *gen_intro
= smartlist_get(generated
->intro_nodes
, i
);
4617 extend_info_t
*par_info
= par_intro
->extend_info
;
4618 extend_info_t
*gen_info
= gen_intro
->extend_info
;
4619 test_assert(!crypto_pk_cmp_keys(gen_info
->onion_key
, par_info
->onion_key
));
4620 test_memeq(gen_info
->identity_digest
, par_info
->identity_digest
,
4622 test_streq(gen_info
->nickname
, par_info
->nickname
);
4623 test_assert(tor_addr_eq(&gen_info
->addr
, &par_info
->addr
));
4624 test_eq(gen_info
->port
, par_info
->port
);
4627 rend_service_descriptor_free(parsed
);
4628 rend_service_descriptor_free(generated
);
4629 parsed
= generated
= NULL
;
4633 for (i
= 0; i
< smartlist_len(descs
); i
++)
4634 rend_encoded_v2_service_descriptor_free(smartlist_get(descs
, i
));
4635 smartlist_free(descs
);
4638 rend_service_descriptor_free(parsed
);
4640 rend_service_descriptor_free(generated
);
4642 crypto_free_pk_env(pk1
);
4644 crypto_free_pk_env(pk2
);
4645 tor_free(intro_points_encrypted
);
4648 /** Run unit tests for GeoIP code. */
4653 time_t now
= time(NULL
);
4656 /* Populate the DB a bit. Add these in order, since we can't do the final
4657 * 'sort' step. These aren't very good IP addresses, but they're perfectly
4658 * fine uint32_t values. */
4659 test_eq(0, geoip_parse_entry("10,50,AB"));
4660 test_eq(0, geoip_parse_entry("52,90,XY"));
4661 test_eq(0, geoip_parse_entry("95,100,AB"));
4662 test_eq(0, geoip_parse_entry("\"105\",\"140\",\"ZZ\""));
4663 test_eq(0, geoip_parse_entry("\"150\",\"190\",\"XY\""));
4664 test_eq(0, geoip_parse_entry("\"200\",\"250\",\"AB\""));
4666 /* We should have 3 countries: ab, xy, zz. */
4667 test_eq(3, geoip_get_n_countries());
4668 /* Make sure that country ID actually works. */
4669 #define NAMEFOR(x) geoip_get_country_name(geoip_get_country_by_ip(x))
4670 test_streq("ab", NAMEFOR(32));
4671 test_streq("??", NAMEFOR(5));
4672 test_streq("??", NAMEFOR(51));
4673 test_streq("xy", NAMEFOR(150));
4674 test_streq("xy", NAMEFOR(190));
4675 test_streq("??", NAMEFOR(2000));
4678 get_options()->BridgeRelay
= 1;
4679 get_options()->BridgeRecordUsageByCountry
= 1;
4680 /* Put 9 observations in AB... */
4681 for (i
=32; i
< 40; ++i
)
4682 geoip_note_client_seen(GEOIP_CLIENT_CONNECT
, i
, now
-7200);
4683 geoip_note_client_seen(GEOIP_CLIENT_CONNECT
, 225, now
-7200);
4684 /* and 3 observations in XY, several times. */
4685 for (j
=0; j
< 10; ++j
)
4686 for (i
=52; i
< 55; ++i
)
4687 geoip_note_client_seen(GEOIP_CLIENT_CONNECT
, i
, now
-3600);
4688 /* and 17 observations in ZZ... */
4689 for (i
=110; i
< 127; ++i
)
4690 geoip_note_client_seen(GEOIP_CLIENT_CONNECT
, i
, now
);
4691 s
= geoip_get_client_history(now
+5*24*60*60, GEOIP_CLIENT_CONNECT
);
4693 test_streq("zz=24,ab=16,xy=8", s
);
4696 /* Now clear out all the AB observations. */
4697 geoip_remove_old_clients(now
-6000);
4698 s
= geoip_get_client_history(now
+5*24*60*60, GEOIP_CLIENT_CONNECT
);
4700 test_streq("zz=24,xy=8", s
);
4706 /** For test_array. Declare an CLI-invocable off-by-default function in the
4707 * unit tests, with function name and user-visible name <b>x</b>*/
4708 #define DISABLED(x) { #x, x, 0, 0, 0 }
4709 /** For test_array. Declare an CLI-invocable unit test function, with function
4710 * name test_<b>x</b>(), and user-visible name <b>x</b> */
4711 #define ENT(x) { #x, test_ ## x, 0, 0, 1 }
4712 /** For test_array. Declare an CLI-invocable unit test function, with function
4713 * name test_<b>x</b>_<b>y</b>(), and user-visible name
4714 * <b>x</b>/<b>y</b>. This function will be treated as a subentry of <b>x</b>,
4715 * so that invoking <b>x</b> from the CLI invokes this test too. */
4716 #define SUBENT(x,y) { #x "/" #y, test_ ## x ## _ ## y, 1, 0, 1 }
4718 /** An array of functions and information for all the unit tests we can run. */
4720 const char *test_name
; /**< How does the user refer to this test from the
4722 void (*test_fn
)(void); /**< What function is called to run this test? */
4723 int is_subent
; /**< Is this a subentry of a bigger set of related tests? */
4724 int selected
; /**< Are we planning to run this one? */
4725 int is_default
; /**< If the user doesn't say what tests they want, do they
4726 * get this function by default? */
4730 SUBENT(crypto
, rng
),
4731 SUBENT(crypto
, aes
),
4732 SUBENT(crypto
, sha
),
4735 SUBENT(crypto
, s2k
),
4736 SUBENT(crypto
, aes_iv
),
4737 SUBENT(crypto
, base32_decode
),
4739 SUBENT(util
, ip6_helpers
),
4741 SUBENT(util
, datadir
),
4742 SUBENT(util
, smartlist_basic
),
4743 SUBENT(util
, smartlist_strings
),
4744 SUBENT(util
, smartlist_overlap
),
4745 SUBENT(util
, smartlist_digests
),
4746 SUBENT(util
, smartlist_join
),
4747 SUBENT(util
, bitarray
),
4748 SUBENT(util
, digestset
),
4749 SUBENT(util
, mempool
),
4750 SUBENT(util
, memarea
),
4751 SUBENT(util
, strmap
),
4752 SUBENT(util
, control_formats
),
4753 SUBENT(util
, pqueue
),
4755 SUBENT(util
, threads
),
4756 SUBENT(util
, order_functions
),
4757 SUBENT(util
, sscanf
),
4758 ENT(onion_handshake
),
4761 ENT(v3_networkstatus
),
4764 SUBENT(rend_fns
, v2
),
4767 DISABLED(bench_aes
),
4768 DISABLED(bench_dmap
),
4769 { NULL
, NULL
, 0, 0, 0 },
4772 static void syntax(void) ATTR_NORETURN
;
4774 /** Print a syntax usage message, and exit.*/
4780 " test [-v|--verbose] [--warn|--notice|--info|--debug]\n"
4782 "Recognized tests are:\n");
4783 for (i
= 0; test_array
[i
].test_name
; ++i
) {
4784 printf(" %s\n", test_array
[i
].test_name
);
4790 /** Main entry point for unit test code: parse the command line, and run
4791 * some unit tests. */
4793 main(int c
, char**v
)
4795 or_options_t
*options
;
4796 char *errmsg
= NULL
;
4798 int verbose
= 0, any_selected
= 0;
4799 int loglevel
= LOG_ERR
;
4803 int r
= CRYPTO_set_mem_ex_functions(_tor_malloc
, _tor_realloc
, _tor_free
);
4808 update_approx_time(time(NULL
));
4809 options
= options_new();
4813 for (i
= 1; i
< c
; ++i
) {
4814 if (!strcmp(v
[i
], "-v") || !strcmp(v
[i
], "--verbose"))
4816 else if (!strcmp(v
[i
], "--warn"))
4817 loglevel
= LOG_WARN
;
4818 else if (!strcmp(v
[i
], "--notice"))
4819 loglevel
= LOG_NOTICE
;
4820 else if (!strcmp(v
[i
], "--info"))
4821 loglevel
= LOG_INFO
;
4822 else if (!strcmp(v
[i
], "--debug"))
4823 loglevel
= LOG_DEBUG
;
4824 else if (!strcmp(v
[i
], "--help") || !strcmp(v
[i
], "-h") || v
[i
][0] == '-')
4828 for (j
= 0; test_array
[j
].test_name
; ++j
) {
4829 if (!strcmp(v
[i
], test_array
[j
].test_name
) ||
4830 (test_array
[j
].is_subent
&&
4831 !strcmpstart(test_array
[j
].test_name
, v
[i
]) &&
4832 test_array
[j
].test_name
[strlen(v
[i
])] == '/') ||
4833 (v
[i
][0] == '=' && !strcmp(v
[i
]+1, test_array
[j
].test_name
))) {
4834 test_array
[j
].selected
= 1;
4840 printf("Unknown test: %s\n", v
[i
]);
4846 if (!any_selected
) {
4847 for (i
= 0; test_array
[i
].test_name
; ++i
) {
4848 test_array
[i
].selected
= test_array
[i
].is_default
;
4853 log_severity_list_t s
;
4854 memset(&s
, 0, sizeof(s
));
4855 set_log_severity_config(loglevel
, LOG_ERR
, &s
);
4856 add_stream_log(&s
, "", fileno(stdout
));
4859 options
->command
= CMD_RUN_UNITTESTS
;
4860 crypto_global_init(0);
4864 options_init(options
);
4865 options
->DataDirectory
= tor_strdup(temp_dir
);
4866 if (set_options(options
, &errmsg
) < 0) {
4867 printf("Failed to set initial options: %s\n", errmsg
);
4874 atexit(remove_directory
);
4876 printf("Running Tor unit tests on %s\n", get_uname());
4878 for (i
= 0; test_array
[i
].test_name
; ++i
) {
4879 if (!test_array
[i
].selected
)
4881 if (!test_array
[i
].is_subent
) {
4882 printf("\n============================== %s\n",test_array
[i
].test_name
);
4883 } else if (test_array
[i
].is_subent
&& verbose
) {
4884 printf("\n%s", test_array
[i
].test_name
);
4886 test_array
[i
].test_fn();
4890 free_pregenerated_keys();
4893 dmalloc_log_unfreed();