1 /* Copyright (c) 2001-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2008, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
6 const char test_c_id
[] =
9 const char tor_svn_revision
[] = "";
13 * \brief Unit tests for many pieces of the lower level Tor modules.
30 /* These macros pull in declarations for some functions and structures that
31 * are typically file-private. */
32 #define BUFFERS_PRIVATE
33 #define CONFIG_PRIVATE
34 #define CONTROL_PRIVATE
35 #define CRYPTO_PRIVATE
36 #define DIRSERV_PRIVATE
37 #define DIRVOTE_PRIVATE
39 #define MEMPOOL_PRIVATE
40 #define ROUTER_PRIVATE
54 static char temp_dir
[256];
59 static int is_setup
= 0;
65 tor_snprintf(temp_dir
, sizeof(temp_dir
),
66 "c:\\windows\\temp\\tor_test_%d", (int)getpid());
69 tor_snprintf(temp_dir
, sizeof(temp_dir
), "/tmp/tor_test_%d", (int) getpid());
70 r
= mkdir(temp_dir
, 0700);
73 fprintf(stderr
, "Can't create directory %s:", temp_dir
);
81 get_fname(const char *name
)
83 static char buf
[1024];
85 tor_snprintf(buf
,sizeof(buf
),"%s/%s",temp_dir
,name
);
90 remove_directory(void)
92 smartlist_t
*elements
= tor_listdir(temp_dir
);
94 SMARTLIST_FOREACH(elements
, const char *, cp
,
96 size_t len
= strlen(cp
)+strlen(temp_dir
)+16;
97 char *tmp
= tor_malloc(len
);
98 tor_snprintf(tmp
, len
, "%s"PATH_SEPARATOR
"%s", temp_dir
, cp
);
102 SMARTLIST_FOREACH(elements
, char *, cp
, tor_free(cp
));
103 smartlist_free(elements
);
108 static crypto_pk_env_t
*
111 static crypto_pk_env_t
*pregen
[5] = {NULL
, NULL
, NULL
, NULL
, NULL
};
112 tor_assert(idx
< (int)(sizeof(pregen
)/sizeof(pregen
[0])));
114 pregen
[idx
] = crypto_new_pk_env();
115 tor_assert(!crypto_pk_generate_key(pregen
[idx
]));
117 return crypto_pk_dup_key(pregen
[idx
]);
126 buf_t
*buf
= NULL
, *buf2
= NULL
;
135 if (!(buf
= buf_new()))
138 //test_eq(buf_capacity(buf), 4096);
139 test_eq(buf_datalen(buf
), 0);
142 * General pointer frobbing
144 for (j
=0;j
<256;++j
) {
147 write_to_buf(str
, 256, buf
);
148 write_to_buf(str
, 256, buf
);
149 test_eq(buf_datalen(buf
), 512);
150 fetch_from_buf(str2
, 200, buf
);
151 test_memeq(str
, str2
, 200);
152 test_eq(buf_datalen(buf
), 312);
153 memset(str2
, 0, sizeof(str2
));
155 fetch_from_buf(str2
, 256, buf
);
156 test_memeq(str
+200, str2
, 56);
157 test_memeq(str
, str2
+56, 200);
158 test_eq(buf_datalen(buf
), 56);
159 memset(str2
, 0, sizeof(str2
));
160 /* Okay, now we should be 512 bytes into the 4096-byte buffer. If we add
161 * another 3584 bytes, we hit the end. */
163 write_to_buf(str
, 256, buf
);
166 test_eq(buf_datalen(buf
), 3896);
167 fetch_from_buf(str2
, 56, buf
);
168 test_eq(buf_datalen(buf
), 3840);
169 test_memeq(str
+200, str2
, 56);
171 memset(str2
, 0, sizeof(str2
));
172 fetch_from_buf(str2
, 256, buf
);
173 test_memeq(str
, str2
, 256);
175 test_eq(buf_datalen(buf
), 0);
179 /* Okay, now make sure growing can work. */
180 buf
= buf_new_with_capacity(16);
181 //test_eq(buf_capacity(buf), 16);
182 write_to_buf(str
+1, 255, buf
);
183 //test_eq(buf_capacity(buf), 256);
184 fetch_from_buf(str2
, 254, buf
);
185 test_memeq(str
+1, str2
, 254);
186 //test_eq(buf_capacity(buf), 256);
188 write_to_buf(str
, 32, buf
);
189 //test_eq(buf_capacity(buf), 256);
191 write_to_buf(str
, 256, buf
);
193 //test_eq(buf_capacity(buf), 512);
194 test_eq(buf_datalen(buf
), 33+256);
195 fetch_from_buf(str2
, 33, buf
);
196 test_eq(*str2
, str
[255]);
198 test_memeq(str2
+1, str
, 32);
199 //test_eq(buf_capacity(buf), 512);
200 test_eq(buf_datalen(buf
), 256);
201 fetch_from_buf(str2
, 256, buf
);
202 test_memeq(str
, str2
, 256);
204 /* now try shrinking: case 1. */
206 buf
= buf_new_with_capacity(33668);
208 write_to_buf(str
,255, buf
);
210 //test_eq(buf_capacity(buf), 33668);
211 test_eq(buf_datalen(buf
), 17085);
212 for (j
=0; j
< 40; ++j
) {
213 fetch_from_buf(str2
, 255,buf
);
214 test_memeq(str2
, str
, 255);
217 /* now try shrinking: case 2. */
219 buf
= buf_new_with_capacity(33668);
221 write_to_buf(str
,255, buf
);
223 for (j
=0; j
< 20; ++j
) {
224 fetch_from_buf(str2
, 255,buf
);
225 test_memeq(str2
, str
, 255);
228 write_to_buf(str
,255, buf
);
230 //test_eq(buf_capacity(buf),33668);
231 for (j
=0; j
< 120; ++j
) {
232 fetch_from_buf(str2
, 255,buf
);
233 test_memeq(str2
, str
, 255);
236 /* Move from buf to buf. */
238 buf
= buf_new_with_capacity(4096);
239 buf2
= buf_new_with_capacity(4096);
241 write_to_buf(str
, 255, buf
);
242 test_eq(buf_datalen(buf
), 25500);
243 for (j
=0;j
<100;++j
) {
245 move_buf_to_buf(buf2
, buf
, &r
);
248 test_eq(buf_datalen(buf
), 24500);
249 test_eq(buf_datalen(buf2
), 1000);
251 fetch_from_buf(str2
, 255, buf2
);
252 test_memeq(str2
, str
, 255);
254 r
= 8192; /*big move*/
255 move_buf_to_buf(buf2
, buf
, &r
);
257 r
= 30000; /* incomplete move */
258 move_buf_to_buf(buf2
, buf
, &r
);
261 fetch_from_buf(str2
, 255, buf2
);
262 test_memeq(str2
, str
, 255);
268 buf
= buf_new_with_capacity(5);
269 cp
= "Testing. This is a moderately long Testing string.";
270 for (j
= 0; cp
[j
]; j
++)
271 write_to_buf(cp
+j
, 1, buf
);
272 test_eq(0, buf_find_string_offset(buf
, "Testing", 7));
273 test_eq(1, buf_find_string_offset(buf
, "esting", 6));
274 test_eq(1, buf_find_string_offset(buf
, "est", 3));
275 test_eq(39, buf_find_string_offset(buf
, "ing str", 7));
276 test_eq(35, buf_find_string_offset(buf
, "Testing str", 11));
277 test_eq(32, buf_find_string_offset(buf
, "ng ", 3));
278 test_eq(43, buf_find_string_offset(buf
, "string.", 7));
279 test_eq(-1, buf_find_string_offset(buf
, "shrdlu", 6));
280 test_eq(-1, buf_find_string_offset(buf
, "Testing thing", 13));
281 test_eq(-1, buf_find_string_offset(buf
, "ngx", 3));
294 s
= open(get_fname("data"), O_WRONLY
|O_CREAT
|O_TRUNC
, 0600);
298 s
= open(get_fname("data"), O_RDONLY
, 0);
300 errno
= 0; /* XXXX */
301 i
= read_to_buf(s
, 10, buf
, &eof
);
302 printf("%s\n", strerror(errno
));
305 //test_eq(buf_capacity(buf), 4096);
306 test_eq(buf_datalen(buf
), 10);
308 test_memeq(str
, (char*)_buf_peek_raw_buffer(buf
), 10);
310 /* Test reading 0 bytes. */
311 i
= read_to_buf(s
, 0, buf
, &eof
);
312 //test_eq(buf_capacity(buf), 512*1024);
313 test_eq(buf_datalen(buf
), 10);
317 /* Now test when buffer is filled exactly. */
318 buf2
= buf_new_with_capacity(6);
319 i
= read_to_buf(s
, 6, buf2
, &eof
);
320 //test_eq(buf_capacity(buf2), 6);
321 test_eq(buf_datalen(buf2
), 6);
324 test_memeq(str
+10, (char*)_buf_peek_raw_buffer(buf2
), 6);
328 /* Now test when buffer is filled with more data to read. */
329 buf2
= buf_new_with_capacity(32);
330 i
= read_to_buf(s
, 128, buf2
, &eof
);
331 //test_eq(buf_capacity(buf2), 128);
332 test_eq(buf_datalen(buf2
), 32);
338 /* Now read to eof. */
339 test_assert(buf_capacity(buf
) > 256);
340 i
= read_to_buf(s
, 1024, buf
, &eof
);
341 test_eq(i
, (256-32-10-6));
342 test_eq(buf_capacity(buf
), MAX_BUF_SIZE
);
343 test_eq(buf_datalen(buf
), 256-6-32);
344 test_memeq(str
, (char*)_buf_peek_raw_buffer(buf
), 10); /* XXX Check rest. */
347 i
= read_to_buf(s
, 1024, buf
, &eof
);
349 test_eq(buf_capacity(buf
), MAX_BUF_SIZE
);
350 test_eq(buf_datalen(buf
), 256-6-32);
365 crypto_dh_env_t
*dh1
= crypto_dh_new();
366 crypto_dh_env_t
*dh2
= crypto_dh_new();
373 test_eq(crypto_dh_get_bytes(dh1
), DH_BYTES
);
374 test_eq(crypto_dh_get_bytes(dh2
), DH_BYTES
);
376 memset(p1
, 0, DH_BYTES
);
377 memset(p2
, 0, DH_BYTES
);
378 test_memeq(p1
, p2
, DH_BYTES
);
379 test_assert(! crypto_dh_get_public(dh1
, p1
, DH_BYTES
));
380 test_memneq(p1
, p2
, DH_BYTES
);
381 test_assert(! crypto_dh_get_public(dh2
, p2
, DH_BYTES
));
382 test_memneq(p1
, p2
, DH_BYTES
);
384 memset(s1
, 0, DH_BYTES
);
385 memset(s2
, 0xFF, DH_BYTES
);
386 s1len
= crypto_dh_compute_secret(dh1
, p2
, DH_BYTES
, s1
, 50);
387 s2len
= crypto_dh_compute_secret(dh2
, p1
, DH_BYTES
, s2
, 50);
388 test_assert(s1len
> 0);
389 test_eq(s1len
, s2len
);
390 test_memeq(s1
, s2
, s1len
);
393 /* XXXX Now fabricate some bad values and make sure they get caught,
394 * Check 0, 1, N-1, >= N, etc.
404 test_crypto_rng(void)
407 char data1
[100], data2
[100];
410 test_assert(! crypto_seed_rng(0));
411 crypto_rand(data1
, 100);
412 crypto_rand(data2
, 100);
413 test_memneq(data1
,data2
,100);
415 for (i
= 0; i
< 100; ++i
) {
418 j
= crypto_rand_int(100);
419 if (i
< 0 || i
>= 100)
421 big
= crypto_rand_uint64(U64_LITERAL(1)<<40);
422 if (big
>= (U64_LITERAL(1)<<40))
424 big
= crypto_rand_uint64(U64_LITERAL(5));
427 host
= crypto_random_hostname(3,8,"www.",".onion");
428 if (strcmpstart(host
,"www.") ||
429 strcmpend(host
,".onion") ||
441 test_crypto_aes(void)
443 char *data1
= NULL
, *data2
= NULL
, *data3
= NULL
;
444 crypto_cipher_env_t
*env1
= NULL
, *env2
= NULL
;
447 data1
= tor_malloc(1024);
448 data2
= tor_malloc(1024);
449 data3
= tor_malloc(1024);
451 /* Now, test encryption and decryption with stream cipher. */
453 for (i
= 1023; i
>0; i
-= 35)
454 strncat(data1
, "Now is the time for all good onions", i
);
456 memset(data2
, 0, 1024);
457 memset(data3
, 0, 1024);
458 env1
= crypto_new_cipher_env();
460 env2
= crypto_new_cipher_env();
462 j
= crypto_cipher_generate_key(env1
);
463 crypto_cipher_set_key(env2
, crypto_cipher_get_key(env1
));
464 crypto_cipher_encrypt_init_cipher(env1
);
465 crypto_cipher_decrypt_init_cipher(env2
);
467 /* Try encrypting 512 chars. */
468 crypto_cipher_encrypt(env1
, data2
, data1
, 512);
469 crypto_cipher_decrypt(env2
, data3
, data2
, 512);
470 test_memeq(data1
, data3
, 512);
471 test_memneq(data1
, data2
, 512);
473 /* Now encrypt 1 at a time, and get 1 at a time. */
474 for (j
= 512; j
< 560; ++j
) {
475 crypto_cipher_encrypt(env1
, data2
+j
, data1
+j
, 1);
477 for (j
= 512; j
< 560; ++j
) {
478 crypto_cipher_decrypt(env2
, data3
+j
, data2
+j
, 1);
480 test_memeq(data1
, data3
, 560);
481 /* Now encrypt 3 at a time, and get 5 at a time. */
482 for (j
= 560; j
< 1024-5; j
+= 3) {
483 crypto_cipher_encrypt(env1
, data2
+j
, data1
+j
, 3);
485 for (j
= 560; j
< 1024-5; j
+= 5) {
486 crypto_cipher_decrypt(env2
, data3
+j
, data2
+j
, 5);
488 test_memeq(data1
, data3
, 1024-5);
489 /* Now make sure that when we encrypt with different chunk sizes, we get
491 crypto_free_cipher_env(env2
);
494 memset(data3
, 0, 1024);
495 env2
= crypto_new_cipher_env();
497 crypto_cipher_set_key(env2
, crypto_cipher_get_key(env1
));
498 crypto_cipher_encrypt_init_cipher(env2
);
499 for (j
= 0; j
< 1024-16; j
+= 17) {
500 crypto_cipher_encrypt(env2
, data3
+j
, data1
+j
, 17);
502 for (j
= 0; j
< 1024-16; ++j
) {
503 if (data2
[j
] != data3
[j
]) {
504 printf("%d: %d\t%d\n", j
, (int) data2
[j
], (int) data3
[j
]);
507 test_memeq(data2
, data3
, 1024-16);
508 crypto_free_cipher_env(env1
);
510 crypto_free_cipher_env(env2
);
513 /* NIST test vector for aes. */
514 env1
= crypto_new_cipher_env(); /* IV starts at 0 */
515 crypto_cipher_set_key(env1
, "\x80\x00\x00\x00\x00\x00\x00\x00"
516 "\x00\x00\x00\x00\x00\x00\x00\x00");
517 crypto_cipher_encrypt_init_cipher(env1
);
518 crypto_cipher_encrypt(env1
, data1
,
519 "\x00\x00\x00\x00\x00\x00\x00\x00"
520 "\x00\x00\x00\x00\x00\x00\x00\x00", 16);
521 test_memeq_hex(data1
, "0EDD33D3C621E546455BD8BA1418BEC8");
523 /* Now test rollover. All these values are originally from a python
525 crypto_cipher_set_iv(env1
, "\x00\x00\x00\x00\x00\x00\x00\x00"
526 "\xff\xff\xff\xff\xff\xff\xff\xff");
527 memset(data2
, 0, 1024);
528 crypto_cipher_encrypt(env1
, data1
, data2
, 32);
529 test_memeq_hex(data1
, "335fe6da56f843199066c14a00a40231"
530 "cdd0b917dbc7186908a6bfb5ffd574d3");
532 crypto_cipher_set_iv(env1
, "\x00\x00\x00\x00\xff\xff\xff\xff"
533 "\xff\xff\xff\xff\xff\xff\xff\xff");
534 memset(data2
, 0, 1024);
535 crypto_cipher_encrypt(env1
, data1
, data2
, 32);
536 test_memeq_hex(data1
, "e627c6423fa2d77832a02b2794094b73"
537 "3e63c721df790d2c6469cc1953a3ffac");
539 crypto_cipher_set_iv(env1
, "\xff\xff\xff\xff\xff\xff\xff\xff"
540 "\xff\xff\xff\xff\xff\xff\xff\xff");
541 memset(data2
, 0, 1024);
542 crypto_cipher_encrypt(env1
, data1
, data2
, 32);
543 test_memeq_hex(data1
, "2aed2bff0de54f9328efd070bf48f70a"
544 "0EDD33D3C621E546455BD8BA1418BEC8");
546 /* Now check rollover on inplace cipher. */
547 crypto_cipher_set_iv(env1
, "\xff\xff\xff\xff\xff\xff\xff\xff"
548 "\xff\xff\xff\xff\xff\xff\xff\xff");
549 crypto_cipher_crypt_inplace(env1
, data2
, 64);
550 test_memeq_hex(data2
, "2aed2bff0de54f9328efd070bf48f70a"
551 "0EDD33D3C621E546455BD8BA1418BEC8"
552 "93e2c5243d6839eac58503919192f7ae"
553 "1908e67cafa08d508816659c2e693191");
554 crypto_cipher_set_iv(env1
, "\xff\xff\xff\xff\xff\xff\xff\xff"
555 "\xff\xff\xff\xff\xff\xff\xff\xff");
556 crypto_cipher_crypt_inplace(env1
, data2
, 64);
557 test_assert(tor_mem_is_zero(data2
, 64));
561 crypto_free_cipher_env(env1
);
563 crypto_free_cipher_env(env2
);
570 test_crypto_sha(void)
572 crypto_digest_env_t
*d1
= NULL
, *d2
= NULL
;
577 char d_out1
[DIGEST_LEN
], d_out2
[DIGEST_LEN
];
579 /* Test SHA-1 with a test vector from the specification. */
580 i
= crypto_digest(data
, "abc", 3);
581 test_memeq_hex(data
, "A9993E364706816ABA3E25717850C26C9CD0D89D");
583 /* Test HMAC-SHA-1 with test cases from RFC2202. */
586 memset(key
, 0x0b, 20);
587 crypto_hmac_sha1(digest
, key
, 20, "Hi There", 8);
588 test_streq(hex_str(digest
, 20),
589 "B617318655057264E28BC0B6FB378C8EF146BE00");
591 crypto_hmac_sha1(digest
, "Jefe", 4, "what do ya want for nothing?", 28);
592 test_streq(hex_str(digest
, 20),
593 "EFFCDF6AE5EB2FA2D27416D5F184DF9C259A7C79");
596 base16_decode(key
, 25,
597 "0102030405060708090a0b0c0d0e0f10111213141516171819", 50);
598 memset(data
, 0xcd, 50);
599 crypto_hmac_sha1(digest
, key
, 25, data
, 50);
600 test_streq(hex_str(digest
, 20),
601 "4C9007F4026250C6BC8414F9BF50C86C2D7235DA");
604 memset(key
, 0xaa, 80);
605 crypto_hmac_sha1(digest
, key
, 80,
606 "Test Using Larger Than Block-Size Key - Hash Key First",
608 test_streq(hex_str(digest
, 20),
609 "AA4AE5E15272D00E95705637CE8A3B55ED402112");
611 /* Incremental digest code. */
612 d1
= crypto_new_digest_env();
614 crypto_digest_add_bytes(d1
, "abcdef", 6);
615 d2
= crypto_digest_dup(d1
);
617 crypto_digest_add_bytes(d2
, "ghijkl", 6);
618 crypto_digest_get_digest(d2
, d_out1
, sizeof(d_out1
));
619 crypto_digest(d_out2
, "abcdefghijkl", 12);
620 test_memeq(d_out1
, d_out2
, DIGEST_LEN
);
621 crypto_digest_assign(d2
, d1
);
622 crypto_digest_add_bytes(d2
, "mno", 3);
623 crypto_digest_get_digest(d2
, d_out1
, sizeof(d_out1
));
624 crypto_digest(d_out2
, "abcdefmno", 9);
625 test_memeq(d_out1
, d_out2
, DIGEST_LEN
);
626 crypto_digest_get_digest(d1
, d_out1
, sizeof(d_out1
));
627 crypto_digest(d_out2
, "abcdef", 6);
628 test_memeq(d_out1
, d_out2
, DIGEST_LEN
);
632 crypto_free_digest_env(d1
);
634 crypto_free_digest_env(d2
);
640 crypto_pk_env_t
*pk1
= NULL
, *pk2
= NULL
;
641 char *encoded
= NULL
;
642 char data1
[1024], data2
[1024], data3
[1024];
646 /* Public-key ciphers */
647 pk1
= pk_generate(0);
648 pk2
= crypto_new_pk_env();
649 test_assert(pk1
&& pk2
);
650 test_assert(! crypto_pk_write_public_key_to_string(pk1
, &encoded
, &size
));
651 test_assert(! crypto_pk_read_public_key_from_string(pk2
, encoded
, size
));
652 test_eq(0, crypto_pk_cmp_keys(pk1
, pk2
));
654 test_eq(128, crypto_pk_keysize(pk1
));
655 test_eq(128, crypto_pk_keysize(pk2
));
657 test_eq(128, crypto_pk_public_encrypt(pk2
, data1
, "Hello whirled.", 15,
658 PK_PKCS1_OAEP_PADDING
));
659 test_eq(128, crypto_pk_public_encrypt(pk1
, data2
, "Hello whirled.", 15,
660 PK_PKCS1_OAEP_PADDING
));
661 /* oaep padding should make encryption not match */
662 test_memneq(data1
, data2
, 128);
663 test_eq(15, crypto_pk_private_decrypt(pk1
, data3
, data1
, 128,
664 PK_PKCS1_OAEP_PADDING
,1));
665 test_streq(data3
, "Hello whirled.");
666 memset(data3
, 0, 1024);
667 test_eq(15, crypto_pk_private_decrypt(pk1
, data3
, data2
, 128,
668 PK_PKCS1_OAEP_PADDING
,1));
669 test_streq(data3
, "Hello whirled.");
670 /* Can't decrypt with public key. */
671 test_eq(-1, crypto_pk_private_decrypt(pk2
, data3
, data2
, 128,
672 PK_PKCS1_OAEP_PADDING
,1));
673 /* Try again with bad padding */
674 memcpy(data2
+1, "XYZZY", 5); /* This has fails ~ once-in-2^40 */
675 test_eq(-1, crypto_pk_private_decrypt(pk1
, data3
, data2
, 128,
676 PK_PKCS1_OAEP_PADDING
,1));
678 /* File operations: save and load private key */
679 test_assert(! crypto_pk_write_private_key_to_filename(pk1
,
680 get_fname("pkey1")));
681 /* failing case for read: can't read. */
682 test_assert(crypto_pk_read_private_key_from_filename(pk2
,
683 get_fname("xyzzy")) < 0);
684 write_str_to_file(get_fname("xyzzy"), "foobar", 6);
685 /* Failing case for read: no key. */
686 test_assert(crypto_pk_read_private_key_from_filename(pk2
,
687 get_fname("xyzzy")) < 0);
688 test_assert(! crypto_pk_read_private_key_from_filename(pk2
,
689 get_fname("pkey1")));
690 test_eq(15, crypto_pk_private_decrypt(pk2
, data3
, data1
, 128,
691 PK_PKCS1_OAEP_PADDING
,1));
693 /* Now try signing. */
694 strlcpy(data1
, "Ossifrage", 1024);
695 test_eq(128, crypto_pk_private_sign(pk1
, data2
, data1
, 10));
696 test_eq(10, crypto_pk_public_checksig(pk1
, data3
, data2
, 128));
697 test_streq(data3
, "Ossifrage");
698 /* Try signing digests. */
699 test_eq(128, crypto_pk_private_sign_digest(pk1
, data2
, data1
, 10));
700 test_eq(20, crypto_pk_public_checksig(pk1
, data3
, data2
, 128));
701 test_eq(0, crypto_pk_public_checksig_digest(pk1
, data1
, 10, data2
, 128));
702 test_eq(-1, crypto_pk_public_checksig_digest(pk1
, data1
, 11, data2
, 128));
703 /*XXXX test failed signing*/
706 crypto_free_pk_env(pk2
);
708 i
= crypto_pk_asn1_encode(pk1
, data1
, 1024);
710 pk2
= crypto_pk_asn1_decode(data1
, i
);
711 test_assert(crypto_pk_cmp_keys(pk1
,pk2
) == 0);
713 /* Try with hybrid encryption wrappers. */
714 crypto_rand(data1
, 1024);
715 for (i
= 0; i
< 3; ++i
) {
716 for (j
= 85; j
< 140; ++j
) {
717 memset(data2
,0,1024);
718 memset(data3
,0,1024);
719 if (i
== 0 && j
< 129)
721 p
= (i
==0)?PK_NO_PADDING
:
722 (i
==1)?PK_PKCS1_PADDING
:PK_PKCS1_OAEP_PADDING
;
723 len
= crypto_pk_public_hybrid_encrypt(pk1
,data2
,data1
,j
,p
,0);
725 len
= crypto_pk_private_hybrid_decrypt(pk1
,data3
,data2
,len
,p
,1);
727 test_memeq(data1
,data3
,j
);
732 crypto_free_pk_env(pk1
);
734 crypto_free_pk_env(pk2
);
741 char *data1
= NULL
, *data2
= NULL
, *data3
= NULL
;
744 data1
= tor_malloc(1024);
745 data2
= tor_malloc(1024);
746 data3
= tor_malloc(1024);
747 test_assert(data1
&& data2
&& data3
);
750 memset(data1
, 6, 1024);
751 for (idx
= 0; idx
< 10; ++idx
) {
752 i
= base64_encode(data2
, 1024, data1
, idx
);
753 j
= base64_decode(data3
, 1024, data2
, i
);
755 test_memeq(data3
, data1
, idx
);
758 strlcpy(data1
, "Test string that contains 35 chars.", 1024);
759 strlcat(data1
, " 2nd string that contains 35 chars.", 1024);
761 i
= base64_encode(data2
, 1024, data1
, 71);
762 j
= base64_decode(data3
, 1024, data2
, i
);
764 test_streq(data3
, data1
);
765 test_assert(data2
[i
] == '\0');
767 crypto_rand(data1
, DIGEST_LEN
);
768 memset(data2
, 100, 1024);
769 digest_to_base64(data2
, data1
);
770 test_eq(BASE64_DIGEST_LEN
, strlen(data2
));
771 test_eq(100, data2
[BASE64_DIGEST_LEN
+2]);
772 memset(data3
, 99, 1024);
773 test_eq(digest_from_base64(data3
, data2
), 0);
774 test_memeq(data1
, data3
, DIGEST_LEN
);
775 test_eq(99, data3
[DIGEST_LEN
+1]);
777 test_assert(digest_from_base64(data3
, "###") < 0);
780 strlcpy(data1
, "5chrs", 1024);
781 /* bit pattern is: [35 63 68 72 73] ->
782 * [00110101 01100011 01101000 01110010 01110011]
783 * By 5s: [00110 10101 10001 10110 10000 11100 10011 10011]
785 base32_encode(data2
, 9, data1
, 5);
786 test_streq(data2
, "gvrwq4tt");
788 strlcpy(data1
, "\xFF\xF5\x6D\x44\xAE\x0D\x5C\xC9\x62\xC4", 1024);
789 base32_encode(data2
, 30, data1
, 10);
790 test_streq(data2
, "772w2rfobvomsywe");
793 strlcpy(data1
, "6chrs\xff", 1024);
794 base16_encode(data2
, 13, data1
, 6);
795 test_streq(data2
, "3663687273FF");
797 strlcpy(data1
, "f0d678affc000100", 1024);
798 i
= base16_decode(data2
, 8, data1
, 16);
800 test_memeq(data2
, "\xf0\xd6\x78\xaf\xfc\x00\x01\x00",8);
802 /* now try some failing base16 decodes */
803 test_eq(-1, base16_decode(data2
, 8, data1
, 15)); /* odd input len */
804 test_eq(-1, base16_decode(data2
, 7, data1
, 16)); /* dest too short */
805 strlcpy(data1
, "f0dz!8affc000100", 1024);
806 test_eq(-1, base16_decode(data2
, 8, data1
, 16));
812 /* Add spaces to fingerprint */
814 data1
= tor_strdup("ABCD1234ABCD56780000ABCD1234ABCD56780000");
815 test_eq(strlen(data1
), 40);
816 data2
= tor_malloc(FINGERPRINT_LEN
+1);
817 add_spaces_to_fp(data2
, FINGERPRINT_LEN
+1, data1
);
818 test_streq(data2
, "ABCD 1234 ABCD 5678 0000 ABCD 1234 ABCD 5678 0000");
823 /* Check fingerprint */
825 test_assert(crypto_pk_check_fingerprint_syntax(
826 "ABCD 1234 ABCD 5678 0000 ABCD 1234 ABCD 5678 0000"));
827 test_assert(!crypto_pk_check_fingerprint_syntax(
828 "ABCD 1234 ABCD 5678 0000 ABCD 1234 ABCD 5678 000"));
829 test_assert(!crypto_pk_check_fingerprint_syntax(
830 "ABCD 1234 ABCD 5678 0000 ABCD 1234 ABCD 5678 00000"));
831 test_assert(!crypto_pk_check_fingerprint_syntax(
832 "ABCD 1234 ABCD 5678 0000 ABCD1234 ABCD 5678 0000"));
833 test_assert(!crypto_pk_check_fingerprint_syntax(
834 "ABCD 1234 ABCD 5678 0000 ABCD1234 ABCD 5678 00000"));
835 test_assert(!crypto_pk_check_fingerprint_syntax(
836 "ACD 1234 ABCD 5678 0000 ABCD 1234 ABCD 5678 00000"));
846 test_crypto_s2k(void)
853 memset(buf
, 0, sizeof(buf
));
854 memset(buf2
, 0, sizeof(buf2
));
855 buf3
= tor_malloc(65536);
856 memset(buf3
, 0, 65536);
858 secret_to_key(buf
+9, 20, "", 0, buf
);
859 crypto_digest(buf2
+9, buf3
, 1024);
860 test_memeq(buf
, buf2
, 29);
862 memcpy(buf
,"vrbacrda",8);
863 memcpy(buf2
,"vrbacrda",8);
866 secret_to_key(buf
+9, 20, "12345678", 8, buf
);
867 for (i
= 0; i
< 65536; i
+= 16) {
868 memcpy(buf3
+i
, "vrbacrda12345678", 16);
870 crypto_digest(buf2
+9, buf3
, 65536);
871 test_memeq(buf
, buf2
, 29);
878 _compare_strs(const void **a
, const void **b
)
880 const char *s1
= *a
, *s2
= *b
;
881 return strcmp(s1
, s2
);
885 _compare_without_first_ch(const void *a
, const void **b
)
887 const char *s1
= a
, *s2
= *b
;
888 return strcasecmp(s1
+1, s2
);
894 struct timeval start
, end
;
896 char timestr
[RFC1123_TIME_LEN
+1];
906 start
.tv_usec
= 5000;
911 test_eq(0L, tv_udiff(&start
, &end
));
915 test_eq(2000L, tv_udiff(&start
, &end
));
919 test_eq(1002000L, tv_udiff(&start
, &end
));
923 test_eq(995000L, tv_udiff(&start
, &end
));
927 test_eq(-1005000L, tv_udiff(&start
, &end
));
929 end
.tv_usec
= 999990;
933 /* The test values here are confirmed to be correct on a platform
934 * with a working timegm. */
935 a_time
.tm_year
= 2003-1900;
941 test_eq((time_t) 1062224095UL, tor_timegm(&a_time
));
942 a_time
.tm_year
= 2004-1900; /* Try a leap year, after feb. */
943 test_eq((time_t) 1093846495UL, tor_timegm(&a_time
));
944 a_time
.tm_mon
= 1; /* Try a leap year, in feb. */
946 test_eq((time_t) 1076393695UL, tor_timegm(&a_time
));
948 format_rfc1123_time(timestr
, 0);
949 test_streq("Thu, 01 Jan 1970 00:00:00 GMT", timestr
);
950 format_rfc1123_time(timestr
, (time_t)1091580502UL);
951 test_streq("Wed, 04 Aug 2004 00:48:22 GMT", timestr
);
954 i
= parse_rfc1123_time(timestr
, &t_res
);
956 test_eq(t_res
, (time_t)1091580502UL);
957 test_eq(-1, parse_rfc1123_time("Wed, zz Aug 2004 99-99x99 GMT", &t_res
));
958 tor_gettimeofday(&start
);
960 /* Tests for corner cases of strl operations */
961 test_eq(5, strlcpy(buf
, "Hello", 0));
962 strlcpy(buf
, "Hello", sizeof(buf
));
963 test_eq(10, strlcat(buf
, "Hello", 5));
965 /* Test tor_strstrip() */
966 strlcpy(buf
, "Testing 1 2 3", sizeof(buf
));
967 tor_strstrip(buf
, ",!");
968 test_streq(buf
, "Testing 1 2 3");
969 strlcpy(buf
, "!Testing 1 2 3?", sizeof(buf
));
970 tor_strstrip(buf
, "!? ");
971 test_streq(buf
, "Testing123");
973 /* Test parse_addr_port */
974 cp
= NULL
; u32
= 3; u16
= 3;
975 test_assert(!parse_addr_port(LOG_WARN
, "1.2.3.4", &cp
, &u32
, &u16
));
976 test_streq(cp
, "1.2.3.4");
977 test_eq(u32
, 0x01020304u
);
980 test_assert(!parse_addr_port(LOG_WARN
, "4.3.2.1:99", &cp
, &u32
, &u16
));
981 test_streq(cp
, "4.3.2.1");
982 test_eq(u32
, 0x04030201u
);
985 test_assert(!parse_addr_port(LOG_WARN
, "nonexistent.address:4040",
987 test_streq(cp
, "nonexistent.address");
990 test_assert(!parse_addr_port(LOG_WARN
, "localhost:9999", &cp
, &u32
, &u16
));
991 test_streq(cp
, "localhost");
992 test_eq(u32
, 0x7f000001u
);
996 test_assert(!parse_addr_port(LOG_WARN
, "localhost", NULL
, &u32
, &u16
));
998 test_eq(u32
, 0x7f000001u
);
1001 test_eq(0, addr_mask_get_bits(0x0u
));
1002 test_eq(32, addr_mask_get_bits(0xFFFFFFFFu
));
1003 test_eq(16, addr_mask_get_bits(0xFFFF0000u
));
1004 test_eq(31, addr_mask_get_bits(0xFFFFFFFEu
));
1005 test_eq(1, addr_mask_get_bits(0x80000000u
));
1007 /* Test tor_parse_long. */
1008 test_eq(10L, tor_parse_long("10",10,0,100,NULL
,NULL
));
1009 test_eq(0L, tor_parse_long("10",10,50,100,NULL
,NULL
));
1010 test_eq(-50L, tor_parse_long("-50",10,-100,100,NULL
,NULL
));
1012 /* Test tor_parse_ulong */
1013 test_eq(10UL, tor_parse_ulong("10",10,0,100,NULL
,NULL
));
1014 test_eq(0UL, tor_parse_ulong("10",10,50,100,NULL
,NULL
));
1016 /* Test tor_parse_uint64. */
1017 test_assert(U64_LITERAL(10) == tor_parse_uint64("10 x",10,0,100, &i
, &cp
));
1018 test_assert(i
== 1);
1019 test_streq(cp
, " x");
1020 test_assert(U64_LITERAL(12345678901) ==
1021 tor_parse_uint64("12345678901",10,0,UINT64_MAX
, &i
, &cp
));
1022 test_assert(i
== 1);
1024 test_assert(U64_LITERAL(0) ==
1025 tor_parse_uint64("12345678901",10,500,INT32_MAX
, &i
, &cp
));
1026 test_assert(i
== 0);
1028 /* Test failing snprintf cases */
1029 test_eq(-1, tor_snprintf(buf
, 0, "Foo"));
1030 test_eq(-1, tor_snprintf(buf
, 2, "Foo"));
1032 /* Test printf with uint64 */
1033 tor_snprintf(buf
, sizeof(buf
), "x!"U64_FORMAT
"!x",
1034 U64_PRINTF_ARG(U64_LITERAL(12345678901)));
1035 test_streq(buf
, "x!12345678901!x");
1037 /* Test parse_config_line_from_str */
1038 strlcpy(buf
, "k v\n" " key value with spaces \n" "keykey val\n"
1040 "k3 \n" "\n" " \n" "#comment\n"
1041 "k4#a\n" "k5#abc\n" "k6 val #with comment\n"
1042 "kseven \"a quoted 'string\"\n"
1043 "k8 \"a \\x71uoted\\n\\\"str\\\\ing\\t\\001\\01\\1\\\"\"\n"
1047 str
= parse_config_line_from_str(str
, &k
, &v
);
1050 tor_free(k
); tor_free(v
);
1051 test_assert(!strcmpstart(str
, "key value with"));
1053 str
= parse_config_line_from_str(str
, &k
, &v
);
1054 test_streq(k
, "key");
1055 test_streq(v
, "value with spaces");
1056 tor_free(k
); tor_free(v
);
1057 test_assert(!strcmpstart(str
, "keykey"));
1059 str
= parse_config_line_from_str(str
, &k
, &v
);
1060 test_streq(k
, "keykey");
1061 test_streq(v
, "val");
1062 tor_free(k
); tor_free(v
);
1063 test_assert(!strcmpstart(str
, "k2\n"));
1065 str
= parse_config_line_from_str(str
, &k
, &v
);
1066 test_streq(k
, "k2");
1068 tor_free(k
); tor_free(v
);
1069 test_assert(!strcmpstart(str
, "k3 \n"));
1071 str
= parse_config_line_from_str(str
, &k
, &v
);
1072 test_streq(k
, "k3");
1074 tor_free(k
); tor_free(v
);
1075 test_assert(!strcmpstart(str
, "#comment"));
1077 str
= parse_config_line_from_str(str
, &k
, &v
);
1078 test_streq(k
, "k4");
1080 tor_free(k
); tor_free(v
);
1081 test_assert(!strcmpstart(str
, "k5#abc"));
1083 str
= parse_config_line_from_str(str
, &k
, &v
);
1084 test_streq(k
, "k5");
1086 tor_free(k
); tor_free(v
);
1087 test_assert(!strcmpstart(str
, "k6"));
1089 str
= parse_config_line_from_str(str
, &k
, &v
);
1090 test_streq(k
, "k6");
1091 test_streq(v
, "val");
1092 tor_free(k
); tor_free(v
);
1093 test_assert(!strcmpstart(str
, "kseven"));
1095 str
= parse_config_line_from_str(str
, &k
, &v
);
1096 test_streq(k
, "kseven");
1097 test_streq(v
, "a quoted 'string");
1098 tor_free(k
); tor_free(v
);
1099 test_assert(!strcmpstart(str
, "k8 "));
1101 str
= parse_config_line_from_str(str
, &k
, &v
);
1102 test_streq(k
, "k8");
1103 test_streq(v
, "a quoted\n\"str\\ing\t\x01\x01\x01\"");
1104 tor_free(k
); tor_free(v
);
1105 test_streq(str
, "");
1107 /* Test for strcmpstart and strcmpend. */
1108 test_assert(strcmpstart("abcdef", "abcdef")==0);
1109 test_assert(strcmpstart("abcdef", "abc")==0);
1110 test_assert(strcmpstart("abcdef", "abd")<0);
1111 test_assert(strcmpstart("abcdef", "abb")>0);
1112 test_assert(strcmpstart("ab", "abb")<0);
1114 test_assert(strcmpend("abcdef", "abcdef")==0);
1115 test_assert(strcmpend("abcdef", "def")==0);
1116 test_assert(strcmpend("abcdef", "deg")<0);
1117 test_assert(strcmpend("abcdef", "dee")>0);
1118 test_assert(strcmpend("ab", "abb")<0);
1120 test_assert(strcasecmpend("AbcDEF", "abcdef")==0);
1121 test_assert(strcasecmpend("abcdef", "dEF")==0);
1122 test_assert(strcasecmpend("abcDEf", "deg")<0);
1123 test_assert(strcasecmpend("abcdef", "DEE")>0);
1124 test_assert(strcasecmpend("ab", "abB")<0);
1126 /* Test mem_is_zero */
1129 test_assert(tor_digest_is_zero(buf
));
1130 test_assert(tor_mem_is_zero(buf
, 10));
1131 test_assert(tor_mem_is_zero(buf
, 20));
1132 test_assert(tor_mem_is_zero(buf
, 128));
1133 test_assert(!tor_mem_is_zero(buf
, 129));
1134 buf
[60] = (char)255;
1135 test_assert(!tor_mem_is_zero(buf
, 128));
1137 test_assert(!tor_mem_is_zero(buf
, 10));
1139 /* Test inet_ntop */
1141 char tmpbuf
[TOR_ADDR_BUF_LEN
];
1142 const char *ip
= "176.192.208.224";
1144 tor_inet_pton(AF_INET
, ip
, &in
);
1145 tor_inet_ntop(AF_INET
, &in
, tmpbuf
, sizeof(tmpbuf
));
1146 test_streq(tmpbuf
, ip
);
1149 /* Test 'escaped' */
1150 test_streq("\"\"", escaped(""));
1151 test_streq("\"abcd\"", escaped("abcd"));
1152 test_streq("\"\\\\\\n\\r\\t\\\"\\'\"", escaped("\\\n\r\t\"\'"));
1153 test_streq("\"z\\001abc\\277d\"", escaped("z\001abc\277d"));
1154 test_assert(NULL
== escaped(NULL
));
1156 /* Test strndup and memdup */
1158 const char *s
= "abcdefghijklmnopqrstuvwxyz";
1159 cp
= tor_strndup(s
, 30);
1160 test_streq(cp
, s
); /* same string, */
1161 test_neq(cp
, s
); /* but different pointers. */
1164 cp
= tor_strndup(s
, 5);
1165 test_streq(cp
, "abcde");
1168 s
= "a\0b\0c\0d\0e\0";
1169 cp
= tor_memdup(s
,10);
1170 test_memeq(cp
, s
, 10); /* same ram, */
1171 test_neq(cp
, s
); /* but different pointers. */
1175 /* Test str-foo functions */
1176 cp
= tor_strdup("abcdef");
1177 test_assert(tor_strisnonupper(cp
));
1179 test_assert(!tor_strisnonupper(cp
));
1181 test_streq(cp
, "ABCDEF");
1182 test_assert(tor_strisprint(cp
));
1184 test_assert(!tor_strisprint(cp
));
1187 /* Test eat_whitespace. */
1189 const char *s
= " \n a";
1190 test_eq_ptr(eat_whitespace(s
), s
+4);
1192 test_eq_ptr(eat_whitespace(s
), s
);
1194 test_eq_ptr(eat_whitespace(s
), s
+5);
1197 /* Test memmem and memstr */
1199 const char *haystack
= "abcde";
1200 tor_assert(!tor_memmem(haystack
, 5, "ef", 2));
1201 test_eq_ptr(tor_memmem(haystack
, 5, "cd", 2), haystack
+ 2);
1202 test_eq_ptr(tor_memmem(haystack
, 5, "cde", 3), haystack
+ 2);
1203 haystack
= "ababcad";
1204 test_eq_ptr(tor_memmem(haystack
, 7, "abc", 3), haystack
+ 2);
1205 test_eq_ptr(tor_memstr(haystack
, 7, "abc"), haystack
+ 2);
1206 test_assert(!tor_memstr(haystack
, 7, "fe"));
1207 test_assert(!tor_memstr(haystack
, 7, "longerthantheoriginal"));
1210 /* Test wrap_string */
1212 smartlist_t
*sl
= smartlist_create();
1213 wrap_string(sl
, "This is a test of string wrapping functionality: woot.",
1215 cp
= smartlist_join_strings(sl
, "", 0, NULL
);
1217 "This is a\ntest of\nstring\nwrapping\nfunctional\nity: woot.\n");
1219 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1220 smartlist_clear(sl
);
1222 wrap_string(sl
, "This is a test of string wrapping functionality: woot.",
1224 cp
= smartlist_join_strings(sl
, "", 0, NULL
);
1226 "### This is a\n# test of string\n# wrapping\n# functionality:\n"
1230 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1234 /* now make sure time works. */
1235 tor_gettimeofday(&end
);
1236 /* We might've timewarped a little. */
1237 test_assert(tv_udiff(&start
, &end
) >= -5000);
1239 /* Test tor_log2(). */
1240 test_eq(tor_log2(64), 6);
1241 test_eq(tor_log2(65), 6);
1242 test_eq(tor_log2(63), 5);
1243 test_eq(tor_log2(1), 0);
1244 test_eq(tor_log2(2), 1);
1245 test_eq(tor_log2(3), 1);
1246 test_eq(tor_log2(4), 2);
1247 test_eq(tor_log2(5), 2);
1248 test_eq(tor_log2(U64_LITERAL(40000000000000000)), 55);
1249 test_eq(tor_log2(UINT64_MAX
), 63);
1251 /* Test round_to_power_of_2 */
1252 test_eq(round_to_power_of_2(120), 128);
1253 test_eq(round_to_power_of_2(128), 128);
1254 test_eq(round_to_power_of_2(130), 128);
1255 test_eq(round_to_power_of_2(U64_LITERAL(40000000000000000)),
1256 U64_LITERAL(1)<<55);
1257 test_eq(round_to_power_of_2(0), 2);
1263 /** Helper: assert that IPv6 addresses <b>a</b> and <b>b</b> are the same. On
1264 * failure, reports an error, describing the addresses as <b>e1</b> and
1265 * <b>e2</b>, and reporting the line number as <b>line</b>. */
1267 _test_eq_ip6(struct in6_addr
*a
, struct in6_addr
*b
, const char *e1
,
1268 const char *e2
, int line
)
1272 for (i
= 0; i
< 16; ++i
) {
1273 if (a
->s6_addr
[i
] != b
->s6_addr
[i
]) {
1279 printf("."); fflush(stdout
);
1281 char buf1
[128], *cp1
;
1282 char buf2
[128], *cp2
;
1284 cp1
= buf1
; cp2
= buf2
;
1285 for (i
=0; i
<16; ++i
) {
1286 tor_snprintf(cp1
, sizeof(buf1
)-(cp1
-buf1
), "%02x", a
->s6_addr
[i
]);
1287 tor_snprintf(cp2
, sizeof(buf2
)-(cp2
-buf2
), "%02x", b
->s6_addr
[i
]);
1289 if ((i
%2)==1 && i
!= 15) {
1295 printf("Line %d: assertion failed: (%s == %s)\n"
1296 " %s != %s\n", line
, e1
, e2
, buf1
, buf2
);
1301 /** Helper: Assert that two strings both decode as IPv6 addresses with
1302 * tor_inet_pton(), and both decode to the same address. */
1303 #define test_pton6_same(a,b) STMT_BEGIN \
1304 test_eq(tor_inet_pton(AF_INET6, a, &a1), 1); \
1305 test_eq(tor_inet_pton(AF_INET6, b, &a2), 1); \
1306 _test_eq_ip6(&a1,&a2,#a,#b,__LINE__); \
1309 /** Helper: Assert that <b>a</b> is recognized as a bad IPv6 address by
1310 * tor_inet_pton(). */
1311 #define test_pton6_bad(a) \
1312 test_eq(0, tor_inet_pton(AF_INET6, a, &a1))
1314 /** Helper: assert that <b>a</b>, when parsed by tor_inet_pton() and displayed
1315 * with tor_inet_ntop(), yields <b>b</b>. Also assert that <b>b</b> parses to
1316 * the same value as <b>a</b>. */
1317 #define test_ntop6_reduces(a,b) STMT_BEGIN \
1318 test_eq(tor_inet_pton(AF_INET6, a, &a1), 1); \
1319 test_streq(tor_inet_ntop(AF_INET6, &a1, buf, sizeof(buf)), b); \
1320 test_eq(tor_inet_pton(AF_INET6, b, &a2), 1); \
1321 _test_eq_ip6(&a1, &a2, a, b, __LINE__); \
1324 /** Helper: assert that <b>a</a> parses by tor_inet_pton() into a address that
1325 * passes tor_addr_is_internal() with <b>for_listening</b> */
1326 #define test_internal_ip(a,for_listening) STMT_BEGIN \
1327 test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
1328 t1.family = AF_INET6; \
1329 if (!tor_addr_is_internal(&t1, for_listening)) \
1330 test_fail_msg( a "was not internal."); \
1333 /** Helper: assert that <b>a</a> parses by tor_inet_pton() into a address that
1334 * does not pass tor_addr_is_internal() with <b>for_listening</b>. */
1335 #define test_external_ip(a,for_listening) STMT_BEGIN \
1336 test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
1337 t1.family = AF_INET6; \
1338 if (tor_addr_is_internal(&t1, for_listening)) \
1339 test_fail_msg(a "was not external."); \
1342 /** Helper: Assert that <b>a</b> and <b>b</b>, when parsed by
1343 * tor_inet_pton(), give addresses that compare in the order defined by
1344 * <b>op</b> with tor_addr_compare(). */
1345 #define test_addr_compare(a, op, b) STMT_BEGIN \
1346 test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
1347 test_eq(tor_inet_pton(AF_INET6, b, &t2.addr.in6_addr), 1); \
1348 t1.family = t2.family = AF_INET6; \
1349 r = tor_addr_compare(&t1,&t2,CMP_SEMANTIC); \
1351 test_fail_msg("failed: tor_addr_compare("a","b") "#op" 0"); \
1354 /** Helper: Assert that <b>a</b> and <b>b</b>, when parsed by
1355 * tor_inet_pton(), give addresses that compare in the order defined by
1356 * <b>op</b> with tor_addr_compare_masked() with <b>m</b> masked. */
1357 #define test_addr_compare_masked(a, op, b, m) STMT_BEGIN \
1358 test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
1359 test_eq(tor_inet_pton(AF_INET6, b, &t2.addr.in6_addr), 1); \
1360 t1.family = t2.family = AF_INET6; \
1361 r = tor_addr_compare_masked(&t1,&t2,m,CMP_SEMANTIC); \
1363 test_fail_msg("failed: tor_addr_compare_masked("a","b","#m") "#op" 0"); \
1366 /** Helper: assert that <b>xx</b> is parseable as a masked IPv6 address with
1367 * ports by <b>tor_parse_mask_addr_ports(), with family <b>f</b>, IP address
1368 * as 4 32-bit words <b>ip1...ip4</b>, mask bits as <b>mm</b>, and port range
1369 * as <b>pt1..pt2</b>. */
1370 #define test_addr_mask_ports_parse(xx, f, ip1, ip2, ip3, ip4, mm, pt1, pt2) \
1372 test_eq(tor_addr_parse_mask_ports(xx, &t1, &mask, &port1, &port2), f); \
1373 p1=tor_inet_ntop(AF_INET6, &t1.addr.in6_addr, bug, sizeof(bug)); \
1374 test_eq(htonl(ip1), tor_addr_to_in6_addr32(&t1)[0]); \
1375 test_eq(htonl(ip2), tor_addr_to_in6_addr32(&t1)[1]); \
1376 test_eq(htonl(ip3), tor_addr_to_in6_addr32(&t1)[2]); \
1377 test_eq(htonl(ip4), tor_addr_to_in6_addr32(&t1)[3]); \
1378 test_eq(mask, mm); \
1379 test_eq(port1, pt1); \
1380 test_eq(port2, pt2); \
1384 test_util_ip6_helpers(void)
1386 char buf
[TOR_ADDR_BUF_LEN
], bug
[TOR_ADDR_BUF_LEN
];
1387 struct in6_addr a1
, a2
;
1390 uint16_t port1
, port2
;
1393 struct sockaddr_storage sa_storage
;
1394 struct sockaddr_in
*sin
;
1395 struct sockaddr_in6
*sin6
;
1397 // struct in_addr b1, b2;
1398 /* Test tor_inet_ntop and tor_inet_pton: IPv6 */
1400 /* ==== Converting to and from sockaddr_t. */
1401 sin
= (struct sockaddr_in
*)&sa_storage
;
1402 sin
->sin_family
= AF_INET
;
1403 sin
->sin_port
= 9090;
1404 sin
->sin_addr
.s_addr
= htonl(0x7f7f0102); /*127.127.1.2*/
1405 tor_addr_from_sockaddr(&t1
, (struct sockaddr
*)sin
, NULL
);
1406 test_eq(tor_addr_family(&t1
), AF_INET
);
1407 test_eq(tor_addr_to_ipv4h(&t1
), 0x7f7f0102);
1409 memset(&sa_storage
, 0, sizeof(sa_storage
));
1410 test_eq(sizeof(struct sockaddr_in
),
1411 tor_addr_to_sockaddr(&t1
, 1234, (struct sockaddr
*)&sa_storage
,
1412 sizeof(sa_storage
)));
1413 test_eq(1234, ntohs(sin
->sin_port
));
1414 test_eq(0x7f7f0102, ntohl(sin
->sin_addr
.s_addr
));
1416 memset(&sa_storage
, 0, sizeof(sa_storage
));
1417 sin6
= (struct sockaddr_in6
*)&sa_storage
;
1418 sin6
->sin6_family
= AF_INET6
;
1419 sin6
->sin6_port
= htons(7070);
1420 sin6
->sin6_addr
.s6_addr
[0] = 128;
1421 tor_addr_from_sockaddr(&t1
, (struct sockaddr
*)sin6
, NULL
);
1422 test_eq(tor_addr_family(&t1
), AF_INET6
);
1423 p1
= tor_addr_to_str(buf
, &t1
, sizeof(buf
), 0);
1424 test_streq(p1
, "8000::");
1426 memset(&sa_storage
, 0, sizeof(sa_storage
));
1427 test_eq(sizeof(struct sockaddr_in6
),
1428 tor_addr_to_sockaddr(&t1
, 9999, (struct sockaddr
*)&sa_storage
,
1429 sizeof(sa_storage
)));
1430 test_eq(AF_INET6
, sin6
->sin6_family
);
1431 test_eq(9999, ntohs(sin6
->sin6_port
));
1432 test_eq(0x80000000, ntohl(S6_ADDR32(sin6
->sin6_addr
)[0]));
1434 /* ==== tor_addr_lookup: static cases. (Can't test dns without knowing we
1435 * have a good resolver. */
1436 test_eq(0, tor_addr_lookup("127.128.129.130", AF_UNSPEC
, &t1
));
1437 test_eq(AF_INET
, tor_addr_family(&t1
));
1438 test_eq(tor_addr_to_ipv4h(&t1
), 0x7f808182);
1440 test_eq(0, tor_addr_lookup("9000::5", AF_UNSPEC
, &t1
));
1441 test_eq(AF_INET6
, tor_addr_family(&t1
));
1442 test_eq(0x90, tor_addr_to_in6_addr8(&t1
)[0]);
1443 test_assert(tor_mem_is_zero((char*)tor_addr_to_in6_addr8(&t1
)+1, 14));
1444 test_eq(0x05, tor_addr_to_in6_addr8(&t1
)[15]);
1446 /* === Test pton: valid af_inet6 */
1447 /* Simple, valid parsing. */
1448 r
= tor_inet_pton(AF_INET6
,
1449 "0102:0304:0506:0708:090A:0B0C:0D0E:0F10", &a1
);
1451 for (i
=0;i
<16;++i
) { test_eq(i
+1, (int)a1
.s6_addr
[i
]); }
1453 test_pton6_same("0102:0304:0506:0708:090A:0B0C:0D0E:0F10",
1454 "0102:0304:0506:0708:090A:0B0C:13.14.15.16");
1455 /* shortened words. */
1456 test_pton6_same("0001:0099:BEEF:0000:0123:FFFF:0001:0001",
1457 "1:99:BEEF:0:0123:FFFF:1:1");
1458 /* zeros at the beginning */
1459 test_pton6_same("0000:0000:0000:0000:0009:C0A8:0001:0001",
1461 test_pton6_same("0000:0000:0000:0000:0009:C0A8:0001:0001",
1462 "::9:c0a8:0.1.0.1");
1463 /* zeros in the middle. */
1464 test_pton6_same("fe80:0000:0000:0000:0202:1111:0001:0001",
1465 "fe80::202:1111:1:1");
1466 /* zeros at the end. */
1467 test_pton6_same("1000:0001:0000:0007:0000:0000:0000:0000",
1470 /* === Test ntop: af_inet6 */
1471 test_ntop6_reduces("0:0:0:0:0:0:0:0", "::");
1473 test_ntop6_reduces("0001:0099:BEEF:0006:0123:FFFF:0001:0001",
1474 "1:99:beef:6:123:ffff:1:1");
1476 //test_ntop6_reduces("0:0:0:0:0:0:c0a8:0101", "::192.168.1.1");
1477 test_ntop6_reduces("0:0:0:0:0:ffff:c0a8:0101", "::ffff:192.168.1.1");
1478 test_ntop6_reduces("002:0:0000:0:3::4", "2::3:0:0:4");
1479 test_ntop6_reduces("0:0::1:0:3", "::1:0:3");
1480 test_ntop6_reduces("008:0::0", "8::");
1481 test_ntop6_reduces("0:0:0:0:0:ffff::1", "::ffff:0.0.0.1");
1482 test_ntop6_reduces("abcd:0:0:0:0:0:7f00::", "abcd::7f00:0");
1483 test_ntop6_reduces("0000:0000:0000:0000:0009:C0A8:0001:0001",
1485 test_ntop6_reduces("fe80:0000:0000:0000:0202:1111:0001:0001",
1486 "fe80::202:1111:1:1");
1487 test_ntop6_reduces("1000:0001:0000:0007:0000:0000:0000:0000",
1490 /* === Test pton: invalid in6. */
1491 test_pton6_bad("foobar.");
1492 test_pton6_bad("55555::");
1493 test_pton6_bad("9:-60::");
1494 test_pton6_bad("1:2:33333:4:0002:3::");
1495 //test_pton6_bad("1:2:3333:4:00002:3::");// BAD, but glibc doesn't say so.
1496 test_pton6_bad("1:2:3333:4:fish:3::");
1497 test_pton6_bad("1:2:3:4:5:6:7:8:9");
1498 test_pton6_bad("1:2:3:4:5:6:7");
1499 test_pton6_bad("1:2:3:4:5:6:1.2.3.4.5");
1500 test_pton6_bad("1:2:3:4:5:6:1.2.3");
1501 test_pton6_bad("::1.2.3");
1502 test_pton6_bad("::1.2.3.4.5");
1503 test_pton6_bad("99");
1505 test_pton6_bad("1::2::3:4");
1506 test_pton6_bad("a:::b:c");
1507 test_pton6_bad(":::a:b:c");
1508 test_pton6_bad("a:b:c:::");
1510 /* test internal checking */
1511 test_external_ip("fbff:ffff::2:7", 0);
1512 test_internal_ip("fc01::2:7", 0);
1513 test_internal_ip("fdff:ffff::f:f", 0);
1514 test_external_ip("fe00::3:f", 0);
1516 test_external_ip("fe7f:ffff::2:7", 0);
1517 test_internal_ip("fe80::2:7", 0);
1518 test_internal_ip("febf:ffff::f:f", 0);
1520 test_internal_ip("fec0::2:7:7", 0);
1521 test_internal_ip("feff:ffff::e:7:7", 0);
1522 test_external_ip("ff00::e:7:7", 0);
1524 test_internal_ip("::", 0);
1525 test_internal_ip("::1", 0);
1526 test_internal_ip("::1", 1);
1527 test_internal_ip("::", 0);
1528 test_external_ip("::", 1);
1529 test_external_ip("::2", 0);
1530 test_external_ip("2001::", 0);
1531 test_external_ip("ffff::", 0);
1533 test_external_ip("::ffff:0.0.0.0", 1);
1534 test_internal_ip("::ffff:0.0.0.0", 0);
1535 test_internal_ip("::ffff:0.255.255.255", 0);
1536 test_external_ip("::ffff:1.0.0.0", 0);
1538 test_external_ip("::ffff:9.255.255.255", 0);
1539 test_internal_ip("::ffff:10.0.0.0", 0);
1540 test_internal_ip("::ffff:10.255.255.255", 0);
1541 test_external_ip("::ffff:11.0.0.0", 0);
1543 test_external_ip("::ffff:126.255.255.255", 0);
1544 test_internal_ip("::ffff:127.0.0.0", 0);
1545 test_internal_ip("::ffff:127.255.255.255", 0);
1546 test_external_ip("::ffff:128.0.0.0", 0);
1548 test_external_ip("::ffff:172.15.255.255", 0);
1549 test_internal_ip("::ffff:172.16.0.0", 0);
1550 test_internal_ip("::ffff:172.31.255.255", 0);
1551 test_external_ip("::ffff:172.32.0.0", 0);
1553 test_external_ip("::ffff:192.167.255.255", 0);
1554 test_internal_ip("::ffff:192.168.0.0", 0);
1555 test_internal_ip("::ffff:192.168.255.255", 0);
1556 test_external_ip("::ffff:192.169.0.0", 0);
1558 test_external_ip("::ffff:169.253.255.255", 0);
1559 test_internal_ip("::ffff:169.254.0.0", 0);
1560 test_internal_ip("::ffff:169.254.255.255", 0);
1561 test_external_ip("::ffff:169.255.0.0", 0);
1562 test_assert(is_internal_IP(0x7f000001, 0));
1564 /* tor_addr_compare(tor_addr_t x2) */
1565 test_addr_compare("ffff::", ==, "ffff::0");
1566 test_addr_compare("0::3:2:1", >, "0::ffff:0.3.2.1");
1567 test_addr_compare("0::2:2:1", >, "0::ffff:0.3.2.1");
1568 test_addr_compare("0::ffff:0.3.2.1", <, "0::0:0:0");
1569 test_addr_compare("0::ffff:5.2.2.1", <, "::ffff:6.0.0.0"); /* XXXX wrong. */
1570 tor_addr_parse_mask_ports("[::ffff:2.3.4.5]", &t1
, NULL
, NULL
, NULL
);
1571 tor_addr_parse_mask_ports("2.3.4.5", &t2
, NULL
, NULL
, NULL
);
1572 test_assert(tor_addr_compare(&t1
, &t2
, CMP_SEMANTIC
) == 0);
1573 tor_addr_parse_mask_ports("[::ffff:2.3.4.4]", &t1
, NULL
, NULL
, NULL
);
1574 tor_addr_parse_mask_ports("2.3.4.5", &t2
, NULL
, NULL
, NULL
);
1575 test_assert(tor_addr_compare(&t1
, &t2
, CMP_SEMANTIC
) < 0);
1577 /* test compare_masked */
1578 test_addr_compare_masked("ffff::", ==, "ffff::0", 128);
1579 test_addr_compare_masked("ffff::", ==, "ffff::0", 64);
1580 test_addr_compare_masked("0::2:2:1", <, "0::8000:2:1", 81);
1581 test_addr_compare_masked("0::2:2:1", ==, "0::8000:2:1", 80);
1583 /* Test decorated addr_to_string. */
1584 test_eq(AF_INET6
, tor_addr_from_str(&t1
, "[123:45:6789::5005:11]"));
1585 p1
= tor_addr_to_str(buf
, &t1
, sizeof(buf
), 1);
1586 test_streq(p1
, "[123:45:6789::5005:11]");
1587 test_eq(AF_INET
, tor_addr_from_str(&t1
, "18.0.0.1"));
1588 p1
= tor_addr_to_str(buf
, &t1
, sizeof(buf
), 1);
1589 test_streq(p1
, "18.0.0.1");
1591 /* test tor_addr_parse_mask_ports */
1592 test_addr_mask_ports_parse("[::f]/17:47-95", AF_INET6
,
1593 0, 0, 0, 0x0000000f, 17, 47, 95);
1594 //test_addr_parse("[::fefe:4.1.1.7/120]:999-1000");
1595 //test_addr_parse_check("::fefe:401:107", 120, 999, 1000);
1596 test_addr_mask_ports_parse("[::ffff:4.1.1.7]/120:443", AF_INET6
,
1597 0, 0, 0x0000ffff, 0x04010107, 120, 443, 443);
1598 test_addr_mask_ports_parse("[abcd:2::44a:0]:2-65000", AF_INET6
,
1599 0xabcd0002, 0, 0, 0x044a0000, 128, 2, 65000);
1601 r
=tor_addr_parse_mask_ports("[fefef::]/112", &t1
, NULL
, NULL
, NULL
);
1602 test_assert(r
== -1);
1603 r
=tor_addr_parse_mask_ports("efef::/112", &t1
, NULL
, NULL
, NULL
);
1604 test_assert(r
== -1);
1605 r
=tor_addr_parse_mask_ports("[f:f:f:f:f:f:f:f::]", &t1
, NULL
, NULL
, NULL
);
1606 test_assert(r
== -1);
1607 r
=tor_addr_parse_mask_ports("[::f:f:f:f:f:f:f:f]", &t1
, NULL
, NULL
, NULL
);
1608 test_assert(r
== -1);
1609 r
=tor_addr_parse_mask_ports("[f:f:f:f:f:f:f:f:f]", &t1
, NULL
, NULL
, NULL
);
1610 test_assert(r
== -1);
1611 /* Test for V4-mapped address with mask < 96. (arguably not valid) */
1612 r
=tor_addr_parse_mask_ports("[::ffff:1.1.2.2/33]", &t1
, &mask
, NULL
, NULL
);
1613 test_assert(r
== -1);
1614 r
=tor_addr_parse_mask_ports("1.1.2.2/33", &t1
, &mask
, NULL
, NULL
);
1615 test_assert(r
== -1);
1616 r
=tor_addr_parse_mask_ports("1.1.2.2/31", &t1
, &mask
, NULL
, NULL
);
1617 test_assert(r
== AF_INET
);
1618 r
=tor_addr_parse_mask_ports("[efef::]/112", &t1
, &mask
, &port1
, &port2
);
1619 test_assert(r
== AF_INET6
);
1620 test_assert(port1
== 1);
1621 test_assert(port2
== 65535);
1623 /* make sure inet address lengths >= max */
1624 test_assert(INET_NTOA_BUF_LEN
>= sizeof("255.255.255.255"));
1625 test_assert(TOR_ADDR_BUF_LEN
>=
1626 sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"));
1628 test_assert(sizeof(tor_addr_t
) >= sizeof(struct in6_addr
));
1630 /* get interface addresses */
1631 r
= get_interface_address6(LOG_DEBUG
, AF_INET
, &t1
);
1632 i
= get_interface_address6(LOG_DEBUG
, AF_INET6
, &t2
);
1634 tor_inet_ntop(AF_INET
, &t1
.sa
.sin_addr
, buf
, sizeof(buf
));
1635 printf("\nv4 address: %s (family=%i)", buf
, IN_FAMILY(&t1
));
1636 tor_inet_ntop(AF_INET6
, &t2
.sa6
.sin6_addr
, buf
, sizeof(buf
));
1637 printf("\nv6 address: %s (family=%i)", buf
, IN_FAMILY(&t2
));
1645 test_util_smartlist(void)
1651 /* XXXX test sort_digests, uniq_strings, uniq_digests */
1653 /* Test smartlist add, del_keeporder, insert, get. */
1654 sl
= smartlist_create();
1655 smartlist_add(sl
, (void*)1);
1656 smartlist_add(sl
, (void*)2);
1657 smartlist_add(sl
, (void*)3);
1658 smartlist_add(sl
, (void*)4);
1659 smartlist_del_keeporder(sl
, 1);
1660 smartlist_insert(sl
, 1, (void*)22);
1661 smartlist_insert(sl
, 0, (void*)0);
1662 smartlist_insert(sl
, 5, (void*)555);
1663 test_eq_ptr((void*)0, smartlist_get(sl
,0));
1664 test_eq_ptr((void*)1, smartlist_get(sl
,1));
1665 test_eq_ptr((void*)22, smartlist_get(sl
,2));
1666 test_eq_ptr((void*)3, smartlist_get(sl
,3));
1667 test_eq_ptr((void*)4, smartlist_get(sl
,4));
1668 test_eq_ptr((void*)555, smartlist_get(sl
,5));
1669 /* Try deleting in the middle. */
1670 smartlist_del(sl
, 1);
1671 test_eq_ptr((void*)555, smartlist_get(sl
, 1));
1672 /* Try deleting at the end. */
1673 smartlist_del(sl
, 4);
1674 test_eq(4, smartlist_len(sl
));
1677 test_assert(smartlist_isin(sl
, (void*)3));
1678 test_assert(!smartlist_isin(sl
, (void*)99));
1680 /* Test split and join */
1681 smartlist_clear(sl
);
1682 test_eq(0, smartlist_len(sl
));
1683 smartlist_split_string(sl
, "abc", ":", 0, 0);
1684 test_eq(1, smartlist_len(sl
));
1685 test_streq("abc", smartlist_get(sl
, 0));
1686 smartlist_split_string(sl
, "a::bc::", "::", 0, 0);
1687 test_eq(4, smartlist_len(sl
));
1688 test_streq("a", smartlist_get(sl
, 1));
1689 test_streq("bc", smartlist_get(sl
, 2));
1690 test_streq("", smartlist_get(sl
, 3));
1691 cp
= smartlist_join_strings(sl
, "", 0, NULL
);
1692 test_streq(cp
, "abcabc");
1694 cp
= smartlist_join_strings(sl
, "!", 0, NULL
);
1695 test_streq(cp
, "abc!a!bc!");
1697 cp
= smartlist_join_strings(sl
, "XY", 0, NULL
);
1698 test_streq(cp
, "abcXYaXYbcXY");
1700 cp
= smartlist_join_strings(sl
, "XY", 1, NULL
);
1701 test_streq(cp
, "abcXYaXYbcXYXY");
1703 cp
= smartlist_join_strings(sl
, "", 1, NULL
);
1704 test_streq(cp
, "abcabc");
1707 smartlist_split_string(sl
, "/def/ /ghijk", "/", 0, 0);
1708 test_eq(8, smartlist_len(sl
));
1709 test_streq("", smartlist_get(sl
, 4));
1710 test_streq("def", smartlist_get(sl
, 5));
1711 test_streq(" ", smartlist_get(sl
, 6));
1712 test_streq("ghijk", smartlist_get(sl
, 7));
1713 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1714 smartlist_clear(sl
);
1716 smartlist_split_string(sl
, "a,bbd,cdef", ",", SPLIT_SKIP_SPACE
, 0);
1717 test_eq(3, smartlist_len(sl
));
1718 test_streq("a", smartlist_get(sl
,0));
1719 test_streq("bbd", smartlist_get(sl
,1));
1720 test_streq("cdef", smartlist_get(sl
,2));
1721 smartlist_split_string(sl
, " z <> zhasd <> <> bnud<> ", "<>",
1722 SPLIT_SKIP_SPACE
, 0);
1723 test_eq(8, smartlist_len(sl
));
1724 test_streq("z", smartlist_get(sl
,3));
1725 test_streq("zhasd", smartlist_get(sl
,4));
1726 test_streq("", smartlist_get(sl
,5));
1727 test_streq("bnud", smartlist_get(sl
,6));
1728 test_streq("", smartlist_get(sl
,7));
1730 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1731 smartlist_clear(sl
);
1733 smartlist_split_string(sl
, " ab\tc \td ef ", NULL
,
1734 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1735 test_eq(4, smartlist_len(sl
));
1736 test_streq("ab", smartlist_get(sl
,0));
1737 test_streq("c", smartlist_get(sl
,1));
1738 test_streq("d", smartlist_get(sl
,2));
1739 test_streq("ef", smartlist_get(sl
,3));
1740 smartlist_split_string(sl
, "ghi\tj", NULL
,
1741 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1742 test_eq(6, smartlist_len(sl
));
1743 test_streq("ghi", smartlist_get(sl
,4));
1744 test_streq("j", smartlist_get(sl
,5));
1746 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1747 smartlist_clear(sl
);
1749 cp
= smartlist_join_strings(sl
, "XY", 0, NULL
);
1752 cp
= smartlist_join_strings(sl
, "XY", 1, NULL
);
1753 test_streq(cp
, "XY");
1756 smartlist_split_string(sl
, " z <> zhasd <> <> bnud<> ", "<>",
1757 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1758 test_eq(3, smartlist_len(sl
));
1759 test_streq("z", smartlist_get(sl
, 0));
1760 test_streq("zhasd", smartlist_get(sl
, 1));
1761 test_streq("bnud", smartlist_get(sl
, 2));
1762 smartlist_split_string(sl
, " z <> zhasd <> <> bnud<> ", "<>",
1763 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 2);
1764 test_eq(5, smartlist_len(sl
));
1765 test_streq("z", smartlist_get(sl
, 3));
1766 test_streq("zhasd <> <> bnud<>", smartlist_get(sl
, 4));
1767 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1768 smartlist_clear(sl
);
1770 smartlist_split_string(sl
, "abcd\n", "\n",
1771 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1772 test_eq(1, smartlist_len(sl
));
1773 test_streq("abcd", smartlist_get(sl
, 0));
1774 smartlist_split_string(sl
, "efgh", "\n",
1775 SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
1776 test_eq(2, smartlist_len(sl
));
1777 test_streq("efgh", smartlist_get(sl
, 1));
1779 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1780 smartlist_clear(sl
);
1782 /* Test swapping, shuffling, and sorting. */
1783 smartlist_split_string(sl
, "the,onion,router,by,arma,and,nickm", ",", 0, 0);
1784 test_eq(7, smartlist_len(sl
));
1785 smartlist_sort(sl
, _compare_strs
);
1786 cp
= smartlist_join_strings(sl
, ",", 0, NULL
);
1787 test_streq(cp
,"and,arma,by,nickm,onion,router,the");
1789 smartlist_swap(sl
, 1, 5);
1790 cp
= smartlist_join_strings(sl
, ",", 0, NULL
);
1791 test_streq(cp
,"and,router,by,nickm,onion,arma,the");
1793 smartlist_shuffle(sl
);
1794 test_eq(7, smartlist_len(sl
));
1795 test_assert(smartlist_string_isin(sl
, "and"));
1796 test_assert(smartlist_string_isin(sl
, "router"));
1797 test_assert(smartlist_string_isin(sl
, "by"));
1798 test_assert(smartlist_string_isin(sl
, "nickm"));
1799 test_assert(smartlist_string_isin(sl
, "onion"));
1800 test_assert(smartlist_string_isin(sl
, "arma"));
1801 test_assert(smartlist_string_isin(sl
, "the"));
1804 smartlist_sort(sl
, _compare_strs
);
1805 test_streq("nickm", smartlist_bsearch(sl
, "zNicKM",
1806 _compare_without_first_ch
));
1807 test_streq("and", smartlist_bsearch(sl
, " AND", _compare_without_first_ch
));
1808 test_eq_ptr(NULL
, smartlist_bsearch(sl
, " ANz", _compare_without_first_ch
));
1810 /* Test bsearch_idx */
1813 test_eq(0, smartlist_bsearch_idx(sl
," aaa",_compare_without_first_ch
,&f
));
1815 test_eq(0, smartlist_bsearch_idx(sl
," and",_compare_without_first_ch
,&f
));
1817 test_eq(1, smartlist_bsearch_idx(sl
," arm",_compare_without_first_ch
,&f
));
1819 test_eq(1, smartlist_bsearch_idx(sl
," arma",_compare_without_first_ch
,&f
));
1821 test_eq(2, smartlist_bsearch_idx(sl
," armb",_compare_without_first_ch
,&f
));
1823 test_eq(7, smartlist_bsearch_idx(sl
," zzzz",_compare_without_first_ch
,&f
));
1827 /* Test reverse() and pop_last() */
1828 smartlist_reverse(sl
);
1829 cp
= smartlist_join_strings(sl
, ",", 0, NULL
);
1830 test_streq(cp
,"the,router,onion,nickm,by,arma,and");
1832 cp
= smartlist_pop_last(sl
);
1833 test_streq(cp
, "and");
1835 test_eq(smartlist_len(sl
), 6);
1836 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1837 smartlist_clear(sl
);
1838 cp
= smartlist_pop_last(sl
);
1842 smartlist_split_string(sl
,
1843 "50,noon,radar,a,man,a,plan,a,canal,panama,radar,noon,50",
1845 smartlist_sort(sl
, _compare_strs
);
1846 smartlist_uniq(sl
, _compare_strs
, _tor_free
);
1847 cp
= smartlist_join_strings(sl
, ",", 0, NULL
);
1848 test_streq(cp
, "50,a,canal,man,noon,panama,plan,radar");
1851 /* Test string_isin and isin_case and num_isin */
1852 test_assert(smartlist_string_isin(sl
, "noon"));
1853 test_assert(!smartlist_string_isin(sl
, "noonoon"));
1854 test_assert(smartlist_string_isin_case(sl
, "nOOn"));
1855 test_assert(!smartlist_string_isin_case(sl
, "nooNooN"));
1856 test_assert(smartlist_string_num_isin(sl
, 50));
1857 test_assert(!smartlist_string_num_isin(sl
, 60));
1859 /* Test smartlist_choose */
1864 void *first
= smartlist_choose(sl
);
1865 test_assert(smartlist_isin(sl
, first
));
1866 for (i
= 0; i
< 100; ++i
) {
1867 void *second
= smartlist_choose(sl
);
1868 if (second
!= first
)
1870 if (!smartlist_isin(sl
, second
))
1873 test_assert(!allsame
);
1876 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1877 smartlist_clear(sl
);
1879 /* Test string_remove and remove and join_strings2 */
1880 smartlist_split_string(sl
,
1881 "Some say the Earth will end in ice and some in fire",
1883 cp
= smartlist_get(sl
, 4);
1884 test_streq(cp
, "will");
1885 smartlist_add(sl
, cp
);
1886 smartlist_remove(sl
, cp
);
1888 cp
= smartlist_join_strings(sl
, ",", 0, NULL
);
1889 test_streq(cp
, "Some,say,the,Earth,fire,end,in,ice,and,some,in");
1891 smartlist_string_remove(sl
, "in");
1892 cp
= smartlist_join_strings2(sl
, "+XX", 1, 0, &sz
);
1893 test_streq(cp
, "Some+say+the+Earth+fire+end+some+ice+and");
1894 test_eq((int)sz
, 40);
1897 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1898 smartlist_clear(sl
);
1901 smartlist_t
*ints
= smartlist_create();
1902 smartlist_t
*odds
= smartlist_create();
1903 smartlist_t
*evens
= smartlist_create();
1904 smartlist_t
*primes
= smartlist_create();
1906 for (i
=1; i
< 10; i
+= 2)
1907 smartlist_add(odds
, (void*)(uintptr_t)i
);
1908 for (i
=0; i
< 10; i
+= 2)
1909 smartlist_add(evens
, (void*)(uintptr_t)i
);
1912 smartlist_add_all(ints
, odds
);
1913 smartlist_add_all(ints
, evens
);
1914 test_eq(smartlist_len(ints
), 10);
1916 smartlist_add(primes
, (void*)2);
1917 smartlist_add(primes
, (void*)3);
1918 smartlist_add(primes
, (void*)5);
1919 smartlist_add(primes
, (void*)7);
1922 test_assert(smartlist_overlap(ints
, odds
));
1923 test_assert(smartlist_overlap(odds
, primes
));
1924 test_assert(smartlist_overlap(evens
, primes
));
1925 test_assert(!smartlist_overlap(odds
, evens
));
1928 smartlist_add_all(sl
, odds
);
1929 smartlist_intersect(sl
, primes
);
1930 test_eq(smartlist_len(sl
), 3);
1931 test_assert(smartlist_isin(sl
, (void*)3));
1932 test_assert(smartlist_isin(sl
, (void*)5));
1933 test_assert(smartlist_isin(sl
, (void*)7));
1936 smartlist_add_all(sl
, primes
);
1937 smartlist_subtract(sl
, odds
);
1938 test_eq(smartlist_len(sl
), 1);
1939 test_assert(smartlist_isin(sl
, (void*)2));
1941 smartlist_free(odds
);
1942 smartlist_free(evens
);
1943 smartlist_free(ints
);
1944 smartlist_free(primes
);
1945 smartlist_clear(sl
);
1950 smartlist_add(sl
, tor_memdup("AAAAAAAAAAAAAAAAAAAA", DIGEST_LEN
));
1951 smartlist_add(sl
, tor_memdup("\00090AAB2AAAAaasdAAAAA", DIGEST_LEN
));
1952 smartlist_add(sl
, tor_memdup("\00090AAB2AAAAaasdAAAAA", DIGEST_LEN
));
1953 test_eq(0, smartlist_digest_isin(NULL
, "AAAAAAAAAAAAAAAAAAAA"));
1954 test_assert(smartlist_digest_isin(sl
, "AAAAAAAAAAAAAAAAAAAA"));
1955 test_assert(smartlist_digest_isin(sl
, "\00090AAB2AAAAaasdAAAAA"));
1956 test_eq(0, smartlist_digest_isin(sl
, "\00090AAB2AAABaasdAAAAA"));
1959 smartlist_sort_digests(sl
);
1960 test_memeq(smartlist_get(sl
, 0), "\00090AAB2AAAAaasdAAAAA", DIGEST_LEN
);
1961 test_memeq(smartlist_get(sl
, 1), "\00090AAB2AAAAaasdAAAAA", DIGEST_LEN
);
1962 test_memeq(smartlist_get(sl
, 2), "AAAAAAAAAAAAAAAAAAAA", DIGEST_LEN
);
1963 test_eq(3, smartlist_len(sl
));
1966 smartlist_uniq_digests(sl
);
1967 test_eq(2, smartlist_len(sl
));
1968 test_memeq(smartlist_get(sl
, 0), "\00090AAB2AAAAaasdAAAAA", DIGEST_LEN
);
1969 test_memeq(smartlist_get(sl
, 1), "AAAAAAAAAAAAAAAAAAAA", DIGEST_LEN
);
1971 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
1972 smartlist_clear(sl
);
1976 smartlist_t
*sl2
= smartlist_create(), *sl3
= smartlist_create(),
1977 *sl4
= smartlist_create();
1978 /* unique, sorted. */
1979 smartlist_split_string(sl
,
1980 "Abashments Ambush Anchorman Bacon Banks Borscht "
1981 "Bunks Inhumane Insurance Knish Know Manners "
1982 "Maraschinos Stamina Sunbonnets Unicorns Wombats",
1984 /* non-unique, sorted. */
1985 smartlist_split_string(sl2
,
1986 "Ambush Anchorman Anchorman Anemias Anemias Bacon "
1987 "Crossbowmen Inhumane Insurance Knish Know Manners "
1988 "Manners Maraschinos Wombats Wombats Work",
1990 SMARTLIST_FOREACH_JOIN(sl
, char *, cp1
,
1993 smartlist_add(sl3
, cp2
)) {
1994 test_streq(cp1
, cp2
);
1995 smartlist_add(sl4
, cp1
);
1996 } SMARTLIST_FOREACH_JOIN_END(cp1
, cp2
);
1998 SMARTLIST_FOREACH(sl3
, const char *, cp
,
1999 test_assert(smartlist_isin(sl2
, cp
) &&
2000 !smartlist_string_isin(sl
, cp
)));
2001 SMARTLIST_FOREACH(sl4
, const char *, cp
,
2002 test_assert(smartlist_isin(sl
, cp
) &&
2003 smartlist_string_isin(sl2
, cp
)));
2004 cp
= smartlist_join_strings(sl3
, ",", 0, NULL
);
2005 test_streq(cp
, "Anemias,Anemias,Crossbowmen,Work");
2007 cp
= smartlist_join_strings(sl4
, ",", 0, NULL
);
2008 test_streq(cp
, "Ambush,Anchorman,Anchorman,Bacon,Inhumane,Insurance,"
2009 "Knish,Know,Manners,Manners,Maraschinos,Wombats,Wombats");
2012 smartlist_free(sl4
);
2013 smartlist_free(sl3
);
2014 SMARTLIST_FOREACH(sl2
, char *, cp
, tor_free(cp
));
2015 smartlist_free(sl2
);
2016 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
2017 smartlist_clear(sl
);
2027 test_util_bitarray(void)
2029 bitarray_t
*ba
= NULL
;
2032 ba
= bitarray_init_zero(1);
2033 test_assert(! bitarray_is_set(ba
, 0));
2034 bitarray_set(ba
, 0);
2035 test_assert(bitarray_is_set(ba
, 0));
2036 bitarray_clear(ba
, 0);
2037 test_assert(! bitarray_is_set(ba
, 0));
2040 ba
= bitarray_init_zero(1023);
2041 for (i
= 1; i
< 64; ) {
2042 for (j
= 0; j
< 1023; ++j
) {
2044 bitarray_set(ba
, j
);
2046 bitarray_clear(ba
, j
);
2048 for (j
= 0; j
< 1023; ++j
) {
2049 if (!bool_eq(bitarray_is_set(ba
, j
), j
%i
))
2067 test_util_digestset(void)
2069 smartlist_t
*included
= smartlist_create();
2073 int false_positives
= 0;
2074 digestset_t
*set
= NULL
;
2076 for (i
= 0; i
< 1000; ++i
) {
2077 crypto_rand(d
, DIGEST_LEN
);
2078 smartlist_add(included
, tor_memdup(d
, DIGEST_LEN
));
2080 set
= digestset_new(1000);
2081 SMARTLIST_FOREACH(included
, const char *, cp
,
2082 if (digestset_isin(set
, cp
))
2085 SMARTLIST_FOREACH(included
, const char *, cp
,
2086 digestset_add(set
, cp
));
2087 SMARTLIST_FOREACH(included
, const char *, cp
,
2088 if (!digestset_isin(set
, cp
))
2091 for (i
= 0; i
< 1000; ++i
) {
2092 crypto_rand(d
, DIGEST_LEN
);
2093 if (digestset_isin(set
, d
))
2096 test_assert(false_positives
< 50); /* Should be far lower. */
2100 digestset_free(set
);
2101 SMARTLIST_FOREACH(included
, char *, cp
, tor_free(cp
));
2102 smartlist_free(included
);
2105 /* stop threads running at once. */
2106 static tor_mutex_t
*_thread_test_mutex
= NULL
;
2107 /* make sure that threads have to run at the same time. */
2108 static tor_mutex_t
*_thread_test_start1
= NULL
;
2109 static tor_mutex_t
*_thread_test_start2
= NULL
;
2110 static strmap_t
*_thread_test_strmap
= NULL
;
2111 static char *_thread1_name
= NULL
;
2112 static char *_thread2_name
= NULL
;
2114 static void _thread_test_func(void* _s
) ATTR_NORETURN
;
2116 static int t1_count
= 0;
2117 static int t2_count
= 0;
2120 _thread_test_func(void* _s
)
2122 /* This function runs in a subthread. It grabs its own mutex (start1 or
2123 * start2) to make sure that it should start, then it repeatedly alters
2124 * _test_thread_strmap protected by _thread_test_mutex. */
2130 if (!strcmp(s
, "thread 1")) {
2131 m
= _thread_test_start1
;
2132 cp
= &_thread1_name
;
2135 m
= _thread_test_start2
;
2136 cp
= &_thread2_name
;
2139 tor_mutex_acquire(m
);
2141 tor_snprintf(buf
, sizeof(buf
), "%lu", tor_get_thread_id());
2142 *cp
= tor_strdup(buf
);
2144 for (i
=0; i
<10000; ++i
) {
2145 tor_mutex_acquire(_thread_test_mutex
);
2146 strmap_set(_thread_test_strmap
, "last to run", *cp
);
2148 tor_mutex_release(_thread_test_mutex
);
2150 tor_mutex_acquire(_thread_test_mutex
);
2151 strmap_set(_thread_test_strmap
, s
, *cp
);
2152 tor_mutex_release(_thread_test_mutex
);
2154 tor_mutex_release(m
);
2160 test_util_threads(void)
2162 char *s1
= NULL
, *s2
= NULL
;
2163 int done
= 0, timedout
= 0;
2165 #ifndef TOR_IS_MULTITHREADED
2166 /* Skip this test if we aren't threading. We should be threading most
2167 * everywhere by now. */
2171 _thread_test_mutex
= tor_mutex_new();
2172 _thread_test_start1
= tor_mutex_new();
2173 _thread_test_start2
= tor_mutex_new();
2174 _thread_test_strmap
= strmap_new();
2175 s1
= tor_strdup("thread 1");
2176 s2
= tor_strdup("thread 2");
2177 tor_mutex_acquire(_thread_test_start1
);
2178 tor_mutex_acquire(_thread_test_start2
);
2179 spawn_func(_thread_test_func
, s1
);
2180 spawn_func(_thread_test_func
, s2
);
2181 tor_mutex_release(_thread_test_start2
);
2182 tor_mutex_release(_thread_test_start1
);
2183 started
= time(NULL
);
2185 tor_mutex_acquire(_thread_test_mutex
);
2186 strmap_assert_ok(_thread_test_strmap
);
2187 if (strmap_get(_thread_test_strmap
, "thread 1") &&
2188 strmap_get(_thread_test_strmap
, "thread 2")) {
2190 } else if (time(NULL
) > started
+ 25) {
2191 timedout
= done
= 1;
2193 tor_mutex_release(_thread_test_mutex
);
2195 tor_mutex_free(_thread_test_mutex
);
2197 tor_mutex_acquire(_thread_test_start1
);
2198 tor_mutex_release(_thread_test_start1
);
2199 tor_mutex_acquire(_thread_test_start2
);
2200 tor_mutex_release(_thread_test_start2
);
2203 printf("\nTimed out: %d %d", t1_count
, t2_count
);
2204 test_assert(strmap_get(_thread_test_strmap
, "thread 1"));
2205 test_assert(strmap_get(_thread_test_strmap
, "thread 2"));
2206 test_assert(!timedout
);
2209 /* different thread IDs. */
2210 test_assert(strcmp(strmap_get(_thread_test_strmap
, "thread 1"),
2211 strmap_get(_thread_test_strmap
, "thread 2")));
2212 test_assert(!strcmp(strmap_get(_thread_test_strmap
, "thread 1"),
2213 strmap_get(_thread_test_strmap
, "last to run")) ||
2214 !strcmp(strmap_get(_thread_test_strmap
, "thread 2"),
2215 strmap_get(_thread_test_strmap
, "last to run")));
2220 tor_free(_thread1_name
);
2221 tor_free(_thread2_name
);
2222 if (_thread_test_strmap
)
2223 strmap_free(_thread_test_strmap
, NULL
);
2224 if (_thread_test_start1
)
2225 tor_mutex_free(_thread_test_start1
);
2226 if (_thread_test_start2
)
2227 tor_mutex_free(_thread_test_start2
);
2231 _compare_strings_for_pqueue(const void *s1
, const void *s2
)
2233 return strcmp((const char*)s1
, (const char*)s2
);
2237 test_util_pqueue(void)
2239 smartlist_t
*sl
= NULL
;
2240 int (*cmp
)(const void *, const void*);
2241 #define OK() smartlist_pqueue_assert_ok(sl, cmp)
2243 cmp
= _compare_strings_for_pqueue
;
2245 sl
= smartlist_create();
2246 smartlist_pqueue_add(sl
, cmp
, (char*)"cows");
2247 smartlist_pqueue_add(sl
, cmp
, (char*)"zebras");
2248 smartlist_pqueue_add(sl
, cmp
, (char*)"fish");
2249 smartlist_pqueue_add(sl
, cmp
, (char*)"frogs");
2250 smartlist_pqueue_add(sl
, cmp
, (char*)"apples");
2251 smartlist_pqueue_add(sl
, cmp
, (char*)"squid");
2252 smartlist_pqueue_add(sl
, cmp
, (char*)"daschunds");
2253 smartlist_pqueue_add(sl
, cmp
, (char*)"eggplants");
2254 smartlist_pqueue_add(sl
, cmp
, (char*)"weissbier");
2255 smartlist_pqueue_add(sl
, cmp
, (char*)"lobsters");
2256 smartlist_pqueue_add(sl
, cmp
, (char*)"roquefort");
2260 test_eq(smartlist_len(sl
), 11);
2261 test_streq(smartlist_get(sl
, 0), "apples");
2262 test_streq(smartlist_pqueue_pop(sl
, cmp
), "apples");
2263 test_eq(smartlist_len(sl
), 10);
2265 test_streq(smartlist_pqueue_pop(sl
, cmp
), "cows");
2266 test_streq(smartlist_pqueue_pop(sl
, cmp
), "daschunds");
2267 smartlist_pqueue_add(sl
, cmp
, (char*)"chinchillas");
2269 smartlist_pqueue_add(sl
, cmp
, (char*)"fireflies");
2271 test_streq(smartlist_pqueue_pop(sl
, cmp
), "chinchillas");
2272 test_streq(smartlist_pqueue_pop(sl
, cmp
), "eggplants");
2273 test_streq(smartlist_pqueue_pop(sl
, cmp
), "fireflies");
2275 test_streq(smartlist_pqueue_pop(sl
, cmp
), "fish");
2276 test_streq(smartlist_pqueue_pop(sl
, cmp
), "frogs");
2277 test_streq(smartlist_pqueue_pop(sl
, cmp
), "lobsters");
2278 test_streq(smartlist_pqueue_pop(sl
, cmp
), "roquefort");
2280 test_eq(smartlist_len(sl
), 3);
2281 test_streq(smartlist_pqueue_pop(sl
, cmp
), "squid");
2282 test_streq(smartlist_pqueue_pop(sl
, cmp
), "weissbier");
2283 test_streq(smartlist_pqueue_pop(sl
, cmp
), "zebras");
2284 test_eq(smartlist_len(sl
), 0);
2294 test_util_gzip(void)
2296 char *buf1
=NULL
, *buf2
=NULL
, *buf3
=NULL
, *cp1
, *cp2
;
2299 tor_zlib_state_t
*state
= NULL
;
2301 buf1
= tor_strdup("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ");
2302 test_assert(detect_compression_method(buf1
, strlen(buf1
)) == UNKNOWN_METHOD
);
2303 if (is_gzip_supported()) {
2304 test_assert(!tor_gzip_compress(&buf2
, &len1
, buf1
, strlen(buf1
)+1,
2307 test_assert(!memcmp(buf2
, "\037\213", 2)); /* Gzip magic. */
2308 test_assert(detect_compression_method(buf2
, len1
) == GZIP_METHOD
);
2310 test_assert(!tor_gzip_uncompress(&buf3
, &len2
, buf2
, len1
,
2311 GZIP_METHOD
, 1, LOG_INFO
));
2313 test_streq(buf1
,buf3
);
2319 test_assert(!tor_gzip_compress(&buf2
, &len1
, buf1
, strlen(buf1
)+1,
2322 test_assert(!memcmp(buf2
, "\x78\xDA", 2)); /* deflate magic. */
2323 test_assert(detect_compression_method(buf2
, len1
) == ZLIB_METHOD
);
2325 test_assert(!tor_gzip_uncompress(&buf3
, &len2
, buf2
, len1
,
2326 ZLIB_METHOD
, 1, LOG_INFO
));
2328 test_streq(buf1
,buf3
);
2330 /* Check whether we can uncompress concatenated, compresed strings. */
2332 buf2
= tor_realloc(buf2
, len1
*2);
2333 memcpy(buf2
+len1
, buf2
, len1
);
2334 test_assert(!tor_gzip_uncompress(&buf3
, &len2
, buf2
, len1
*2,
2335 ZLIB_METHOD
, 1, LOG_INFO
));
2336 test_eq(len2
, (strlen(buf1
)+1)*2);
2338 "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ\0"
2339 "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ\0",
2340 (strlen(buf1
)+1)*2);
2346 /* Check whether we can uncompress partial strings. */
2348 tor_strdup("String with low redundancy that won't be compressed much.");
2349 test_assert(!tor_gzip_compress(&buf2
, &len1
, buf1
, strlen(buf1
)+1,
2351 tor_assert(len1
>16);
2352 /* when we allow an uncomplete string, we should succeed.*/
2353 tor_assert(!tor_gzip_uncompress(&buf3
, &len2
, buf2
, len1
-16,
2354 ZLIB_METHOD
, 0, LOG_INFO
));
2356 tor_assert(len2
> 5);
2357 tor_assert(!strcmpstart(buf1
, buf3
));
2359 /* when we demand a complete string, this must fail. */
2361 tor_assert(tor_gzip_uncompress(&buf3
, &len2
, buf2
, len1
-16,
2362 ZLIB_METHOD
, 1, LOG_INFO
));
2365 /* Now, try streaming compression. */
2369 state
= tor_zlib_new(1, ZLIB_METHOD
);
2371 cp1
= buf1
= tor_malloc(1024);
2373 ccp2
= "ABCDEFGHIJABCDEFGHIJ";
2375 test_assert(tor_zlib_process(state
, &cp1
, &len1
, &ccp2
, &len2
, 0)
2377 test_eq(len2
, 0); /* Make sure we compressed it all. */
2378 test_assert(cp1
> buf1
);
2382 test_assert(tor_zlib_process(state
, &cp1
, &len1
, &ccp2
, &len2
, 1)
2385 test_assert(cp1
> cp2
); /* Make sure we really added something. */
2387 tor_assert(!tor_gzip_uncompress(&buf3
, &len2
, buf1
, 1024-len1
,
2388 ZLIB_METHOD
, 1, LOG_WARN
));
2389 test_streq(buf3
, "ABCDEFGHIJABCDEFGHIJ"); /*Make sure it compressed right.*/
2393 tor_zlib_free(state
);
2400 test_util_strmap(void)
2403 strmap_iter_t
*iter
;
2406 char *visited
= NULL
;
2407 smartlist_t
*found_keys
= NULL
;
2410 test_eq(strmap_size(map
), 0);
2411 test_assert(strmap_isempty(map
));
2412 v
= strmap_set(map
, "K1", (void*)99);
2414 test_assert(!strmap_isempty(map
));
2415 v
= strmap_set(map
, "K2", (void*)101);
2417 v
= strmap_set(map
, "K1", (void*)100);
2418 test_eq(v
, (void*)99);
2419 test_eq_ptr(strmap_get(map
,"K1"), (void*)100);
2420 test_eq_ptr(strmap_get(map
,"K2"), (void*)101);
2421 test_eq_ptr(strmap_get(map
,"K-not-there"), NULL
);
2422 strmap_assert_ok(map
);
2424 v
= strmap_remove(map
,"K2");
2425 strmap_assert_ok(map
);
2426 test_eq_ptr(v
, (void*)101);
2427 test_eq_ptr(strmap_get(map
,"K2"), NULL
);
2428 test_eq_ptr(strmap_remove(map
,"K2"), NULL
);
2430 strmap_set(map
, "K2", (void*)101);
2431 strmap_set(map
, "K3", (void*)102);
2432 strmap_set(map
, "K4", (void*)103);
2433 test_eq(strmap_size(map
), 4);
2434 strmap_assert_ok(map
);
2435 strmap_set(map
, "K5", (void*)104);
2436 strmap_set(map
, "K6", (void*)105);
2437 strmap_assert_ok(map
);
2439 /* Test iterator. */
2440 iter
= strmap_iter_init(map
);
2441 found_keys
= smartlist_create();
2442 while (!strmap_iter_done(iter
)) {
2443 strmap_iter_get(iter
,&k
,&v
);
2444 smartlist_add(found_keys
, tor_strdup(k
));
2445 test_eq_ptr(v
, strmap_get(map
, k
));
2447 if (!strcmp(k
, "K2")) {
2448 iter
= strmap_iter_next_rmv(map
,iter
);
2450 iter
= strmap_iter_next(map
,iter
);
2454 /* Make sure we removed K2, but not the others. */
2455 test_eq_ptr(strmap_get(map
, "K2"), NULL
);
2456 test_eq_ptr(strmap_get(map
, "K5"), (void*)104);
2457 /* Make sure we visited everyone once */
2458 smartlist_sort_strings(found_keys
);
2459 visited
= smartlist_join_strings(found_keys
, ":", 0, NULL
);
2460 test_streq(visited
, "K1:K2:K3:K4:K5:K6");
2462 strmap_assert_ok(map
);
2463 /* Clean up after ourselves. */
2464 strmap_free(map
, NULL
);
2467 /* Now try some lc functions. */
2469 strmap_set_lc(map
,"Ab.C", (void*)1);
2470 test_eq_ptr(strmap_get(map
,"ab.c"), (void*)1);
2471 strmap_assert_ok(map
);
2472 test_eq_ptr(strmap_get_lc(map
,"AB.C"), (void*)1);
2473 test_eq_ptr(strmap_get(map
,"AB.C"), NULL
);
2474 test_eq_ptr(strmap_remove_lc(map
,"aB.C"), (void*)1);
2475 strmap_assert_ok(map
);
2476 test_eq_ptr(strmap_get_lc(map
,"AB.C"), NULL
);
2480 strmap_free(map
,NULL
);
2482 SMARTLIST_FOREACH(found_keys
, char *, cp
, tor_free(cp
));
2483 smartlist_free(found_keys
);
2489 test_util_mmap(void)
2491 char *fname1
= tor_strdup(get_fname("mapped_1"));
2492 char *fname2
= tor_strdup(get_fname("mapped_2"));
2493 char *fname3
= tor_strdup(get_fname("mapped_3"));
2494 const size_t buflen
= 17000;
2495 char *buf
= tor_malloc(17000);
2496 tor_mmap_t
*mapping
= NULL
;
2498 crypto_rand(buf
, buflen
);
2500 mapping
= tor_mmap_file(fname1
);
2501 test_assert(! mapping
);
2503 write_str_to_file(fname1
, "Short file.", 1);
2504 write_bytes_to_file(fname2
, buf
, buflen
, 1);
2505 write_bytes_to_file(fname3
, buf
, 16384, 1);
2507 mapping
= tor_mmap_file(fname1
);
2508 test_assert(mapping
);
2509 test_eq(mapping
->size
, strlen("Short file."));
2510 test_streq(mapping
->data
, "Short file.");
2512 tor_munmap_file(mapping
);
2514 test_assert(unlink(fname1
) == 0);
2516 /* make sure we can unlink. */
2517 test_assert(unlink(fname1
) == 0);
2518 test_streq(mapping
->data
, "Short file.");
2519 tor_munmap_file(mapping
);
2523 /* Now a zero-length file. */
2524 write_str_to_file(fname1
, "", 1);
2525 mapping
= tor_mmap_file(fname1
);
2526 test_eq(mapping
, NULL
);
2527 test_eq(ERANGE
, errno
);
2530 /* Make sure that we fail to map a no-longer-existent file. */
2531 mapping
= tor_mmap_file(fname1
);
2532 test_assert(mapping
== NULL
);
2534 /* Now try a big file that stretches across a few pages and isn't aligned */
2535 mapping
= tor_mmap_file(fname2
);
2536 test_assert(mapping
);
2537 test_eq(mapping
->size
, buflen
);
2538 test_memeq(mapping
->data
, buf
, buflen
);
2539 tor_munmap_file(mapping
);
2542 /* Now try a big aligned file. */
2543 mapping
= tor_mmap_file(fname3
);
2544 test_assert(mapping
);
2545 test_eq(mapping
->size
, 16384);
2546 test_memeq(mapping
->data
, buf
, 16384);
2547 tor_munmap_file(mapping
);
2561 tor_munmap_file(mapping
);
2565 test_util_control_formats(void)
2569 "..This is a test\r\nof the emergency \nbroadcast\r\n..system.\r\nZ.\r\n";
2572 sz
= read_escaped_data(inp
, strlen(inp
), &out
);
2574 ".This is a test\nof the emergency \nbroadcast\n.system.\nZ.\n");
2575 test_eq(sz
, strlen(out
));
2582 test_onion_handshake(void)
2585 crypto_dh_env_t
*c_dh
= NULL
;
2586 char c_buf
[ONIONSKIN_CHALLENGE_LEN
];
2590 char s_buf
[ONIONSKIN_REPLY_LEN
];
2594 crypto_pk_env_t
*pk
= NULL
;
2596 pk
= pk_generate(0);
2598 /* client handshake 1. */
2599 memset(c_buf
, 0, ONIONSKIN_CHALLENGE_LEN
);
2600 test_assert(! onion_skin_create(pk
, &c_dh
, c_buf
));
2602 /* server handshake */
2603 memset(s_buf
, 0, ONIONSKIN_REPLY_LEN
);
2604 memset(s_keys
, 0, 40);
2605 test_assert(! onion_skin_server_handshake(c_buf
, pk
, NULL
,
2606 s_buf
, s_keys
, 40));
2608 /* client handshake 2 */
2609 memset(c_keys
, 0, 40);
2610 test_assert(! onion_skin_client_handshake(c_dh
, s_buf
, c_keys
, 40));
2612 if (memcmp(c_keys
, s_keys
, 40)) {
2616 test_memeq(c_keys
, s_keys
, 40);
2617 memset(s_buf
, 0, 40);
2618 test_memneq(c_keys
, s_buf
, 40);
2622 crypto_dh_free(c_dh
);
2624 crypto_free_pk_env(pk
);
2627 extern smartlist_t
*fingerprint_list
;
2630 test_dir_format(void)
2632 char buf
[8192], buf2
[8192];
2634 char fingerprint
[FINGERPRINT_LEN
+1];
2635 char *pk1_str
= NULL
, *pk2_str
= NULL
, *pk3_str
= NULL
, *cp
;
2636 size_t pk1_str_len
, pk2_str_len
, pk3_str_len
;
2637 routerinfo_t
*r1
, *r2
;
2638 crypto_pk_env_t
*pk1
= NULL
, *pk2
= NULL
, *pk3
= NULL
;
2639 routerinfo_t
*rp1
= NULL
, *rp2
= NULL
;
2640 addr_policy_t
*ex1
, *ex2
;
2641 routerlist_t
*dir1
= NULL
, *dir2
= NULL
;
2644 pk1
= pk_generate(0);
2645 pk2
= pk_generate(1);
2646 pk3
= pk_generate(2);
2648 test_assert( is_legal_nickname("a"));
2649 test_assert(!is_legal_nickname(""));
2650 test_assert(!is_legal_nickname("abcdefghijklmnopqrst")); /* 20 chars */
2651 test_assert(!is_legal_nickname("hyphen-")); /* bad char */
2652 test_assert( is_legal_nickname("abcdefghijklmnopqrs")); /* 19 chars */
2653 test_assert(!is_legal_nickname("$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2655 test_assert( is_legal_nickname_or_hexdigest(
2656 "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2657 test_assert( is_legal_nickname_or_hexdigest(
2658 "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA=fred"));
2659 test_assert( is_legal_nickname_or_hexdigest(
2660 "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA~fred"));
2662 test_assert(!is_legal_nickname_or_hexdigest(
2663 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2665 test_assert(!is_legal_nickname_or_hexdigest(
2666 "$AAAAAAzAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2667 /* hex part too long */
2668 test_assert(!is_legal_nickname_or_hexdigest(
2669 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2670 test_assert(!is_legal_nickname_or_hexdigest(
2671 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=fred"));
2673 test_assert(!is_legal_nickname_or_hexdigest(
2674 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="));
2675 test_assert(!is_legal_nickname_or_hexdigest(
2676 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~"));
2677 test_assert(!is_legal_nickname_or_hexdigest(
2678 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~hyphen-"));
2679 test_assert(!is_legal_nickname_or_hexdigest(
2680 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~"
2681 "abcdefghijklmnoppqrst"));
2682 /* Bad extra char. */
2683 test_assert(!is_legal_nickname_or_hexdigest(
2684 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA!"));
2685 test_assert(is_legal_nickname_or_hexdigest("xyzzy"));
2686 test_assert(is_legal_nickname_or_hexdigest("abcdefghijklmnopqrs"));
2687 test_assert(!is_legal_nickname_or_hexdigest("abcdefghijklmnopqrst"));
2689 get_platform_str(platform
, sizeof(platform
));
2690 r1
= tor_malloc_zero(sizeof(routerinfo_t
));
2691 r1
->address
= tor_strdup("18.244.0.1");
2692 r1
->addr
= 0xc0a80001u
; /* 192.168.0.1 */
2693 r1
->cache_info
.published_on
= 0;
2695 r1
->dir_port
= 9003;
2696 r1
->onion_pkey
= crypto_pk_dup_key(pk1
);
2697 r1
->identity_pkey
= crypto_pk_dup_key(pk2
);
2698 r1
->bandwidthrate
= 1000;
2699 r1
->bandwidthburst
= 5000;
2700 r1
->bandwidthcapacity
= 10000;
2701 r1
->exit_policy
= NULL
;
2702 r1
->nickname
= tor_strdup("Magri");
2703 r1
->platform
= tor_strdup(platform
);
2705 ex1
= tor_malloc_zero(sizeof(addr_policy_t
));
2706 ex2
= tor_malloc_zero(sizeof(addr_policy_t
));
2707 ex1
->policy_type
= ADDR_POLICY_ACCEPT
;
2708 tor_addr_from_ipv4h(&ex1
->addr
, 0);
2710 ex1
->prt_min
= ex1
->prt_max
= 80;
2711 ex2
->policy_type
= ADDR_POLICY_REJECT
;
2712 tor_addr_from_ipv4h(&ex2
->addr
, 18<<24);
2714 ex2
->prt_min
= ex2
->prt_max
= 24;
2715 r2
= tor_malloc_zero(sizeof(routerinfo_t
));
2716 r2
->address
= tor_strdup("1.1.1.1");
2717 r2
->addr
= 0x0a030201u
; /* 10.3.2.1 */
2718 r2
->platform
= tor_strdup(platform
);
2719 r2
->cache_info
.published_on
= 5;
2722 r2
->onion_pkey
= crypto_pk_dup_key(pk2
);
2723 r2
->identity_pkey
= crypto_pk_dup_key(pk1
);
2724 r2
->bandwidthrate
= r2
->bandwidthburst
= r2
->bandwidthcapacity
= 3000;
2725 r2
->exit_policy
= smartlist_create();
2726 smartlist_add(r2
->exit_policy
, ex2
);
2727 smartlist_add(r2
->exit_policy
, ex1
);
2728 r2
->nickname
= tor_strdup("Fred");
2730 test_assert(!crypto_pk_write_public_key_to_string(pk1
, &pk1_str
,
2732 test_assert(!crypto_pk_write_public_key_to_string(pk2
, &pk2_str
,
2734 test_assert(!crypto_pk_write_public_key_to_string(pk3
, &pk3_str
,
2737 memset(buf
, 0, 2048);
2738 test_assert(router_dump_router_to_string(buf
, 2048, r1
, pk2
)>0);
2740 strlcpy(buf2
, "router Magri 18.244.0.1 9000 0 9003\n"
2741 "platform Tor "VERSION
" on ", sizeof(buf2
));
2742 strlcat(buf2
, get_uname(), sizeof(buf2
));
2744 "opt protocols Link 1 2 Circuit 1\n"
2745 "published 1970-01-01 00:00:00\n"
2746 "opt fingerprint ", sizeof(buf2
));
2747 test_assert(!crypto_pk_get_fingerprint(pk2
, fingerprint
, 1));
2748 strlcat(buf2
, fingerprint
, sizeof(buf2
));
2749 strlcat(buf2
, "\nuptime 0\n"
2750 /* XXX the "0" above is hardcoded, but even if we made it reflect
2751 * uptime, that still wouldn't make it right, because the two
2752 * descriptors might be made on different seconds... hm. */
2753 "bandwidth 1000 5000 10000\n"
2754 "opt extra-info-digest 0000000000000000000000000000000000000000\n"
2755 "onion-key\n", sizeof(buf2
));
2756 strlcat(buf2
, pk1_str
, sizeof(buf2
));
2757 strlcat(buf2
, "signing-key\n", sizeof(buf2
));
2758 strlcat(buf2
, pk2_str
, sizeof(buf2
));
2759 strlcat(buf2
, "reject *:*\nrouter-signature\n", sizeof(buf2
));
2760 buf
[strlen(buf2
)] = '\0'; /* Don't compare the sig; it's never the same
2763 test_streq(buf
, buf2
);
2765 test_assert(router_dump_router_to_string(buf
, 2048, r1
, pk2
)>0);
2767 rp1
= router_parse_entry_from_string((const char*)cp
,NULL
,1,0,NULL
);
2769 test_streq(rp1
->address
, r1
->address
);
2770 test_eq(rp1
->or_port
, r1
->or_port
);
2771 //test_eq(rp1->dir_port, r1->dir_port);
2772 test_eq(rp1
->bandwidthrate
, r1
->bandwidthrate
);
2773 test_eq(rp1
->bandwidthburst
, r1
->bandwidthburst
);
2774 test_eq(rp1
->bandwidthcapacity
, r1
->bandwidthcapacity
);
2775 test_assert(crypto_pk_cmp_keys(rp1
->onion_pkey
, pk1
) == 0);
2776 test_assert(crypto_pk_cmp_keys(rp1
->identity_pkey
, pk2
) == 0);
2777 //test_assert(rp1->exit_policy == NULL);
2780 /* XXX Once we have exit policies, test this again. XXX */
2781 strlcpy(buf2
, "router tor.tor.tor 9005 0 0 3000\n", sizeof(buf2
));
2782 strlcat(buf2
, pk2_str
, sizeof(buf2
));
2783 strlcat(buf2
, "signing-key\n", sizeof(buf2
));
2784 strlcat(buf2
, pk1_str
, sizeof(buf2
));
2785 strlcat(buf2
, "accept *:80\nreject 18.*:24\n\n", sizeof(buf2
));
2786 test_assert(router_dump_router_to_string(buf
, 2048, &r2
, pk2
)>0);
2787 test_streq(buf
, buf2
);
2790 rp2
= router_parse_entry_from_string(&cp
,1);
2792 test_streq(rp2
->address
, r2
.address
);
2793 test_eq(rp2
->or_port
, r2
.or_port
);
2794 test_eq(rp2
->dir_port
, r2
.dir_port
);
2795 test_eq(rp2
->bandwidth
, r2
.bandwidth
);
2796 test_assert(crypto_pk_cmp_keys(rp2
->onion_pkey
, pk2
) == 0);
2797 test_assert(crypto_pk_cmp_keys(rp2
->identity_pkey
, pk1
) == 0);
2798 test_eq(rp2
->exit_policy
->policy_type
, EXIT_POLICY_ACCEPT
);
2799 test_streq(rp2
->exit_policy
->string
, "accept *:80");
2800 test_streq(rp2
->exit_policy
->address
, "*");
2801 test_streq(rp2
->exit_policy
->port
, "80");
2802 test_eq(rp2
->exit_policy
->next
->policy_type
, EXIT_POLICY_REJECT
);
2803 test_streq(rp2
->exit_policy
->next
->string
, "reject 18.*:24");
2804 test_streq(rp2
->exit_policy
->next
->address
, "18.*");
2805 test_streq(rp2
->exit_policy
->next
->port
, "24");
2806 test_assert(rp2
->exit_policy
->next
->next
== NULL
);
2808 /* Okay, now for the directories. */
2810 fingerprint_list
= smartlist_create();
2811 crypto_pk_get_fingerprint(pk2
, buf
, 1);
2812 add_fingerprint_to_dir("Magri", buf
, fingerprint_list
);
2813 crypto_pk_get_fingerprint(pk1
, buf
, 1);
2814 add_fingerprint_to_dir("Fred", buf
, fingerprint_list
);
2820 /* XXXX NM re-enable. */
2821 /* Make sure routers aren't too far in the past any more. */
2822 r1
->cache_info
.published_on
= time(NULL
);
2823 r2
->cache_info
.published_on
= time(NULL
)-3*60*60;
2824 test_assert(router_dump_router_to_string(buf
, 2048, r1
, pk2
)>0);
2825 test_eq(dirserv_add_descriptor(buf
,&m
), 2);
2826 test_assert(router_dump_router_to_string(buf
, 2048, r2
, pk1
)>0);
2827 test_eq(dirserv_add_descriptor(buf
,&m
), 2);
2828 get_options()->Nickname
= tor_strdup("DirServer");
2829 test_assert(!dirserv_dump_directory_to_string(&cp
,pk3
, 0));
2830 crypto_pk_get_digest(pk3
, d
);
2831 test_assert(!router_parse_directory(cp
));
2832 test_eq(2, smartlist_len(dir1
->routers
));
2836 dirserv_free_fingerprint_list();
2841 if (pk1
) crypto_free_pk_env(pk1
);
2842 if (pk2
) crypto_free_pk_env(pk2
);
2843 if (pk3
) crypto_free_pk_env(pk3
);
2844 if (rp1
) routerinfo_free(rp1
);
2845 if (rp2
) routerinfo_free(rp2
);
2846 tor_free(dir1
); /* XXXX And more !*/
2847 tor_free(dir2
); /* And more !*/
2848 routerinfo_free(r1
);
2849 routerinfo_free(r2
);
2851 /* Try out version parsing functionality */
2852 test_eq(0, tor_version_parse("0.3.4pre2-cvs", &ver1
));
2853 test_eq(0, ver1
.major
);
2854 test_eq(3, ver1
.minor
);
2855 test_eq(4, ver1
.micro
);
2856 test_eq(VER_PRE
, ver1
.status
);
2857 test_eq(2, ver1
.patchlevel
);
2858 test_eq(0, tor_version_parse("0.3.4rc1", &ver1
));
2859 test_eq(0, ver1
.major
);
2860 test_eq(3, ver1
.minor
);
2861 test_eq(4, ver1
.micro
);
2862 test_eq(VER_RC
, ver1
.status
);
2863 test_eq(1, ver1
.patchlevel
);
2864 test_eq(0, tor_version_parse("1.3.4", &ver1
));
2865 test_eq(1, ver1
.major
);
2866 test_eq(3, ver1
.minor
);
2867 test_eq(4, ver1
.micro
);
2868 test_eq(VER_RELEASE
, ver1
.status
);
2869 test_eq(0, ver1
.patchlevel
);
2870 test_eq(0, tor_version_parse("1.3.4.999", &ver1
));
2871 test_eq(1, ver1
.major
);
2872 test_eq(3, ver1
.minor
);
2873 test_eq(4, ver1
.micro
);
2874 test_eq(VER_RELEASE
, ver1
.status
);
2875 test_eq(999, ver1
.patchlevel
);
2876 test_eq(0, tor_version_parse("0.1.2.4-alpha", &ver1
));
2877 test_eq(0, ver1
.major
);
2878 test_eq(1, ver1
.minor
);
2879 test_eq(2, ver1
.micro
);
2880 test_eq(4, ver1
.patchlevel
);
2881 test_eq(VER_RELEASE
, ver1
.status
);
2882 test_streq("alpha", ver1
.status_tag
);
2883 test_eq(0, tor_version_parse("0.1.2.4", &ver1
));
2884 test_eq(0, ver1
.major
);
2885 test_eq(1, ver1
.minor
);
2886 test_eq(2, ver1
.micro
);
2887 test_eq(4, ver1
.patchlevel
);
2888 test_eq(VER_RELEASE
, ver1
.status
);
2889 test_streq("", ver1
.status_tag
);
2891 #define test_eq_vs(vs1, vs2) test_eq_type(version_status_t, "%d", (vs1), (vs2))
2892 #define test_v_i_o(val, ver, lst) \
2893 test_eq_vs(val, tor_version_is_obsolete(ver, lst))
2895 /* make sure tor_version_is_obsolete() works */
2896 test_v_i_o(VS_OLD
, "0.0.1", "Tor 0.0.2");
2897 test_v_i_o(VS_OLD
, "0.0.1", "0.0.2, Tor 0.0.3");
2898 test_v_i_o(VS_OLD
, "0.0.1", "0.0.2,Tor 0.0.3");
2899 test_v_i_o(VS_OLD
, "0.0.1","0.0.3,BetterTor 0.0.1");
2900 test_v_i_o(VS_RECOMMENDED
, "0.0.2", "Tor 0.0.2,Tor 0.0.3");
2901 test_v_i_o(VS_NEW_IN_SERIES
, "0.0.2", "Tor 0.0.2pre1,Tor 0.0.3");
2902 test_v_i_o(VS_OLD
, "0.0.2", "Tor 0.0.2.1,Tor 0.0.3");
2903 test_v_i_o(VS_NEW
, "0.1.0", "Tor 0.0.2,Tor 0.0.3");
2904 test_v_i_o(VS_RECOMMENDED
, "0.0.7rc2", "0.0.7,Tor 0.0.7rc2,Tor 0.0.8");
2905 test_v_i_o(VS_OLD
, "0.0.5.0", "0.0.5.1-cvs");
2906 test_v_i_o(VS_NEW_IN_SERIES
, "0.0.5.1-cvs", "0.0.5, 0.0.6");
2907 /* Not on list, but newer than any in same series. */
2908 test_v_i_o(VS_NEW_IN_SERIES
, "0.1.0.3",
2909 "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
2910 /* Series newer than any on list. */
2911 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");
2912 /* Series older than any on list. */
2913 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");
2914 /* Not on list, not newer than any on same series. */
2915 test_v_i_o(VS_UNRECOMMENDED
, "0.1.0.1",
2916 "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
2917 /* On list, not newer than any on same series. */
2918 test_v_i_o(VS_UNRECOMMENDED
,
2919 "0.1.0.1", "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
2920 test_eq(0, tor_version_as_new_as("Tor 0.0.5", "0.0.9pre1-cvs"));
2921 test_eq(1, tor_version_as_new_as(
2922 "Tor 0.0.8 on Darwin 64-121-192-100.c3-0."
2923 "sfpo-ubr1.sfrn-sfpo.ca.cable.rcn.com Power Macintosh",
2925 test_eq(0, tor_version_as_new_as(
2926 "Tor 0.0.8 on Darwin 64-121-192-100.c3-0."
2927 "sfpo-ubr1.sfrn-sfpo.ca.cable.rcn.com Power Macintosh", "0.0.8.2"));
2929 /* Now try svn revisions. */
2930 test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100)",
2931 "Tor 0.2.1.0-dev (r99)"));
2932 test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100) on Banana Jr",
2933 "Tor 0.2.1.0-dev (r99) on Hal 9000"));
2934 test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100)",
2935 "Tor 0.2.1.0-dev on Colossus"));
2936 test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev (r99)",
2937 "Tor 0.2.1.0-dev (r100)"));
2938 test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev (r99) on MCP",
2939 "Tor 0.2.1.0-dev (r100) on AM"));
2940 test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev",
2941 "Tor 0.2.1.0-dev (r99)"));
2942 test_eq(1, tor_version_as_new_as("Tor 0.2.1.1",
2943 "Tor 0.2.1.0-dev (r99)"));
2948 extern const char AUTHORITY_CERT_1
[];
2949 extern const char AUTHORITY_SIGNKEY_1
[];
2950 extern const char AUTHORITY_CERT_2
[];
2951 extern const char AUTHORITY_SIGNKEY_2
[];
2952 extern const char AUTHORITY_CERT_3
[];
2953 extern const char AUTHORITY_SIGNKEY_3
[];
2956 test_same_voter(networkstatus_voter_info_t
*v1
,
2957 networkstatus_voter_info_t
*v2
)
2959 test_streq(v1
->nickname
, v2
->nickname
);
2960 test_memeq(v1
->identity_digest
, v2
->identity_digest
, DIGEST_LEN
);
2961 test_streq(v1
->address
, v2
->address
);
2962 test_eq(v1
->addr
, v2
->addr
);
2963 test_eq(v1
->dir_port
, v2
->dir_port
);
2964 test_eq(v1
->or_port
, v2
->or_port
);
2965 test_streq(v1
->contact
, v2
->contact
);
2966 test_memeq(v1
->vote_digest
, v2
->vote_digest
, DIGEST_LEN
);
2972 test_util_order_functions(void)
2975 // int a=12,b=24,c=25,d=60,e=77;
2977 #define median() median_int(lst, n)
2980 test_eq(12, median()); /* 12 */
2982 //smartlist_shuffle(sl);
2983 test_eq(12, median()); /* 12, 77 */
2985 //smartlist_shuffle(sl);
2986 test_eq(77, median()); /* 12, 77, 77 */
2988 test_eq(24, median()); /* 12,24,77,77 */
2992 //smartlist_shuffle(sl);
2993 test_eq(25, median()); /* 12,12,24,25,60,77,77 */
3000 static routerinfo_t
*
3001 generate_ri_from_rs(const vote_routerstatus_t
*vrs
)
3004 const routerstatus_t
*rs
= &vrs
->status
;
3005 static time_t published
= 0;
3007 r
= tor_malloc_zero(sizeof(routerinfo_t
));
3008 memcpy(r
->cache_info
.identity_digest
, rs
->identity_digest
, DIGEST_LEN
);
3009 memcpy(r
->cache_info
.signed_descriptor_digest
, rs
->descriptor_digest
,
3011 r
->cache_info
.do_not_cache
= 1;
3012 r
->cache_info
.routerlist_index
= -1;
3013 r
->cache_info
.signed_descriptor_body
=
3014 tor_strdup("123456789012345678901234567890123");
3015 r
->cache_info
.signed_descriptor_len
=
3016 strlen(r
->cache_info
.signed_descriptor_body
);
3017 r
->exit_policy
= smartlist_create();
3018 r
->cache_info
.published_on
= ++published
+ time(NULL
);
3023 test_v3_networkstatus(void)
3025 authority_cert_t
*cert1
, *cert2
, *cert3
;
3026 crypto_pk_env_t
*sign_skey_1
, *sign_skey_2
, *sign_skey_3
;
3027 crypto_pk_env_t
*sign_skey_leg1
;
3028 const char *msg
=NULL
;
3030 time_t now
= time(NULL
);
3031 networkstatus_voter_info_t
*voter
;
3032 networkstatus_t
*vote
, *v1
, *v2
, *v3
, *con
;
3033 vote_routerstatus_t
*vrs
;
3035 char *v1_text
, *v2_text
, *v3_text
, *consensus_text
, *cp
;
3036 smartlist_t
*votes
= smartlist_create();
3038 /* Parse certificates and keys. */
3039 cert1
= authority_cert_parse_from_string(AUTHORITY_CERT_1
, NULL
);
3041 cert2
= authority_cert_parse_from_string(AUTHORITY_CERT_2
, NULL
);
3043 cert3
= authority_cert_parse_from_string(AUTHORITY_CERT_3
, NULL
);
3045 sign_skey_1
= crypto_new_pk_env();
3046 sign_skey_2
= crypto_new_pk_env();
3047 sign_skey_3
= crypto_new_pk_env();
3048 sign_skey_leg1
= pk_generate(4);
3050 test_assert(!crypto_pk_read_private_key_from_string(sign_skey_1
,
3051 AUTHORITY_SIGNKEY_1
));
3052 test_assert(!crypto_pk_read_private_key_from_string(sign_skey_2
,
3053 AUTHORITY_SIGNKEY_2
));
3054 test_assert(!crypto_pk_read_private_key_from_string(sign_skey_3
,
3055 AUTHORITY_SIGNKEY_3
));
3057 test_assert(!crypto_pk_cmp_keys(sign_skey_1
, cert1
->signing_key
));
3058 test_assert(!crypto_pk_cmp_keys(sign_skey_2
, cert2
->signing_key
));
3061 * Set up a vote; generate it; try to parse it.
3063 vote
= tor_malloc_zero(sizeof(networkstatus_t
));
3064 vote
->type
= NS_TYPE_VOTE
;
3065 vote
->published
= now
;
3066 vote
->valid_after
= now
+1000;
3067 vote
->fresh_until
= now
+2000;
3068 vote
->valid_until
= now
+3000;
3069 vote
->vote_seconds
= 100;
3070 vote
->dist_seconds
= 200;
3071 vote
->supported_methods
= smartlist_create();
3072 smartlist_split_string(vote
->supported_methods
, "1 2 3", NULL
, 0, -1);
3073 vote
->client_versions
= tor_strdup("0.1.2.14,0.1.2.15");
3074 vote
->server_versions
= tor_strdup("0.1.2.14,0.1.2.15,0.1.2.16");
3075 vote
->known_flags
= smartlist_create();
3076 smartlist_split_string(vote
->known_flags
,
3077 "Authority Exit Fast Guard Running Stable V2Dir Valid",
3078 0, SPLIT_SKIP_SPACE
|SPLIT_IGNORE_BLANK
, 0);
3079 vote
->voters
= smartlist_create();
3080 voter
= tor_malloc_zero(sizeof(networkstatus_voter_info_t
));
3081 voter
->nickname
= tor_strdup("Voter1");
3082 voter
->address
= tor_strdup("1.2.3.4");
3083 voter
->addr
= 0x01020304;
3084 voter
->dir_port
= 80;
3085 voter
->or_port
= 9000;
3086 voter
->contact
= tor_strdup("voter@example.com");
3087 crypto_pk_get_digest(cert1
->identity_key
, voter
->identity_digest
);
3088 smartlist_add(vote
->voters
, voter
);
3089 vote
->cert
= authority_cert_dup(cert1
);
3090 vote
->routerstatus_list
= smartlist_create();
3091 /* add the first routerstatus. */
3092 vrs
= tor_malloc_zero(sizeof(vote_routerstatus_t
));
3094 vrs
->version
= tor_strdup("0.1.2.14");
3095 rs
->published_on
= now
-1500;
3096 strlcpy(rs
->nickname
, "router2", sizeof(rs
->nickname
));
3097 memset(rs
->identity_digest
, 3, DIGEST_LEN
);
3098 memset(rs
->descriptor_digest
, 78, DIGEST_LEN
);
3099 rs
->addr
= 0x99008801;
3101 rs
->dir_port
= 8000;
3102 /* all flags but running cleared */
3104 smartlist_add(vote
->routerstatus_list
, vrs
);
3105 test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs
), &msg
,0,0)>=0);
3107 /* add the second routerstatus. */
3108 vrs
= tor_malloc_zero(sizeof(vote_routerstatus_t
));
3110 vrs
->version
= tor_strdup("0.2.0.5");
3111 rs
->published_on
= now
-1000;
3112 strlcpy(rs
->nickname
, "router1", sizeof(rs
->nickname
));
3113 memset(rs
->identity_digest
, 5, DIGEST_LEN
);
3114 memset(rs
->descriptor_digest
, 77, DIGEST_LEN
);
3115 rs
->addr
= 0x99009901;
3118 rs
->is_exit
= rs
->is_stable
= rs
->is_fast
= rs
->is_running
=
3119 rs
->is_valid
= rs
->is_v2_dir
= rs
->is_possible_guard
= 1;
3120 smartlist_add(vote
->routerstatus_list
, vrs
);
3121 test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs
), &msg
,0,0)>=0);
3123 /* add the third routerstatus. */
3124 vrs
= tor_malloc_zero(sizeof(vote_routerstatus_t
));
3126 vrs
->version
= tor_strdup("0.1.0.3");
3127 rs
->published_on
= now
-1000;
3128 strlcpy(rs
->nickname
, "router3", sizeof(rs
->nickname
));
3129 memset(rs
->identity_digest
, 33, DIGEST_LEN
);
3130 memset(rs
->descriptor_digest
, 79, DIGEST_LEN
);
3131 rs
->addr
= 0xAA009901;
3133 rs
->dir_port
= 9999;
3134 rs
->is_authority
= rs
->is_exit
= rs
->is_stable
= rs
->is_fast
=
3135 rs
->is_running
= rs
->is_valid
= rs
->is_v2_dir
= rs
->is_possible_guard
= 1;
3136 smartlist_add(vote
->routerstatus_list
, vrs
);
3137 test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs
), &msg
,0,0)>=0);
3139 /* add a fourth routerstatus that is not running. */
3140 vrs
= tor_malloc_zero(sizeof(vote_routerstatus_t
));
3142 vrs
->version
= tor_strdup("0.1.6.3");
3143 rs
->published_on
= now
-1000;
3144 strlcpy(rs
->nickname
, "router4", sizeof(rs
->nickname
));
3145 memset(rs
->identity_digest
, 34, DIGEST_LEN
);
3146 memset(rs
->descriptor_digest
, 48, DIGEST_LEN
);
3147 rs
->addr
= 0xC0000203;
3149 rs
->dir_port
= 1999;
3150 /* Running flag (and others) cleared */
3151 smartlist_add(vote
->routerstatus_list
, vrs
);
3152 test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs
), &msg
,0,0)>=0);
3154 /* dump the vote and try to parse it. */
3155 v1_text
= format_networkstatus_vote(sign_skey_1
, vote
);
3156 test_assert(v1_text
);
3157 v1
= networkstatus_parse_vote_from_string(v1_text
, NULL
, NS_TYPE_VOTE
);
3160 /* Make sure the parsed thing was right. */
3161 test_eq(v1
->type
, NS_TYPE_VOTE
);
3162 test_eq(v1
->published
, vote
->published
);
3163 test_eq(v1
->valid_after
, vote
->valid_after
);
3164 test_eq(v1
->fresh_until
, vote
->fresh_until
);
3165 test_eq(v1
->valid_until
, vote
->valid_until
);
3166 test_eq(v1
->vote_seconds
, vote
->vote_seconds
);
3167 test_eq(v1
->dist_seconds
, vote
->dist_seconds
);
3168 test_streq(v1
->client_versions
, vote
->client_versions
);
3169 test_streq(v1
->server_versions
, vote
->server_versions
);
3170 test_assert(v1
->voters
&& smartlist_len(v1
->voters
));
3171 voter
= smartlist_get(v1
->voters
, 0);
3172 test_streq(voter
->nickname
, "Voter1");
3173 test_streq(voter
->address
, "1.2.3.4");
3174 test_eq(voter
->addr
, 0x01020304);
3175 test_eq(voter
->dir_port
, 80);
3176 test_eq(voter
->or_port
, 9000);
3177 test_streq(voter
->contact
, "voter@example.com");
3178 test_assert(v1
->cert
);
3179 test_assert(!crypto_pk_cmp_keys(sign_skey_1
, v1
->cert
->signing_key
));
3180 cp
= smartlist_join_strings(v1
->known_flags
, ":", 0, NULL
);
3181 test_streq(cp
, "Authority:Exit:Fast:Guard:Running:Stable:V2Dir:Valid");
3183 test_eq(smartlist_len(v1
->routerstatus_list
), 4);
3184 /* Check the first routerstatus. */
3185 vrs
= smartlist_get(v1
->routerstatus_list
, 0);
3187 test_streq(vrs
->version
, "0.1.2.14");
3188 test_eq(rs
->published_on
, now
-1500);
3189 test_streq(rs
->nickname
, "router2");
3190 test_memeq(rs
->identity_digest
,
3191 "\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3",
3193 test_memeq(rs
->descriptor_digest
, "NNNNNNNNNNNNNNNNNNNN", DIGEST_LEN
);
3194 test_eq(rs
->addr
, 0x99008801);
3195 test_eq(rs
->or_port
, 443);
3196 test_eq(rs
->dir_port
, 8000);
3197 test_eq(vrs
->flags
, U64_LITERAL(16)); // no flags except "running"
3198 /* Check the second routerstatus. */
3199 vrs
= smartlist_get(v1
->routerstatus_list
, 1);
3201 test_streq(vrs
->version
, "0.2.0.5");
3202 test_eq(rs
->published_on
, now
-1000);
3203 test_streq(rs
->nickname
, "router1");
3204 test_memeq(rs
->identity_digest
,
3205 "\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5",
3207 test_memeq(rs
->descriptor_digest
, "MMMMMMMMMMMMMMMMMMMM", DIGEST_LEN
);
3208 test_eq(rs
->addr
, 0x99009901);
3209 test_eq(rs
->or_port
, 443);
3210 test_eq(rs
->dir_port
, 0);
3211 test_eq(vrs
->flags
, U64_LITERAL(254)); // all flags except "authority."
3213 /* Generate second vote. It disagrees on some of the times,
3214 * and doesn't list versions, and knows some crazy flags */
3215 vote
->published
= now
+1;
3216 vote
->fresh_until
= now
+3005;
3217 vote
->dist_seconds
= 300;
3218 authority_cert_free(vote
->cert
);
3219 vote
->cert
= authority_cert_dup(cert2
);
3220 tor_free(vote
->client_versions
);
3221 tor_free(vote
->server_versions
);
3222 voter
= smartlist_get(vote
->voters
, 0);
3223 tor_free(voter
->nickname
);
3224 tor_free(voter
->address
);
3225 voter
->nickname
= tor_strdup("Voter2");
3226 voter
->address
= tor_strdup("2.3.4.5");
3227 voter
->addr
= 0x02030405;
3228 crypto_pk_get_digest(cert2
->identity_key
, voter
->identity_digest
);
3229 smartlist_add(vote
->known_flags
, tor_strdup("MadeOfCheese"));
3230 smartlist_add(vote
->known_flags
, tor_strdup("MadeOfTin"));
3231 smartlist_sort_strings(vote
->known_flags
);
3232 vrs
= smartlist_get(vote
->routerstatus_list
, 2);
3233 smartlist_del_keeporder(vote
->routerstatus_list
, 2);
3234 tor_free(vrs
->version
);
3236 vrs
= smartlist_get(vote
->routerstatus_list
, 0);
3237 vrs
->status
.is_fast
= 1;
3238 /* generate and parse. */
3239 v2_text
= format_networkstatus_vote(sign_skey_2
, vote
);
3240 test_assert(v2_text
);
3241 v2
= networkstatus_parse_vote_from_string(v2_text
, NULL
, NS_TYPE_VOTE
);
3243 /* Check that flags come out right.*/
3244 cp
= smartlist_join_strings(v2
->known_flags
, ":", 0, NULL
);
3245 test_streq(cp
, "Authority:Exit:Fast:Guard:MadeOfCheese:MadeOfTin:"
3246 "Running:Stable:V2Dir:Valid");
3248 vrs
= smartlist_get(v2
->routerstatus_list
, 1);
3249 /* 1023 - authority(1) - madeofcheese(16) - madeoftin(32) */
3250 test_eq(vrs
->flags
, U64_LITERAL(974));
3252 /* Generate the third vote. */
3253 vote
->published
= now
;
3254 vote
->fresh_until
= now
+2003;
3255 vote
->dist_seconds
= 250;
3256 authority_cert_free(vote
->cert
);
3257 vote
->cert
= authority_cert_dup(cert3
);
3258 smartlist_add(vote
->supported_methods
, tor_strdup("4"));
3259 vote
->client_versions
= tor_strdup("0.1.2.14,0.1.2.17");
3260 vote
->server_versions
= tor_strdup("0.1.2.10,0.1.2.15,0.1.2.16");
3261 voter
= smartlist_get(vote
->voters
, 0);
3262 tor_free(voter
->nickname
);
3263 tor_free(voter
->address
);
3264 voter
->nickname
= tor_strdup("Voter3");
3265 voter
->address
= tor_strdup("3.4.5.6");
3266 voter
->addr
= 0x03040506;
3267 crypto_pk_get_digest(cert3
->identity_key
, voter
->identity_digest
);
3268 /* This one has a legacy id. */
3269 memset(voter
->legacy_id_digest
, (int)'A', DIGEST_LEN
);
3270 vrs
= smartlist_get(vote
->routerstatus_list
, 0);
3271 smartlist_del_keeporder(vote
->routerstatus_list
, 0);
3272 tor_free(vrs
->version
);
3274 vrs
= smartlist_get(vote
->routerstatus_list
, 0);
3275 memset(vrs
->status
.descriptor_digest
, (int)'Z', DIGEST_LEN
);
3276 test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs
), &msg
,0,0)>=0);
3278 v3_text
= format_networkstatus_vote(sign_skey_3
, vote
);
3279 test_assert(v3_text
);
3281 v3
= networkstatus_parse_vote_from_string(v3_text
, NULL
, NS_TYPE_VOTE
);
3284 /* Compute a consensus as voter 3. */
3285 smartlist_add(votes
, v3
);
3286 smartlist_add(votes
, v1
);
3287 smartlist_add(votes
, v2
);
3288 consensus_text
= networkstatus_compute_consensus(votes
, 3,
3289 cert3
->identity_key
,
3291 "AAAAAAAAAAAAAAAAAAAA",
3293 test_assert(consensus_text
);
3294 con
= networkstatus_parse_vote_from_string(consensus_text
, NULL
,
3297 //log_notice(LD_GENERAL, "<<%s>>\n<<%s>>\n<<%s>>\n",
3298 // v1_text, v2_text, v3_text);
3300 /* Check consensus contents. */
3301 test_assert(con
->type
== NS_TYPE_CONSENSUS
);
3302 test_eq(con
->published
, 0); /* this field only appears in votes. */
3303 test_eq(con
->valid_after
, now
+1000);
3304 test_eq(con
->fresh_until
, now
+2003); /* median */
3305 test_eq(con
->valid_until
, now
+3000);
3306 test_eq(con
->vote_seconds
, 100);
3307 test_eq(con
->dist_seconds
, 250); /* median */
3308 test_streq(con
->client_versions
, "0.1.2.14");
3309 test_streq(con
->server_versions
, "0.1.2.15,0.1.2.16");
3310 cp
= smartlist_join_strings(v2
->known_flags
, ":", 0, NULL
);
3311 test_streq(cp
, "Authority:Exit:Fast:Guard:MadeOfCheese:MadeOfTin:"
3312 "Running:Stable:V2Dir:Valid");
3314 test_eq(4, smartlist_len(con
->voters
)); /*3 voters, 1 legacy key.*/
3315 /* The voter id digests should be in this order. */
3316 test_assert(memcmp(cert2
->cache_info
.identity_digest
,
3317 cert3
->cache_info
.identity_digest
,DIGEST_LEN
)<0);
3318 test_assert(memcmp(cert3
->cache_info
.identity_digest
,
3319 cert1
->cache_info
.identity_digest
,DIGEST_LEN
)<0);
3320 test_same_voter(smartlist_get(con
->voters
, 1),
3321 smartlist_get(v2
->voters
, 0));
3322 test_same_voter(smartlist_get(con
->voters
, 2),
3323 smartlist_get(v3
->voters
, 0));
3324 test_same_voter(smartlist_get(con
->voters
, 3),
3325 smartlist_get(v1
->voters
, 0));
3327 test_assert(!con
->cert
);
3328 test_eq(2, smartlist_len(con
->routerstatus_list
));
3329 /* There should be two listed routers: one with identity 3, one with
3331 /* This one showed up in 2 digests. */
3332 rs
= smartlist_get(con
->routerstatus_list
, 0);
3333 test_memeq(rs
->identity_digest
,
3334 "\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3",
3336 test_memeq(rs
->descriptor_digest
, "NNNNNNNNNNNNNNNNNNNN", DIGEST_LEN
);
3337 test_assert(!rs
->is_authority
);
3338 test_assert(!rs
->is_exit
);
3339 test_assert(!rs
->is_fast
);
3340 test_assert(!rs
->is_possible_guard
);
3341 test_assert(!rs
->is_stable
);
3342 test_assert(rs
->is_running
); /* If it wasn't running it wouldn't be here */
3343 test_assert(!rs
->is_v2_dir
);
3344 test_assert(!rs
->is_valid
);
3345 test_assert(!rs
->is_named
);
3346 /* XXXX check version */
3348 rs
= smartlist_get(con
->routerstatus_list
, 1);
3349 /* This one showed up in 3 digests. Twice with ID 'M', once with 'Z'. */
3350 test_memeq(rs
->identity_digest
,
3351 "\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5",
3353 test_streq(rs
->nickname
, "router1");
3354 test_memeq(rs
->descriptor_digest
, "MMMMMMMMMMMMMMMMMMMM", DIGEST_LEN
);
3355 test_eq(rs
->published_on
, now
-1000);
3356 test_eq(rs
->addr
, 0x99009901);
3357 test_eq(rs
->or_port
, 443);
3358 test_eq(rs
->dir_port
, 0);
3359 test_assert(!rs
->is_authority
);
3360 test_assert(rs
->is_exit
);
3361 test_assert(rs
->is_fast
);
3362 test_assert(rs
->is_possible_guard
);
3363 test_assert(rs
->is_stable
);
3364 test_assert(rs
->is_running
);
3365 test_assert(rs
->is_v2_dir
);
3366 test_assert(rs
->is_valid
);
3367 test_assert(!rs
->is_named
);
3368 /* XXXX check version */
3370 /* Check signatures. the first voter is pseudo. The second one hasn't
3371 signed. The third one has signed: validate it. */
3372 voter
= smartlist_get(con
->voters
, 1);
3373 test_assert(!voter
->signature
);
3374 test_assert(!voter
->good_signature
);
3375 test_assert(!voter
->bad_signature
);
3377 voter
= smartlist_get(con
->voters
, 2);
3378 test_assert(voter
->signature
);
3379 test_assert(!voter
->good_signature
);
3380 test_assert(!voter
->bad_signature
);
3381 test_assert(!networkstatus_check_voter_signature(con
,
3382 smartlist_get(con
->voters
, 2),
3384 test_assert(voter
->signature
);
3385 test_assert(voter
->good_signature
);
3386 test_assert(!voter
->bad_signature
);
3389 char *consensus_text2
, *consensus_text3
;
3390 networkstatus_t
*con2
, *con3
;
3391 char *detached_text1
, *detached_text2
;
3392 ns_detached_signatures_t
*dsig1
, *dsig2
;
3393 const char *msg
=NULL
;
3394 /* Compute the other two signed consensuses. */
3395 smartlist_shuffle(votes
);
3396 consensus_text2
= networkstatus_compute_consensus(votes
, 3,
3397 cert2
->identity_key
,
3398 sign_skey_2
, NULL
,NULL
);
3399 smartlist_shuffle(votes
);
3400 consensus_text3
= networkstatus_compute_consensus(votes
, 3,
3401 cert1
->identity_key
,
3402 sign_skey_1
, NULL
,NULL
);
3403 test_assert(consensus_text2
);
3404 test_assert(consensus_text3
);
3405 con2
= networkstatus_parse_vote_from_string(consensus_text2
, NULL
,
3407 con3
= networkstatus_parse_vote_from_string(consensus_text3
, NULL
,
3412 /* All three should have the same digest. */
3413 test_memeq(con
->networkstatus_digest
, con2
->networkstatus_digest
,
3415 test_memeq(con
->networkstatus_digest
, con3
->networkstatus_digest
,
3418 /* Extract a detached signature from con3. */
3419 detached_text1
= networkstatus_get_detached_signatures(con3
);
3420 tor_assert(detached_text1
);
3421 /* Try to parse it. */
3422 dsig1
= networkstatus_parse_detached_signatures(detached_text1
, NULL
);
3425 /* Are parsed values as expected? */
3426 test_eq(dsig1
->valid_after
, con3
->valid_after
);
3427 test_eq(dsig1
->fresh_until
, con3
->fresh_until
);
3428 test_eq(dsig1
->valid_until
, con3
->valid_until
);
3429 test_memeq(dsig1
->networkstatus_digest
, con3
->networkstatus_digest
,
3431 test_eq(1, smartlist_len(dsig1
->signatures
));
3432 voter
= smartlist_get(dsig1
->signatures
, 0);
3433 test_memeq(voter
->identity_digest
, cert1
->cache_info
.identity_digest
,
3436 /* Try adding it to con2. */
3437 detached_text2
= networkstatus_get_detached_signatures(con2
);
3438 test_eq(1, networkstatus_add_detached_signatures(con2
, dsig1
, &msg
));
3439 tor_free(detached_text2
);
3440 detached_text2
= networkstatus_get_detached_signatures(con2
);
3441 //printf("\n<%s>\n", detached_text2);
3442 dsig2
= networkstatus_parse_detached_signatures(detached_text2
, NULL
);
3446 SMARTLIST_FOREACH(dsig2->signatures, networkstatus_voter_info_t *, vi, {
3448 base16_encode(hd, sizeof(hd), vi->identity_digest, DIGEST_LEN);
3452 test_eq(2, smartlist_len(dsig2
->signatures
));
3454 /* Try adding to con2 twice; verify that nothing changes. */
3455 test_eq(0, networkstatus_add_detached_signatures(con2
, dsig1
, &msg
));
3458 test_eq(2, networkstatus_add_detached_signatures(con
, dsig2
, &msg
));
3459 /* Check signatures */
3460 test_assert(!networkstatus_check_voter_signature(con
,
3461 smartlist_get(con
->voters
, 1),
3463 test_assert(!networkstatus_check_voter_signature(con
,
3464 smartlist_get(con
->voters
, 3),
3467 networkstatus_vote_free(con2
);
3468 networkstatus_vote_free(con3
);
3469 tor_free(consensus_text2
);
3470 tor_free(consensus_text3
);
3471 tor_free(detached_text1
);
3472 tor_free(detached_text2
);
3473 ns_detached_signatures_free(dsig1
);
3474 ns_detached_signatures_free(dsig2
);
3477 smartlist_free(votes
);
3481 tor_free(consensus_text
);
3482 networkstatus_vote_free(vote
);
3483 networkstatus_vote_free(v1
);
3484 networkstatus_vote_free(v2
);
3485 networkstatus_vote_free(v3
);
3486 networkstatus_vote_free(con
);
3487 crypto_free_pk_env(sign_skey_1
);
3488 crypto_free_pk_env(sign_skey_2
);
3489 crypto_free_pk_env(sign_skey_3
);
3490 authority_cert_free(cert1
);
3491 authority_cert_free(cert2
);
3492 authority_cert_free(cert3
);
3498 test_policy_summary_helper(const char *policy_str
,
3499 const char *expected_summary
)
3502 smartlist_t
*policy
= NULL
;
3503 char *summary
= NULL
;
3506 line
.key
= (char*)"foo";
3507 line
.value
= (char *)policy_str
;
3510 test_assert(0 == policies_parse_exit_policy(&line
, &policy
, 0, NULL
));
3511 summary
= policy_summarize(policy
);
3513 test_assert(summary
!= NULL
);
3514 test_streq(summary
, expected_summary
);
3519 addr_policy_list_free(policy
);
3526 smartlist_t
*policy
= NULL
, *policy2
= NULL
;
3530 smartlist_t
*sm
= NULL
;
3531 char *policy_str
= NULL
;
3533 policy
= smartlist_create();
3535 p
= router_parse_addr_policy_item_from_string("reject 192.168.0.0/16:*",-1);
3536 test_assert(p
!= NULL
);
3537 test_eq(ADDR_POLICY_REJECT
, p
->policy_type
);
3538 tor_addr_from_ipv4h(&tar
, 0xc0a80000u
);
3539 test_eq(0, tor_addr_compare(&p
->addr
, &tar
, CMP_EXACT
));
3540 test_eq(16, p
->maskbits
);
3541 test_eq(1, p
->prt_min
);
3542 test_eq(65535, p
->prt_max
);
3544 smartlist_add(policy
, p
);
3546 test_assert(ADDR_POLICY_ACCEPTED
==
3547 compare_addr_to_addr_policy(0x01020304u
, 2, policy
));
3548 test_assert(ADDR_POLICY_PROBABLY_ACCEPTED
==
3549 compare_addr_to_addr_policy(0, 2, policy
));
3550 test_assert(ADDR_POLICY_REJECTED
==
3551 compare_addr_to_addr_policy(0xc0a80102, 2, policy
));
3554 test_assert(0 == policies_parse_exit_policy(NULL
, &policy2
, 1, NULL
));
3555 test_assert(policy2
);
3557 test_assert(!exit_policy_is_general_exit(policy
));
3558 test_assert(exit_policy_is_general_exit(policy2
));
3559 test_assert(!exit_policy_is_general_exit(NULL
));
3561 test_assert(cmp_addr_policies(policy
, policy2
));
3562 test_assert(cmp_addr_policies(policy
, NULL
));
3563 test_assert(!cmp_addr_policies(policy2
, policy2
));
3564 test_assert(!cmp_addr_policies(NULL
, NULL
));
3566 test_assert(!policy_is_reject_star(policy2
));
3567 test_assert(policy_is_reject_star(policy
));
3568 test_assert(policy_is_reject_star(NULL
));
3570 addr_policy_list_free(policy
);
3573 /* make sure compacting logic works. */
3575 line
.key
= (char*)"foo";
3576 line
.value
= (char*)"accept *:80,reject private:*,reject *:*";
3578 test_assert(0 == policies_parse_exit_policy(&line
, &policy
, 0, NULL
));
3579 test_assert(policy
);
3580 //test_streq(policy->string, "accept *:80");
3581 //test_streq(policy->next->string, "reject *:*");
3582 test_eq(smartlist_len(policy
), 2);
3584 /* test policy summaries */
3585 /* check if we properly ignore private IP addresses */
3586 test_policy_summary_helper("reject 192.168.0.0/16:*,"
3587 "reject 0.0.0.0/8:*,"
3588 "reject 10.0.0.0/8:*,"
3593 /* check all accept policies, and proper counting of rejects */
3594 test_policy_summary_helper("reject 11.0.0.0/9:80,"
3595 "reject 12.0.0.0/9:80,"
3596 "reject 13.0.0.0/9:80,"
3597 "reject 14.0.0.0/9:80,"
3598 "accept *:*", "accept 1-65535");
3599 test_policy_summary_helper("reject 11.0.0.0/9:80,"
3600 "reject 12.0.0.0/9:80,"
3601 "reject 13.0.0.0/9:80,"
3602 "reject 14.0.0.0/9:80,"
3603 "reject 15.0.0.0:81,"
3604 "accept *:*", "accept 1-65535");
3605 test_policy_summary_helper("reject 11.0.0.0/9:80,"
3606 "reject 12.0.0.0/9:80,"
3607 "reject 13.0.0.0/9:80,"
3608 "reject 14.0.0.0/9:80,"
3609 "reject 15.0.0.0:80,"
3613 test_policy_summary_helper("accept 11.0.0.0/9:80,"
3617 test_policy_summary_helper("accept *:80,"
3622 "accept 80-81,100-111");
3624 test_policy_summary_helper("accept *:1,"
3628 "accept 1,3,65535");
3630 test_policy_summary_helper("accept *:1,"
3636 test_policy_summary_helper("reject *:1,"
3643 /* truncation ports */
3644 sm
= smartlist_create();
3645 for (i
=1; i
<2000; i
+=2) {
3646 char buf
[POLICY_BUF_LEN
];
3647 tor_snprintf(buf
, sizeof(buf
), "reject *:%d", i
);
3648 smartlist_add(sm
, tor_strdup(buf
));
3650 smartlist_add(sm
, tor_strdup("accept *:*"));
3651 policy_str
= smartlist_join_strings(sm
, ",", 0, NULL
);
3652 test_policy_summary_helper( policy_str
,
3653 "accept 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,"
3654 "46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,"
3655 "92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,"
3656 "130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,"
3657 "166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198,200,"
3658 "202,204,206,208,210,212,214,216,218,220,222,224,226,228,230,232,234,236,"
3659 "238,240,242,244,246,248,250,252,254,256,258,260,262,264,266,268,270,272,"
3660 "274,276,278,280,282,284,286,288,290,292,294,296,298,300,302,304,306,308,"
3661 "310,312,314,316,318,320,322,324,326,328,330,332,334,336,338,340,342,344,"
3662 "346,348,350,352,354,356,358,360,362,364,366,368,370,372,374,376,378,380,"
3663 "382,384,386,388,390,392,394,396,398,400,402,404,406,408,410,412,414,416,"
3664 "418,420,422,424,426,428,430,432,434,436,438,440,442,444,446,448,450,452,"
3665 "454,456,458,460,462,464,466,468,470,472,474,476,478,480,482,484,486,488,"
3666 "490,492,494,496,498,500,502,504,506,508,510,512,514,516,518,520,522");
3670 addr_policy_list_free(policy
);
3672 addr_policy_list_free(policy2
);
3673 tor_free(policy_str
);
3675 SMARTLIST_FOREACH(sm
, char *, s
, tor_free(s
));
3683 char address1
[] = "fooaddress.onion";
3684 char address2
[] = "aaaaaaaaaaaaaaaa.onion";
3685 char address3
[] = "fooaddress.exit";
3686 char address4
[] = "www.torproject.org";
3687 rend_service_descriptor_t
*d1
= NULL
, *d2
= NULL
;
3688 char *encoded
= NULL
;
3690 crypto_pk_env_t
*pk1
= NULL
, *pk2
= NULL
;
3693 pk1
= pk_generate(0);
3694 pk2
= pk_generate(1);
3696 /* Test unversioned (v0) descriptor */
3697 d1
= tor_malloc_zero(sizeof(rend_service_descriptor_t
));
3698 d1
->pk
= crypto_pk_dup_key(pk1
);
3700 d1
->timestamp
= now
;
3702 d1
->intro_nodes
= smartlist_create();
3703 for (i
= 0; i
< 3; i
++) {
3704 rend_intro_point_t
*intro
= tor_malloc_zero(sizeof(rend_intro_point_t
));
3705 intro
->extend_info
= tor_malloc_zero(sizeof(extend_info_t
));
3706 crypto_rand(intro
->extend_info
->identity_digest
, DIGEST_LEN
);
3707 intro
->extend_info
->nickname
[0] = '$';
3708 base16_encode(intro
->extend_info
->nickname
+1, HEX_DIGEST_LEN
+1,
3709 intro
->extend_info
->identity_digest
, DIGEST_LEN
);
3710 smartlist_add(d1
->intro_nodes
, intro
);
3712 test_assert(! rend_encode_service_descriptor(d1
, pk1
, &encoded
, &len
));
3713 d2
= rend_parse_service_descriptor(encoded
, len
);
3716 test_assert(!crypto_pk_cmp_keys(d1
->pk
, d2
->pk
));
3717 test_eq(d2
->timestamp
, now
);
3718 test_eq(d2
->version
, 0);
3719 test_eq(d2
->protocols
, 1<<2);
3720 test_eq(smartlist_len(d2
->intro_nodes
), 3);
3721 for (i
= 0; i
< 3; i
++) {
3722 rend_intro_point_t
*intro1
= smartlist_get(d1
->intro_nodes
, i
);
3723 rend_intro_point_t
*intro2
= smartlist_get(d2
->intro_nodes
, i
);
3724 test_streq(intro1
->extend_info
->nickname
,
3725 intro2
->extend_info
->nickname
);
3728 test_assert(BAD_HOSTNAME
== parse_extended_hostname(address1
));
3729 test_assert(ONION_HOSTNAME
== parse_extended_hostname(address2
));
3730 test_assert(EXIT_HOSTNAME
== parse_extended_hostname(address3
));
3731 test_assert(NORMAL_HOSTNAME
== parse_extended_hostname(address4
));
3735 crypto_free_pk_env(pk1
);
3737 crypto_free_pk_env(pk2
);
3739 rend_service_descriptor_free(d1
);
3741 rend_service_descriptor_free(d2
);
3750 crypto_cipher_env_t
*c
;
3751 struct timeval start
, end
;
3752 const int iters
= 100000;
3754 c
= crypto_new_cipher_env();
3755 crypto_cipher_generate_key(c
);
3756 crypto_cipher_encrypt_init_cipher(c
);
3757 for (len
= 1; len
<= 8192; len
*= 2) {
3758 b1
= tor_malloc_zero(len
);
3759 b2
= tor_malloc_zero(len
);
3760 tor_gettimeofday(&start
);
3761 for (i
= 0; i
< iters
; ++i
) {
3762 crypto_cipher_encrypt(c
, b1
, b2
, len
);
3764 tor_gettimeofday(&end
);
3767 nsec
= (uint64_t) tv_udiff(&start
,&end
);
3769 nsec
/= (iters
*len
);
3770 printf("%d bytes: "U64_FORMAT
" nsec per byte\n", len
,
3771 U64_PRINTF_ARG(nsec
));
3773 crypto_free_cipher_env(c
);
3779 smartlist_t
*sl
= smartlist_create();
3780 smartlist_t
*sl2
= smartlist_create();
3781 struct timeval start
, end
, pt2
, pt3
, pt4
;
3782 const int iters
= 10000;
3783 const int elts
= 4000;
3784 const int fpostests
= 1000000;
3787 digestmap_t
*dm
= digestmap_new();
3788 digestset_t
*ds
= digestset_new(elts
);
3790 for (i
= 0; i
< elts
; ++i
) {
3792 smartlist_add(sl
, tor_memdup(d
, 20));
3794 for (i
= 0; i
< elts
; ++i
) {
3796 smartlist_add(sl2
, tor_memdup(d
, 20));
3798 printf("nbits=%d\n", ds
->mask
+1);
3800 tor_gettimeofday(&start
);
3801 for (i
= 0; i
< iters
; ++i
) {
3802 SMARTLIST_FOREACH(sl
, const char *, cp
, digestmap_set(dm
, cp
, (void*)1));
3804 tor_gettimeofday(&pt2
);
3805 for (i
= 0; i
< iters
; ++i
) {
3806 SMARTLIST_FOREACH(sl
, const char *, cp
, digestmap_get(dm
, cp
));
3807 SMARTLIST_FOREACH(sl2
, const char *, cp
, digestmap_get(dm
, cp
));
3809 tor_gettimeofday(&pt3
);
3810 for (i
= 0; i
< iters
; ++i
) {
3811 SMARTLIST_FOREACH(sl
, const char *, cp
, digestset_add(ds
, cp
));
3813 tor_gettimeofday(&pt4
);
3814 for (i
= 0; i
< iters
; ++i
) {
3815 SMARTLIST_FOREACH(sl
, const char *, cp
, n
+= digestset_isin(ds
, cp
));
3816 SMARTLIST_FOREACH(sl2
, const char *, cp
, n
+= digestset_isin(ds
, cp
));
3818 tor_gettimeofday(&end
);
3820 for (i
= 0; i
< fpostests
; ++i
) {
3822 if (digestset_isin(ds
, d
)) ++fp
;
3825 printf("%ld\n",(unsigned long)tv_udiff(&start
, &pt2
));
3826 printf("%ld\n",(unsigned long)tv_udiff(&pt2
, &pt3
));
3827 printf("%ld\n",(unsigned long)tv_udiff(&pt3
, &pt4
));
3828 printf("%ld\n",(unsigned long)tv_udiff(&pt4
, &end
));
3829 printf("-- %d\n", n
);
3830 printf("++ %f\n", fp
/(double)fpostests
);
3831 digestmap_free(dm
, NULL
);
3833 SMARTLIST_FOREACH(sl
, char *, cp
, tor_free(cp
));
3834 SMARTLIST_FOREACH(sl2
, char *, cp
, tor_free(cp
));
3836 smartlist_free(sl2
);
3840 test_util_mempool(void)
3842 mp_pool_t
*pool
= NULL
;
3843 smartlist_t
*allocated
= NULL
;
3846 pool
= mp_pool_new(1, 100);
3847 test_assert(pool
->new_chunk_capacity
>= 100);
3848 test_assert(pool
->item_alloc_size
>= sizeof(void*)+1);
3849 mp_pool_destroy(pool
);
3852 pool
= mp_pool_new(241, 2500);
3853 test_assert(pool
->new_chunk_capacity
>= 10);
3854 test_assert(pool
->item_alloc_size
>= sizeof(void*)+241);
3855 test_eq(pool
->item_alloc_size
& 0x03, 0);
3856 test_assert(pool
->new_chunk_capacity
< 60);
3858 allocated
= smartlist_create();
3859 for (i
= 0; i
< 20000; ++i
) {
3860 if (smartlist_len(allocated
) < 20 || crypto_rand_int(2)) {
3861 void *m
= mp_pool_get(pool
);
3862 memset(m
, 0x09, 241);
3863 smartlist_add(allocated
, m
);
3864 //printf("%d: %p\n", i, m);
3865 //mp_pool_assert_ok(pool);
3867 int idx
= crypto_rand_int(smartlist_len(allocated
));
3868 void *m
= smartlist_get(allocated
, idx
);
3869 //printf("%d: free %p\n", i, m);
3870 smartlist_del(allocated
, idx
);
3872 //mp_pool_assert_ok(pool);
3874 if (crypto_rand_int(777)==0)
3875 mp_pool_clean(pool
, 1, 1);
3878 mp_pool_assert_ok(pool
);
3883 SMARTLIST_FOREACH(allocated
, void *, m
, mp_pool_release(m
));
3884 mp_pool_assert_ok(pool
);
3885 mp_pool_clean(pool
, 0, 0);
3886 mp_pool_assert_ok(pool
);
3887 smartlist_free(allocated
);
3891 mp_pool_destroy(pool
);
3895 test_util_memarea(void)
3897 memarea_t
*area
= memarea_new(1024);
3898 char *p1
, *p2
, *p3
, *p1_orig
;
3902 p1_orig
= p1
= memarea_alloc(area
,64);
3903 p2
= memarea_alloc_zero(area
,52);
3904 p3
= memarea_alloc(area
,11);
3906 test_assert(memarea_owns_ptr(area
, p1
));
3907 test_assert(memarea_owns_ptr(area
, p2
));
3908 test_assert(memarea_owns_ptr(area
, p3
));
3909 /* Make sure we left enough space. */
3910 test_assert(p1
+64 <= p2
);
3911 test_assert(p2
+52 <= p3
);
3912 /* Make sure we aligned. */
3913 test_eq(((uintptr_t)p1
) % sizeof(void*), 0);
3914 test_eq(((uintptr_t)p2
) % sizeof(void*), 0);
3915 test_eq(((uintptr_t)p3
) % sizeof(void*), 0);
3916 test_assert(!memarea_owns_ptr(area
, p3
+8192));
3917 test_assert(!memarea_owns_ptr(area
, p3
+30));
3918 test_assert(tor_mem_is_zero(p2
, 52));
3919 /* Make sure we don't overalign. */
3920 p1
= memarea_alloc(area
, 1);
3921 p2
= memarea_alloc(area
, 1);
3922 test_eq(p1
+sizeof(void*), p2
);
3924 void *ptr
= tor_malloc(64);
3925 test_assert(!memarea_owns_ptr(area
, ptr
));
3929 /* memarea_memdup */
3931 char *ptr
= tor_malloc(64);
3932 crypto_rand(ptr
, 64);
3933 p1
= memarea_memdup(area
, ptr
, 64);
3934 test_assert(p1
!= ptr
);
3935 test_memeq(p1
, ptr
, 64);
3939 /* memarea_strdup. */
3940 p1
= memarea_strdup(area
,"");
3941 p2
= memarea_strdup(area
, "abcd");
3945 test_streq(p2
, "abcd");
3947 /* memarea_strndup. */
3949 const char *s
= "Ad ogni porta batte la morte e grida: il nome!";
3950 /* (From Turandot, act 3.) */
3951 size_t len
= strlen(s
);
3952 p1
= memarea_strndup(area
, s
, 1000);
3953 p2
= memarea_strndup(area
, s
, 10);
3955 test_assert(p2
>= p1
+ len
+ 1);
3956 test_memeq(s
, p2
, 10);
3957 test_eq(p2
[10], '\0');
3958 p3
= memarea_strndup(area
, s
, len
);
3960 p3
= memarea_strndup(area
, s
, len
-1);
3961 test_memeq(s
, p3
, len
-1);
3962 test_eq(p3
[len
-1], '\0');
3965 memarea_clear(area
);
3966 p1
= memarea_alloc(area
, 1);
3967 test_eq(p1
, p1_orig
);
3968 memarea_clear(area
);
3970 /* Check for running over an area's size. */
3971 for (i
= 0; i
< 512; ++i
) {
3972 p1
= memarea_alloc(area
, crypto_rand_int(5)+1);
3973 test_assert(memarea_owns_ptr(area
, p1
));
3975 memarea_assert_ok(area
);
3976 /* Make sure we can allocate a too-big object. */
3977 p1
= memarea_alloc_zero(area
, 9000);
3978 p2
= memarea_alloc_zero(area
, 16);
3979 test_assert(memarea_owns_ptr(area
, p1
));
3980 test_assert(memarea_owns_ptr(area
, p2
));
3983 memarea_drop_all(area
);
3987 test_util_datadir(void)
3992 f
= get_datadir_fname(NULL
);
3993 test_streq(f
, temp_dir
);
3995 f
= get_datadir_fname("state");
3996 tor_snprintf(buf
, sizeof(buf
), "%s"PATH_SEPARATOR
"state", temp_dir
);
3999 f
= get_datadir_fname2("cache", "thingy");
4000 tor_snprintf(buf
, sizeof(buf
),
4001 "%s"PATH_SEPARATOR
"cache"PATH_SEPARATOR
"thingy", temp_dir
);
4004 f
= get_datadir_fname2_suffix("cache", "thingy", ".foo");
4005 tor_snprintf(buf
, sizeof(buf
),
4006 "%s"PATH_SEPARATOR
"cache"PATH_SEPARATOR
"thingy.foo", temp_dir
);
4009 f
= get_datadir_fname_suffix("cache", ".foo");
4010 tor_snprintf(buf
, sizeof(buf
), "%s"PATH_SEPARATOR
"cache.foo",
4018 /* Test AES-CTR encryption and decryption with IV. */
4020 test_crypto_aes_iv(void)
4022 crypto_cipher_env_t
*cipher
;
4023 char *plain
, *encrypted1
, *encrypted2
, *decrypted1
, *decrypted2
;
4024 char plain_1
[1], plain_15
[15], plain_16
[16], plain_17
[17];
4025 char key1
[16], key2
[16];
4026 size_t encrypted_size
, decrypted_size
;
4028 plain
= tor_malloc(4095);
4029 encrypted1
= tor_malloc(4095 + 1 + 16);
4030 encrypted2
= tor_malloc(4095 + 1 + 16);
4031 decrypted1
= tor_malloc(4095 + 1);
4032 decrypted2
= tor_malloc(4095 + 1);
4034 crypto_rand(plain
, 4095);
4035 crypto_rand(key1
, 16);
4036 crypto_rand(key2
, 16);
4037 crypto_rand(plain_1
, 1);
4038 crypto_rand(plain_15
, 15);
4039 crypto_rand(plain_16
, 16);
4040 crypto_rand(plain_17
, 17);
4041 key1
[0] = key2
[0] + 128; /* Make sure that contents are different. */
4042 /* Encrypt and decrypt with the same key. */
4043 cipher
= crypto_create_init_cipher(key1
, 1);
4044 encrypted_size
= crypto_cipher_encrypt_with_iv(cipher
, encrypted1
, 16 + 4095,
4046 crypto_free_cipher_env(cipher
);
4048 test_eq(encrypted_size
, 16 + 4095);
4049 cipher
= crypto_create_init_cipher(key1
, 0);
4050 decrypted_size
= crypto_cipher_decrypt_with_iv(cipher
, decrypted1
, 4095,
4051 encrypted1
, encrypted_size
);
4052 crypto_free_cipher_env(cipher
);
4054 test_eq(decrypted_size
, 4095);
4055 test_memeq(plain
, decrypted1
, 4095);
4056 /* Encrypt a second time (with a new random initialization vector). */
4057 cipher
= crypto_create_init_cipher(key1
, 1);
4058 encrypted_size
= crypto_cipher_encrypt_with_iv(cipher
, encrypted2
, 16 + 4095,
4060 crypto_free_cipher_env(cipher
);
4062 test_eq(encrypted_size
, 16 + 4095);
4063 cipher
= crypto_create_init_cipher(key1
, 0);
4064 decrypted_size
= crypto_cipher_decrypt_with_iv(cipher
, decrypted2
, 4095,
4065 encrypted2
, encrypted_size
);
4066 crypto_free_cipher_env(cipher
);
4068 test_eq(decrypted_size
, 4095);
4069 test_memeq(plain
, decrypted2
, 4095);
4070 test_memneq(encrypted1
, encrypted2
, encrypted_size
);
4071 /* Decrypt with the wrong key. */
4072 cipher
= crypto_create_init_cipher(key2
, 0);
4073 decrypted_size
= crypto_cipher_decrypt_with_iv(cipher
, decrypted2
, 4095,
4074 encrypted1
, encrypted_size
);
4075 crypto_free_cipher_env(cipher
);
4077 test_memneq(plain
, decrypted2
, encrypted_size
);
4078 /* Alter the initialization vector. */
4079 encrypted1
[0] += 42;
4080 cipher
= crypto_create_init_cipher(key1
, 0);
4081 decrypted_size
= crypto_cipher_decrypt_with_iv(cipher
, decrypted1
, 4095,
4082 encrypted1
, encrypted_size
);
4083 crypto_free_cipher_env(cipher
);
4085 test_memneq(plain
, decrypted2
, 4095);
4086 /* Special length case: 1. */
4087 cipher
= crypto_create_init_cipher(key1
, 1);
4088 encrypted_size
= crypto_cipher_encrypt_with_iv(cipher
, encrypted1
, 16 + 1,
4090 crypto_free_cipher_env(cipher
);
4092 test_eq(encrypted_size
, 16 + 1);
4093 cipher
= crypto_create_init_cipher(key1
, 0);
4094 decrypted_size
= crypto_cipher_decrypt_with_iv(cipher
, decrypted1
, 1,
4095 encrypted1
, encrypted_size
);
4096 crypto_free_cipher_env(cipher
);
4098 test_eq(decrypted_size
, 1);
4099 test_memeq(plain_1
, decrypted1
, 1);
4100 /* Special length case: 15. */
4101 cipher
= crypto_create_init_cipher(key1
, 1);
4102 encrypted_size
= crypto_cipher_encrypt_with_iv(cipher
, encrypted1
, 16 + 15,
4104 crypto_free_cipher_env(cipher
);
4106 test_eq(encrypted_size
, 16 + 15);
4107 cipher
= crypto_create_init_cipher(key1
, 0);
4108 decrypted_size
= crypto_cipher_decrypt_with_iv(cipher
, decrypted1
, 15,
4109 encrypted1
, encrypted_size
);
4110 crypto_free_cipher_env(cipher
);
4112 test_eq(decrypted_size
, 15);
4113 test_memeq(plain_15
, decrypted1
, 15);
4114 /* Special length case: 16. */
4115 cipher
= crypto_create_init_cipher(key1
, 1);
4116 encrypted_size
= crypto_cipher_encrypt_with_iv(cipher
, encrypted1
, 16 + 16,
4118 crypto_free_cipher_env(cipher
);
4120 test_eq(encrypted_size
, 16 + 16);
4121 cipher
= crypto_create_init_cipher(key1
, 0);
4122 decrypted_size
= crypto_cipher_decrypt_with_iv(cipher
, decrypted1
, 16,
4123 encrypted1
, encrypted_size
);
4124 crypto_free_cipher_env(cipher
);
4126 test_eq(decrypted_size
, 16);
4127 test_memeq(plain_16
, decrypted1
, 16);
4128 /* Special length case: 17. */
4129 cipher
= crypto_create_init_cipher(key1
, 1);
4130 encrypted_size
= crypto_cipher_encrypt_with_iv(cipher
, encrypted1
, 16 + 17,
4132 crypto_free_cipher_env(cipher
);
4134 test_eq(encrypted_size
, 16 + 17);
4135 cipher
= crypto_create_init_cipher(key1
, 0);
4136 decrypted_size
= crypto_cipher_decrypt_with_iv(cipher
, decrypted1
, 17,
4137 encrypted1
, encrypted_size
);
4138 test_eq(decrypted_size
, 17);
4139 test_memeq(plain_17
, decrypted1
, 17);
4144 tor_free(encrypted1
);
4145 tor_free(encrypted2
);
4146 tor_free(decrypted1
);
4147 tor_free(decrypted2
);
4149 crypto_free_cipher_env(cipher
);
4152 /* Test base32 decoding. */
4154 test_crypto_base32_decode(void)
4156 char plain
[60], encoded
[96 + 1], decoded
[60];
4158 crypto_rand(plain
, 60);
4159 /* Encode and decode a random string. */
4160 base32_encode(encoded
, 96 + 1, plain
, 60);
4161 res
= base32_decode(decoded
, 60, encoded
, 96);
4163 test_memeq(plain
, decoded
, 60);
4164 /* Encode, uppercase, and decode a random string. */
4165 base32_encode(encoded
, 96 + 1, plain
, 60);
4166 tor_strupper(encoded
);
4167 res
= base32_decode(decoded
, 60, encoded
, 96);
4169 test_memeq(plain
, decoded
, 60);
4170 /* Change encoded string and decode. */
4171 if (encoded
[0] == 'A' || encoded
[0] == 'a')
4175 res
= base32_decode(decoded
, 60, encoded
, 96);
4177 test_memneq(plain
, decoded
, 60);
4178 /* Bad encodings. */
4180 res
= base32_decode(decoded
, 60, encoded
, 96);
4181 test_assert(res
< 0);
4187 /* Test encoding and parsing of v2 rendezvous service descriptors. */
4189 test_rend_fns_v2(void)
4191 rend_service_descriptor_t
*generated
= NULL
, *parsed
= NULL
;
4192 char service_id
[DIGEST_LEN
];
4193 char service_id_base32
[REND_SERVICE_ID_LEN_BASE32
+1];
4194 const char *next_desc
;
4195 smartlist_t
*descs
= smartlist_create();
4196 char computed_desc_id
[DIGEST_LEN
];
4197 char parsed_desc_id
[DIGEST_LEN
];
4198 crypto_pk_env_t
*pk1
= NULL
, *pk2
= NULL
;
4200 char *intro_points_encrypted
= NULL
;
4201 size_t intro_points_size
;
4202 size_t encoded_size
;
4204 pk1
= pk_generate(0);
4205 pk2
= pk_generate(1);
4206 generated
= tor_malloc_zero(sizeof(rend_service_descriptor_t
));
4207 generated
->pk
= crypto_pk_dup_key(pk1
);
4208 crypto_pk_get_digest(generated
->pk
, service_id
);
4209 base32_encode(service_id_base32
, REND_SERVICE_ID_LEN_BASE32
+1,
4210 service_id
, REND_SERVICE_ID_LEN
);
4212 generated
->timestamp
= now
;
4213 generated
->version
= 2;
4214 generated
->protocols
= 42;
4215 generated
->intro_nodes
= smartlist_create();
4217 for (i
= 0; i
< 3; i
++) {
4218 rend_intro_point_t
*intro
= tor_malloc_zero(sizeof(rend_intro_point_t
));
4219 crypto_pk_env_t
*okey
= pk_generate(2 + i
);
4220 intro
->extend_info
= tor_malloc_zero(sizeof(extend_info_t
));
4221 intro
->extend_info
->onion_key
= crypto_pk_dup_key(okey
);
4222 crypto_pk_get_digest(intro
->extend_info
->onion_key
,
4223 intro
->extend_info
->identity_digest
);
4224 //crypto_rand(info->identity_digest, DIGEST_LEN); /* Would this work? */
4225 intro
->extend_info
->nickname
[0] = '$';
4226 base16_encode(intro
->extend_info
->nickname
+ 1,
4227 sizeof(intro
->extend_info
->nickname
) - 1,
4228 intro
->extend_info
->identity_digest
, DIGEST_LEN
);
4229 /* Does not cover all IP addresses. */
4230 tor_addr_from_ipv4h(&intro
->extend_info
->addr
, crypto_rand_int(65536));
4231 intro
->extend_info
->port
= crypto_rand_int(65536);
4232 intro
->intro_key
= crypto_pk_dup_key(pk2
);
4233 smartlist_add(generated
->intro_nodes
, intro
);
4235 test_assert(rend_encode_v2_descriptors(descs
, generated
, now
, 0,
4236 REND_NO_AUTH
, NULL
, NULL
) > 0);
4237 test_assert(rend_compute_v2_desc_id(computed_desc_id
, service_id_base32
,
4238 NULL
, now
, 0) == 0);
4239 test_memeq(((rend_encoded_v2_service_descriptor_t
*)
4240 smartlist_get(descs
, 0))->desc_id
, computed_desc_id
, DIGEST_LEN
);
4241 test_assert(rend_parse_v2_service_descriptor(&parsed
, parsed_desc_id
,
4242 &intro_points_encrypted
,
4246 ((rend_encoded_v2_service_descriptor_t
*)
4247 smartlist_get(descs
, 0))->desc_str
) == 0);
4248 test_assert(parsed
);
4249 test_memeq(((rend_encoded_v2_service_descriptor_t
*)
4250 smartlist_get(descs
, 0))->desc_id
, parsed_desc_id
, DIGEST_LEN
);
4251 test_assert(rend_parse_introduction_points(parsed
, intro_points_encrypted
,
4252 intro_points_size
) == 3);
4253 test_assert(!crypto_pk_cmp_keys(generated
->pk
, parsed
->pk
));
4254 test_eq(parsed
->timestamp
, now
);
4255 test_eq(parsed
->version
, 2);
4256 test_eq(parsed
->protocols
, 42);
4257 test_eq(smartlist_len(parsed
->intro_nodes
), 3);
4258 for (i
= 0; i
< smartlist_len(parsed
->intro_nodes
); i
++) {
4259 rend_intro_point_t
*par_intro
= smartlist_get(parsed
->intro_nodes
, i
),
4260 *gen_intro
= smartlist_get(generated
->intro_nodes
, i
);
4261 extend_info_t
*par_info
= par_intro
->extend_info
;
4262 extend_info_t
*gen_info
= gen_intro
->extend_info
;
4263 test_assert(!crypto_pk_cmp_keys(gen_info
->onion_key
, par_info
->onion_key
));
4264 test_memeq(gen_info
->identity_digest
, par_info
->identity_digest
,
4266 test_streq(gen_info
->nickname
, par_info
->nickname
);
4267 test_assert(tor_addr_eq(&gen_info
->addr
, &par_info
->addr
));
4268 test_eq(gen_info
->port
, par_info
->port
);
4273 for (i
= 0; i
< smartlist_len(descs
); i
++)
4274 rend_encoded_v2_service_descriptor_free(smartlist_get(descs
, i
));
4275 smartlist_free(descs
);
4278 rend_service_descriptor_free(parsed
);
4280 rend_service_descriptor_free(generated
);
4282 crypto_free_pk_env(pk1
);
4284 crypto_free_pk_env(pk2
);
4285 tor_free(intro_points_encrypted
);
4292 time_t now
= time(NULL
);
4295 /* Populate the DB a bit. Add these in order, since we can't do the final
4296 * 'sort' step. These aren't very good IP addresses, but they're perfectly
4297 * fine uint32_t values. */
4298 test_eq(0, geoip_parse_entry("10,50,AB"));
4299 test_eq(0, geoip_parse_entry("52,90,XY"));
4300 test_eq(0, geoip_parse_entry("95,100,AB"));
4301 test_eq(0, geoip_parse_entry("\"105\",\"140\",\"ZZ\""));
4302 test_eq(0, geoip_parse_entry("\"150\",\"190\",\"XY\""));
4303 test_eq(0, geoip_parse_entry("\"200\",\"250\",\"AB\""));
4305 /* We should have 3 countries: ab, xy, zz. */
4306 test_eq(3, geoip_get_n_countries());
4307 /* Make sure that country ID actually works. */
4308 #define NAMEFOR(x) geoip_get_country_name(geoip_get_country_by_ip(x))
4309 test_streq("ab", NAMEFOR(32));
4310 test_streq("??", NAMEFOR(5));
4311 test_streq("??", NAMEFOR(51));
4312 test_streq("xy", NAMEFOR(150));
4313 test_streq("xy", NAMEFOR(190));
4314 test_streq("??", NAMEFOR(2000));
4317 get_options()->BridgeRelay
= 1;
4318 get_options()->BridgeRecordUsageByCountry
= 1;
4319 /* Put 9 observations in AB... */
4320 for (i
=32; i
< 40; ++i
)
4321 geoip_note_client_seen(GEOIP_CLIENT_CONNECT
, i
, now
);
4322 geoip_note_client_seen(GEOIP_CLIENT_CONNECT
, 225, now
);
4323 /* and 3 observations in XY, several times. */
4324 for (j
=0; j
< 10; ++j
)
4325 for (i
=52; i
< 55; ++i
)
4326 geoip_note_client_seen(GEOIP_CLIENT_CONNECT
, i
, now
-3600);
4327 /* and 17 observations in ZZ... */
4328 for (i
=110; i
< 127; ++i
)
4329 geoip_note_client_seen(GEOIP_CLIENT_CONNECT
, i
, now
-7200);
4330 s
= geoip_get_client_history(now
+5*24*60*60, GEOIP_CLIENT_CONNECT
);
4332 test_streq("zz=24,ab=16,xy=8", s
);
4335 /* Now clear out all the zz observations. */
4336 geoip_remove_old_clients(now
-6000);
4337 s
= geoip_get_client_history(now
+5*24*60*60, GEOIP_CLIENT_CONNECT
);
4339 test_streq("ab=16,xy=8", s
);
4345 #define ENT(x) { #x, test_ ## x, 0, 0 }
4346 #define SUBENT(x,y) { #x "/" #y, test_ ## x ## _ ## y, 1, 0 }
4349 const char *test_name
;
4350 void (*test_fn
)(void);
4356 SUBENT(crypto
, rng
),
4357 SUBENT(crypto
, aes
),
4358 SUBENT(crypto
, sha
),
4361 SUBENT(crypto
, s2k
),
4362 SUBENT(crypto
, aes_iv
),
4363 SUBENT(crypto
, base32_decode
),
4365 SUBENT(util
, ip6_helpers
),
4367 SUBENT(util
, datadir
),
4368 SUBENT(util
, smartlist
),
4369 SUBENT(util
, bitarray
),
4370 SUBENT(util
, digestset
),
4371 SUBENT(util
, mempool
),
4372 SUBENT(util
, memarea
),
4373 SUBENT(util
, strmap
),
4374 SUBENT(util
, control_formats
),
4375 SUBENT(util
, pqueue
),
4377 SUBENT(util
, threads
),
4378 SUBENT(util
, order_functions
),
4379 ENT(onion_handshake
),
4381 ENT(v3_networkstatus
),
4384 SUBENT(rend_fns
, v2
),
4386 { NULL
, NULL
, 0, 0 },
4389 static void syntax(void) ATTR_NORETURN
;
4395 " test [-v|--verbose] [--warn|--notice|--info|--debug]\n"
4397 "Recognized tests are:\n");
4398 for (i
= 0; test_array
[i
].test_name
; ++i
) {
4399 printf(" %s\n", test_array
[i
].test_name
);
4406 main(int c
, char**v
)
4408 or_options_t
*options
= options_new();
4409 char *errmsg
= NULL
;
4411 int verbose
= 0, any_selected
= 0;
4412 int loglevel
= LOG_ERR
;
4417 for (i
= 1; i
< c
; ++i
) {
4418 if (!strcmp(v
[i
], "-v") || !strcmp(v
[i
], "--verbose"))
4420 else if (!strcmp(v
[i
], "--warn"))
4421 loglevel
= LOG_WARN
;
4422 else if (!strcmp(v
[i
], "--notice"))
4423 loglevel
= LOG_NOTICE
;
4424 else if (!strcmp(v
[i
], "--info"))
4425 loglevel
= LOG_INFO
;
4426 else if (!strcmp(v
[i
], "--debug"))
4427 loglevel
= LOG_DEBUG
;
4428 else if (!strcmp(v
[i
], "--help") || !strcmp(v
[i
], "-h") || v
[i
][0] == '-')
4432 for (j
= 0; test_array
[j
].test_name
; ++j
) {
4433 if (!strcmp(v
[i
], test_array
[j
].test_name
) ||
4434 (test_array
[j
].is_subent
&&
4435 !strcmpstart(test_array
[j
].test_name
, v
[i
]) &&
4436 test_array
[j
].test_name
[strlen(v
[i
])] == '/') ||
4437 (v
[i
][0] == '=' && !strcmp(v
[i
]+1, test_array
[j
].test_name
))) {
4438 test_array
[j
].selected
= 1;
4444 printf("Unknown test: %s\n", v
[i
]);
4450 if (!any_selected
) {
4451 for (i
= 0; test_array
[i
].test_name
; ++i
) {
4452 test_array
[i
].selected
= 1;
4457 log_severity_list_t s
;
4458 memset(&s
, 0, sizeof(s
));
4459 set_log_severity_config(loglevel
, LOG_ERR
, &s
);
4460 add_stream_log(&s
, "", stdout
);
4463 options
->command
= CMD_RUN_UNITTESTS
;
4464 crypto_global_init(0);
4468 options_init(options
);
4469 options
->DataDirectory
= tor_strdup(temp_dir
);
4470 if (set_options(options
, &errmsg
) < 0) {
4471 printf("Failed to set initial options: %s\n", errmsg
);
4488 atexit(remove_directory
);
4490 printf("Running Tor unit tests on %s\n", get_uname());
4492 for (i
= 0; test_array
[i
].test_name
; ++i
) {
4493 if (!test_array
[i
].selected
)
4495 if (!test_array
[i
].is_subent
) {
4496 printf("\n============================== %s\n",test_array
[i
].test_name
);
4497 } else if (test_array
[i
].is_subent
&& verbose
) {
4498 printf("\n%s", test_array
[i
].test_name
);
4500 test_array
[i
].test_fn();
4506 dmalloc_log_unfreed();