Use S_CASE for ehostunreach, not E_CASE. Partial backport of 69deb22f. Fixes 0.2...
[tor/rransom.git] / src / or / test.c
blob14ba953544c6ad0dc2d15a6c749c169ec0493d79
1 /* Copyright (c) 2001-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2010, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
6 /* Ordinarily defined in tor_main.c; this bit is just here to provide one
7 * since we're not linking to tor_main.c */
8 const char tor_svn_revision[] = "";
10 /**
11 * \file test.c
12 * \brief Unit tests for many pieces of the lower level Tor modules.
13 **/
15 #include "orconfig.h"
17 #include <stdio.h>
18 #ifdef HAVE_FCNTL_H
19 #include <fcntl.h>
20 #endif
22 #ifdef MS_WINDOWS
23 /* For mkdir() */
24 #include <direct.h>
25 #else
26 #include <dirent.h>
27 #endif
29 /* These macros pull in declarations for some functions and structures that
30 * are typically file-private. */
31 #define BUFFERS_PRIVATE
32 #define CONFIG_PRIVATE
33 #define CONTROL_PRIVATE
34 #define CRYPTO_PRIVATE
35 #define DIRSERV_PRIVATE
36 #define DIRVOTE_PRIVATE
37 #define GEOIP_PRIVATE
38 #define MEMPOOL_PRIVATE
39 #define ROUTER_PRIVATE
41 #include "or.h"
42 #include "test.h"
43 #include "torgzip.h"
44 #include "mempool.h"
45 #include "memarea.h"
47 #ifdef USE_DMALLOC
48 #include <dmalloc.h>
49 #include <openssl/crypto.h>
50 #endif
52 /** Set to true if any unit test has failed. Mostly, this is set by the macros
53 * in test.h */
54 int have_failed = 0;
56 /** Temporary directory (set up by setup_directory) under which we store all
57 * our files during testing. */
58 static char temp_dir[256];
60 /** Select and create the temporary directory we'll use to run our unit tests.
61 * Store it in <b>temp_dir</b>. Exit immediately if we can't create it.
62 * idempotent. */
63 static void
64 setup_directory(void)
66 static int is_setup = 0;
67 int r;
68 if (is_setup) return;
70 #ifdef MS_WINDOWS
71 // XXXX
72 tor_snprintf(temp_dir, sizeof(temp_dir),
73 "c:\\windows\\temp\\tor_test_%d", (int)getpid());
74 r = mkdir(temp_dir);
75 #else
76 tor_snprintf(temp_dir, sizeof(temp_dir), "/tmp/tor_test_%d", (int) getpid());
77 r = mkdir(temp_dir, 0700);
78 #endif
79 if (r) {
80 fprintf(stderr, "Can't create directory %s:", temp_dir);
81 perror("");
82 exit(1);
84 is_setup = 1;
87 /** Return a filename relative to our testing temporary directory */
88 static const char *
89 get_fname(const char *name)
91 static char buf[1024];
92 setup_directory();
93 tor_snprintf(buf,sizeof(buf),"%s/%s",temp_dir,name);
94 return buf;
97 /** Remove all files stored under the temporary directory, and the directory
98 * itself. */
99 static void
100 remove_directory(void)
102 smartlist_t *elements = tor_listdir(temp_dir);
103 if (elements) {
104 SMARTLIST_FOREACH(elements, const char *, cp,
106 size_t len = strlen(cp)+strlen(temp_dir)+16;
107 char *tmp = tor_malloc(len);
108 tor_snprintf(tmp, len, "%s"PATH_SEPARATOR"%s", temp_dir, cp);
109 unlink(tmp);
110 tor_free(tmp);
112 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
113 smartlist_free(elements);
115 rmdir(temp_dir);
118 /** Define this if unit tests spend too much time generating public keys*/
119 #undef CACHE_GENERATED_KEYS
121 static crypto_pk_env_t *pregen_keys[5] = {NULL, NULL, NULL, NULL, NULL};
122 #define N_PREGEN_KEYS ((int)(sizeof(pregen_keys)/sizeof(pregen_keys[0])))
124 /** Generate and return a new keypair for use in unit tests. If we're using
125 * the key cache optimization, we might reuse keys: we only guarantee that
126 * keys made with distinct values for <b>idx</b> are different. The value of
127 * <b>idx</b> must be at least 0, and less than N_PREGEN_KEYS. */
128 static crypto_pk_env_t *
129 pk_generate(int idx)
131 #ifdef CACHE_GENERATED_KEYS
132 tor_assert(idx < N_PREGEN_KEYS);
133 if (! pregen_keys[idx]) {
134 pregen_keys[idx] = crypto_new_pk_env();
135 tor_assert(!crypto_pk_generate_key(pregen_keys[idx]));
137 return crypto_pk_dup_key(pregen_keys[idx]);
138 #else
139 crypto_pk_env_t *result;
140 (void) idx;
141 result = crypto_new_pk_env();
142 tor_assert(!crypto_pk_generate_key(result));
143 return result;
144 #endif
147 /** Free all storage used for the cached key optimization. */
148 static void
149 free_pregenerated_keys(void)
151 unsigned idx;
152 for (idx = 0; idx < N_PREGEN_KEYS; ++idx) {
153 if (pregen_keys[idx]) {
154 crypto_free_pk_env(pregen_keys[idx]);
155 pregen_keys[idx] = NULL;
160 /** Run unit tests for buffers.c */
161 static void
162 test_buffers(void)
164 char str[256];
165 char str2[256];
167 buf_t *buf = NULL, *buf2 = NULL;
168 const char *cp;
170 int j;
171 size_t r;
173 /****
174 * buf_new
175 ****/
176 if (!(buf = buf_new()))
177 test_fail();
179 //test_eq(buf_capacity(buf), 4096);
180 test_eq(buf_datalen(buf), 0);
182 /****
183 * General pointer frobbing
185 for (j=0;j<256;++j) {
186 str[j] = (char)j;
188 write_to_buf(str, 256, buf);
189 write_to_buf(str, 256, buf);
190 test_eq(buf_datalen(buf), 512);
191 fetch_from_buf(str2, 200, buf);
192 test_memeq(str, str2, 200);
193 test_eq(buf_datalen(buf), 312);
194 memset(str2, 0, sizeof(str2));
196 fetch_from_buf(str2, 256, buf);
197 test_memeq(str+200, str2, 56);
198 test_memeq(str, str2+56, 200);
199 test_eq(buf_datalen(buf), 56);
200 memset(str2, 0, sizeof(str2));
201 /* Okay, now we should be 512 bytes into the 4096-byte buffer. If we add
202 * another 3584 bytes, we hit the end. */
203 for (j=0;j<15;++j) {
204 write_to_buf(str, 256, buf);
206 assert_buf_ok(buf);
207 test_eq(buf_datalen(buf), 3896);
208 fetch_from_buf(str2, 56, buf);
209 test_eq(buf_datalen(buf), 3840);
210 test_memeq(str+200, str2, 56);
211 for (j=0;j<15;++j) {
212 memset(str2, 0, sizeof(str2));
213 fetch_from_buf(str2, 256, buf);
214 test_memeq(str, str2, 256);
216 test_eq(buf_datalen(buf), 0);
217 buf_free(buf);
218 buf = NULL;
220 /* Okay, now make sure growing can work. */
221 buf = buf_new_with_capacity(16);
222 //test_eq(buf_capacity(buf), 16);
223 write_to_buf(str+1, 255, buf);
224 //test_eq(buf_capacity(buf), 256);
225 fetch_from_buf(str2, 254, buf);
226 test_memeq(str+1, str2, 254);
227 //test_eq(buf_capacity(buf), 256);
228 assert_buf_ok(buf);
229 write_to_buf(str, 32, buf);
230 //test_eq(buf_capacity(buf), 256);
231 assert_buf_ok(buf);
232 write_to_buf(str, 256, buf);
233 assert_buf_ok(buf);
234 //test_eq(buf_capacity(buf), 512);
235 test_eq(buf_datalen(buf), 33+256);
236 fetch_from_buf(str2, 33, buf);
237 test_eq(*str2, str[255]);
239 test_memeq(str2+1, str, 32);
240 //test_eq(buf_capacity(buf), 512);
241 test_eq(buf_datalen(buf), 256);
242 fetch_from_buf(str2, 256, buf);
243 test_memeq(str, str2, 256);
245 /* now try shrinking: case 1. */
246 buf_free(buf);
247 buf = buf_new_with_capacity(33668);
248 for (j=0;j<67;++j) {
249 write_to_buf(str,255, buf);
251 //test_eq(buf_capacity(buf), 33668);
252 test_eq(buf_datalen(buf), 17085);
253 for (j=0; j < 40; ++j) {
254 fetch_from_buf(str2, 255,buf);
255 test_memeq(str2, str, 255);
258 /* now try shrinking: case 2. */
259 buf_free(buf);
260 buf = buf_new_with_capacity(33668);
261 for (j=0;j<67;++j) {
262 write_to_buf(str,255, buf);
264 for (j=0; j < 20; ++j) {
265 fetch_from_buf(str2, 255,buf);
266 test_memeq(str2, str, 255);
268 for (j=0;j<80;++j) {
269 write_to_buf(str,255, buf);
271 //test_eq(buf_capacity(buf),33668);
272 for (j=0; j < 120; ++j) {
273 fetch_from_buf(str2, 255,buf);
274 test_memeq(str2, str, 255);
277 /* Move from buf to buf. */
278 buf_free(buf);
279 buf = buf_new_with_capacity(4096);
280 buf2 = buf_new_with_capacity(4096);
281 for (j=0;j<100;++j)
282 write_to_buf(str, 255, buf);
283 test_eq(buf_datalen(buf), 25500);
284 for (j=0;j<100;++j) {
285 r = 10;
286 move_buf_to_buf(buf2, buf, &r);
287 test_eq(r, 0);
289 test_eq(buf_datalen(buf), 24500);
290 test_eq(buf_datalen(buf2), 1000);
291 for (j=0;j<3;++j) {
292 fetch_from_buf(str2, 255, buf2);
293 test_memeq(str2, str, 255);
295 r = 8192; /*big move*/
296 move_buf_to_buf(buf2, buf, &r);
297 test_eq(r, 0);
298 r = 30000; /* incomplete move */
299 move_buf_to_buf(buf2, buf, &r);
300 test_eq(r, 13692);
301 for (j=0;j<97;++j) {
302 fetch_from_buf(str2, 255, buf2);
303 test_memeq(str2, str, 255);
305 buf_free(buf);
306 buf_free(buf2);
307 buf = buf2 = NULL;
309 buf = buf_new_with_capacity(5);
310 cp = "Testing. This is a moderately long Testing string.";
311 for (j = 0; cp[j]; j++)
312 write_to_buf(cp+j, 1, buf);
313 test_eq(0, buf_find_string_offset(buf, "Testing", 7));
314 test_eq(1, buf_find_string_offset(buf, "esting", 6));
315 test_eq(1, buf_find_string_offset(buf, "est", 3));
316 test_eq(39, buf_find_string_offset(buf, "ing str", 7));
317 test_eq(35, buf_find_string_offset(buf, "Testing str", 11));
318 test_eq(32, buf_find_string_offset(buf, "ng ", 3));
319 test_eq(43, buf_find_string_offset(buf, "string.", 7));
320 test_eq(-1, buf_find_string_offset(buf, "shrdlu", 6));
321 test_eq(-1, buf_find_string_offset(buf, "Testing thing", 13));
322 test_eq(-1, buf_find_string_offset(buf, "ngx", 3));
323 buf_free(buf);
324 buf = NULL;
326 #if 0
328 int s;
329 int eof;
330 int i;
331 buf_t *buf2;
332 /****
333 * read_to_buf
334 ****/
335 s = open(get_fname("data"), O_WRONLY|O_CREAT|O_TRUNC, 0600);
336 write(s, str, 256);
337 close(s);
339 s = open(get_fname("data"), O_RDONLY, 0);
340 eof = 0;
341 errno = 0; /* XXXX */
342 i = read_to_buf(s, 10, buf, &eof);
343 printf("%s\n", strerror(errno));
344 test_eq(i, 10);
345 test_eq(eof, 0);
346 //test_eq(buf_capacity(buf), 4096);
347 test_eq(buf_datalen(buf), 10);
349 test_memeq(str, (char*)_buf_peek_raw_buffer(buf), 10);
351 /* Test reading 0 bytes. */
352 i = read_to_buf(s, 0, buf, &eof);
353 //test_eq(buf_capacity(buf), 512*1024);
354 test_eq(buf_datalen(buf), 10);
355 test_eq(eof, 0);
356 test_eq(i, 0);
358 /* Now test when buffer is filled exactly. */
359 buf2 = buf_new_with_capacity(6);
360 i = read_to_buf(s, 6, buf2, &eof);
361 //test_eq(buf_capacity(buf2), 6);
362 test_eq(buf_datalen(buf2), 6);
363 test_eq(eof, 0);
364 test_eq(i, 6);
365 test_memeq(str+10, (char*)_buf_peek_raw_buffer(buf2), 6);
366 buf_free(buf2);
367 buf2 = NULL;
369 /* Now test when buffer is filled with more data to read. */
370 buf2 = buf_new_with_capacity(32);
371 i = read_to_buf(s, 128, buf2, &eof);
372 //test_eq(buf_capacity(buf2), 128);
373 test_eq(buf_datalen(buf2), 32);
374 test_eq(eof, 0);
375 test_eq(i, 32);
376 buf_free(buf2);
377 buf2 = NULL;
379 /* Now read to eof. */
380 test_assert(buf_capacity(buf) > 256);
381 i = read_to_buf(s, 1024, buf, &eof);
382 test_eq(i, (256-32-10-6));
383 test_eq(buf_capacity(buf), MAX_BUF_SIZE);
384 test_eq(buf_datalen(buf), 256-6-32);
385 test_memeq(str, (char*)_buf_peek_raw_buffer(buf), 10); /* XXX Check rest. */
386 test_eq(eof, 0);
388 i = read_to_buf(s, 1024, buf, &eof);
389 test_eq(i, 0);
390 test_eq(buf_capacity(buf), MAX_BUF_SIZE);
391 test_eq(buf_datalen(buf), 256-6-32);
392 test_eq(eof, 1);
394 #endif
396 done:
397 if (buf)
398 buf_free(buf);
399 if (buf2)
400 buf_free(buf2);
403 /** Run unit tests for Diffie-Hellman functionality. */
404 static void
405 test_crypto_dh(void)
407 crypto_dh_env_t *dh1 = crypto_dh_new();
408 crypto_dh_env_t *dh2 = crypto_dh_new();
409 char p1[DH_BYTES];
410 char p2[DH_BYTES];
411 char s1[DH_BYTES];
412 char s2[DH_BYTES];
413 ssize_t s1len, s2len;
415 test_eq(crypto_dh_get_bytes(dh1), DH_BYTES);
416 test_eq(crypto_dh_get_bytes(dh2), DH_BYTES);
418 memset(p1, 0, DH_BYTES);
419 memset(p2, 0, DH_BYTES);
420 test_memeq(p1, p2, DH_BYTES);
421 test_assert(! crypto_dh_get_public(dh1, p1, DH_BYTES));
422 test_memneq(p1, p2, DH_BYTES);
423 test_assert(! crypto_dh_get_public(dh2, p2, DH_BYTES));
424 test_memneq(p1, p2, DH_BYTES);
426 memset(s1, 0, DH_BYTES);
427 memset(s2, 0xFF, DH_BYTES);
428 s1len = crypto_dh_compute_secret(dh1, p2, DH_BYTES, s1, 50);
429 s2len = crypto_dh_compute_secret(dh2, p1, DH_BYTES, s2, 50);
430 test_assert(s1len > 0);
431 test_eq(s1len, s2len);
432 test_memeq(s1, s2, s1len);
435 /* XXXX Now fabricate some bad values and make sure they get caught,
436 * Check 0, 1, N-1, >= N, etc.
440 done:
441 crypto_dh_free(dh1);
442 crypto_dh_free(dh2);
445 /** Run unit tests for our random number generation function and its wrappers.
447 static void
448 test_crypto_rng(void)
450 int i, j, allok;
451 char data1[100], data2[100];
453 /* Try out RNG. */
454 test_assert(! crypto_seed_rng(0));
455 crypto_rand(data1, 100);
456 crypto_rand(data2, 100);
457 test_memneq(data1,data2,100);
458 allok = 1;
459 for (i = 0; i < 100; ++i) {
460 uint64_t big;
461 char *host;
462 j = crypto_rand_int(100);
463 if (i < 0 || i >= 100)
464 allok = 0;
465 big = crypto_rand_uint64(U64_LITERAL(1)<<40);
466 if (big >= (U64_LITERAL(1)<<40))
467 allok = 0;
468 big = crypto_rand_uint64(U64_LITERAL(5));
469 if (big >= 5)
470 allok = 0;
471 host = crypto_random_hostname(3,8,"www.",".onion");
472 if (strcmpstart(host,"www.") ||
473 strcmpend(host,".onion") ||
474 strlen(host) < 13 ||
475 strlen(host) > 18)
476 allok = 0;
477 tor_free(host);
479 test_assert(allok);
480 done:
484 /** Run unit tests for our AES functionality */
485 static void
486 test_crypto_aes(void)
488 char *data1 = NULL, *data2 = NULL, *data3 = NULL;
489 crypto_cipher_env_t *env1 = NULL, *env2 = NULL;
490 int i, j;
492 data1 = tor_malloc(1024);
493 data2 = tor_malloc(1024);
494 data3 = tor_malloc(1024);
496 /* Now, test encryption and decryption with stream cipher. */
497 data1[0]='\0';
498 for (i = 1023; i>0; i -= 35)
499 strncat(data1, "Now is the time for all good onions", i);
501 memset(data2, 0, 1024);
502 memset(data3, 0, 1024);
503 env1 = crypto_new_cipher_env();
504 test_neq(env1, 0);
505 env2 = crypto_new_cipher_env();
506 test_neq(env2, 0);
507 j = crypto_cipher_generate_key(env1);
508 crypto_cipher_set_key(env2, crypto_cipher_get_key(env1));
509 crypto_cipher_encrypt_init_cipher(env1);
510 crypto_cipher_decrypt_init_cipher(env2);
512 /* Try encrypting 512 chars. */
513 crypto_cipher_encrypt(env1, data2, data1, 512);
514 crypto_cipher_decrypt(env2, data3, data2, 512);
515 test_memeq(data1, data3, 512);
516 test_memneq(data1, data2, 512);
518 /* Now encrypt 1 at a time, and get 1 at a time. */
519 for (j = 512; j < 560; ++j) {
520 crypto_cipher_encrypt(env1, data2+j, data1+j, 1);
522 for (j = 512; j < 560; ++j) {
523 crypto_cipher_decrypt(env2, data3+j, data2+j, 1);
525 test_memeq(data1, data3, 560);
526 /* Now encrypt 3 at a time, and get 5 at a time. */
527 for (j = 560; j < 1024-5; j += 3) {
528 crypto_cipher_encrypt(env1, data2+j, data1+j, 3);
530 for (j = 560; j < 1024-5; j += 5) {
531 crypto_cipher_decrypt(env2, data3+j, data2+j, 5);
533 test_memeq(data1, data3, 1024-5);
534 /* Now make sure that when we encrypt with different chunk sizes, we get
535 the same results. */
536 crypto_free_cipher_env(env2);
537 env2 = NULL;
539 memset(data3, 0, 1024);
540 env2 = crypto_new_cipher_env();
541 test_neq(env2, 0);
542 crypto_cipher_set_key(env2, crypto_cipher_get_key(env1));
543 crypto_cipher_encrypt_init_cipher(env2);
544 for (j = 0; j < 1024-16; j += 17) {
545 crypto_cipher_encrypt(env2, data3+j, data1+j, 17);
547 for (j= 0; j < 1024-16; ++j) {
548 if (data2[j] != data3[j]) {
549 printf("%d: %d\t%d\n", j, (int) data2[j], (int) data3[j]);
552 test_memeq(data2, data3, 1024-16);
553 crypto_free_cipher_env(env1);
554 env1 = NULL;
555 crypto_free_cipher_env(env2);
556 env2 = NULL;
558 /* NIST test vector for aes. */
559 env1 = crypto_new_cipher_env(); /* IV starts at 0 */
560 crypto_cipher_set_key(env1, "\x80\x00\x00\x00\x00\x00\x00\x00"
561 "\x00\x00\x00\x00\x00\x00\x00\x00");
562 crypto_cipher_encrypt_init_cipher(env1);
563 crypto_cipher_encrypt(env1, data1,
564 "\x00\x00\x00\x00\x00\x00\x00\x00"
565 "\x00\x00\x00\x00\x00\x00\x00\x00", 16);
566 test_memeq_hex(data1, "0EDD33D3C621E546455BD8BA1418BEC8");
568 /* Now test rollover. All these values are originally from a python
569 * script. */
570 crypto_cipher_set_iv(env1, "\x00\x00\x00\x00\x00\x00\x00\x00"
571 "\xff\xff\xff\xff\xff\xff\xff\xff");
572 memset(data2, 0, 1024);
573 crypto_cipher_encrypt(env1, data1, data2, 32);
574 test_memeq_hex(data1, "335fe6da56f843199066c14a00a40231"
575 "cdd0b917dbc7186908a6bfb5ffd574d3");
577 crypto_cipher_set_iv(env1, "\x00\x00\x00\x00\xff\xff\xff\xff"
578 "\xff\xff\xff\xff\xff\xff\xff\xff");
579 memset(data2, 0, 1024);
580 crypto_cipher_encrypt(env1, data1, data2, 32);
581 test_memeq_hex(data1, "e627c6423fa2d77832a02b2794094b73"
582 "3e63c721df790d2c6469cc1953a3ffac");
584 crypto_cipher_set_iv(env1, "\xff\xff\xff\xff\xff\xff\xff\xff"
585 "\xff\xff\xff\xff\xff\xff\xff\xff");
586 memset(data2, 0, 1024);
587 crypto_cipher_encrypt(env1, data1, data2, 32);
588 test_memeq_hex(data1, "2aed2bff0de54f9328efd070bf48f70a"
589 "0EDD33D3C621E546455BD8BA1418BEC8");
591 /* Now check rollover on inplace cipher. */
592 crypto_cipher_set_iv(env1, "\xff\xff\xff\xff\xff\xff\xff\xff"
593 "\xff\xff\xff\xff\xff\xff\xff\xff");
594 crypto_cipher_crypt_inplace(env1, data2, 64);
595 test_memeq_hex(data2, "2aed2bff0de54f9328efd070bf48f70a"
596 "0EDD33D3C621E546455BD8BA1418BEC8"
597 "93e2c5243d6839eac58503919192f7ae"
598 "1908e67cafa08d508816659c2e693191");
599 crypto_cipher_set_iv(env1, "\xff\xff\xff\xff\xff\xff\xff\xff"
600 "\xff\xff\xff\xff\xff\xff\xff\xff");
601 crypto_cipher_crypt_inplace(env1, data2, 64);
602 test_assert(tor_mem_is_zero(data2, 64));
604 done:
605 if (env1)
606 crypto_free_cipher_env(env1);
607 if (env2)
608 crypto_free_cipher_env(env2);
609 tor_free(data1);
610 tor_free(data2);
611 tor_free(data3);
614 /** Run unit tests for our SHA-1 functionality */
615 static void
616 test_crypto_sha(void)
618 crypto_digest_env_t *d1 = NULL, *d2 = NULL;
619 int i;
620 char key[80];
621 char digest[20];
622 char data[50];
623 char d_out1[DIGEST_LEN], d_out2[DIGEST_LEN];
625 /* Test SHA-1 with a test vector from the specification. */
626 i = crypto_digest(data, "abc", 3);
627 test_memeq_hex(data, "A9993E364706816ABA3E25717850C26C9CD0D89D");
629 /* Test HMAC-SHA-1 with test cases from RFC2202. */
631 /* Case 1. */
632 memset(key, 0x0b, 20);
633 crypto_hmac_sha1(digest, key, 20, "Hi There", 8);
634 test_streq(hex_str(digest, 20),
635 "B617318655057264E28BC0B6FB378C8EF146BE00");
636 /* Case 2. */
637 crypto_hmac_sha1(digest, "Jefe", 4, "what do ya want for nothing?", 28);
638 test_streq(hex_str(digest, 20),
639 "EFFCDF6AE5EB2FA2D27416D5F184DF9C259A7C79");
641 /* Case 4. */
642 base16_decode(key, 25,
643 "0102030405060708090a0b0c0d0e0f10111213141516171819", 50);
644 memset(data, 0xcd, 50);
645 crypto_hmac_sha1(digest, key, 25, data, 50);
646 test_streq(hex_str(digest, 20),
647 "4C9007F4026250C6BC8414F9BF50C86C2D7235DA");
649 /* Case . */
650 memset(key, 0xaa, 80);
651 crypto_hmac_sha1(digest, key, 80,
652 "Test Using Larger Than Block-Size Key - Hash Key First",
653 54);
654 test_streq(hex_str(digest, 20),
655 "AA4AE5E15272D00E95705637CE8A3B55ED402112");
657 /* Incremental digest code. */
658 d1 = crypto_new_digest_env();
659 test_assert(d1);
660 crypto_digest_add_bytes(d1, "abcdef", 6);
661 d2 = crypto_digest_dup(d1);
662 test_assert(d2);
663 crypto_digest_add_bytes(d2, "ghijkl", 6);
664 crypto_digest_get_digest(d2, d_out1, sizeof(d_out1));
665 crypto_digest(d_out2, "abcdefghijkl", 12);
666 test_memeq(d_out1, d_out2, DIGEST_LEN);
667 crypto_digest_assign(d2, d1);
668 crypto_digest_add_bytes(d2, "mno", 3);
669 crypto_digest_get_digest(d2, d_out1, sizeof(d_out1));
670 crypto_digest(d_out2, "abcdefmno", 9);
671 test_memeq(d_out1, d_out2, DIGEST_LEN);
672 crypto_digest_get_digest(d1, d_out1, sizeof(d_out1));
673 crypto_digest(d_out2, "abcdef", 6);
674 test_memeq(d_out1, d_out2, DIGEST_LEN);
676 done:
677 if (d1)
678 crypto_free_digest_env(d1);
679 if (d2)
680 crypto_free_digest_env(d2);
683 /** Run unit tests for our public key crypto functions */
684 static void
685 test_crypto_pk(void)
687 crypto_pk_env_t *pk1 = NULL, *pk2 = NULL;
688 char *encoded = NULL;
689 char data1[1024], data2[1024], data3[1024];
690 size_t size;
691 int i, j, p, len;
693 /* Public-key ciphers */
694 pk1 = pk_generate(0);
695 pk2 = crypto_new_pk_env();
696 test_assert(pk1 && pk2);
697 test_assert(! crypto_pk_write_public_key_to_string(pk1, &encoded, &size));
698 test_assert(! crypto_pk_read_public_key_from_string(pk2, encoded, size));
699 test_eq(0, crypto_pk_cmp_keys(pk1, pk2));
701 test_eq(128, crypto_pk_keysize(pk1));
702 test_eq(128, crypto_pk_keysize(pk2));
704 test_eq(128, crypto_pk_public_encrypt(pk2, data1, "Hello whirled.", 15,
705 PK_PKCS1_OAEP_PADDING));
706 test_eq(128, crypto_pk_public_encrypt(pk1, data2, "Hello whirled.", 15,
707 PK_PKCS1_OAEP_PADDING));
708 /* oaep padding should make encryption not match */
709 test_memneq(data1, data2, 128);
710 test_eq(15, crypto_pk_private_decrypt(pk1, data3, data1, 128,
711 PK_PKCS1_OAEP_PADDING,1));
712 test_streq(data3, "Hello whirled.");
713 memset(data3, 0, 1024);
714 test_eq(15, crypto_pk_private_decrypt(pk1, data3, data2, 128,
715 PK_PKCS1_OAEP_PADDING,1));
716 test_streq(data3, "Hello whirled.");
717 /* Can't decrypt with public key. */
718 test_eq(-1, crypto_pk_private_decrypt(pk2, data3, data2, 128,
719 PK_PKCS1_OAEP_PADDING,1));
720 /* Try again with bad padding */
721 memcpy(data2+1, "XYZZY", 5); /* This has fails ~ once-in-2^40 */
722 test_eq(-1, crypto_pk_private_decrypt(pk1, data3, data2, 128,
723 PK_PKCS1_OAEP_PADDING,1));
725 /* File operations: save and load private key */
726 test_assert(! crypto_pk_write_private_key_to_filename(pk1,
727 get_fname("pkey1")));
728 /* failing case for read: can't read. */
729 test_assert(crypto_pk_read_private_key_from_filename(pk2,
730 get_fname("xyzzy")) < 0);
731 write_str_to_file(get_fname("xyzzy"), "foobar", 6);
732 /* Failing case for read: no key. */
733 test_assert(crypto_pk_read_private_key_from_filename(pk2,
734 get_fname("xyzzy")) < 0);
735 test_assert(! crypto_pk_read_private_key_from_filename(pk2,
736 get_fname("pkey1")));
737 test_eq(15, crypto_pk_private_decrypt(pk2, data3, data1, 128,
738 PK_PKCS1_OAEP_PADDING,1));
740 /* Now try signing. */
741 strlcpy(data1, "Ossifrage", 1024);
742 test_eq(128, crypto_pk_private_sign(pk1, data2, data1, 10));
743 test_eq(10, crypto_pk_public_checksig(pk1, data3, data2, 128));
744 test_streq(data3, "Ossifrage");
745 /* Try signing digests. */
746 test_eq(128, crypto_pk_private_sign_digest(pk1, data2, data1, 10));
747 test_eq(20, crypto_pk_public_checksig(pk1, data3, data2, 128));
748 test_eq(0, crypto_pk_public_checksig_digest(pk1, data1, 10, data2, 128));
749 test_eq(-1, crypto_pk_public_checksig_digest(pk1, data1, 11, data2, 128));
750 /*XXXX test failed signing*/
752 /* Try encoding */
753 crypto_free_pk_env(pk2);
754 pk2 = NULL;
755 i = crypto_pk_asn1_encode(pk1, data1, 1024);
756 test_assert(i>0);
757 pk2 = crypto_pk_asn1_decode(data1, i);
758 test_assert(crypto_pk_cmp_keys(pk1,pk2) == 0);
760 /* Try with hybrid encryption wrappers. */
761 crypto_rand(data1, 1024);
762 for (i = 0; i < 3; ++i) {
763 for (j = 85; j < 140; ++j) {
764 memset(data2,0,1024);
765 memset(data3,0,1024);
766 if (i == 0 && j < 129)
767 continue;
768 p = (i==0)?PK_NO_PADDING:
769 (i==1)?PK_PKCS1_PADDING:PK_PKCS1_OAEP_PADDING;
770 len = crypto_pk_public_hybrid_encrypt(pk1,data2,data1,j,p,0);
771 test_assert(len>=0);
772 len = crypto_pk_private_hybrid_decrypt(pk1,data3,data2,len,p,1);
773 test_eq(len,j);
774 test_memeq(data1,data3,j);
778 /* Try copy_full */
779 crypto_free_pk_env(pk2);
780 pk2 = crypto_pk_copy_full(pk1);
781 test_assert(pk2 != NULL);
782 test_neq_ptr(pk1, pk2);
783 test_assert(crypto_pk_cmp_keys(pk1,pk2) == 0);
785 done:
786 if (pk1)
787 crypto_free_pk_env(pk1);
788 if (pk2)
789 crypto_free_pk_env(pk2);
790 tor_free(encoded);
793 /** Run unit tests for misc crypto functionality. */
794 static void
795 test_crypto(void)
797 char *data1 = NULL, *data2 = NULL, *data3 = NULL;
798 int i, j, idx;
800 data1 = tor_malloc(1024);
801 data2 = tor_malloc(1024);
802 data3 = tor_malloc(1024);
803 test_assert(data1 && data2 && data3);
805 /* Base64 tests */
806 memset(data1, 6, 1024);
807 for (idx = 0; idx < 10; ++idx) {
808 i = base64_encode(data2, 1024, data1, idx);
809 test_assert(i >= 0);
810 j = base64_decode(data3, 1024, data2, i);
811 test_eq(j,idx);
812 test_memeq(data3, data1, idx);
815 strlcpy(data1, "Test string that contains 35 chars.", 1024);
816 strlcat(data1, " 2nd string that contains 35 chars.", 1024);
818 i = base64_encode(data2, 1024, data1, 71);
819 j = base64_decode(data3, 1024, data2, i);
820 test_eq(j, 71);
821 test_streq(data3, data1);
822 test_assert(data2[i] == '\0');
824 crypto_rand(data1, DIGEST_LEN);
825 memset(data2, 100, 1024);
826 digest_to_base64(data2, data1);
827 test_eq(BASE64_DIGEST_LEN, strlen(data2));
828 test_eq(100, data2[BASE64_DIGEST_LEN+2]);
829 memset(data3, 99, 1024);
830 test_eq(digest_from_base64(data3, data2), 0);
831 test_memeq(data1, data3, DIGEST_LEN);
832 test_eq(99, data3[DIGEST_LEN+1]);
834 test_assert(digest_from_base64(data3, "###") < 0);
836 /* Base32 tests */
837 strlcpy(data1, "5chrs", 1024);
838 /* bit pattern is: [35 63 68 72 73] ->
839 * [00110101 01100011 01101000 01110010 01110011]
840 * By 5s: [00110 10101 10001 10110 10000 11100 10011 10011]
842 base32_encode(data2, 9, data1, 5);
843 test_streq(data2, "gvrwq4tt");
845 strlcpy(data1, "\xFF\xF5\x6D\x44\xAE\x0D\x5C\xC9\x62\xC4", 1024);
846 base32_encode(data2, 30, data1, 10);
847 test_streq(data2, "772w2rfobvomsywe");
849 /* Base16 tests */
850 strlcpy(data1, "6chrs\xff", 1024);
851 base16_encode(data2, 13, data1, 6);
852 test_streq(data2, "3663687273FF");
854 strlcpy(data1, "f0d678affc000100", 1024);
855 i = base16_decode(data2, 8, data1, 16);
856 test_eq(i,0);
857 test_memeq(data2, "\xf0\xd6\x78\xaf\xfc\x00\x01\x00",8);
859 /* now try some failing base16 decodes */
860 test_eq(-1, base16_decode(data2, 8, data1, 15)); /* odd input len */
861 test_eq(-1, base16_decode(data2, 7, data1, 16)); /* dest too short */
862 strlcpy(data1, "f0dz!8affc000100", 1024);
863 test_eq(-1, base16_decode(data2, 8, data1, 16));
865 tor_free(data1);
866 tor_free(data2);
867 tor_free(data3);
869 /* Add spaces to fingerprint */
871 data1 = tor_strdup("ABCD1234ABCD56780000ABCD1234ABCD56780000");
872 test_eq(strlen(data1), 40);
873 data2 = tor_malloc(FINGERPRINT_LEN+1);
874 add_spaces_to_fp(data2, FINGERPRINT_LEN+1, data1);
875 test_streq(data2, "ABCD 1234 ABCD 5678 0000 ABCD 1234 ABCD 5678 0000");
876 tor_free(data1);
877 tor_free(data2);
880 /* Check fingerprint */
882 test_assert(crypto_pk_check_fingerprint_syntax(
883 "ABCD 1234 ABCD 5678 0000 ABCD 1234 ABCD 5678 0000"));
884 test_assert(!crypto_pk_check_fingerprint_syntax(
885 "ABCD 1234 ABCD 5678 0000 ABCD 1234 ABCD 5678 000"));
886 test_assert(!crypto_pk_check_fingerprint_syntax(
887 "ABCD 1234 ABCD 5678 0000 ABCD 1234 ABCD 5678 00000"));
888 test_assert(!crypto_pk_check_fingerprint_syntax(
889 "ABCD 1234 ABCD 5678 0000 ABCD1234 ABCD 5678 0000"));
890 test_assert(!crypto_pk_check_fingerprint_syntax(
891 "ABCD 1234 ABCD 5678 0000 ABCD1234 ABCD 5678 00000"));
892 test_assert(!crypto_pk_check_fingerprint_syntax(
893 "ACD 1234 ABCD 5678 0000 ABCD 1234 ABCD 5678 00000"));
896 done:
897 tor_free(data1);
898 tor_free(data2);
899 tor_free(data3);
902 /** Run unit tests for our secret-to-key passphrase hashing functionality. */
903 static void
904 test_crypto_s2k(void)
906 char buf[29];
907 char buf2[29];
908 char *buf3 = NULL;
909 int i;
911 memset(buf, 0, sizeof(buf));
912 memset(buf2, 0, sizeof(buf2));
913 buf3 = tor_malloc(65536);
914 memset(buf3, 0, 65536);
916 secret_to_key(buf+9, 20, "", 0, buf);
917 crypto_digest(buf2+9, buf3, 1024);
918 test_memeq(buf, buf2, 29);
920 memcpy(buf,"vrbacrda",8);
921 memcpy(buf2,"vrbacrda",8);
922 buf[8] = 96;
923 buf2[8] = 96;
924 secret_to_key(buf+9, 20, "12345678", 8, buf);
925 for (i = 0; i < 65536; i += 16) {
926 memcpy(buf3+i, "vrbacrda12345678", 16);
928 crypto_digest(buf2+9, buf3, 65536);
929 test_memeq(buf, buf2, 29);
931 done:
932 tor_free(buf3);
935 /** Helper: return a tristate based on comparing the strings in *<b>a</b> and
936 * *<b>b</b>. */
937 static int
938 _compare_strs(const void **a, const void **b)
940 const char *s1 = *a, *s2 = *b;
941 return strcmp(s1, s2);
944 /** Helper: return a tristate based on comparing the strings in *<b>a</b> and
945 * *<b>b</b>, excluding a's first character, and ignoring case. */
946 static int
947 _compare_without_first_ch(const void *a, const void **b)
949 const char *s1 = a, *s2 = *b;
950 return strcasecmp(s1+1, s2);
953 /** Test basic utility functionality. */
954 static void
955 test_util(void)
957 struct timeval start, end;
958 struct tm a_time;
959 char timestr[RFC1123_TIME_LEN+1];
960 char buf[1024];
961 time_t t_res;
962 int i;
963 uint32_t u32;
964 uint16_t u16;
965 char *cp, *k, *v;
966 const char *str;
968 start.tv_sec = 5;
969 start.tv_usec = 5000;
971 end.tv_sec = 5;
972 end.tv_usec = 5000;
974 test_eq(0L, tv_udiff(&start, &end));
976 end.tv_usec = 7000;
978 test_eq(2000L, tv_udiff(&start, &end));
980 end.tv_sec = 6;
982 test_eq(1002000L, tv_udiff(&start, &end));
984 end.tv_usec = 0;
986 test_eq(995000L, tv_udiff(&start, &end));
988 end.tv_sec = 4;
990 test_eq(-1005000L, tv_udiff(&start, &end));
992 end.tv_usec = 999990;
993 start.tv_sec = 1;
994 start.tv_usec = 500;
996 /* The test values here are confirmed to be correct on a platform
997 * with a working timegm. */
998 a_time.tm_year = 2003-1900;
999 a_time.tm_mon = 7;
1000 a_time.tm_mday = 30;
1001 a_time.tm_hour = 6;
1002 a_time.tm_min = 14;
1003 a_time.tm_sec = 55;
1004 test_eq((time_t) 1062224095UL, tor_timegm(&a_time));
1005 a_time.tm_year = 2004-1900; /* Try a leap year, after feb. */
1006 test_eq((time_t) 1093846495UL, tor_timegm(&a_time));
1007 a_time.tm_mon = 1; /* Try a leap year, in feb. */
1008 a_time.tm_mday = 10;
1009 test_eq((time_t) 1076393695UL, tor_timegm(&a_time));
1011 format_rfc1123_time(timestr, 0);
1012 test_streq("Thu, 01 Jan 1970 00:00:00 GMT", timestr);
1013 format_rfc1123_time(timestr, (time_t)1091580502UL);
1014 test_streq("Wed, 04 Aug 2004 00:48:22 GMT", timestr);
1016 t_res = 0;
1017 i = parse_rfc1123_time(timestr, &t_res);
1018 test_eq(i,0);
1019 test_eq(t_res, (time_t)1091580502UL);
1020 test_eq(-1, parse_rfc1123_time("Wed, zz Aug 2004 99-99x99 GMT", &t_res));
1021 tor_gettimeofday(&start);
1023 /* Tests for corner cases of strl operations */
1024 test_eq(5, strlcpy(buf, "Hello", 0));
1025 strlcpy(buf, "Hello", sizeof(buf));
1026 test_eq(10, strlcat(buf, "Hello", 5));
1028 /* Test tor_strstrip() */
1029 strlcpy(buf, "Testing 1 2 3", sizeof(buf));
1030 tor_strstrip(buf, ",!");
1031 test_streq(buf, "Testing 1 2 3");
1032 strlcpy(buf, "!Testing 1 2 3?", sizeof(buf));
1033 tor_strstrip(buf, "!? ");
1034 test_streq(buf, "Testing123");
1036 /* Test parse_addr_port */
1037 cp = NULL; u32 = 3; u16 = 3;
1038 test_assert(!parse_addr_port(LOG_WARN, "1.2.3.4", &cp, &u32, &u16));
1039 test_streq(cp, "1.2.3.4");
1040 test_eq(u32, 0x01020304u);
1041 test_eq(u16, 0);
1042 tor_free(cp);
1043 test_assert(!parse_addr_port(LOG_WARN, "4.3.2.1:99", &cp, &u32, &u16));
1044 test_streq(cp, "4.3.2.1");
1045 test_eq(u32, 0x04030201u);
1046 test_eq(u16, 99);
1047 tor_free(cp);
1048 test_assert(!parse_addr_port(LOG_WARN, "nonexistent.address:4040",
1049 &cp, NULL, &u16));
1050 test_streq(cp, "nonexistent.address");
1051 test_eq(u16, 4040);
1052 tor_free(cp);
1053 test_assert(!parse_addr_port(LOG_WARN, "localhost:9999", &cp, &u32, &u16));
1054 test_streq(cp, "localhost");
1055 test_eq(u32, 0x7f000001u);
1056 test_eq(u16, 9999);
1057 tor_free(cp);
1058 u32 = 3;
1059 test_assert(!parse_addr_port(LOG_WARN, "localhost", NULL, &u32, &u16));
1060 test_eq(cp, NULL);
1061 test_eq(u32, 0x7f000001u);
1062 test_eq(u16, 0);
1063 tor_free(cp);
1064 test_eq(0, addr_mask_get_bits(0x0u));
1065 test_eq(32, addr_mask_get_bits(0xFFFFFFFFu));
1066 test_eq(16, addr_mask_get_bits(0xFFFF0000u));
1067 test_eq(31, addr_mask_get_bits(0xFFFFFFFEu));
1068 test_eq(1, addr_mask_get_bits(0x80000000u));
1070 /* Test tor_parse_long. */
1071 test_eq(10L, tor_parse_long("10",10,0,100,NULL,NULL));
1072 test_eq(0L, tor_parse_long("10",10,50,100,NULL,NULL));
1073 test_eq(-50L, tor_parse_long("-50",10,-100,100,NULL,NULL));
1075 /* Test tor_parse_ulong */
1076 test_eq(10UL, tor_parse_ulong("10",10,0,100,NULL,NULL));
1077 test_eq(0UL, tor_parse_ulong("10",10,50,100,NULL,NULL));
1079 /* Test tor_parse_uint64. */
1080 test_assert(U64_LITERAL(10) == tor_parse_uint64("10 x",10,0,100, &i, &cp));
1081 test_assert(i == 1);
1082 test_streq(cp, " x");
1083 test_assert(U64_LITERAL(12345678901) ==
1084 tor_parse_uint64("12345678901",10,0,UINT64_MAX, &i, &cp));
1085 test_assert(i == 1);
1086 test_streq(cp, "");
1087 test_assert(U64_LITERAL(0) ==
1088 tor_parse_uint64("12345678901",10,500,INT32_MAX, &i, &cp));
1089 test_assert(i == 0);
1091 /* Test failing snprintf cases */
1092 test_eq(-1, tor_snprintf(buf, 0, "Foo"));
1093 test_eq(-1, tor_snprintf(buf, 2, "Foo"));
1095 /* Test printf with uint64 */
1096 tor_snprintf(buf, sizeof(buf), "x!"U64_FORMAT"!x",
1097 U64_PRINTF_ARG(U64_LITERAL(12345678901)));
1098 test_streq(buf, "x!12345678901!x");
1100 /* Test parse_config_line_from_str */
1101 strlcpy(buf, "k v\n" " key value with spaces \n" "keykey val\n"
1102 "k2\n"
1103 "k3 \n" "\n" " \n" "#comment\n"
1104 "k4#a\n" "k5#abc\n" "k6 val #with comment\n"
1105 "kseven \"a quoted 'string\"\n"
1106 "k8 \"a \\x71uoted\\n\\\"str\\\\ing\\t\\001\\01\\1\\\"\"\n"
1107 , sizeof(buf));
1108 str = buf;
1110 str = parse_config_line_from_str(str, &k, &v);
1111 test_streq(k, "k");
1112 test_streq(v, "v");
1113 tor_free(k); tor_free(v);
1114 test_assert(!strcmpstart(str, "key value with"));
1116 str = parse_config_line_from_str(str, &k, &v);
1117 test_streq(k, "key");
1118 test_streq(v, "value with spaces");
1119 tor_free(k); tor_free(v);
1120 test_assert(!strcmpstart(str, "keykey"));
1122 str = parse_config_line_from_str(str, &k, &v);
1123 test_streq(k, "keykey");
1124 test_streq(v, "val");
1125 tor_free(k); tor_free(v);
1126 test_assert(!strcmpstart(str, "k2\n"));
1128 str = parse_config_line_from_str(str, &k, &v);
1129 test_streq(k, "k2");
1130 test_streq(v, "");
1131 tor_free(k); tor_free(v);
1132 test_assert(!strcmpstart(str, "k3 \n"));
1134 str = parse_config_line_from_str(str, &k, &v);
1135 test_streq(k, "k3");
1136 test_streq(v, "");
1137 tor_free(k); tor_free(v);
1138 test_assert(!strcmpstart(str, "#comment"));
1140 str = parse_config_line_from_str(str, &k, &v);
1141 test_streq(k, "k4");
1142 test_streq(v, "");
1143 tor_free(k); tor_free(v);
1144 test_assert(!strcmpstart(str, "k5#abc"));
1146 str = parse_config_line_from_str(str, &k, &v);
1147 test_streq(k, "k5");
1148 test_streq(v, "");
1149 tor_free(k); tor_free(v);
1150 test_assert(!strcmpstart(str, "k6"));
1152 str = parse_config_line_from_str(str, &k, &v);
1153 test_streq(k, "k6");
1154 test_streq(v, "val");
1155 tor_free(k); tor_free(v);
1156 test_assert(!strcmpstart(str, "kseven"));
1158 str = parse_config_line_from_str(str, &k, &v);
1159 test_streq(k, "kseven");
1160 test_streq(v, "a quoted \'string");
1161 tor_free(k); tor_free(v);
1162 test_assert(!strcmpstart(str, "k8 "));
1164 str = parse_config_line_from_str(str, &k, &v);
1165 test_streq(k, "k8");
1166 test_streq(v, "a quoted\n\"str\\ing\t\x01\x01\x01\"");
1167 tor_free(k); tor_free(v);
1168 test_streq(str, "");
1170 /* Test for strcmpstart and strcmpend. */
1171 test_assert(strcmpstart("abcdef", "abcdef")==0);
1172 test_assert(strcmpstart("abcdef", "abc")==0);
1173 test_assert(strcmpstart("abcdef", "abd")<0);
1174 test_assert(strcmpstart("abcdef", "abb")>0);
1175 test_assert(strcmpstart("ab", "abb")<0);
1177 test_assert(strcmpend("abcdef", "abcdef")==0);
1178 test_assert(strcmpend("abcdef", "def")==0);
1179 test_assert(strcmpend("abcdef", "deg")<0);
1180 test_assert(strcmpend("abcdef", "dee")>0);
1181 test_assert(strcmpend("ab", "abb")<0);
1183 test_assert(strcasecmpend("AbcDEF", "abcdef")==0);
1184 test_assert(strcasecmpend("abcdef", "dEF")==0);
1185 test_assert(strcasecmpend("abcDEf", "deg")<0);
1186 test_assert(strcasecmpend("abcdef", "DEE")>0);
1187 test_assert(strcasecmpend("ab", "abB")<0);
1189 /* Test mem_is_zero */
1190 memset(buf,0,128);
1191 buf[128] = 'x';
1192 test_assert(tor_digest_is_zero(buf));
1193 test_assert(tor_mem_is_zero(buf, 10));
1194 test_assert(tor_mem_is_zero(buf, 20));
1195 test_assert(tor_mem_is_zero(buf, 128));
1196 test_assert(!tor_mem_is_zero(buf, 129));
1197 buf[60] = (char)255;
1198 test_assert(!tor_mem_is_zero(buf, 128));
1199 buf[0] = (char)1;
1200 test_assert(!tor_mem_is_zero(buf, 10));
1202 /* Test inet_ntop */
1204 char tmpbuf[TOR_ADDR_BUF_LEN];
1205 const char *ip = "176.192.208.224";
1206 struct in_addr in;
1207 tor_inet_pton(AF_INET, ip, &in);
1208 tor_inet_ntop(AF_INET, &in, tmpbuf, sizeof(tmpbuf));
1209 test_streq(tmpbuf, ip);
1212 /* Test 'escaped' */
1213 test_streq("\"\"", escaped(""));
1214 test_streq("\"abcd\"", escaped("abcd"));
1215 test_streq("\"\\\\\\n\\r\\t\\\"\\'\"", escaped("\\\n\r\t\"\'"));
1216 test_streq("\"z\\001abc\\277d\"", escaped("z\001abc\277d"));
1217 test_assert(NULL == escaped(NULL));
1219 /* Test strndup and memdup */
1221 const char *s = "abcdefghijklmnopqrstuvwxyz";
1222 cp = tor_strndup(s, 30);
1223 test_streq(cp, s); /* same string, */
1224 test_neq(cp, s); /* but different pointers. */
1225 tor_free(cp);
1227 cp = tor_strndup(s, 5);
1228 test_streq(cp, "abcde");
1229 tor_free(cp);
1231 s = "a\0b\0c\0d\0e\0";
1232 cp = tor_memdup(s,10);
1233 test_memeq(cp, s, 10); /* same ram, */
1234 test_neq(cp, s); /* but different pointers. */
1235 tor_free(cp);
1238 /* Test str-foo functions */
1239 cp = tor_strdup("abcdef");
1240 test_assert(tor_strisnonupper(cp));
1241 cp[3] = 'D';
1242 test_assert(!tor_strisnonupper(cp));
1243 tor_strupper(cp);
1244 test_streq(cp, "ABCDEF");
1245 test_assert(tor_strisprint(cp));
1246 cp[3] = 3;
1247 test_assert(!tor_strisprint(cp));
1248 tor_free(cp);
1250 /* Test eat_whitespace. */
1252 const char *s = " \n a";
1253 test_eq_ptr(eat_whitespace(s), s+4);
1254 s = "abcd";
1255 test_eq_ptr(eat_whitespace(s), s);
1256 s = "#xyz\nab";
1257 test_eq_ptr(eat_whitespace(s), s+5);
1260 /* Test memmem and memstr */
1262 const char *haystack = "abcde";
1263 tor_assert(!tor_memmem(haystack, 5, "ef", 2));
1264 test_eq_ptr(tor_memmem(haystack, 5, "cd", 2), haystack + 2);
1265 test_eq_ptr(tor_memmem(haystack, 5, "cde", 3), haystack + 2);
1266 haystack = "ababcad";
1267 test_eq_ptr(tor_memmem(haystack, 7, "abc", 3), haystack + 2);
1268 test_eq_ptr(tor_memstr(haystack, 7, "abc"), haystack + 2);
1269 test_assert(!tor_memstr(haystack, 7, "fe"));
1270 test_assert(!tor_memstr(haystack, 7, "longerthantheoriginal"));
1273 /* Test wrap_string */
1275 smartlist_t *sl = smartlist_create();
1276 wrap_string(sl, "This is a test of string wrapping functionality: woot.",
1277 10, "", "");
1278 cp = smartlist_join_strings(sl, "", 0, NULL);
1279 test_streq(cp,
1280 "This is a\ntest of\nstring\nwrapping\nfunctional\nity: woot.\n");
1281 tor_free(cp);
1282 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1283 smartlist_clear(sl);
1285 wrap_string(sl, "This is a test of string wrapping functionality: woot.",
1286 16, "### ", "# ");
1287 cp = smartlist_join_strings(sl, "", 0, NULL);
1288 test_streq(cp,
1289 "### This is a\n# test of string\n# wrapping\n# functionality:\n"
1290 "# woot.\n");
1292 tor_free(cp);
1293 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1294 smartlist_free(sl);
1297 tor_gettimeofday(&start);
1298 /* now make sure time works. */
1299 tor_gettimeofday(&end);
1300 /* We might've timewarped a little. */
1301 test_assert(tv_udiff(&start, &end) >= -5000);
1303 /* Test tor_log2(). */
1304 test_eq(tor_log2(64), 6);
1305 test_eq(tor_log2(65), 6);
1306 test_eq(tor_log2(63), 5);
1307 test_eq(tor_log2(1), 0);
1308 test_eq(tor_log2(2), 1);
1309 test_eq(tor_log2(3), 1);
1310 test_eq(tor_log2(4), 2);
1311 test_eq(tor_log2(5), 2);
1312 test_eq(tor_log2(U64_LITERAL(40000000000000000)), 55);
1313 test_eq(tor_log2(UINT64_MAX), 63);
1315 /* Test round_to_power_of_2 */
1316 test_eq(round_to_power_of_2(120), 128);
1317 test_eq(round_to_power_of_2(128), 128);
1318 test_eq(round_to_power_of_2(130), 128);
1319 test_eq(round_to_power_of_2(U64_LITERAL(40000000000000000)),
1320 U64_LITERAL(1)<<55);
1321 test_eq(round_to_power_of_2(0), 2);
1323 done:
1327 /** Helper: assert that IPv6 addresses <b>a</b> and <b>b</b> are the same. On
1328 * failure, reports an error, describing the addresses as <b>e1</b> and
1329 * <b>e2</b>, and reporting the line number as <b>line</b>. */
1330 static void
1331 _test_eq_ip6(struct in6_addr *a, struct in6_addr *b, const char *e1,
1332 const char *e2, int line)
1334 int i;
1335 int ok = 1;
1336 for (i = 0; i < 16; ++i) {
1337 if (a->s6_addr[i] != b->s6_addr[i]) {
1338 ok = 0;
1339 break;
1342 if (ok) {
1343 printf("."); fflush(stdout);
1344 } else {
1345 char buf1[128], *cp1;
1346 char buf2[128], *cp2;
1347 have_failed = 1;
1348 cp1 = buf1; cp2 = buf2;
1349 for (i=0; i<16; ++i) {
1350 tor_snprintf(cp1, sizeof(buf1)-(cp1-buf1), "%02x", a->s6_addr[i]);
1351 tor_snprintf(cp2, sizeof(buf2)-(cp2-buf2), "%02x", b->s6_addr[i]);
1352 cp1 += 2; cp2 += 2;
1353 if ((i%2)==1 && i != 15) {
1354 *cp1++ = ':';
1355 *cp2++ = ':';
1358 *cp1 = *cp2 = '\0';
1359 printf("Line %d: assertion failed: (%s == %s)\n"
1360 " %s != %s\n", line, e1, e2, buf1, buf2);
1361 fflush(stdout);
1365 /** Helper: Assert that two strings both decode as IPv6 addresses with
1366 * tor_inet_pton(), and both decode to the same address. */
1367 #define test_pton6_same(a,b) STMT_BEGIN \
1368 test_eq(tor_inet_pton(AF_INET6, a, &a1), 1); \
1369 test_eq(tor_inet_pton(AF_INET6, b, &a2), 1); \
1370 _test_eq_ip6(&a1,&a2,#a,#b,__LINE__); \
1371 STMT_END
1373 /** Helper: Assert that <b>a</b> is recognized as a bad IPv6 address by
1374 * tor_inet_pton(). */
1375 #define test_pton6_bad(a) \
1376 test_eq(0, tor_inet_pton(AF_INET6, a, &a1))
1378 /** Helper: assert that <b>a</b>, when parsed by tor_inet_pton() and displayed
1379 * with tor_inet_ntop(), yields <b>b</b>. Also assert that <b>b</b> parses to
1380 * the same value as <b>a</b>. */
1381 #define test_ntop6_reduces(a,b) STMT_BEGIN \
1382 test_eq(tor_inet_pton(AF_INET6, a, &a1), 1); \
1383 test_streq(tor_inet_ntop(AF_INET6, &a1, buf, sizeof(buf)), b); \
1384 test_eq(tor_inet_pton(AF_INET6, b, &a2), 1); \
1385 _test_eq_ip6(&a1, &a2, a, b, __LINE__); \
1386 STMT_END
1388 /** Helper: assert that <b>a</b> parses by tor_inet_pton() into a address that
1389 * passes tor_addr_is_internal() with <b>for_listening</b>. */
1390 #define test_internal_ip(a,for_listening) STMT_BEGIN \
1391 test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
1392 t1.family = AF_INET6; \
1393 if (!tor_addr_is_internal(&t1, for_listening)) \
1394 test_fail_msg( a "was not internal."); \
1395 STMT_END
1397 /** Helper: assert that <b>a</b> parses by tor_inet_pton() into a address that
1398 * does not pass tor_addr_is_internal() with <b>for_listening</b>. */
1399 #define test_external_ip(a,for_listening) STMT_BEGIN \
1400 test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
1401 t1.family = AF_INET6; \
1402 if (tor_addr_is_internal(&t1, for_listening)) \
1403 test_fail_msg(a "was not external."); \
1404 STMT_END
1406 /** Helper: Assert that <b>a</b> and <b>b</b>, when parsed by
1407 * tor_inet_pton(), give addresses that compare in the order defined by
1408 * <b>op</b> with tor_addr_compare(). */
1409 #define test_addr_compare(a, op, b) STMT_BEGIN \
1410 test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
1411 test_eq(tor_inet_pton(AF_INET6, b, &t2.addr.in6_addr), 1); \
1412 t1.family = t2.family = AF_INET6; \
1413 r = tor_addr_compare(&t1,&t2,CMP_SEMANTIC); \
1414 if (!(r op 0)) \
1415 test_fail_msg("failed: tor_addr_compare("a","b") "#op" 0"); \
1416 STMT_END
1418 /** Helper: Assert that <b>a</b> and <b>b</b>, when parsed by
1419 * tor_inet_pton(), give addresses that compare in the order defined by
1420 * <b>op</b> with tor_addr_compare_masked() with <b>m</b> masked. */
1421 #define test_addr_compare_masked(a, op, b, m) STMT_BEGIN \
1422 test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
1423 test_eq(tor_inet_pton(AF_INET6, b, &t2.addr.in6_addr), 1); \
1424 t1.family = t2.family = AF_INET6; \
1425 r = tor_addr_compare_masked(&t1,&t2,m,CMP_SEMANTIC); \
1426 if (!(r op 0)) \
1427 test_fail_msg("failed: tor_addr_compare_masked("a","b","#m") "#op" 0"); \
1428 STMT_END
1430 /** Helper: assert that <b>xx</b> is parseable as a masked IPv6 address with
1431 * ports by tor_parse_mask_addr_ports(), with family <b>f</b>, IP address
1432 * as 4 32-bit words <b>ip1...ip4</b>, mask bits as <b>mm</b>, and port range
1433 * as <b>pt1..pt2</b>. */
1434 #define test_addr_mask_ports_parse(xx, f, ip1, ip2, ip3, ip4, mm, pt1, pt2) \
1435 STMT_BEGIN \
1436 test_eq(tor_addr_parse_mask_ports(xx, &t1, &mask, &port1, &port2), f); \
1437 p1=tor_inet_ntop(AF_INET6, &t1.addr.in6_addr, bug, sizeof(bug)); \
1438 test_eq(htonl(ip1), tor_addr_to_in6_addr32(&t1)[0]); \
1439 test_eq(htonl(ip2), tor_addr_to_in6_addr32(&t1)[1]); \
1440 test_eq(htonl(ip3), tor_addr_to_in6_addr32(&t1)[2]); \
1441 test_eq(htonl(ip4), tor_addr_to_in6_addr32(&t1)[3]); \
1442 test_eq(mask, mm); \
1443 test_eq(port1, pt1); \
1444 test_eq(port2, pt2); \
1445 STMT_END
1447 /** Run unit tests for IPv6 encoding/decoding/manipulation functions. */
1448 static void
1449 test_util_ip6_helpers(void)
1451 char buf[TOR_ADDR_BUF_LEN], bug[TOR_ADDR_BUF_LEN];
1452 struct in6_addr a1, a2;
1453 tor_addr_t t1, t2;
1454 int r, i;
1455 uint16_t port1, port2;
1456 maskbits_t mask;
1457 const char *p1;
1458 struct sockaddr_storage sa_storage;
1459 struct sockaddr_in *sin;
1460 struct sockaddr_in6 *sin6;
1462 // struct in_addr b1, b2;
1463 /* Test tor_inet_ntop and tor_inet_pton: IPv6 */
1465 /* ==== Converting to and from sockaddr_t. */
1466 sin = (struct sockaddr_in *)&sa_storage;
1467 sin->sin_family = AF_INET;
1468 sin->sin_port = 9090;
1469 sin->sin_addr.s_addr = htonl(0x7f7f0102); /*127.127.1.2*/
1470 tor_addr_from_sockaddr(&t1, (struct sockaddr *)sin, NULL);
1471 test_eq(tor_addr_family(&t1), AF_INET);
1472 test_eq(tor_addr_to_ipv4h(&t1), 0x7f7f0102);
1474 memset(&sa_storage, 0, sizeof(sa_storage));
1475 test_eq(sizeof(struct sockaddr_in),
1476 tor_addr_to_sockaddr(&t1, 1234, (struct sockaddr *)&sa_storage,
1477 sizeof(sa_storage)));
1478 test_eq(1234, ntohs(sin->sin_port));
1479 test_eq(0x7f7f0102, ntohl(sin->sin_addr.s_addr));
1481 memset(&sa_storage, 0, sizeof(sa_storage));
1482 sin6 = (struct sockaddr_in6 *)&sa_storage;
1483 sin6->sin6_family = AF_INET6;
1484 sin6->sin6_port = htons(7070);
1485 sin6->sin6_addr.s6_addr[0] = 128;
1486 tor_addr_from_sockaddr(&t1, (struct sockaddr *)sin6, NULL);
1487 test_eq(tor_addr_family(&t1), AF_INET6);
1488 p1 = tor_addr_to_str(buf, &t1, sizeof(buf), 0);
1489 test_streq(p1, "8000::");
1491 memset(&sa_storage, 0, sizeof(sa_storage));
1492 test_eq(sizeof(struct sockaddr_in6),
1493 tor_addr_to_sockaddr(&t1, 9999, (struct sockaddr *)&sa_storage,
1494 sizeof(sa_storage)));
1495 test_eq(AF_INET6, sin6->sin6_family);
1496 test_eq(9999, ntohs(sin6->sin6_port));
1497 test_eq(0x80000000, ntohl(S6_ADDR32(sin6->sin6_addr)[0]));
1499 /* ==== tor_addr_lookup: static cases. (Can't test dns without knowing we
1500 * have a good resolver. */
1501 test_eq(0, tor_addr_lookup("127.128.129.130", AF_UNSPEC, &t1));
1502 test_eq(AF_INET, tor_addr_family(&t1));
1503 test_eq(tor_addr_to_ipv4h(&t1), 0x7f808182);
1505 test_eq(0, tor_addr_lookup("9000::5", AF_UNSPEC, &t1));
1506 test_eq(AF_INET6, tor_addr_family(&t1));
1507 test_eq(0x90, tor_addr_to_in6_addr8(&t1)[0]);
1508 test_assert(tor_mem_is_zero((char*)tor_addr_to_in6_addr8(&t1)+1, 14));
1509 test_eq(0x05, tor_addr_to_in6_addr8(&t1)[15]);
1511 /* === Test pton: valid af_inet6 */
1512 /* Simple, valid parsing. */
1513 r = tor_inet_pton(AF_INET6,
1514 "0102:0304:0506:0708:090A:0B0C:0D0E:0F10", &a1);
1515 test_assert(r==1);
1516 for (i=0;i<16;++i) { test_eq(i+1, (int)a1.s6_addr[i]); }
1517 /* ipv4 ending. */
1518 test_pton6_same("0102:0304:0506:0708:090A:0B0C:0D0E:0F10",
1519 "0102:0304:0506:0708:090A:0B0C:13.14.15.16");
1520 /* shortened words. */
1521 test_pton6_same("0001:0099:BEEF:0000:0123:FFFF:0001:0001",
1522 "1:99:BEEF:0:0123:FFFF:1:1");
1523 /* zeros at the beginning */
1524 test_pton6_same("0000:0000:0000:0000:0009:C0A8:0001:0001",
1525 "::9:c0a8:1:1");
1526 test_pton6_same("0000:0000:0000:0000:0009:C0A8:0001:0001",
1527 "::9:c0a8:0.1.0.1");
1528 /* zeros in the middle. */
1529 test_pton6_same("fe80:0000:0000:0000:0202:1111:0001:0001",
1530 "fe80::202:1111:1:1");
1531 /* zeros at the end. */
1532 test_pton6_same("1000:0001:0000:0007:0000:0000:0000:0000",
1533 "1000:1:0:7::");
1535 /* === Test ntop: af_inet6 */
1536 test_ntop6_reduces("0:0:0:0:0:0:0:0", "::");
1538 test_ntop6_reduces("0001:0099:BEEF:0006:0123:FFFF:0001:0001",
1539 "1:99:beef:6:123:ffff:1:1");
1541 //test_ntop6_reduces("0:0:0:0:0:0:c0a8:0101", "::192.168.1.1");
1542 test_ntop6_reduces("0:0:0:0:0:ffff:c0a8:0101", "::ffff:192.168.1.1");
1543 test_ntop6_reduces("002:0:0000:0:3::4", "2::3:0:0:4");
1544 test_ntop6_reduces("0:0::1:0:3", "::1:0:3");
1545 test_ntop6_reduces("008:0::0", "8::");
1546 test_ntop6_reduces("0:0:0:0:0:ffff::1", "::ffff:0.0.0.1");
1547 test_ntop6_reduces("abcd:0:0:0:0:0:7f00::", "abcd::7f00:0");
1548 test_ntop6_reduces("0000:0000:0000:0000:0009:C0A8:0001:0001",
1549 "::9:c0a8:1:1");
1550 test_ntop6_reduces("fe80:0000:0000:0000:0202:1111:0001:0001",
1551 "fe80::202:1111:1:1");
1552 test_ntop6_reduces("1000:0001:0000:0007:0000:0000:0000:0000",
1553 "1000:1:0:7::");
1555 /* === Test pton: invalid in6. */
1556 test_pton6_bad("foobar.");
1557 test_pton6_bad("55555::");
1558 test_pton6_bad("9:-60::");
1559 test_pton6_bad("1:2:33333:4:0002:3::");
1560 //test_pton6_bad("1:2:3333:4:00002:3::");// BAD, but glibc doesn't say so.
1561 test_pton6_bad("1:2:3333:4:fish:3::");
1562 test_pton6_bad("1:2:3:4:5:6:7:8:9");
1563 test_pton6_bad("1:2:3:4:5:6:7");
1564 test_pton6_bad("1:2:3:4:5:6:1.2.3.4.5");
1565 test_pton6_bad("1:2:3:4:5:6:1.2.3");
1566 test_pton6_bad("::1.2.3");
1567 test_pton6_bad("::1.2.3.4.5");
1568 test_pton6_bad("99");
1569 test_pton6_bad("");
1570 test_pton6_bad("1::2::3:4");
1571 test_pton6_bad("a:::b:c");
1572 test_pton6_bad(":::a:b:c");
1573 test_pton6_bad("a:b:c:::");
1575 /* test internal checking */
1576 test_external_ip("fbff:ffff::2:7", 0);
1577 test_internal_ip("fc01::2:7", 0);
1578 test_internal_ip("fdff:ffff::f:f", 0);
1579 test_external_ip("fe00::3:f", 0);
1581 test_external_ip("fe7f:ffff::2:7", 0);
1582 test_internal_ip("fe80::2:7", 0);
1583 test_internal_ip("febf:ffff::f:f", 0);
1585 test_internal_ip("fec0::2:7:7", 0);
1586 test_internal_ip("feff:ffff::e:7:7", 0);
1587 test_external_ip("ff00::e:7:7", 0);
1589 test_internal_ip("::", 0);
1590 test_internal_ip("::1", 0);
1591 test_internal_ip("::1", 1);
1592 test_internal_ip("::", 0);
1593 test_external_ip("::", 1);
1594 test_external_ip("::2", 0);
1595 test_external_ip("2001::", 0);
1596 test_external_ip("ffff::", 0);
1598 test_external_ip("::ffff:0.0.0.0", 1);
1599 test_internal_ip("::ffff:0.0.0.0", 0);
1600 test_internal_ip("::ffff:0.255.255.255", 0);
1601 test_external_ip("::ffff:1.0.0.0", 0);
1603 test_external_ip("::ffff:9.255.255.255", 0);
1604 test_internal_ip("::ffff:10.0.0.0", 0);
1605 test_internal_ip("::ffff:10.255.255.255", 0);
1606 test_external_ip("::ffff:11.0.0.0", 0);
1608 test_external_ip("::ffff:126.255.255.255", 0);
1609 test_internal_ip("::ffff:127.0.0.0", 0);
1610 test_internal_ip("::ffff:127.255.255.255", 0);
1611 test_external_ip("::ffff:128.0.0.0", 0);
1613 test_external_ip("::ffff:172.15.255.255", 0);
1614 test_internal_ip("::ffff:172.16.0.0", 0);
1615 test_internal_ip("::ffff:172.31.255.255", 0);
1616 test_external_ip("::ffff:172.32.0.0", 0);
1618 test_external_ip("::ffff:192.167.255.255", 0);
1619 test_internal_ip("::ffff:192.168.0.0", 0);
1620 test_internal_ip("::ffff:192.168.255.255", 0);
1621 test_external_ip("::ffff:192.169.0.0", 0);
1623 test_external_ip("::ffff:169.253.255.255", 0);
1624 test_internal_ip("::ffff:169.254.0.0", 0);
1625 test_internal_ip("::ffff:169.254.255.255", 0);
1626 test_external_ip("::ffff:169.255.0.0", 0);
1627 test_assert(is_internal_IP(0x7f000001, 0));
1629 /* tor_addr_compare(tor_addr_t x2) */
1630 test_addr_compare("ffff::", ==, "ffff::0");
1631 test_addr_compare("0::3:2:1", <, "0::ffff:0.3.2.1");
1632 test_addr_compare("0::2:2:1", <, "0::ffff:0.3.2.1");
1633 test_addr_compare("0::ffff:0.3.2.1", >, "0::0:0:0");
1634 test_addr_compare("0::ffff:5.2.2.1", <, "::ffff:6.0.0.0"); /* XXXX wrong. */
1635 tor_addr_parse_mask_ports("[::ffff:2.3.4.5]", &t1, NULL, NULL, NULL);
1636 tor_addr_parse_mask_ports("2.3.4.5", &t2, NULL, NULL, NULL);
1637 test_assert(tor_addr_compare(&t1, &t2, CMP_SEMANTIC) == 0);
1638 tor_addr_parse_mask_ports("[::ffff:2.3.4.4]", &t1, NULL, NULL, NULL);
1639 tor_addr_parse_mask_ports("2.3.4.5", &t2, NULL, NULL, NULL);
1640 test_assert(tor_addr_compare(&t1, &t2, CMP_SEMANTIC) < 0);
1642 /* test compare_masked */
1643 test_addr_compare_masked("ffff::", ==, "ffff::0", 128);
1644 test_addr_compare_masked("ffff::", ==, "ffff::0", 64);
1645 test_addr_compare_masked("0::2:2:1", <, "0::8000:2:1", 81);
1646 test_addr_compare_masked("0::2:2:1", ==, "0::8000:2:1", 80);
1648 /* Test decorated addr_to_string. */
1649 test_eq(AF_INET6, tor_addr_from_str(&t1, "[123:45:6789::5005:11]"));
1650 p1 = tor_addr_to_str(buf, &t1, sizeof(buf), 1);
1651 test_streq(p1, "[123:45:6789::5005:11]");
1652 test_eq(AF_INET, tor_addr_from_str(&t1, "18.0.0.1"));
1653 p1 = tor_addr_to_str(buf, &t1, sizeof(buf), 1);
1654 test_streq(p1, "18.0.0.1");
1656 /* Test tor_addr_parse_reverse_lookup_name */
1657 i = tor_addr_parse_reverse_lookup_name(&t1, "Foobar.baz", AF_UNSPEC, 0);
1658 test_eq(0, i);
1659 i = tor_addr_parse_reverse_lookup_name(&t1, "Foobar.baz", AF_UNSPEC, 1);
1660 test_eq(0, i);
1661 i = tor_addr_parse_reverse_lookup_name(&t1, "1.0.168.192.in-addr.arpa",
1662 AF_UNSPEC, 1);
1663 test_eq(1, i);
1664 test_eq(tor_addr_family(&t1), AF_INET);
1665 p1 = tor_addr_to_str(buf, &t1, sizeof(buf), 1);
1666 test_streq(p1, "192.168.0.1");
1667 i = tor_addr_parse_reverse_lookup_name(&t1, "192.168.0.99", AF_UNSPEC, 0);
1668 test_eq(0, i);
1669 i = tor_addr_parse_reverse_lookup_name(&t1, "192.168.0.99", AF_UNSPEC, 1);
1670 test_eq(1, i);
1671 p1 = tor_addr_to_str(buf, &t1, sizeof(buf), 1);
1672 test_streq(p1, "192.168.0.99");
1673 memset(&t1, 0, sizeof(t1));
1674 i = tor_addr_parse_reverse_lookup_name(&t1,
1675 "0.1.2.3.4.5.6.7.8.9.a.b.c.d.e.f."
1676 "f.e.e.b.1.e.b.e.e.f.f.e.e.e.d.9."
1677 "ip6.ARPA",
1678 AF_UNSPEC, 0);
1679 test_eq(1, i);
1680 p1 = tor_addr_to_str(buf, &t1, sizeof(buf), 1);
1681 test_streq(p1, "[9dee:effe:ebe1:beef:fedc:ba98:7654:3210]");
1682 /* Failing cases. */
1683 i = tor_addr_parse_reverse_lookup_name(&t1,
1684 "6.7.8.9.a.b.c.d.e.f."
1685 "f.e.e.b.1.e.b.e.e.f.f.e.e.e.d.9."
1686 "ip6.ARPA",
1687 AF_UNSPEC, 0);
1688 test_eq(i, -1);
1689 i = tor_addr_parse_reverse_lookup_name(&t1,
1690 "6.7.8.9.a.b.c.d.e.f.a.b.c.d.e.f.0."
1691 "f.e.e.b.1.e.b.e.e.f.f.e.e.e.d.9."
1692 "ip6.ARPA",
1693 AF_UNSPEC, 0);
1694 test_eq(i, -1);
1695 i = tor_addr_parse_reverse_lookup_name(&t1,
1696 "6.7.8.9.a.b.c.d.e.f.X.0.0.0.0.9."
1697 "f.e.e.b.1.e.b.e.e.f.f.e.e.e.d.9."
1698 "ip6.ARPA",
1699 AF_UNSPEC, 0);
1700 test_eq(i, -1);
1701 i = tor_addr_parse_reverse_lookup_name(&t1, "32.1.1.in-addr.arpa",
1702 AF_UNSPEC, 0);
1703 test_eq(i, -1);
1704 i = tor_addr_parse_reverse_lookup_name(&t1, ".in-addr.arpa",
1705 AF_UNSPEC, 0);
1706 test_eq(i, -1);
1707 i = tor_addr_parse_reverse_lookup_name(&t1, "1.2.3.4.5.in-addr.arpa",
1708 AF_UNSPEC, 0);
1709 test_eq(i, -1);
1710 i = tor_addr_parse_reverse_lookup_name(&t1, "1.2.3.4.5.in-addr.arpa",
1711 AF_INET6, 0);
1712 test_eq(i, -1);
1713 i = tor_addr_parse_reverse_lookup_name(&t1,
1714 "6.7.8.9.a.b.c.d.e.f.a.b.c.d.e.0."
1715 "f.e.e.b.1.e.b.e.e.f.f.e.e.e.d.9."
1716 "ip6.ARPA",
1717 AF_INET, 0);
1718 test_eq(i, -1);
1720 /* test tor_addr_parse_mask_ports */
1721 test_addr_mask_ports_parse("[::f]/17:47-95", AF_INET6,
1722 0, 0, 0, 0x0000000f, 17, 47, 95);
1723 //test_addr_parse("[::fefe:4.1.1.7/120]:999-1000");
1724 //test_addr_parse_check("::fefe:401:107", 120, 999, 1000);
1725 test_addr_mask_ports_parse("[::ffff:4.1.1.7]/120:443", AF_INET6,
1726 0, 0, 0x0000ffff, 0x04010107, 120, 443, 443);
1727 test_addr_mask_ports_parse("[abcd:2::44a:0]:2-65000", AF_INET6,
1728 0xabcd0002, 0, 0, 0x044a0000, 128, 2, 65000);
1730 r=tor_addr_parse_mask_ports("[fefef::]/112", &t1, NULL, NULL, NULL);
1731 test_assert(r == -1);
1732 r=tor_addr_parse_mask_ports("efef::/112", &t1, NULL, NULL, NULL);
1733 test_assert(r == -1);
1734 r=tor_addr_parse_mask_ports("[f:f:f:f:f:f:f:f::]", &t1, NULL, NULL, NULL);
1735 test_assert(r == -1);
1736 r=tor_addr_parse_mask_ports("[::f:f:f:f:f:f:f:f]", &t1, NULL, NULL, NULL);
1737 test_assert(r == -1);
1738 r=tor_addr_parse_mask_ports("[f:f:f:f:f:f:f:f:f]", &t1, NULL, NULL, NULL);
1739 test_assert(r == -1);
1740 /* Test for V4-mapped address with mask < 96. (arguably not valid) */
1741 r=tor_addr_parse_mask_ports("[::ffff:1.1.2.2/33]", &t1, &mask, NULL, NULL);
1742 test_assert(r == -1);
1743 r=tor_addr_parse_mask_ports("1.1.2.2/33", &t1, &mask, NULL, NULL);
1744 test_assert(r == -1);
1745 r=tor_addr_parse_mask_ports("1.1.2.2/31", &t1, &mask, NULL, NULL);
1746 test_assert(r == AF_INET);
1747 r=tor_addr_parse_mask_ports("[efef::]/112", &t1, &mask, &port1, &port2);
1748 test_assert(r == AF_INET6);
1749 test_assert(port1 == 1);
1750 test_assert(port2 == 65535);
1752 /* make sure inet address lengths >= max */
1753 test_assert(INET_NTOA_BUF_LEN >= sizeof("255.255.255.255"));
1754 test_assert(TOR_ADDR_BUF_LEN >=
1755 sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"));
1757 test_assert(sizeof(tor_addr_t) >= sizeof(struct in6_addr));
1759 /* get interface addresses */
1760 r = get_interface_address6(LOG_DEBUG, AF_INET, &t1);
1761 i = get_interface_address6(LOG_DEBUG, AF_INET6, &t2);
1762 #if 0
1763 tor_inet_ntop(AF_INET, &t1.sa.sin_addr, buf, sizeof(buf));
1764 printf("\nv4 address: %s (family=%i)", buf, IN_FAMILY(&t1));
1765 tor_inet_ntop(AF_INET6, &t2.sa6.sin6_addr, buf, sizeof(buf));
1766 printf("\nv6 address: %s (family=%i)", buf, IN_FAMILY(&t2));
1767 #endif
1769 done:
1773 /** Run unit tests for basic dynamic-sized array functionality. */
1774 static void
1775 test_util_smartlist_basic(void)
1777 smartlist_t *sl;
1779 /* XXXX test sort_digests, uniq_strings, uniq_digests */
1781 /* Test smartlist add, del_keeporder, insert, get. */
1782 sl = smartlist_create();
1783 smartlist_add(sl, (void*)1);
1784 smartlist_add(sl, (void*)2);
1785 smartlist_add(sl, (void*)3);
1786 smartlist_add(sl, (void*)4);
1787 smartlist_del_keeporder(sl, 1);
1788 smartlist_insert(sl, 1, (void*)22);
1789 smartlist_insert(sl, 0, (void*)0);
1790 smartlist_insert(sl, 5, (void*)555);
1791 test_eq_ptr((void*)0, smartlist_get(sl,0));
1792 test_eq_ptr((void*)1, smartlist_get(sl,1));
1793 test_eq_ptr((void*)22, smartlist_get(sl,2));
1794 test_eq_ptr((void*)3, smartlist_get(sl,3));
1795 test_eq_ptr((void*)4, smartlist_get(sl,4));
1796 test_eq_ptr((void*)555, smartlist_get(sl,5));
1797 /* Try deleting in the middle. */
1798 smartlist_del(sl, 1);
1799 test_eq_ptr((void*)555, smartlist_get(sl, 1));
1800 /* Try deleting at the end. */
1801 smartlist_del(sl, 4);
1802 test_eq(4, smartlist_len(sl));
1804 /* test isin. */
1805 test_assert(smartlist_isin(sl, (void*)3));
1806 test_assert(!smartlist_isin(sl, (void*)99));
1808 done:
1809 smartlist_free(sl);
1812 /** Run unit tests for smartlist-of-strings functionality. */
1813 static void
1814 test_util_smartlist_strings(void)
1816 smartlist_t *sl = smartlist_create();
1817 char *cp=NULL, *cp_alloc=NULL;
1818 size_t sz;
1820 /* Test split and join */
1821 test_eq(0, smartlist_len(sl));
1822 smartlist_split_string(sl, "abc", ":", 0, 0);
1823 test_eq(1, smartlist_len(sl));
1824 test_streq("abc", smartlist_get(sl, 0));
1825 smartlist_split_string(sl, "a::bc::", "::", 0, 0);
1826 test_eq(4, smartlist_len(sl));
1827 test_streq("a", smartlist_get(sl, 1));
1828 test_streq("bc", smartlist_get(sl, 2));
1829 test_streq("", smartlist_get(sl, 3));
1830 cp_alloc = smartlist_join_strings(sl, "", 0, NULL);
1831 test_streq(cp_alloc, "abcabc");
1832 tor_free(cp_alloc);
1833 cp_alloc = smartlist_join_strings(sl, "!", 0, NULL);
1834 test_streq(cp_alloc, "abc!a!bc!");
1835 tor_free(cp_alloc);
1836 cp_alloc = smartlist_join_strings(sl, "XY", 0, NULL);
1837 test_streq(cp_alloc, "abcXYaXYbcXY");
1838 tor_free(cp_alloc);
1839 cp_alloc = smartlist_join_strings(sl, "XY", 1, NULL);
1840 test_streq(cp_alloc, "abcXYaXYbcXYXY");
1841 tor_free(cp_alloc);
1842 cp_alloc = smartlist_join_strings(sl, "", 1, NULL);
1843 test_streq(cp_alloc, "abcabc");
1844 tor_free(cp_alloc);
1846 smartlist_split_string(sl, "/def/ /ghijk", "/", 0, 0);
1847 test_eq(8, smartlist_len(sl));
1848 test_streq("", smartlist_get(sl, 4));
1849 test_streq("def", smartlist_get(sl, 5));
1850 test_streq(" ", smartlist_get(sl, 6));
1851 test_streq("ghijk", smartlist_get(sl, 7));
1852 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1853 smartlist_clear(sl);
1855 smartlist_split_string(sl, "a,bbd,cdef", ",", SPLIT_SKIP_SPACE, 0);
1856 test_eq(3, smartlist_len(sl));
1857 test_streq("a", smartlist_get(sl,0));
1858 test_streq("bbd", smartlist_get(sl,1));
1859 test_streq("cdef", smartlist_get(sl,2));
1860 smartlist_split_string(sl, " z <> zhasd <> <> bnud<> ", "<>",
1861 SPLIT_SKIP_SPACE, 0);
1862 test_eq(8, smartlist_len(sl));
1863 test_streq("z", smartlist_get(sl,3));
1864 test_streq("zhasd", smartlist_get(sl,4));
1865 test_streq("", smartlist_get(sl,5));
1866 test_streq("bnud", smartlist_get(sl,6));
1867 test_streq("", smartlist_get(sl,7));
1869 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1870 smartlist_clear(sl);
1872 smartlist_split_string(sl, " ab\tc \td ef ", NULL,
1873 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1874 test_eq(4, smartlist_len(sl));
1875 test_streq("ab", smartlist_get(sl,0));
1876 test_streq("c", smartlist_get(sl,1));
1877 test_streq("d", smartlist_get(sl,2));
1878 test_streq("ef", smartlist_get(sl,3));
1879 smartlist_split_string(sl, "ghi\tj", NULL,
1880 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1881 test_eq(6, smartlist_len(sl));
1882 test_streq("ghi", smartlist_get(sl,4));
1883 test_streq("j", smartlist_get(sl,5));
1885 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1886 smartlist_clear(sl);
1888 cp_alloc = smartlist_join_strings(sl, "XY", 0, NULL);
1889 test_streq(cp_alloc, "");
1890 tor_free(cp_alloc);
1891 cp_alloc = smartlist_join_strings(sl, "XY", 1, NULL);
1892 test_streq(cp_alloc, "XY");
1893 tor_free(cp_alloc);
1895 smartlist_split_string(sl, " z <> zhasd <> <> bnud<> ", "<>",
1896 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1897 test_eq(3, smartlist_len(sl));
1898 test_streq("z", smartlist_get(sl, 0));
1899 test_streq("zhasd", smartlist_get(sl, 1));
1900 test_streq("bnud", smartlist_get(sl, 2));
1901 smartlist_split_string(sl, " z <> zhasd <> <> bnud<> ", "<>",
1902 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
1903 test_eq(5, smartlist_len(sl));
1904 test_streq("z", smartlist_get(sl, 3));
1905 test_streq("zhasd <> <> bnud<>", smartlist_get(sl, 4));
1906 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1907 smartlist_clear(sl);
1909 smartlist_split_string(sl, "abcd\n", "\n",
1910 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1911 test_eq(1, smartlist_len(sl));
1912 test_streq("abcd", smartlist_get(sl, 0));
1913 smartlist_split_string(sl, "efgh", "\n",
1914 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1915 test_eq(2, smartlist_len(sl));
1916 test_streq("efgh", smartlist_get(sl, 1));
1918 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1919 smartlist_clear(sl);
1921 /* Test swapping, shuffling, and sorting. */
1922 smartlist_split_string(sl, "the,onion,router,by,arma,and,nickm", ",", 0, 0);
1923 test_eq(7, smartlist_len(sl));
1924 smartlist_sort(sl, _compare_strs);
1925 cp_alloc = smartlist_join_strings(sl, ",", 0, NULL);
1926 test_streq(cp_alloc,"and,arma,by,nickm,onion,router,the");
1927 tor_free(cp_alloc);
1928 smartlist_swap(sl, 1, 5);
1929 cp_alloc = smartlist_join_strings(sl, ",", 0, NULL);
1930 test_streq(cp_alloc,"and,router,by,nickm,onion,arma,the");
1931 tor_free(cp_alloc);
1932 smartlist_shuffle(sl);
1933 test_eq(7, smartlist_len(sl));
1934 test_assert(smartlist_string_isin(sl, "and"));
1935 test_assert(smartlist_string_isin(sl, "router"));
1936 test_assert(smartlist_string_isin(sl, "by"));
1937 test_assert(smartlist_string_isin(sl, "nickm"));
1938 test_assert(smartlist_string_isin(sl, "onion"));
1939 test_assert(smartlist_string_isin(sl, "arma"));
1940 test_assert(smartlist_string_isin(sl, "the"));
1942 /* Test bsearch. */
1943 smartlist_sort(sl, _compare_strs);
1944 test_streq("nickm", smartlist_bsearch(sl, "zNicKM",
1945 _compare_without_first_ch));
1946 test_streq("and", smartlist_bsearch(sl, " AND", _compare_without_first_ch));
1947 test_eq_ptr(NULL, smartlist_bsearch(sl, " ANz", _compare_without_first_ch));
1949 /* Test bsearch_idx */
1951 int f;
1952 test_eq(0, smartlist_bsearch_idx(sl," aaa",_compare_without_first_ch,&f));
1953 test_eq(f, 0);
1954 test_eq(0, smartlist_bsearch_idx(sl," and",_compare_without_first_ch,&f));
1955 test_eq(f, 1);
1956 test_eq(1, smartlist_bsearch_idx(sl," arm",_compare_without_first_ch,&f));
1957 test_eq(f, 0);
1958 test_eq(1, smartlist_bsearch_idx(sl," arma",_compare_without_first_ch,&f));
1959 test_eq(f, 1);
1960 test_eq(2, smartlist_bsearch_idx(sl," armb",_compare_without_first_ch,&f));
1961 test_eq(f, 0);
1962 test_eq(7, smartlist_bsearch_idx(sl," zzzz",_compare_without_first_ch,&f));
1963 test_eq(f, 0);
1966 /* Test reverse() and pop_last() */
1967 smartlist_reverse(sl);
1968 cp_alloc = smartlist_join_strings(sl, ",", 0, NULL);
1969 test_streq(cp_alloc,"the,router,onion,nickm,by,arma,and");
1970 tor_free(cp_alloc);
1971 cp_alloc = smartlist_pop_last(sl);
1972 test_streq(cp_alloc, "and");
1973 tor_free(cp_alloc);
1974 test_eq(smartlist_len(sl), 6);
1975 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1976 smartlist_clear(sl);
1977 cp_alloc = smartlist_pop_last(sl);
1978 test_eq(cp_alloc, NULL);
1980 /* Test uniq() */
1981 smartlist_split_string(sl,
1982 "50,noon,radar,a,man,a,plan,a,canal,panama,radar,noon,50",
1983 ",", 0, 0);
1984 smartlist_sort(sl, _compare_strs);
1985 smartlist_uniq(sl, _compare_strs, _tor_free);
1986 cp_alloc = smartlist_join_strings(sl, ",", 0, NULL);
1987 test_streq(cp_alloc, "50,a,canal,man,noon,panama,plan,radar");
1988 tor_free(cp_alloc);
1990 /* Test string_isin and isin_case and num_isin */
1991 test_assert(smartlist_string_isin(sl, "noon"));
1992 test_assert(!smartlist_string_isin(sl, "noonoon"));
1993 test_assert(smartlist_string_isin_case(sl, "nOOn"));
1994 test_assert(!smartlist_string_isin_case(sl, "nooNooN"));
1995 test_assert(smartlist_string_num_isin(sl, 50));
1996 test_assert(!smartlist_string_num_isin(sl, 60));
1998 /* Test smartlist_choose */
2000 int i;
2001 int allsame = 1;
2002 int allin = 1;
2003 void *first = smartlist_choose(sl);
2004 test_assert(smartlist_isin(sl, first));
2005 for (i = 0; i < 100; ++i) {
2006 void *second = smartlist_choose(sl);
2007 if (second != first)
2008 allsame = 0;
2009 if (!smartlist_isin(sl, second))
2010 allin = 0;
2012 test_assert(!allsame);
2013 test_assert(allin);
2015 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
2016 smartlist_clear(sl);
2018 /* Test string_remove and remove and join_strings2 */
2019 smartlist_split_string(sl,
2020 "Some say the Earth will end in ice and some in fire",
2021 " ", 0, 0);
2022 cp = smartlist_get(sl, 4);
2023 test_streq(cp, "will");
2024 smartlist_add(sl, cp);
2025 smartlist_remove(sl, cp);
2026 tor_free(cp);
2027 cp_alloc = smartlist_join_strings(sl, ",", 0, NULL);
2028 test_streq(cp_alloc, "Some,say,the,Earth,fire,end,in,ice,and,some,in");
2029 tor_free(cp_alloc);
2030 smartlist_string_remove(sl, "in");
2031 cp_alloc = smartlist_join_strings2(sl, "+XX", 1, 0, &sz);
2032 test_streq(cp_alloc, "Some+say+the+Earth+fire+end+some+ice+and");
2033 test_eq((int)sz, 40);
2035 done:
2037 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
2038 smartlist_free(sl);
2039 tor_free(cp_alloc);
2042 /** Run unit tests for smartlist set manipulation functions. */
2043 static void
2044 test_util_smartlist_overlap(void)
2046 smartlist_t *sl = smartlist_create();
2047 smartlist_t *ints = smartlist_create();
2048 smartlist_t *odds = smartlist_create();
2049 smartlist_t *evens = smartlist_create();
2050 smartlist_t *primes = smartlist_create();
2051 int i;
2052 for (i=1; i < 10; i += 2)
2053 smartlist_add(odds, (void*)(uintptr_t)i);
2054 for (i=0; i < 10; i += 2)
2055 smartlist_add(evens, (void*)(uintptr_t)i);
2057 /* add_all */
2058 smartlist_add_all(ints, odds);
2059 smartlist_add_all(ints, evens);
2060 test_eq(smartlist_len(ints), 10);
2062 smartlist_add(primes, (void*)2);
2063 smartlist_add(primes, (void*)3);
2064 smartlist_add(primes, (void*)5);
2065 smartlist_add(primes, (void*)7);
2067 /* overlap */
2068 test_assert(smartlist_overlap(ints, odds));
2069 test_assert(smartlist_overlap(odds, primes));
2070 test_assert(smartlist_overlap(evens, primes));
2071 test_assert(!smartlist_overlap(odds, evens));
2073 /* intersect */
2074 smartlist_add_all(sl, odds);
2075 smartlist_intersect(sl, primes);
2076 test_eq(smartlist_len(sl), 3);
2077 test_assert(smartlist_isin(sl, (void*)3));
2078 test_assert(smartlist_isin(sl, (void*)5));
2079 test_assert(smartlist_isin(sl, (void*)7));
2081 /* subtract */
2082 smartlist_add_all(sl, primes);
2083 smartlist_subtract(sl, odds);
2084 test_eq(smartlist_len(sl), 1);
2085 test_assert(smartlist_isin(sl, (void*)2));
2087 done:
2088 smartlist_free(odds);
2089 smartlist_free(evens);
2090 smartlist_free(ints);
2091 smartlist_free(primes);
2092 smartlist_free(sl);
2095 /** Run unit tests for smartlist-of-digests functions. */
2096 static void
2097 test_util_smartlist_digests(void)
2099 smartlist_t *sl = smartlist_create();
2101 /* digest_isin. */
2102 smartlist_add(sl, tor_memdup("AAAAAAAAAAAAAAAAAAAA", DIGEST_LEN));
2103 smartlist_add(sl, tor_memdup("\00090AAB2AAAAaasdAAAAA", DIGEST_LEN));
2104 smartlist_add(sl, tor_memdup("\00090AAB2AAAAaasdAAAAA", DIGEST_LEN));
2105 test_eq(0, smartlist_digest_isin(NULL, "AAAAAAAAAAAAAAAAAAAA"));
2106 test_assert(smartlist_digest_isin(sl, "AAAAAAAAAAAAAAAAAAAA"));
2107 test_assert(smartlist_digest_isin(sl, "\00090AAB2AAAAaasdAAAAA"));
2108 test_eq(0, smartlist_digest_isin(sl, "\00090AAB2AAABaasdAAAAA"));
2110 /* sort digests */
2111 smartlist_sort_digests(sl);
2112 test_memeq(smartlist_get(sl, 0), "\00090AAB2AAAAaasdAAAAA", DIGEST_LEN);
2113 test_memeq(smartlist_get(sl, 1), "\00090AAB2AAAAaasdAAAAA", DIGEST_LEN);
2114 test_memeq(smartlist_get(sl, 2), "AAAAAAAAAAAAAAAAAAAA", DIGEST_LEN);
2115 test_eq(3, smartlist_len(sl));
2117 /* uniq_digests */
2118 smartlist_uniq_digests(sl);
2119 test_eq(2, smartlist_len(sl));
2120 test_memeq(smartlist_get(sl, 0), "\00090AAB2AAAAaasdAAAAA", DIGEST_LEN);
2121 test_memeq(smartlist_get(sl, 1), "AAAAAAAAAAAAAAAAAAAA", DIGEST_LEN);
2123 done:
2124 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
2125 smartlist_free(sl);
2128 /** Run unit tests for concatenate-a-smartlist-of-strings functions. */
2129 static void
2130 test_util_smartlist_join(void)
2132 smartlist_t *sl = smartlist_create();
2133 smartlist_t *sl2 = smartlist_create(), *sl3 = smartlist_create(),
2134 *sl4 = smartlist_create();
2135 char *joined=NULL;
2136 /* unique, sorted. */
2137 smartlist_split_string(sl,
2138 "Abashments Ambush Anchorman Bacon Banks Borscht "
2139 "Bunks Inhumane Insurance Knish Know Manners "
2140 "Maraschinos Stamina Sunbonnets Unicorns Wombats",
2141 " ", 0, 0);
2142 /* non-unique, sorted. */
2143 smartlist_split_string(sl2,
2144 "Ambush Anchorman Anchorman Anemias Anemias Bacon "
2145 "Crossbowmen Inhumane Insurance Knish Know Manners "
2146 "Manners Maraschinos Wombats Wombats Work",
2147 " ", 0, 0);
2148 SMARTLIST_FOREACH_JOIN(sl, char *, cp1,
2149 sl2, char *, cp2,
2150 strcmp(cp1,cp2),
2151 smartlist_add(sl3, cp2)) {
2152 test_streq(cp1, cp2);
2153 smartlist_add(sl4, cp1);
2154 } SMARTLIST_FOREACH_JOIN_END(cp1, cp2);
2156 SMARTLIST_FOREACH(sl3, const char *, cp,
2157 test_assert(smartlist_isin(sl2, cp) &&
2158 !smartlist_string_isin(sl, cp)));
2159 SMARTLIST_FOREACH(sl4, const char *, cp,
2160 test_assert(smartlist_isin(sl, cp) &&
2161 smartlist_string_isin(sl2, cp)));
2162 joined = smartlist_join_strings(sl3, ",", 0, NULL);
2163 test_streq(joined, "Anemias,Anemias,Crossbowmen,Work");
2164 tor_free(joined);
2165 joined = smartlist_join_strings(sl4, ",", 0, NULL);
2166 test_streq(joined, "Ambush,Anchorman,Anchorman,Bacon,Inhumane,Insurance,"
2167 "Knish,Know,Manners,Manners,Maraschinos,Wombats,Wombats");
2168 tor_free(joined);
2170 done:
2171 smartlist_free(sl4);
2172 smartlist_free(sl3);
2173 SMARTLIST_FOREACH(sl2, char *, cp, tor_free(cp));
2174 smartlist_free(sl2);
2175 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
2176 smartlist_free(sl);
2177 tor_free(joined);
2180 /** Run unit tests for bitarray code */
2181 static void
2182 test_util_bitarray(void)
2184 bitarray_t *ba = NULL;
2185 int i, j, ok=1;
2187 ba = bitarray_init_zero(1);
2188 test_assert(ba);
2189 test_assert(! bitarray_is_set(ba, 0));
2190 bitarray_set(ba, 0);
2191 test_assert(bitarray_is_set(ba, 0));
2192 bitarray_clear(ba, 0);
2193 test_assert(! bitarray_is_set(ba, 0));
2194 bitarray_free(ba);
2196 ba = bitarray_init_zero(1023);
2197 for (i = 1; i < 64; ) {
2198 for (j = 0; j < 1023; ++j) {
2199 if (j % i)
2200 bitarray_set(ba, j);
2201 else
2202 bitarray_clear(ba, j);
2204 for (j = 0; j < 1023; ++j) {
2205 if (!bool_eq(bitarray_is_set(ba, j), j%i))
2206 ok = 0;
2208 test_assert(ok);
2209 if (i < 7)
2210 ++i;
2211 else if (i == 28)
2212 i = 32;
2213 else
2214 i += 7;
2217 done:
2218 if (ba)
2219 bitarray_free(ba);
2222 /** Run unit tests for digest set code (implemented as a hashtable or as a
2223 * bloom filter) */
2224 static void
2225 test_util_digestset(void)
2227 smartlist_t *included = smartlist_create();
2228 char d[DIGEST_LEN];
2229 int i;
2230 int ok = 1;
2231 int false_positives = 0;
2232 digestset_t *set = NULL;
2234 for (i = 0; i < 1000; ++i) {
2235 crypto_rand(d, DIGEST_LEN);
2236 smartlist_add(included, tor_memdup(d, DIGEST_LEN));
2238 set = digestset_new(1000);
2239 SMARTLIST_FOREACH(included, const char *, cp,
2240 if (digestset_isin(set, cp))
2241 ok = 0);
2242 test_assert(ok);
2243 SMARTLIST_FOREACH(included, const char *, cp,
2244 digestset_add(set, cp));
2245 SMARTLIST_FOREACH(included, const char *, cp,
2246 if (!digestset_isin(set, cp))
2247 ok = 0);
2248 test_assert(ok);
2249 for (i = 0; i < 1000; ++i) {
2250 crypto_rand(d, DIGEST_LEN);
2251 if (digestset_isin(set, d))
2252 ++false_positives;
2254 test_assert(false_positives < 50); /* Should be far lower. */
2256 done:
2257 if (set)
2258 digestset_free(set);
2259 SMARTLIST_FOREACH(included, char *, cp, tor_free(cp));
2260 smartlist_free(included);
2263 /** mutex for thread test to stop the threads hitting data at the same time. */
2264 static tor_mutex_t *_thread_test_mutex = NULL;
2265 /** mutexes for the thread test to make sure that the threads have to
2266 * interleave somewhat. */
2267 static tor_mutex_t *_thread_test_start1 = NULL,
2268 *_thread_test_start2 = NULL;
2269 /** Shared strmap for the thread test. */
2270 static strmap_t *_thread_test_strmap = NULL;
2271 /** The name of thread1 for the thread test */
2272 static char *_thread1_name = NULL;
2273 /** The name of thread2 for the thread test */
2274 static char *_thread2_name = NULL;
2276 static void _thread_test_func(void* _s) ATTR_NORETURN;
2278 /** How many iterations have the threads in the unit test run? */
2279 static int t1_count = 0, t2_count = 0;
2281 /** Helper function for threading unit tests: This function runs in a
2282 * subthread. It grabs its own mutex (start1 or start2) to make sure that it
2283 * should start, then it repeatedly alters _test_thread_strmap protected by
2284 * _thread_test_mutex. */
2285 static void
2286 _thread_test_func(void* _s)
2288 char *s = _s;
2289 int i, *count;
2290 tor_mutex_t *m;
2291 char buf[64];
2292 char **cp;
2293 if (!strcmp(s, "thread 1")) {
2294 m = _thread_test_start1;
2295 cp = &_thread1_name;
2296 count = &t1_count;
2297 } else {
2298 m = _thread_test_start2;
2299 cp = &_thread2_name;
2300 count = &t2_count;
2302 tor_mutex_acquire(m);
2304 tor_snprintf(buf, sizeof(buf), "%lu", tor_get_thread_id());
2305 *cp = tor_strdup(buf);
2307 for (i=0; i<10000; ++i) {
2308 tor_mutex_acquire(_thread_test_mutex);
2309 strmap_set(_thread_test_strmap, "last to run", *cp);
2310 ++*count;
2311 tor_mutex_release(_thread_test_mutex);
2313 tor_mutex_acquire(_thread_test_mutex);
2314 strmap_set(_thread_test_strmap, s, *cp);
2315 tor_mutex_release(_thread_test_mutex);
2317 tor_mutex_release(m);
2319 spawn_exit();
2322 /** Run unit tests for threading logic. */
2323 static void
2324 test_util_threads(void)
2326 char *s1 = NULL, *s2 = NULL;
2327 int done = 0, timedout = 0;
2328 time_t started;
2329 #ifndef MS_WINDOWS
2330 struct timeval tv;
2331 tv.tv_sec=0;
2332 tv.tv_usec=10;
2333 #endif
2334 #ifndef TOR_IS_MULTITHREADED
2335 /* Skip this test if we aren't threading. We should be threading most
2336 * everywhere by now. */
2337 if (1)
2338 return;
2339 #endif
2340 _thread_test_mutex = tor_mutex_new();
2341 _thread_test_start1 = tor_mutex_new();
2342 _thread_test_start2 = tor_mutex_new();
2343 _thread_test_strmap = strmap_new();
2344 s1 = tor_strdup("thread 1");
2345 s2 = tor_strdup("thread 2");
2346 tor_mutex_acquire(_thread_test_start1);
2347 tor_mutex_acquire(_thread_test_start2);
2348 spawn_func(_thread_test_func, s1);
2349 spawn_func(_thread_test_func, s2);
2350 tor_mutex_release(_thread_test_start2);
2351 tor_mutex_release(_thread_test_start1);
2352 started = time(NULL);
2353 while (!done) {
2354 tor_mutex_acquire(_thread_test_mutex);
2355 strmap_assert_ok(_thread_test_strmap);
2356 if (strmap_get(_thread_test_strmap, "thread 1") &&
2357 strmap_get(_thread_test_strmap, "thread 2")) {
2358 done = 1;
2359 } else if (time(NULL) > started + 25) {
2360 timedout = done = 1;
2362 tor_mutex_release(_thread_test_mutex);
2363 #ifndef MS_WINDOWS
2364 /* Prevent the main thread from starving the worker threads. */
2365 select(0, NULL, NULL, NULL, &tv);
2366 #endif
2369 tor_mutex_acquire(_thread_test_start1);
2370 tor_mutex_release(_thread_test_start1);
2371 tor_mutex_acquire(_thread_test_start2);
2372 tor_mutex_release(_thread_test_start2);
2374 tor_mutex_free(_thread_test_mutex);
2376 if (timedout) {
2377 printf("\nTimed out: %d %d", t1_count, t2_count);
2378 test_assert(strmap_get(_thread_test_strmap, "thread 1"));
2379 test_assert(strmap_get(_thread_test_strmap, "thread 2"));
2380 test_assert(!timedout);
2383 /* different thread IDs. */
2384 test_assert(strcmp(strmap_get(_thread_test_strmap, "thread 1"),
2385 strmap_get(_thread_test_strmap, "thread 2")));
2386 test_assert(!strcmp(strmap_get(_thread_test_strmap, "thread 1"),
2387 strmap_get(_thread_test_strmap, "last to run")) ||
2388 !strcmp(strmap_get(_thread_test_strmap, "thread 2"),
2389 strmap_get(_thread_test_strmap, "last to run")));
2391 done:
2392 tor_free(s1);
2393 tor_free(s2);
2394 tor_free(_thread1_name);
2395 tor_free(_thread2_name);
2396 if (_thread_test_strmap)
2397 strmap_free(_thread_test_strmap, NULL);
2398 if (_thread_test_start1)
2399 tor_mutex_free(_thread_test_start1);
2400 if (_thread_test_start2)
2401 tor_mutex_free(_thread_test_start2);
2404 /** Helper: return a tristate based on comparing two strings. */
2405 static int
2406 _compare_strings_for_pqueue(const void *s1, const void *s2)
2408 return strcmp((const char*)s1, (const char*)s2);
2411 /** Run unit tests for heap-based priority queue functions. */
2412 static void
2413 test_util_pqueue(void)
2415 smartlist_t *sl = smartlist_create();
2416 int (*cmp)(const void *, const void*);
2417 #define OK() smartlist_pqueue_assert_ok(sl, cmp)
2419 cmp = _compare_strings_for_pqueue;
2421 smartlist_pqueue_add(sl, cmp, (char*)"cows");
2422 smartlist_pqueue_add(sl, cmp, (char*)"zebras");
2423 smartlist_pqueue_add(sl, cmp, (char*)"fish");
2424 smartlist_pqueue_add(sl, cmp, (char*)"frogs");
2425 smartlist_pqueue_add(sl, cmp, (char*)"apples");
2426 smartlist_pqueue_add(sl, cmp, (char*)"squid");
2427 smartlist_pqueue_add(sl, cmp, (char*)"daschunds");
2428 smartlist_pqueue_add(sl, cmp, (char*)"eggplants");
2429 smartlist_pqueue_add(sl, cmp, (char*)"weissbier");
2430 smartlist_pqueue_add(sl, cmp, (char*)"lobsters");
2431 smartlist_pqueue_add(sl, cmp, (char*)"roquefort");
2433 OK();
2435 test_eq(smartlist_len(sl), 11);
2436 test_streq(smartlist_get(sl, 0), "apples");
2437 test_streq(smartlist_pqueue_pop(sl, cmp), "apples");
2438 test_eq(smartlist_len(sl), 10);
2439 OK();
2440 test_streq(smartlist_pqueue_pop(sl, cmp), "cows");
2441 test_streq(smartlist_pqueue_pop(sl, cmp), "daschunds");
2442 smartlist_pqueue_add(sl, cmp, (char*)"chinchillas");
2443 OK();
2444 smartlist_pqueue_add(sl, cmp, (char*)"fireflies");
2445 OK();
2446 test_streq(smartlist_pqueue_pop(sl, cmp), "chinchillas");
2447 test_streq(smartlist_pqueue_pop(sl, cmp), "eggplants");
2448 test_streq(smartlist_pqueue_pop(sl, cmp), "fireflies");
2449 OK();
2450 test_streq(smartlist_pqueue_pop(sl, cmp), "fish");
2451 test_streq(smartlist_pqueue_pop(sl, cmp), "frogs");
2452 test_streq(smartlist_pqueue_pop(sl, cmp), "lobsters");
2453 test_streq(smartlist_pqueue_pop(sl, cmp), "roquefort");
2454 OK();
2455 test_eq(smartlist_len(sl), 3);
2456 test_streq(smartlist_pqueue_pop(sl, cmp), "squid");
2457 test_streq(smartlist_pqueue_pop(sl, cmp), "weissbier");
2458 test_streq(smartlist_pqueue_pop(sl, cmp), "zebras");
2459 test_eq(smartlist_len(sl), 0);
2460 OK();
2461 #undef OK
2463 done:
2465 smartlist_free(sl);
2468 /** Run unit tests for compression functions */
2469 static void
2470 test_util_gzip(void)
2472 char *buf1=NULL, *buf2=NULL, *buf3=NULL, *cp1, *cp2;
2473 const char *ccp2;
2474 size_t len1, len2;
2475 tor_zlib_state_t *state = NULL;
2477 buf1 = tor_strdup("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ");
2478 test_assert(detect_compression_method(buf1, strlen(buf1)) == UNKNOWN_METHOD);
2479 if (is_gzip_supported()) {
2480 test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
2481 GZIP_METHOD));
2482 test_assert(buf2);
2483 test_assert(!memcmp(buf2, "\037\213", 2)); /* Gzip magic. */
2484 test_assert(detect_compression_method(buf2, len1) == GZIP_METHOD);
2486 test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1,
2487 GZIP_METHOD, 1, LOG_INFO));
2488 test_assert(buf3);
2489 test_streq(buf1,buf3);
2491 tor_free(buf2);
2492 tor_free(buf3);
2495 test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
2496 ZLIB_METHOD));
2497 test_assert(buf2);
2498 test_assert(!memcmp(buf2, "\x78\xDA", 2)); /* deflate magic. */
2499 test_assert(detect_compression_method(buf2, len1) == ZLIB_METHOD);
2501 test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1,
2502 ZLIB_METHOD, 1, LOG_INFO));
2503 test_assert(buf3);
2504 test_streq(buf1,buf3);
2506 /* Check whether we can uncompress concatenated, compressed strings. */
2507 tor_free(buf3);
2508 buf2 = tor_realloc(buf2, len1*2);
2509 memcpy(buf2+len1, buf2, len1);
2510 test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1*2,
2511 ZLIB_METHOD, 1, LOG_INFO));
2512 test_eq(len2, (strlen(buf1)+1)*2);
2513 test_memeq(buf3,
2514 "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ\0"
2515 "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ\0",
2516 (strlen(buf1)+1)*2);
2518 tor_free(buf1);
2519 tor_free(buf2);
2520 tor_free(buf3);
2522 /* Check whether we can uncompress partial strings. */
2523 buf1 =
2524 tor_strdup("String with low redundancy that won't be compressed much.");
2525 test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
2526 ZLIB_METHOD));
2527 tor_assert(len1>16);
2528 /* when we allow an incomplete string, we should succeed.*/
2529 tor_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1-16,
2530 ZLIB_METHOD, 0, LOG_INFO));
2531 buf3[len2]='\0';
2532 tor_assert(len2 > 5);
2533 tor_assert(!strcmpstart(buf1, buf3));
2535 /* when we demand a complete string, this must fail. */
2536 tor_free(buf3);
2537 tor_assert(tor_gzip_uncompress(&buf3, &len2, buf2, len1-16,
2538 ZLIB_METHOD, 1, LOG_INFO));
2539 tor_assert(!buf3);
2541 /* Now, try streaming compression. */
2542 tor_free(buf1);
2543 tor_free(buf2);
2544 tor_free(buf3);
2545 state = tor_zlib_new(1, ZLIB_METHOD);
2546 tor_assert(state);
2547 cp1 = buf1 = tor_malloc(1024);
2548 len1 = 1024;
2549 ccp2 = "ABCDEFGHIJABCDEFGHIJ";
2550 len2 = 21;
2551 test_assert(tor_zlib_process(state, &cp1, &len1, &ccp2, &len2, 0)
2552 == TOR_ZLIB_OK);
2553 test_eq(len2, 0); /* Make sure we compressed it all. */
2554 test_assert(cp1 > buf1);
2556 len2 = 0;
2557 cp2 = cp1;
2558 test_assert(tor_zlib_process(state, &cp1, &len1, &ccp2, &len2, 1)
2559 == TOR_ZLIB_DONE);
2560 test_eq(len2, 0);
2561 test_assert(cp1 > cp2); /* Make sure we really added something. */
2563 tor_assert(!tor_gzip_uncompress(&buf3, &len2, buf1, 1024-len1,
2564 ZLIB_METHOD, 1, LOG_WARN));
2565 test_streq(buf3, "ABCDEFGHIJABCDEFGHIJ"); /*Make sure it compressed right.*/
2567 done:
2568 if (state)
2569 tor_zlib_free(state);
2570 tor_free(buf2);
2571 tor_free(buf3);
2572 tor_free(buf1);
2575 /** Run unit tests for string-to-void* map functions */
2576 static void
2577 test_util_strmap(void)
2579 strmap_t *map;
2580 strmap_iter_t *iter;
2581 const char *k;
2582 void *v;
2583 char *visited = NULL;
2584 smartlist_t *found_keys = NULL;
2586 map = strmap_new();
2587 test_assert(map);
2588 test_eq(strmap_size(map), 0);
2589 test_assert(strmap_isempty(map));
2590 v = strmap_set(map, "K1", (void*)99);
2591 test_eq(v, NULL);
2592 test_assert(!strmap_isempty(map));
2593 v = strmap_set(map, "K2", (void*)101);
2594 test_eq(v, NULL);
2595 v = strmap_set(map, "K1", (void*)100);
2596 test_eq(v, (void*)99);
2597 test_eq_ptr(strmap_get(map,"K1"), (void*)100);
2598 test_eq_ptr(strmap_get(map,"K2"), (void*)101);
2599 test_eq_ptr(strmap_get(map,"K-not-there"), NULL);
2600 strmap_assert_ok(map);
2602 v = strmap_remove(map,"K2");
2603 strmap_assert_ok(map);
2604 test_eq_ptr(v, (void*)101);
2605 test_eq_ptr(strmap_get(map,"K2"), NULL);
2606 test_eq_ptr(strmap_remove(map,"K2"), NULL);
2608 strmap_set(map, "K2", (void*)101);
2609 strmap_set(map, "K3", (void*)102);
2610 strmap_set(map, "K4", (void*)103);
2611 test_eq(strmap_size(map), 4);
2612 strmap_assert_ok(map);
2613 strmap_set(map, "K5", (void*)104);
2614 strmap_set(map, "K6", (void*)105);
2615 strmap_assert_ok(map);
2617 /* Test iterator. */
2618 iter = strmap_iter_init(map);
2619 found_keys = smartlist_create();
2620 while (!strmap_iter_done(iter)) {
2621 strmap_iter_get(iter,&k,&v);
2622 smartlist_add(found_keys, tor_strdup(k));
2623 test_eq_ptr(v, strmap_get(map, k));
2625 if (!strcmp(k, "K2")) {
2626 iter = strmap_iter_next_rmv(map,iter);
2627 } else {
2628 iter = strmap_iter_next(map,iter);
2632 /* Make sure we removed K2, but not the others. */
2633 test_eq_ptr(strmap_get(map, "K2"), NULL);
2634 test_eq_ptr(strmap_get(map, "K5"), (void*)104);
2635 /* Make sure we visited everyone once */
2636 smartlist_sort_strings(found_keys);
2637 visited = smartlist_join_strings(found_keys, ":", 0, NULL);
2638 test_streq(visited, "K1:K2:K3:K4:K5:K6");
2640 strmap_assert_ok(map);
2641 /* Clean up after ourselves. */
2642 strmap_free(map, NULL);
2643 map = NULL;
2645 /* Now try some lc functions. */
2646 map = strmap_new();
2647 strmap_set_lc(map,"Ab.C", (void*)1);
2648 test_eq_ptr(strmap_get(map,"ab.c"), (void*)1);
2649 strmap_assert_ok(map);
2650 test_eq_ptr(strmap_get_lc(map,"AB.C"), (void*)1);
2651 test_eq_ptr(strmap_get(map,"AB.C"), NULL);
2652 test_eq_ptr(strmap_remove_lc(map,"aB.C"), (void*)1);
2653 strmap_assert_ok(map);
2654 test_eq_ptr(strmap_get_lc(map,"AB.C"), NULL);
2656 done:
2657 if (map)
2658 strmap_free(map,NULL);
2659 if (found_keys) {
2660 SMARTLIST_FOREACH(found_keys, char *, cp, tor_free(cp));
2661 smartlist_free(found_keys);
2663 tor_free(visited);
2666 /** Run unit tests for mmap() wrapper functionality. */
2667 static void
2668 test_util_mmap(void)
2670 char *fname1 = tor_strdup(get_fname("mapped_1"));
2671 char *fname2 = tor_strdup(get_fname("mapped_2"));
2672 char *fname3 = tor_strdup(get_fname("mapped_3"));
2673 const size_t buflen = 17000;
2674 char *buf = tor_malloc(17000);
2675 tor_mmap_t *mapping = NULL;
2677 crypto_rand(buf, buflen);
2679 mapping = tor_mmap_file(fname1);
2680 test_assert(! mapping);
2682 write_str_to_file(fname1, "Short file.", 1);
2683 write_bytes_to_file(fname2, buf, buflen, 1);
2684 write_bytes_to_file(fname3, buf, 16384, 1);
2686 mapping = tor_mmap_file(fname1);
2687 test_assert(mapping);
2688 test_eq(mapping->size, strlen("Short file."));
2689 test_streq(mapping->data, "Short file.");
2690 #ifdef MS_WINDOWS
2691 tor_munmap_file(mapping);
2692 mapping = NULL;
2693 test_assert(unlink(fname1) == 0);
2694 #else
2695 /* make sure we can unlink. */
2696 test_assert(unlink(fname1) == 0);
2697 test_streq(mapping->data, "Short file.");
2698 tor_munmap_file(mapping);
2699 mapping = NULL;
2700 #endif
2702 /* Now a zero-length file. */
2703 write_str_to_file(fname1, "", 1);
2704 mapping = tor_mmap_file(fname1);
2705 test_eq(mapping, NULL);
2706 test_eq(ERANGE, errno);
2707 unlink(fname1);
2709 /* Make sure that we fail to map a no-longer-existent file. */
2710 mapping = tor_mmap_file(fname1);
2711 test_assert(mapping == NULL);
2713 /* Now try a big file that stretches across a few pages and isn't aligned */
2714 mapping = tor_mmap_file(fname2);
2715 test_assert(mapping);
2716 test_eq(mapping->size, buflen);
2717 test_memeq(mapping->data, buf, buflen);
2718 tor_munmap_file(mapping);
2719 mapping = NULL;
2721 /* Now try a big aligned file. */
2722 mapping = tor_mmap_file(fname3);
2723 test_assert(mapping);
2724 test_eq(mapping->size, 16384);
2725 test_memeq(mapping->data, buf, 16384);
2726 tor_munmap_file(mapping);
2727 mapping = NULL;
2729 done:
2730 unlink(fname1);
2731 unlink(fname2);
2732 unlink(fname3);
2734 tor_free(fname1);
2735 tor_free(fname2);
2736 tor_free(fname3);
2737 tor_free(buf);
2739 if (mapping)
2740 tor_munmap_file(mapping);
2743 /** Run unit tests for escaping/unescaping data for use by controllers. */
2744 static void
2745 test_util_control_formats(void)
2747 char *out = NULL;
2748 const char *inp =
2749 "..This is a test\r\nof the emergency \nbroadcast\r\n..system.\r\nZ.\r\n";
2750 size_t sz;
2752 sz = read_escaped_data(inp, strlen(inp), &out);
2753 test_streq(out,
2754 ".This is a test\nof the emergency \nbroadcast\n.system.\nZ.\n");
2755 test_eq(sz, strlen(out));
2757 done:
2758 tor_free(out);
2761 static void
2762 test_util_sscanf(void)
2764 unsigned u1, u2, u3;
2765 char s1[10], s2[10], s3[10], ch;
2766 int r;
2768 r = tor_sscanf("hello world", "hello world"); /* String match: success */
2769 test_eq(r, 0);
2770 r = tor_sscanf("hello world 3", "hello worlb %u", &u1); /* String fail */
2771 test_eq(r, 0);
2772 r = tor_sscanf("12345", "%u", &u1); /* Simple number */
2773 test_eq(r, 1);
2774 test_eq(u1, 12345u);
2775 r = tor_sscanf("", "%u", &u1); /* absent number */
2776 test_eq(r, 0);
2777 r = tor_sscanf("A", "%u", &u1); /* bogus number */
2778 test_eq(r, 0);
2779 r = tor_sscanf("4294967295", "%u", &u1); /* UINT32_MAX should work. */
2780 test_eq(r, 1);
2781 test_eq(u1, 4294967295u);
2782 r = tor_sscanf("4294967296", "%u", &u1); /* Always say -1 at 32 bits. */
2783 test_eq(r, 0);
2784 r = tor_sscanf("123456", "%2u%u", &u1, &u2); /* Width */
2785 test_eq(r, 2);
2786 test_eq(u1, 12u);
2787 test_eq(u2, 3456u);
2788 r = tor_sscanf("!12:3:456", "!%2u:%2u:%3u", &u1, &u2, &u3); /* separators */
2789 test_eq(r, 3);
2790 test_eq(u1, 12u);
2791 test_eq(u2, 3u);
2792 test_eq(u3, 456u);
2793 r = tor_sscanf("12:3:045", "%2u:%2u:%3u", &u1, &u2, &u3); /* 0s */
2794 test_eq(r, 3);
2795 test_eq(u1, 12u);
2796 test_eq(u2, 3u);
2797 test_eq(u3, 45u);
2798 /* %u does not match space.*/
2799 r = tor_sscanf("12:3: 45", "%2u:%2u:%3u", &u1, &u2, &u3);
2800 test_eq(r, 2);
2801 /* %u does not match negative numbers. */
2802 r = tor_sscanf("12:3:-4", "%2u:%2u:%3u", &u1, &u2, &u3);
2803 test_eq(r, 2);
2804 /* Arbitrary amounts of 0-padding are okay */
2805 r = tor_sscanf("12:03:000000000000000099", "%2u:%2u:%u", &u1, &u2, &u3);
2806 test_eq(r, 3);
2807 test_eq(u1, 12u);
2808 test_eq(u2, 3u);
2809 test_eq(u3, 99u);
2811 r = tor_sscanf("99% fresh", "%3u%% fresh", &u1); /* percents are scannable.*/
2812 test_eq(r, 1);
2813 test_eq(u1, 99);
2815 r = tor_sscanf("hello", "%s", s1); /* %s needs a number. */
2816 test_eq(r, -1);
2818 r = tor_sscanf("hello", "%3s%7s", s1, s2); /* %s matches characters. */
2819 test_eq(r, 2);
2820 test_streq(s1, "hel");
2821 test_streq(s2, "lo");
2822 r = tor_sscanf("WD40", "%2s%u", s3, &u1); /* %s%u */
2823 test_eq(r, 2);
2824 test_streq(s3, "WD");
2825 test_eq(u1, 40);
2826 r = tor_sscanf("76trombones", "%6u%9s", &u1, s1); /* %u%s */
2827 test_eq(r, 2);
2828 test_eq(u1, 76);
2829 test_streq(s1, "trombones");
2830 r = tor_sscanf("hello world", "%9s %9s", s1, s2); /* %s doesn't eat space. */
2831 test_eq(r, 2);
2832 test_streq(s1, "hello");
2833 test_streq(s2, "world");
2834 r = tor_sscanf("hi", "%9s%9s%3s", s1, s2, s3); /* %s can be empty. */
2835 test_eq(r, 3);
2836 test_streq(s1, "hi");
2837 test_streq(s2, "");
2838 test_streq(s3, "");
2840 r = tor_sscanf("1.2.3", "%u.%u.%u%c", &u1, &u2, &u3, &ch);
2841 test_eq(r, 3);
2842 r = tor_sscanf("1.2.3 foobar", "%u.%u.%u%c", &u1, &u2, &u3, &ch);
2843 test_eq(r, 4);
2845 done:
2849 /** Run unit tests for the onion handshake code. */
2850 static void
2851 test_onion_handshake(void)
2853 /* client-side */
2854 crypto_dh_env_t *c_dh = NULL;
2855 char c_buf[ONIONSKIN_CHALLENGE_LEN];
2856 char c_keys[40];
2858 /* server-side */
2859 char s_buf[ONIONSKIN_REPLY_LEN];
2860 char s_keys[40];
2862 /* shared */
2863 crypto_pk_env_t *pk = NULL;
2865 pk = pk_generate(0);
2867 /* client handshake 1. */
2868 memset(c_buf, 0, ONIONSKIN_CHALLENGE_LEN);
2869 test_assert(! onion_skin_create(pk, &c_dh, c_buf));
2871 /* server handshake */
2872 memset(s_buf, 0, ONIONSKIN_REPLY_LEN);
2873 memset(s_keys, 0, 40);
2874 test_assert(! onion_skin_server_handshake(c_buf, pk, NULL,
2875 s_buf, s_keys, 40));
2877 /* client handshake 2 */
2878 memset(c_keys, 0, 40);
2879 test_assert(! onion_skin_client_handshake(c_dh, s_buf, c_keys, 40));
2881 if (memcmp(c_keys, s_keys, 40)) {
2882 puts("Aiiiie");
2883 exit(1);
2885 test_memeq(c_keys, s_keys, 40);
2886 memset(s_buf, 0, 40);
2887 test_memneq(c_keys, s_buf, 40);
2889 done:
2890 if (c_dh)
2891 crypto_dh_free(c_dh);
2892 if (pk)
2893 crypto_free_pk_env(pk);
2896 /** Run unit tests for router descriptor generation logic. */
2897 static void
2898 test_dir_format(void)
2900 char buf[8192], buf2[8192];
2901 char platform[256];
2902 char fingerprint[FINGERPRINT_LEN+1];
2903 char *pk1_str = NULL, *pk2_str = NULL, *pk3_str = NULL, *cp;
2904 size_t pk1_str_len, pk2_str_len, pk3_str_len;
2905 routerinfo_t *r1=NULL, *r2=NULL;
2906 crypto_pk_env_t *pk1 = NULL, *pk2 = NULL, *pk3 = NULL;
2907 routerinfo_t *rp1 = NULL;
2908 addr_policy_t *ex1, *ex2;
2909 routerlist_t *dir1 = NULL, *dir2 = NULL;
2910 tor_version_t ver1;
2912 pk1 = pk_generate(0);
2913 pk2 = pk_generate(1);
2914 pk3 = pk_generate(2);
2916 test_assert( is_legal_nickname("a"));
2917 test_assert(!is_legal_nickname(""));
2918 test_assert(!is_legal_nickname("abcdefghijklmnopqrst")); /* 20 chars */
2919 test_assert(!is_legal_nickname("hyphen-")); /* bad char */
2920 test_assert( is_legal_nickname("abcdefghijklmnopqrs")); /* 19 chars */
2921 test_assert(!is_legal_nickname("$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2922 /* valid */
2923 test_assert( is_legal_nickname_or_hexdigest(
2924 "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2925 test_assert( is_legal_nickname_or_hexdigest(
2926 "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA=fred"));
2927 test_assert( is_legal_nickname_or_hexdigest(
2928 "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA~fred"));
2929 /* too short */
2930 test_assert(!is_legal_nickname_or_hexdigest(
2931 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2932 /* illegal char */
2933 test_assert(!is_legal_nickname_or_hexdigest(
2934 "$AAAAAAzAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2935 /* hex part too long */
2936 test_assert(!is_legal_nickname_or_hexdigest(
2937 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2938 test_assert(!is_legal_nickname_or_hexdigest(
2939 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=fred"));
2940 /* Bad nickname */
2941 test_assert(!is_legal_nickname_or_hexdigest(
2942 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="));
2943 test_assert(!is_legal_nickname_or_hexdigest(
2944 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~"));
2945 test_assert(!is_legal_nickname_or_hexdigest(
2946 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~hyphen-"));
2947 test_assert(!is_legal_nickname_or_hexdigest(
2948 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~"
2949 "abcdefghijklmnoppqrst"));
2950 /* Bad extra char. */
2951 test_assert(!is_legal_nickname_or_hexdigest(
2952 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA!"));
2953 test_assert(is_legal_nickname_or_hexdigest("xyzzy"));
2954 test_assert(is_legal_nickname_or_hexdigest("abcdefghijklmnopqrs"));
2955 test_assert(!is_legal_nickname_or_hexdigest("abcdefghijklmnopqrst"));
2957 get_platform_str(platform, sizeof(platform));
2958 r1 = tor_malloc_zero(sizeof(routerinfo_t));
2959 r1->address = tor_strdup("18.244.0.1");
2960 r1->addr = 0xc0a80001u; /* 192.168.0.1 */
2961 r1->cache_info.published_on = 0;
2962 r1->or_port = 9000;
2963 r1->dir_port = 9003;
2964 r1->onion_pkey = crypto_pk_dup_key(pk1);
2965 r1->identity_pkey = crypto_pk_dup_key(pk2);
2966 r1->bandwidthrate = 1000;
2967 r1->bandwidthburst = 5000;
2968 r1->bandwidthcapacity = 10000;
2969 r1->exit_policy = NULL;
2970 r1->nickname = tor_strdup("Magri");
2971 r1->platform = tor_strdup(platform);
2973 ex1 = tor_malloc_zero(sizeof(addr_policy_t));
2974 ex2 = tor_malloc_zero(sizeof(addr_policy_t));
2975 ex1->policy_type = ADDR_POLICY_ACCEPT;
2976 tor_addr_from_ipv4h(&ex1->addr, 0);
2977 ex1->maskbits = 0;
2978 ex1->prt_min = ex1->prt_max = 80;
2979 ex2->policy_type = ADDR_POLICY_REJECT;
2980 tor_addr_from_ipv4h(&ex2->addr, 18<<24);
2981 ex2->maskbits = 8;
2982 ex2->prt_min = ex2->prt_max = 24;
2983 r2 = tor_malloc_zero(sizeof(routerinfo_t));
2984 r2->address = tor_strdup("1.1.1.1");
2985 r2->addr = 0x0a030201u; /* 10.3.2.1 */
2986 r2->platform = tor_strdup(platform);
2987 r2->cache_info.published_on = 5;
2988 r2->or_port = 9005;
2989 r2->dir_port = 0;
2990 r2->onion_pkey = crypto_pk_dup_key(pk2);
2991 r2->identity_pkey = crypto_pk_dup_key(pk1);
2992 r2->bandwidthrate = r2->bandwidthburst = r2->bandwidthcapacity = 3000;
2993 r2->exit_policy = smartlist_create();
2994 smartlist_add(r2->exit_policy, ex2);
2995 smartlist_add(r2->exit_policy, ex1);
2996 r2->nickname = tor_strdup("Fred");
2998 test_assert(!crypto_pk_write_public_key_to_string(pk1, &pk1_str,
2999 &pk1_str_len));
3000 test_assert(!crypto_pk_write_public_key_to_string(pk2 , &pk2_str,
3001 &pk2_str_len));
3002 test_assert(!crypto_pk_write_public_key_to_string(pk3 , &pk3_str,
3003 &pk3_str_len));
3005 memset(buf, 0, 2048);
3006 test_assert(router_dump_router_to_string(buf, 2048, r1, pk2)>0);
3008 strlcpy(buf2, "router Magri 18.244.0.1 9000 0 9003\n"
3009 "platform Tor "VERSION" on ", sizeof(buf2));
3010 strlcat(buf2, get_uname(), sizeof(buf2));
3011 strlcat(buf2, "\n"
3012 "opt protocols Link 1 2 Circuit 1\n"
3013 "published 1970-01-01 00:00:00\n"
3014 "opt fingerprint ", sizeof(buf2));
3015 test_assert(!crypto_pk_get_fingerprint(pk2, fingerprint, 1));
3016 strlcat(buf2, fingerprint, sizeof(buf2));
3017 strlcat(buf2, "\nuptime 0\n"
3018 /* XXX the "0" above is hard-coded, but even if we made it reflect
3019 * uptime, that still wouldn't make it right, because the two
3020 * descriptors might be made on different seconds... hm. */
3021 "bandwidth 1000 5000 10000\n"
3022 "opt extra-info-digest 0000000000000000000000000000000000000000\n"
3023 "onion-key\n", sizeof(buf2));
3024 strlcat(buf2, pk1_str, sizeof(buf2));
3025 strlcat(buf2, "signing-key\n", sizeof(buf2));
3026 strlcat(buf2, pk2_str, sizeof(buf2));
3027 strlcat(buf2, "opt hidden-service-dir\n", sizeof(buf2));
3028 strlcat(buf2, "reject *:*\nrouter-signature\n", sizeof(buf2));
3029 buf[strlen(buf2)] = '\0'; /* Don't compare the sig; it's never the same
3030 * twice */
3032 test_streq(buf, buf2);
3034 test_assert(router_dump_router_to_string(buf, 2048, r1, pk2)>0);
3035 cp = buf;
3036 rp1 = router_parse_entry_from_string((const char*)cp,NULL,1,0,NULL);
3037 test_assert(rp1);
3038 test_streq(rp1->address, r1->address);
3039 test_eq(rp1->or_port, r1->or_port);
3040 //test_eq(rp1->dir_port, r1->dir_port);
3041 test_eq(rp1->bandwidthrate, r1->bandwidthrate);
3042 test_eq(rp1->bandwidthburst, r1->bandwidthburst);
3043 test_eq(rp1->bandwidthcapacity, r1->bandwidthcapacity);
3044 test_assert(crypto_pk_cmp_keys(rp1->onion_pkey, pk1) == 0);
3045 test_assert(crypto_pk_cmp_keys(rp1->identity_pkey, pk2) == 0);
3046 //test_assert(rp1->exit_policy == NULL);
3048 #if 0
3049 /* XXX Once we have exit policies, test this again. XXX */
3050 strlcpy(buf2, "router tor.tor.tor 9005 0 0 3000\n", sizeof(buf2));
3051 strlcat(buf2, pk2_str, sizeof(buf2));
3052 strlcat(buf2, "signing-key\n", sizeof(buf2));
3053 strlcat(buf2, pk1_str, sizeof(buf2));
3054 strlcat(buf2, "accept *:80\nreject 18.*:24\n\n", sizeof(buf2));
3055 test_assert(router_dump_router_to_string(buf, 2048, &r2, pk2)>0);
3056 test_streq(buf, buf2);
3058 cp = buf;
3059 rp2 = router_parse_entry_from_string(&cp,1);
3060 test_assert(rp2);
3061 test_streq(rp2->address, r2.address);
3062 test_eq(rp2->or_port, r2.or_port);
3063 test_eq(rp2->dir_port, r2.dir_port);
3064 test_eq(rp2->bandwidth, r2.bandwidth);
3065 test_assert(crypto_pk_cmp_keys(rp2->onion_pkey, pk2) == 0);
3066 test_assert(crypto_pk_cmp_keys(rp2->identity_pkey, pk1) == 0);
3067 test_eq(rp2->exit_policy->policy_type, EXIT_POLICY_ACCEPT);
3068 test_streq(rp2->exit_policy->string, "accept *:80");
3069 test_streq(rp2->exit_policy->address, "*");
3070 test_streq(rp2->exit_policy->port, "80");
3071 test_eq(rp2->exit_policy->next->policy_type, EXIT_POLICY_REJECT);
3072 test_streq(rp2->exit_policy->next->string, "reject 18.*:24");
3073 test_streq(rp2->exit_policy->next->address, "18.*");
3074 test_streq(rp2->exit_policy->next->port, "24");
3075 test_assert(rp2->exit_policy->next->next == NULL);
3077 /* Okay, now for the directories. */
3079 fingerprint_list = smartlist_create();
3080 crypto_pk_get_fingerprint(pk2, buf, 1);
3081 add_fingerprint_to_dir("Magri", buf, fingerprint_list);
3082 crypto_pk_get_fingerprint(pk1, buf, 1);
3083 add_fingerprint_to_dir("Fred", buf, fingerprint_list);
3087 char d[DIGEST_LEN];
3088 const char *m;
3089 /* XXXX NM re-enable. */
3090 /* Make sure routers aren't too far in the past any more. */
3091 r1->cache_info.published_on = time(NULL);
3092 r2->cache_info.published_on = time(NULL)-3*60*60;
3093 test_assert(router_dump_router_to_string(buf, 2048, r1, pk2)>0);
3094 test_eq(dirserv_add_descriptor(buf,&m,""), ROUTER_ADDED_NOTIFY_GENERATOR);
3095 test_assert(router_dump_router_to_string(buf, 2048, r2, pk1)>0);
3096 test_eq(dirserv_add_descriptor(buf,&m,""), ROUTER_ADDED_NOTIFY_GENERATOR);
3097 get_options()->Nickname = tor_strdup("DirServer");
3098 test_assert(!dirserv_dump_directory_to_string(&cp,pk3, 0));
3099 crypto_pk_get_digest(pk3, d);
3100 test_assert(!router_parse_directory(cp));
3101 test_eq(2, smartlist_len(dir1->routers));
3102 tor_free(cp);
3104 #endif
3105 dirserv_free_fingerprint_list();
3107 /* Try out version parsing functionality */
3108 test_eq(0, tor_version_parse("0.3.4pre2-cvs", &ver1));
3109 test_eq(0, ver1.major);
3110 test_eq(3, ver1.minor);
3111 test_eq(4, ver1.micro);
3112 test_eq(VER_PRE, ver1.status);
3113 test_eq(2, ver1.patchlevel);
3114 test_eq(0, tor_version_parse("0.3.4rc1", &ver1));
3115 test_eq(0, ver1.major);
3116 test_eq(3, ver1.minor);
3117 test_eq(4, ver1.micro);
3118 test_eq(VER_RC, ver1.status);
3119 test_eq(1, ver1.patchlevel);
3120 test_eq(0, tor_version_parse("1.3.4", &ver1));
3121 test_eq(1, ver1.major);
3122 test_eq(3, ver1.minor);
3123 test_eq(4, ver1.micro);
3124 test_eq(VER_RELEASE, ver1.status);
3125 test_eq(0, ver1.patchlevel);
3126 test_eq(0, tor_version_parse("1.3.4.999", &ver1));
3127 test_eq(1, ver1.major);
3128 test_eq(3, ver1.minor);
3129 test_eq(4, ver1.micro);
3130 test_eq(VER_RELEASE, ver1.status);
3131 test_eq(999, ver1.patchlevel);
3132 test_eq(0, tor_version_parse("0.1.2.4-alpha", &ver1));
3133 test_eq(0, ver1.major);
3134 test_eq(1, ver1.minor);
3135 test_eq(2, ver1.micro);
3136 test_eq(4, ver1.patchlevel);
3137 test_eq(VER_RELEASE, ver1.status);
3138 test_streq("alpha", ver1.status_tag);
3139 test_eq(0, tor_version_parse("0.1.2.4", &ver1));
3140 test_eq(0, ver1.major);
3141 test_eq(1, ver1.minor);
3142 test_eq(2, ver1.micro);
3143 test_eq(4, ver1.patchlevel);
3144 test_eq(VER_RELEASE, ver1.status);
3145 test_streq("", ver1.status_tag);
3147 #define test_eq_vs(vs1, vs2) test_eq_type(version_status_t, "%d", (vs1), (vs2))
3148 #define test_v_i_o(val, ver, lst) \
3149 test_eq_vs(val, tor_version_is_obsolete(ver, lst))
3151 /* make sure tor_version_is_obsolete() works */
3152 test_v_i_o(VS_OLD, "0.0.1", "Tor 0.0.2");
3153 test_v_i_o(VS_OLD, "0.0.1", "0.0.2, Tor 0.0.3");
3154 test_v_i_o(VS_OLD, "0.0.1", "0.0.2,Tor 0.0.3");
3155 test_v_i_o(VS_OLD, "0.0.1","0.0.3,BetterTor 0.0.1");
3156 test_v_i_o(VS_RECOMMENDED, "0.0.2", "Tor 0.0.2,Tor 0.0.3");
3157 test_v_i_o(VS_NEW_IN_SERIES, "0.0.2", "Tor 0.0.2pre1,Tor 0.0.3");
3158 test_v_i_o(VS_OLD, "0.0.2", "Tor 0.0.2.1,Tor 0.0.3");
3159 test_v_i_o(VS_NEW, "0.1.0", "Tor 0.0.2,Tor 0.0.3");
3160 test_v_i_o(VS_RECOMMENDED, "0.0.7rc2", "0.0.7,Tor 0.0.7rc2,Tor 0.0.8");
3161 test_v_i_o(VS_OLD, "0.0.5.0", "0.0.5.1-cvs");
3162 test_v_i_o(VS_NEW_IN_SERIES, "0.0.5.1-cvs", "0.0.5, 0.0.6");
3163 /* Not on list, but newer than any in same series. */
3164 test_v_i_o(VS_NEW_IN_SERIES, "0.1.0.3",
3165 "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
3166 /* Series newer than any on list. */
3167 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");
3168 /* Series older than any on list. */
3169 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");
3170 /* Not on list, not newer than any on same series. */
3171 test_v_i_o(VS_UNRECOMMENDED, "0.1.0.1",
3172 "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
3173 /* On list, not newer than any on same series. */
3174 test_v_i_o(VS_UNRECOMMENDED,
3175 "0.1.0.1", "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
3176 test_eq(0, tor_version_as_new_as("Tor 0.0.5", "0.0.9pre1-cvs"));
3177 test_eq(1, tor_version_as_new_as(
3178 "Tor 0.0.8 on Darwin 64-121-192-100.c3-0."
3179 "sfpo-ubr1.sfrn-sfpo.ca.cable.rcn.com Power Macintosh",
3180 "0.0.8rc2"));
3181 test_eq(0, tor_version_as_new_as(
3182 "Tor 0.0.8 on Darwin 64-121-192-100.c3-0."
3183 "sfpo-ubr1.sfrn-sfpo.ca.cable.rcn.com Power Macintosh", "0.0.8.2"));
3185 /* Now try svn revisions. */
3186 test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100)",
3187 "Tor 0.2.1.0-dev (r99)"));
3188 test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100) on Banana Jr",
3189 "Tor 0.2.1.0-dev (r99) on Hal 9000"));
3190 test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100)",
3191 "Tor 0.2.1.0-dev on Colossus"));
3192 test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev (r99)",
3193 "Tor 0.2.1.0-dev (r100)"));
3194 test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev (r99) on MCP",
3195 "Tor 0.2.1.0-dev (r100) on AM"));
3196 test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev",
3197 "Tor 0.2.1.0-dev (r99)"));
3198 test_eq(1, tor_version_as_new_as("Tor 0.2.1.1",
3199 "Tor 0.2.1.0-dev (r99)"));
3200 done:
3201 if (r1)
3202 routerinfo_free(r1);
3203 if (r2)
3204 routerinfo_free(r2);
3206 tor_free(pk1_str);
3207 tor_free(pk2_str);
3208 tor_free(pk3_str);
3209 if (pk1) crypto_free_pk_env(pk1);
3210 if (pk2) crypto_free_pk_env(pk2);
3211 if (pk3) crypto_free_pk_env(pk3);
3212 if (rp1) routerinfo_free(rp1);
3213 tor_free(dir1); /* XXXX And more !*/
3214 tor_free(dir2); /* And more !*/
3217 /** Run unit tests for misc directory functions. */
3218 static void
3219 test_dirutil(void)
3221 smartlist_t *sl = smartlist_create();
3222 fp_pair_t *pair;
3224 dir_split_resource_into_fingerprint_pairs(
3225 /* Two pairs, out of order, with one duplicate. */
3226 "73656372657420646174612E0000000000FFFFFF-"
3227 "557365204145532d32353620696e73746561642e+"
3228 "73656372657420646174612E0000000000FFFFFF-"
3229 "557365204145532d32353620696e73746561642e+"
3230 "48657861646563696d616c2069736e277420736f-"
3231 "676f6f6420666f7220686964696e6720796f7572.z", sl);
3233 test_eq(smartlist_len(sl), 2);
3234 pair = smartlist_get(sl, 0);
3235 test_memeq(pair->first, "Hexadecimal isn't so", DIGEST_LEN);
3236 test_memeq(pair->second, "good for hiding your", DIGEST_LEN);
3237 pair = smartlist_get(sl, 1);
3238 test_memeq(pair->first, "secret data.\0\0\0\0\0\xff\xff\xff", DIGEST_LEN);
3239 test_memeq(pair->second, "Use AES-256 instead.", DIGEST_LEN);
3241 done:
3242 SMARTLIST_FOREACH(sl, fp_pair_t *, pair, tor_free(pair));
3243 smartlist_free(sl);
3246 extern const char AUTHORITY_CERT_1[];
3247 extern const char AUTHORITY_SIGNKEY_1[];
3248 extern const char AUTHORITY_CERT_2[];
3249 extern const char AUTHORITY_SIGNKEY_2[];
3250 extern const char AUTHORITY_CERT_3[];
3251 extern const char AUTHORITY_SIGNKEY_3[];
3253 /** Helper: Test that two networkstatus_voter_info_t do in fact represent the
3254 * same voting authority, and that they do in fact have all the same
3255 * information. */
3256 static void
3257 test_same_voter(networkstatus_voter_info_t *v1,
3258 networkstatus_voter_info_t *v2)
3260 test_streq(v1->nickname, v2->nickname);
3261 test_memeq(v1->identity_digest, v2->identity_digest, DIGEST_LEN);
3262 test_streq(v1->address, v2->address);
3263 test_eq(v1->addr, v2->addr);
3264 test_eq(v1->dir_port, v2->dir_port);
3265 test_eq(v1->or_port, v2->or_port);
3266 test_streq(v1->contact, v2->contact);
3267 test_memeq(v1->vote_digest, v2->vote_digest, DIGEST_LEN);
3268 done:
3272 /** Run unit tests for getting the median of a list. */
3273 static void
3274 test_util_order_functions(void)
3276 int lst[25], n = 0;
3277 // int a=12,b=24,c=25,d=60,e=77;
3279 #define median() median_int(lst, n)
3281 lst[n++] = 12;
3282 test_eq(12, median()); /* 12 */
3283 lst[n++] = 77;
3284 //smartlist_shuffle(sl);
3285 test_eq(12, median()); /* 12, 77 */
3286 lst[n++] = 77;
3287 //smartlist_shuffle(sl);
3288 test_eq(77, median()); /* 12, 77, 77 */
3289 lst[n++] = 24;
3290 test_eq(24, median()); /* 12,24,77,77 */
3291 lst[n++] = 60;
3292 lst[n++] = 12;
3293 lst[n++] = 25;
3294 //smartlist_shuffle(sl);
3295 test_eq(25, median()); /* 12,12,24,25,60,77,77 */
3296 #undef median
3298 done:
3302 /** Helper: Make a new routerinfo containing the right information for a
3303 * given vote_routerstatus_t. */
3304 static routerinfo_t *
3305 generate_ri_from_rs(const vote_routerstatus_t *vrs)
3307 routerinfo_t *r;
3308 const routerstatus_t *rs = &vrs->status;
3309 static time_t published = 0;
3311 r = tor_malloc_zero(sizeof(routerinfo_t));
3312 memcpy(r->cache_info.identity_digest, rs->identity_digest, DIGEST_LEN);
3313 memcpy(r->cache_info.signed_descriptor_digest, rs->descriptor_digest,
3314 DIGEST_LEN);
3315 r->cache_info.do_not_cache = 1;
3316 r->cache_info.routerlist_index = -1;
3317 r->cache_info.signed_descriptor_body =
3318 tor_strdup("123456789012345678901234567890123");
3319 r->cache_info.signed_descriptor_len =
3320 strlen(r->cache_info.signed_descriptor_body);
3321 r->exit_policy = smartlist_create();
3322 r->cache_info.published_on = ++published + time(NULL);
3323 return r;
3326 /** Run unit tests for generating and parsing V3 consensus networkstatus
3327 * documents. */
3328 static void
3329 test_v3_networkstatus(void)
3331 authority_cert_t *cert1=NULL, *cert2=NULL, *cert3=NULL;
3332 crypto_pk_env_t *sign_skey_1=NULL, *sign_skey_2=NULL, *sign_skey_3=NULL;
3333 crypto_pk_env_t *sign_skey_leg1=NULL;
3334 const char *msg=NULL;
3336 time_t now = time(NULL);
3337 networkstatus_voter_info_t *voter;
3338 networkstatus_t *vote=NULL, *v1=NULL, *v2=NULL, *v3=NULL, *con=NULL;
3339 vote_routerstatus_t *vrs;
3340 routerstatus_t *rs;
3341 char *v1_text=NULL, *v2_text=NULL, *v3_text=NULL, *consensus_text=NULL, *cp;
3342 smartlist_t *votes = smartlist_create();
3344 /* For generating the two other consensuses. */
3345 char *detached_text1=NULL, *detached_text2=NULL;
3346 char *consensus_text2=NULL, *consensus_text3=NULL;
3347 networkstatus_t *con2=NULL, *con3=NULL;
3348 ns_detached_signatures_t *dsig1=NULL, *dsig2=NULL;
3350 /* Parse certificates and keys. */
3351 cert1 = authority_cert_parse_from_string(AUTHORITY_CERT_1, NULL);
3352 test_assert(cert1);
3353 test_assert(cert1->is_cross_certified);
3354 cert2 = authority_cert_parse_from_string(AUTHORITY_CERT_2, NULL);
3355 test_assert(cert2);
3356 cert3 = authority_cert_parse_from_string(AUTHORITY_CERT_3, NULL);
3357 test_assert(cert3);
3358 sign_skey_1 = crypto_new_pk_env();
3359 sign_skey_2 = crypto_new_pk_env();
3360 sign_skey_3 = crypto_new_pk_env();
3361 sign_skey_leg1 = pk_generate(4);
3363 test_assert(!crypto_pk_read_private_key_from_string(sign_skey_1,
3364 AUTHORITY_SIGNKEY_1));
3365 test_assert(!crypto_pk_read_private_key_from_string(sign_skey_2,
3366 AUTHORITY_SIGNKEY_2));
3367 test_assert(!crypto_pk_read_private_key_from_string(sign_skey_3,
3368 AUTHORITY_SIGNKEY_3));
3370 test_assert(!crypto_pk_cmp_keys(sign_skey_1, cert1->signing_key));
3371 test_assert(!crypto_pk_cmp_keys(sign_skey_2, cert2->signing_key));
3374 * Set up a vote; generate it; try to parse it.
3376 vote = tor_malloc_zero(sizeof(networkstatus_t));
3377 vote->type = NS_TYPE_VOTE;
3378 vote->published = now;
3379 vote->valid_after = now+1000;
3380 vote->fresh_until = now+2000;
3381 vote->valid_until = now+3000;
3382 vote->vote_seconds = 100;
3383 vote->dist_seconds = 200;
3384 vote->supported_methods = smartlist_create();
3385 smartlist_split_string(vote->supported_methods, "1 2 3", NULL, 0, -1);
3386 vote->client_versions = tor_strdup("0.1.2.14,0.1.2.15");
3387 vote->server_versions = tor_strdup("0.1.2.14,0.1.2.15,0.1.2.16");
3388 vote->known_flags = smartlist_create();
3389 smartlist_split_string(vote->known_flags,
3390 "Authority Exit Fast Guard Running Stable V2Dir Valid",
3391 0, SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
3392 vote->voters = smartlist_create();
3393 voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
3394 voter->nickname = tor_strdup("Voter1");
3395 voter->address = tor_strdup("1.2.3.4");
3396 voter->addr = 0x01020304;
3397 voter->dir_port = 80;
3398 voter->or_port = 9000;
3399 voter->contact = tor_strdup("voter@example.com");
3400 crypto_pk_get_digest(cert1->identity_key, voter->identity_digest);
3401 smartlist_add(vote->voters, voter);
3402 vote->cert = authority_cert_dup(cert1);
3403 vote->routerstatus_list = smartlist_create();
3404 /* add the first routerstatus. */
3405 vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
3406 rs = &vrs->status;
3407 vrs->version = tor_strdup("0.1.2.14");
3408 rs->published_on = now-1500;
3409 strlcpy(rs->nickname, "router2", sizeof(rs->nickname));
3410 memset(rs->identity_digest, 3, DIGEST_LEN);
3411 memset(rs->descriptor_digest, 78, DIGEST_LEN);
3412 rs->addr = 0x99008801;
3413 rs->or_port = 443;
3414 rs->dir_port = 8000;
3415 /* all flags but running cleared */
3416 rs->is_running = 1;
3417 smartlist_add(vote->routerstatus_list, vrs);
3418 test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs), &msg,0,0)>=0);
3420 /* add the second routerstatus. */
3421 vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
3422 rs = &vrs->status;
3423 vrs->version = tor_strdup("0.2.0.5");
3424 rs->published_on = now-1000;
3425 strlcpy(rs->nickname, "router1", sizeof(rs->nickname));
3426 memset(rs->identity_digest, 5, DIGEST_LEN);
3427 memset(rs->descriptor_digest, 77, DIGEST_LEN);
3428 rs->addr = 0x99009901;
3429 rs->or_port = 443;
3430 rs->dir_port = 0;
3431 rs->is_exit = rs->is_stable = rs->is_fast = rs->is_running =
3432 rs->is_valid = rs->is_v2_dir = rs->is_possible_guard = 1;
3433 smartlist_add(vote->routerstatus_list, vrs);
3434 test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs), &msg,0,0)>=0);
3436 /* add the third routerstatus. */
3437 vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
3438 rs = &vrs->status;
3439 vrs->version = tor_strdup("0.1.0.3");
3440 rs->published_on = now-1000;
3441 strlcpy(rs->nickname, "router3", sizeof(rs->nickname));
3442 memset(rs->identity_digest, 33, DIGEST_LEN);
3443 memset(rs->descriptor_digest, 79, DIGEST_LEN);
3444 rs->addr = 0xAA009901;
3445 rs->or_port = 400;
3446 rs->dir_port = 9999;
3447 rs->is_authority = rs->is_exit = rs->is_stable = rs->is_fast =
3448 rs->is_running = rs->is_valid = rs->is_v2_dir = rs->is_possible_guard = 1;
3449 smartlist_add(vote->routerstatus_list, vrs);
3450 test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs), &msg,0,0)>=0);
3452 /* add a fourth routerstatus that is not running. */
3453 vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
3454 rs = &vrs->status;
3455 vrs->version = tor_strdup("0.1.6.3");
3456 rs->published_on = now-1000;
3457 strlcpy(rs->nickname, "router4", sizeof(rs->nickname));
3458 memset(rs->identity_digest, 34, DIGEST_LEN);
3459 memset(rs->descriptor_digest, 48, DIGEST_LEN);
3460 rs->addr = 0xC0000203;
3461 rs->or_port = 500;
3462 rs->dir_port = 1999;
3463 /* Running flag (and others) cleared */
3464 smartlist_add(vote->routerstatus_list, vrs);
3465 test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs), &msg,0,0)>=0);
3467 /* dump the vote and try to parse it. */
3468 v1_text = format_networkstatus_vote(sign_skey_1, vote);
3469 test_assert(v1_text);
3470 v1 = networkstatus_parse_vote_from_string(v1_text, NULL, NS_TYPE_VOTE);
3471 test_assert(v1);
3473 /* Make sure the parsed thing was right. */
3474 test_eq(v1->type, NS_TYPE_VOTE);
3475 test_eq(v1->published, vote->published);
3476 test_eq(v1->valid_after, vote->valid_after);
3477 test_eq(v1->fresh_until, vote->fresh_until);
3478 test_eq(v1->valid_until, vote->valid_until);
3479 test_eq(v1->vote_seconds, vote->vote_seconds);
3480 test_eq(v1->dist_seconds, vote->dist_seconds);
3481 test_streq(v1->client_versions, vote->client_versions);
3482 test_streq(v1->server_versions, vote->server_versions);
3483 test_assert(v1->voters && smartlist_len(v1->voters));
3484 voter = smartlist_get(v1->voters, 0);
3485 test_streq(voter->nickname, "Voter1");
3486 test_streq(voter->address, "1.2.3.4");
3487 test_eq(voter->addr, 0x01020304);
3488 test_eq(voter->dir_port, 80);
3489 test_eq(voter->or_port, 9000);
3490 test_streq(voter->contact, "voter@example.com");
3491 test_assert(v1->cert);
3492 test_assert(!crypto_pk_cmp_keys(sign_skey_1, v1->cert->signing_key));
3493 cp = smartlist_join_strings(v1->known_flags, ":", 0, NULL);
3494 test_streq(cp, "Authority:Exit:Fast:Guard:Running:Stable:V2Dir:Valid");
3495 tor_free(cp);
3496 test_eq(smartlist_len(v1->routerstatus_list), 4);
3497 /* Check the first routerstatus. */
3498 vrs = smartlist_get(v1->routerstatus_list, 0);
3499 rs = &vrs->status;
3500 test_streq(vrs->version, "0.1.2.14");
3501 test_eq(rs->published_on, now-1500);
3502 test_streq(rs->nickname, "router2");
3503 test_memeq(rs->identity_digest,
3504 "\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3",
3505 DIGEST_LEN);
3506 test_memeq(rs->descriptor_digest, "NNNNNNNNNNNNNNNNNNNN", DIGEST_LEN);
3507 test_eq(rs->addr, 0x99008801);
3508 test_eq(rs->or_port, 443);
3509 test_eq(rs->dir_port, 8000);
3510 test_eq(vrs->flags, U64_LITERAL(16)); // no flags except "running"
3511 /* Check the second routerstatus. */
3512 vrs = smartlist_get(v1->routerstatus_list, 1);
3513 rs = &vrs->status;
3514 test_streq(vrs->version, "0.2.0.5");
3515 test_eq(rs->published_on, now-1000);
3516 test_streq(rs->nickname, "router1");
3517 test_memeq(rs->identity_digest,
3518 "\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5",
3519 DIGEST_LEN);
3520 test_memeq(rs->descriptor_digest, "MMMMMMMMMMMMMMMMMMMM", DIGEST_LEN);
3521 test_eq(rs->addr, 0x99009901);
3522 test_eq(rs->or_port, 443);
3523 test_eq(rs->dir_port, 0);
3524 test_eq(vrs->flags, U64_LITERAL(254)); // all flags except "authority."
3526 /* Generate second vote. It disagrees on some of the times,
3527 * and doesn't list versions, and knows some crazy flags */
3528 vote->published = now+1;
3529 vote->fresh_until = now+3005;
3530 vote->dist_seconds = 300;
3531 authority_cert_free(vote->cert);
3532 vote->cert = authority_cert_dup(cert2);
3533 tor_free(vote->client_versions);
3534 tor_free(vote->server_versions);
3535 voter = smartlist_get(vote->voters, 0);
3536 tor_free(voter->nickname);
3537 tor_free(voter->address);
3538 voter->nickname = tor_strdup("Voter2");
3539 voter->address = tor_strdup("2.3.4.5");
3540 voter->addr = 0x02030405;
3541 crypto_pk_get_digest(cert2->identity_key, voter->identity_digest);
3542 smartlist_add(vote->known_flags, tor_strdup("MadeOfCheese"));
3543 smartlist_add(vote->known_flags, tor_strdup("MadeOfTin"));
3544 smartlist_sort_strings(vote->known_flags);
3545 vrs = smartlist_get(vote->routerstatus_list, 2);
3546 smartlist_del_keeporder(vote->routerstatus_list, 2);
3547 tor_free(vrs->version);
3548 tor_free(vrs);
3549 vrs = smartlist_get(vote->routerstatus_list, 0);
3550 vrs->status.is_fast = 1;
3551 /* generate and parse. */
3552 v2_text = format_networkstatus_vote(sign_skey_2, vote);
3553 test_assert(v2_text);
3554 v2 = networkstatus_parse_vote_from_string(v2_text, NULL, NS_TYPE_VOTE);
3555 test_assert(v2);
3556 /* Check that flags come out right.*/
3557 cp = smartlist_join_strings(v2->known_flags, ":", 0, NULL);
3558 test_streq(cp, "Authority:Exit:Fast:Guard:MadeOfCheese:MadeOfTin:"
3559 "Running:Stable:V2Dir:Valid");
3560 tor_free(cp);
3561 vrs = smartlist_get(v2->routerstatus_list, 1);
3562 /* 1023 - authority(1) - madeofcheese(16) - madeoftin(32) */
3563 test_eq(vrs->flags, U64_LITERAL(974));
3565 /* Generate the third vote. */
3566 vote->published = now;
3567 vote->fresh_until = now+2003;
3568 vote->dist_seconds = 250;
3569 authority_cert_free(vote->cert);
3570 vote->cert = authority_cert_dup(cert3);
3571 smartlist_add(vote->supported_methods, tor_strdup("4"));
3572 vote->client_versions = tor_strdup("0.1.2.14,0.1.2.17");
3573 vote->server_versions = tor_strdup("0.1.2.10,0.1.2.15,0.1.2.16");
3574 voter = smartlist_get(vote->voters, 0);
3575 tor_free(voter->nickname);
3576 tor_free(voter->address);
3577 voter->nickname = tor_strdup("Voter3");
3578 voter->address = tor_strdup("3.4.5.6");
3579 voter->addr = 0x03040506;
3580 crypto_pk_get_digest(cert3->identity_key, voter->identity_digest);
3581 /* This one has a legacy id. */
3582 memset(voter->legacy_id_digest, (int)'A', DIGEST_LEN);
3583 vrs = smartlist_get(vote->routerstatus_list, 0);
3584 smartlist_del_keeporder(vote->routerstatus_list, 0);
3585 tor_free(vrs->version);
3586 tor_free(vrs);
3587 vrs = smartlist_get(vote->routerstatus_list, 0);
3588 memset(vrs->status.descriptor_digest, (int)'Z', DIGEST_LEN);
3589 test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs), &msg,0,0)>=0);
3591 v3_text = format_networkstatus_vote(sign_skey_3, vote);
3592 test_assert(v3_text);
3594 v3 = networkstatus_parse_vote_from_string(v3_text, NULL, NS_TYPE_VOTE);
3595 test_assert(v3);
3597 /* Compute a consensus as voter 3. */
3598 smartlist_add(votes, v3);
3599 smartlist_add(votes, v1);
3600 smartlist_add(votes, v2);
3601 consensus_text = networkstatus_compute_consensus(votes, 3,
3602 cert3->identity_key,
3603 sign_skey_3,
3604 "AAAAAAAAAAAAAAAAAAAA",
3605 sign_skey_leg1);
3606 test_assert(consensus_text);
3607 con = networkstatus_parse_vote_from_string(consensus_text, NULL,
3608 NS_TYPE_CONSENSUS);
3609 test_assert(con);
3610 //log_notice(LD_GENERAL, "<<%s>>\n<<%s>>\n<<%s>>\n",
3611 // v1_text, v2_text, v3_text);
3613 /* Check consensus contents. */
3614 test_assert(con->type == NS_TYPE_CONSENSUS);
3615 test_eq(con->published, 0); /* this field only appears in votes. */
3616 test_eq(con->valid_after, now+1000);
3617 test_eq(con->fresh_until, now+2003); /* median */
3618 test_eq(con->valid_until, now+3000);
3619 test_eq(con->vote_seconds, 100);
3620 test_eq(con->dist_seconds, 250); /* median */
3621 test_streq(con->client_versions, "0.1.2.14");
3622 test_streq(con->server_versions, "0.1.2.15,0.1.2.16");
3623 cp = smartlist_join_strings(v2->known_flags, ":", 0, NULL);
3624 test_streq(cp, "Authority:Exit:Fast:Guard:MadeOfCheese:MadeOfTin:"
3625 "Running:Stable:V2Dir:Valid");
3626 tor_free(cp);
3627 test_eq(4, smartlist_len(con->voters)); /*3 voters, 1 legacy key.*/
3628 /* The voter id digests should be in this order. */
3629 test_assert(memcmp(cert2->cache_info.identity_digest,
3630 cert1->cache_info.identity_digest,DIGEST_LEN)<0);
3631 test_assert(memcmp(cert1->cache_info.identity_digest,
3632 cert3->cache_info.identity_digest,DIGEST_LEN)<0);
3633 test_same_voter(smartlist_get(con->voters, 1),
3634 smartlist_get(v2->voters, 0));
3635 test_same_voter(smartlist_get(con->voters, 2),
3636 smartlist_get(v1->voters, 0));
3637 test_same_voter(smartlist_get(con->voters, 3),
3638 smartlist_get(v3->voters, 0));
3640 test_assert(!con->cert);
3641 test_eq(2, smartlist_len(con->routerstatus_list));
3642 /* There should be two listed routers: one with identity 3, one with
3643 * identity 5. */
3644 /* This one showed up in 2 digests. */
3645 rs = smartlist_get(con->routerstatus_list, 0);
3646 test_memeq(rs->identity_digest,
3647 "\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3",
3648 DIGEST_LEN);
3649 test_memeq(rs->descriptor_digest, "NNNNNNNNNNNNNNNNNNNN", DIGEST_LEN);
3650 test_assert(!rs->is_authority);
3651 test_assert(!rs->is_exit);
3652 test_assert(!rs->is_fast);
3653 test_assert(!rs->is_possible_guard);
3654 test_assert(!rs->is_stable);
3655 test_assert(rs->is_running); /* If it wasn't running it wouldn't be here */
3656 test_assert(!rs->is_v2_dir);
3657 test_assert(!rs->is_valid);
3658 test_assert(!rs->is_named);
3659 /* XXXX check version */
3661 rs = smartlist_get(con->routerstatus_list, 1);
3662 /* This one showed up in 3 digests. Twice with ID 'M', once with 'Z'. */
3663 test_memeq(rs->identity_digest,
3664 "\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5",
3665 DIGEST_LEN);
3666 test_streq(rs->nickname, "router1");
3667 test_memeq(rs->descriptor_digest, "MMMMMMMMMMMMMMMMMMMM", DIGEST_LEN);
3668 test_eq(rs->published_on, now-1000);
3669 test_eq(rs->addr, 0x99009901);
3670 test_eq(rs->or_port, 443);
3671 test_eq(rs->dir_port, 0);
3672 test_assert(!rs->is_authority);
3673 test_assert(rs->is_exit);
3674 test_assert(rs->is_fast);
3675 test_assert(rs->is_possible_guard);
3676 test_assert(rs->is_stable);
3677 test_assert(rs->is_running);
3678 test_assert(rs->is_v2_dir);
3679 test_assert(rs->is_valid);
3680 test_assert(!rs->is_named);
3681 /* XXXX check version */
3682 // x231
3683 // x213
3685 /* Check signatures. the first voter is a pseudo-entry with a legacy key.
3686 * The second one hasn't signed. The fourth one has signed: validate it. */
3687 voter = smartlist_get(con->voters, 1);
3688 test_assert(!voter->signature);
3689 test_assert(!voter->good_signature);
3690 test_assert(!voter->bad_signature);
3692 voter = smartlist_get(con->voters, 3);
3693 test_assert(voter->signature);
3694 test_assert(!voter->good_signature);
3695 test_assert(!voter->bad_signature);
3696 test_assert(!networkstatus_check_voter_signature(con,
3697 smartlist_get(con->voters, 3),
3698 cert3));
3699 test_assert(voter->signature);
3700 test_assert(voter->good_signature);
3701 test_assert(!voter->bad_signature);
3704 const char *msg=NULL;
3705 /* Compute the other two signed consensuses. */
3706 smartlist_shuffle(votes);
3707 consensus_text2 = networkstatus_compute_consensus(votes, 3,
3708 cert2->identity_key,
3709 sign_skey_2, NULL,NULL);
3710 smartlist_shuffle(votes);
3711 consensus_text3 = networkstatus_compute_consensus(votes, 3,
3712 cert1->identity_key,
3713 sign_skey_1, NULL,NULL);
3714 test_assert(consensus_text2);
3715 test_assert(consensus_text3);
3716 con2 = networkstatus_parse_vote_from_string(consensus_text2, NULL,
3717 NS_TYPE_CONSENSUS);
3718 con3 = networkstatus_parse_vote_from_string(consensus_text3, NULL,
3719 NS_TYPE_CONSENSUS);
3720 test_assert(con2);
3721 test_assert(con3);
3723 /* All three should have the same digest. */
3724 test_memeq(con->networkstatus_digest, con2->networkstatus_digest,
3725 DIGEST_LEN);
3726 test_memeq(con->networkstatus_digest, con3->networkstatus_digest,
3727 DIGEST_LEN);
3729 /* Extract a detached signature from con3. */
3730 detached_text1 = networkstatus_get_detached_signatures(con3);
3731 tor_assert(detached_text1);
3732 /* Try to parse it. */
3733 dsig1 = networkstatus_parse_detached_signatures(detached_text1, NULL);
3734 tor_assert(dsig1);
3736 /* Are parsed values as expected? */
3737 test_eq(dsig1->valid_after, con3->valid_after);
3738 test_eq(dsig1->fresh_until, con3->fresh_until);
3739 test_eq(dsig1->valid_until, con3->valid_until);
3740 test_memeq(dsig1->networkstatus_digest, con3->networkstatus_digest,
3741 DIGEST_LEN);
3742 test_eq(1, smartlist_len(dsig1->signatures));
3743 voter = smartlist_get(dsig1->signatures, 0);
3744 test_memeq(voter->identity_digest, cert1->cache_info.identity_digest,
3745 DIGEST_LEN);
3747 /* Try adding it to con2. */
3748 detached_text2 = networkstatus_get_detached_signatures(con2);
3749 test_eq(1, networkstatus_add_detached_signatures(con2, dsig1, &msg));
3750 tor_free(detached_text2);
3751 detached_text2 = networkstatus_get_detached_signatures(con2);
3752 //printf("\n<%s>\n", detached_text2);
3753 dsig2 = networkstatus_parse_detached_signatures(detached_text2, NULL);
3754 test_assert(dsig2);
3756 printf("\n");
3757 SMARTLIST_FOREACH(dsig2->signatures, networkstatus_voter_info_t *, vi, {
3758 char hd[64];
3759 base16_encode(hd, sizeof(hd), vi->identity_digest, DIGEST_LEN);
3760 printf("%s\n", hd);
3763 test_eq(2, smartlist_len(dsig2->signatures));
3765 /* Try adding to con2 twice; verify that nothing changes. */
3766 test_eq(0, networkstatus_add_detached_signatures(con2, dsig1, &msg));
3768 /* Add to con. */
3769 test_eq(2, networkstatus_add_detached_signatures(con, dsig2, &msg));
3770 /* Check signatures */
3771 test_assert(!networkstatus_check_voter_signature(con,
3772 smartlist_get(con->voters, 1),
3773 cert2));
3774 test_assert(!networkstatus_check_voter_signature(con,
3775 smartlist_get(con->voters, 2),
3776 cert1));
3780 done:
3781 smartlist_free(votes);
3782 tor_free(v1_text);
3783 tor_free(v2_text);
3784 tor_free(v3_text);
3785 tor_free(consensus_text);
3787 if (vote)
3788 networkstatus_vote_free(vote);
3789 if (v1)
3790 networkstatus_vote_free(v1);
3791 if (v2)
3792 networkstatus_vote_free(v2);
3793 if (v3)
3794 networkstatus_vote_free(v3);
3795 if (con)
3796 networkstatus_vote_free(con);
3797 if (sign_skey_1)
3798 crypto_free_pk_env(sign_skey_1);
3799 if (sign_skey_2)
3800 crypto_free_pk_env(sign_skey_2);
3801 if (sign_skey_3)
3802 crypto_free_pk_env(sign_skey_3);
3803 if (sign_skey_leg1)
3804 crypto_free_pk_env(sign_skey_leg1);
3805 if (cert1)
3806 authority_cert_free(cert1);
3807 if (cert2)
3808 authority_cert_free(cert2);
3809 if (cert3)
3810 authority_cert_free(cert3);
3812 tor_free(consensus_text2);
3813 tor_free(consensus_text3);
3814 tor_free(detached_text1);
3815 tor_free(detached_text2);
3816 if (con2)
3817 networkstatus_vote_free(con2);
3818 if (con3)
3819 networkstatus_vote_free(con3);
3820 if (dsig1)
3821 ns_detached_signatures_free(dsig1);
3822 if (dsig2)
3823 ns_detached_signatures_free(dsig2);
3826 /** Helper: Parse the exit policy string in <b>policy_str</b>, and make sure
3827 * that policies_summarize() produces the string <b>expected_summary</b> from
3828 * it. */
3829 static void
3830 test_policy_summary_helper(const char *policy_str,
3831 const char *expected_summary)
3833 config_line_t line;
3834 smartlist_t *policy = smartlist_create();
3835 char *summary = NULL;
3836 int r;
3838 line.key = (char*)"foo";
3839 line.value = (char *)policy_str;
3840 line.next = NULL;
3842 r = policies_parse_exit_policy(&line, &policy, 0, NULL);
3843 test_eq(r, 0);
3844 summary = policy_summarize(policy);
3846 test_assert(summary != NULL);
3847 test_streq(summary, expected_summary);
3849 done:
3850 tor_free(summary);
3851 if (policy)
3852 addr_policy_list_free(policy);
3855 /** Run unit tests for generating summary lines of exit policies */
3856 static void
3857 test_policies(void)
3859 int i;
3860 smartlist_t *policy = NULL, *policy2 = NULL;
3861 addr_policy_t *p;
3862 tor_addr_t tar;
3863 config_line_t line;
3864 smartlist_t *sm = NULL;
3865 char *policy_str = NULL;
3867 policy = smartlist_create();
3869 p = router_parse_addr_policy_item_from_string("reject 192.168.0.0/16:*",-1);
3870 test_assert(p != NULL);
3871 test_eq(ADDR_POLICY_REJECT, p->policy_type);
3872 tor_addr_from_ipv4h(&tar, 0xc0a80000u);
3873 test_eq(0, tor_addr_compare(&p->addr, &tar, CMP_EXACT));
3874 test_eq(16, p->maskbits);
3875 test_eq(1, p->prt_min);
3876 test_eq(65535, p->prt_max);
3878 smartlist_add(policy, p);
3880 test_assert(ADDR_POLICY_ACCEPTED ==
3881 compare_addr_to_addr_policy(0x01020304u, 2, policy));
3882 test_assert(ADDR_POLICY_PROBABLY_ACCEPTED ==
3883 compare_addr_to_addr_policy(0, 2, policy));
3884 test_assert(ADDR_POLICY_REJECTED ==
3885 compare_addr_to_addr_policy(0xc0a80102, 2, policy));
3887 policy2 = NULL;
3888 test_assert(0 == policies_parse_exit_policy(NULL, &policy2, 1, NULL));
3889 test_assert(policy2);
3891 test_assert(!exit_policy_is_general_exit(policy));
3892 test_assert(exit_policy_is_general_exit(policy2));
3893 test_assert(!exit_policy_is_general_exit(NULL));
3895 test_assert(cmp_addr_policies(policy, policy2));
3896 test_assert(cmp_addr_policies(policy, NULL));
3897 test_assert(!cmp_addr_policies(policy2, policy2));
3898 test_assert(!cmp_addr_policies(NULL, NULL));
3900 test_assert(!policy_is_reject_star(policy2));
3901 test_assert(policy_is_reject_star(policy));
3902 test_assert(policy_is_reject_star(NULL));
3904 addr_policy_list_free(policy);
3905 policy = NULL;
3907 /* make sure compacting logic works. */
3908 policy = NULL;
3909 line.key = (char*)"foo";
3910 line.value = (char*)"accept *:80,reject private:*,reject *:*";
3911 line.next = NULL;
3912 test_assert(0 == policies_parse_exit_policy(&line, &policy, 0, NULL));
3913 test_assert(policy);
3914 //test_streq(policy->string, "accept *:80");
3915 //test_streq(policy->next->string, "reject *:*");
3916 test_eq(smartlist_len(policy), 2);
3918 /* test policy summaries */
3919 /* check if we properly ignore private IP addresses */
3920 test_policy_summary_helper("reject 192.168.0.0/16:*,"
3921 "reject 0.0.0.0/8:*,"
3922 "reject 10.0.0.0/8:*,"
3923 "accept *:10-30,"
3924 "accept *:90,"
3925 "reject *:*",
3926 "accept 10-30,90");
3927 /* check all accept policies, and proper counting of rejects */
3928 test_policy_summary_helper("reject 11.0.0.0/9:80,"
3929 "reject 12.0.0.0/9:80,"
3930 "reject 13.0.0.0/9:80,"
3931 "reject 14.0.0.0/9:80,"
3932 "accept *:*", "accept 1-65535");
3933 test_policy_summary_helper("reject 11.0.0.0/9:80,"
3934 "reject 12.0.0.0/9:80,"
3935 "reject 13.0.0.0/9:80,"
3936 "reject 14.0.0.0/9:80,"
3937 "reject 15.0.0.0:81,"
3938 "accept *:*", "accept 1-65535");
3939 test_policy_summary_helper("reject 11.0.0.0/9:80,"
3940 "reject 12.0.0.0/9:80,"
3941 "reject 13.0.0.0/9:80,"
3942 "reject 14.0.0.0/9:80,"
3943 "reject 15.0.0.0:80,"
3944 "accept *:*",
3945 "reject 80");
3946 /* no exits */
3947 test_policy_summary_helper("accept 11.0.0.0/9:80,"
3948 "reject *:*",
3949 "reject 1-65535");
3950 /* port merging */
3951 test_policy_summary_helper("accept *:80,"
3952 "accept *:81,"
3953 "accept *:100-110,"
3954 "accept *:111,"
3955 "reject *:*",
3956 "accept 80-81,100-111");
3957 /* border ports */
3958 test_policy_summary_helper("accept *:1,"
3959 "accept *:3,"
3960 "accept *:65535,"
3961 "reject *:*",
3962 "accept 1,3,65535");
3963 /* holes */
3964 test_policy_summary_helper("accept *:1,"
3965 "accept *:3,"
3966 "accept *:5,"
3967 "accept *:7,"
3968 "reject *:*",
3969 "accept 1,3,5,7");
3970 test_policy_summary_helper("reject *:1,"
3971 "reject *:3,"
3972 "reject *:5,"
3973 "reject *:7,"
3974 "accept *:*",
3975 "reject 1,3,5,7");
3977 /* truncation ports */
3978 sm = smartlist_create();
3979 for (i=1; i<2000; i+=2) {
3980 char buf[POLICY_BUF_LEN];
3981 tor_snprintf(buf, sizeof(buf), "reject *:%d", i);
3982 smartlist_add(sm, tor_strdup(buf));
3984 smartlist_add(sm, tor_strdup("accept *:*"));
3985 policy_str = smartlist_join_strings(sm, ",", 0, NULL);
3986 test_policy_summary_helper( policy_str,
3987 "accept 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,"
3988 "46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,"
3989 "92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,"
3990 "130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,"
3991 "166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198,200,"
3992 "202,204,206,208,210,212,214,216,218,220,222,224,226,228,230,232,234,236,"
3993 "238,240,242,244,246,248,250,252,254,256,258,260,262,264,266,268,270,272,"
3994 "274,276,278,280,282,284,286,288,290,292,294,296,298,300,302,304,306,308,"
3995 "310,312,314,316,318,320,322,324,326,328,330,332,334,336,338,340,342,344,"
3996 "346,348,350,352,354,356,358,360,362,364,366,368,370,372,374,376,378,380,"
3997 "382,384,386,388,390,392,394,396,398,400,402,404,406,408,410,412,414,416,"
3998 "418,420,422,424,426,428,430,432,434,436,438,440,442,444,446,448,450,452,"
3999 "454,456,458,460,462,464,466,468,470,472,474,476,478,480,482,484,486,488,"
4000 "490,492,494,496,498,500,502,504,506,508,510,512,514,516,518,520,522");
4002 done:
4003 if (policy)
4004 addr_policy_list_free(policy);
4005 if (policy2)
4006 addr_policy_list_free(policy2);
4007 tor_free(policy_str);
4008 if (sm) {
4009 SMARTLIST_FOREACH(sm, char *, s, tor_free(s));
4010 smartlist_free(sm);
4014 /** Run unit tests for basic rendezvous functions. */
4015 static void
4016 test_rend_fns(void)
4018 char address1[] = "fooaddress.onion";
4019 char address2[] = "aaaaaaaaaaaaaaaa.onion";
4020 char address3[] = "fooaddress.exit";
4021 char address4[] = "www.torproject.org";
4022 rend_service_descriptor_t *d1 =
4023 tor_malloc_zero(sizeof(rend_service_descriptor_t));
4024 rend_service_descriptor_t *d2 = NULL;
4025 char *encoded = NULL;
4026 size_t len;
4027 time_t now;
4028 int i;
4029 crypto_pk_env_t *pk1 = pk_generate(0), *pk2 = pk_generate(1);
4031 /* Test unversioned (v0) descriptor */
4032 d1->pk = crypto_pk_dup_key(pk1);
4033 now = time(NULL);
4034 d1->timestamp = now;
4035 d1->version = 0;
4036 d1->intro_nodes = smartlist_create();
4037 for (i = 0; i < 3; i++) {
4038 rend_intro_point_t *intro = tor_malloc_zero(sizeof(rend_intro_point_t));
4039 intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
4040 crypto_rand(intro->extend_info->identity_digest, DIGEST_LEN);
4041 intro->extend_info->nickname[0] = '$';
4042 base16_encode(intro->extend_info->nickname+1, HEX_DIGEST_LEN+1,
4043 intro->extend_info->identity_digest, DIGEST_LEN);
4044 smartlist_add(d1->intro_nodes, intro);
4046 test_assert(! rend_encode_service_descriptor(d1, pk1, &encoded, &len));
4047 d2 = rend_parse_service_descriptor(encoded, len);
4048 test_assert(d2);
4050 test_assert(!crypto_pk_cmp_keys(d1->pk, d2->pk));
4051 test_eq(d2->timestamp, now);
4052 test_eq(d2->version, 0);
4053 test_eq(d2->protocols, 1<<2);
4054 test_eq(smartlist_len(d2->intro_nodes), 3);
4055 for (i = 0; i < 3; i++) {
4056 rend_intro_point_t *intro1 = smartlist_get(d1->intro_nodes, i);
4057 rend_intro_point_t *intro2 = smartlist_get(d2->intro_nodes, i);
4058 test_streq(intro1->extend_info->nickname,
4059 intro2->extend_info->nickname);
4062 test_assert(BAD_HOSTNAME == parse_extended_hostname(address1));
4063 test_assert(ONION_HOSTNAME == parse_extended_hostname(address2));
4064 test_assert(EXIT_HOSTNAME == parse_extended_hostname(address3));
4065 test_assert(NORMAL_HOSTNAME == parse_extended_hostname(address4));
4067 crypto_free_pk_env(pk1);
4068 crypto_free_pk_env(pk2);
4069 pk1 = pk2 = NULL;
4070 rend_service_descriptor_free(d1);
4071 rend_service_descriptor_free(d2);
4072 d1 = d2 = NULL;
4074 done:
4075 if (pk1)
4076 crypto_free_pk_env(pk1);
4077 if (pk2)
4078 crypto_free_pk_env(pk2);
4079 if (d1)
4080 rend_service_descriptor_free(d1);
4081 if (d2)
4082 rend_service_descriptor_free(d2);
4083 tor_free(encoded);
4086 /** Run AES performance benchmarks. */
4087 static void
4088 bench_aes(void)
4090 int len, i;
4091 char *b1, *b2;
4092 crypto_cipher_env_t *c;
4093 struct timeval start, end;
4094 const int iters = 100000;
4095 uint64_t nsec;
4096 c = crypto_new_cipher_env();
4097 crypto_cipher_generate_key(c);
4098 crypto_cipher_encrypt_init_cipher(c);
4099 for (len = 1; len <= 8192; len *= 2) {
4100 b1 = tor_malloc_zero(len);
4101 b2 = tor_malloc_zero(len);
4102 tor_gettimeofday(&start);
4103 for (i = 0; i < iters; ++i) {
4104 crypto_cipher_encrypt(c, b1, b2, len);
4106 tor_gettimeofday(&end);
4107 tor_free(b1);
4108 tor_free(b2);
4109 nsec = (uint64_t) tv_udiff(&start,&end);
4110 nsec *= 1000;
4111 nsec /= (iters*len);
4112 printf("%d bytes: "U64_FORMAT" nsec per byte\n", len,
4113 U64_PRINTF_ARG(nsec));
4115 crypto_free_cipher_env(c);
4118 /** Run digestmap_t performance benchmarks. */
4119 static void
4120 bench_dmap(void)
4122 smartlist_t *sl = smartlist_create();
4123 smartlist_t *sl2 = smartlist_create();
4124 struct timeval start, end, pt2, pt3, pt4;
4125 const int iters = 10000;
4126 const int elts = 4000;
4127 const int fpostests = 1000000;
4128 char d[20];
4129 int i,n=0, fp = 0;
4130 digestmap_t *dm = digestmap_new();
4131 digestset_t *ds = digestset_new(elts);
4133 for (i = 0; i < elts; ++i) {
4134 crypto_rand(d, 20);
4135 smartlist_add(sl, tor_memdup(d, 20));
4137 for (i = 0; i < elts; ++i) {
4138 crypto_rand(d, 20);
4139 smartlist_add(sl2, tor_memdup(d, 20));
4141 printf("nbits=%d\n", ds->mask+1);
4143 tor_gettimeofday(&start);
4144 for (i = 0; i < iters; ++i) {
4145 SMARTLIST_FOREACH(sl, const char *, cp, digestmap_set(dm, cp, (void*)1));
4147 tor_gettimeofday(&pt2);
4148 for (i = 0; i < iters; ++i) {
4149 SMARTLIST_FOREACH(sl, const char *, cp, digestmap_get(dm, cp));
4150 SMARTLIST_FOREACH(sl2, const char *, cp, digestmap_get(dm, cp));
4152 tor_gettimeofday(&pt3);
4153 for (i = 0; i < iters; ++i) {
4154 SMARTLIST_FOREACH(sl, const char *, cp, digestset_add(ds, cp));
4156 tor_gettimeofday(&pt4);
4157 for (i = 0; i < iters; ++i) {
4158 SMARTLIST_FOREACH(sl, const char *, cp, n += digestset_isin(ds, cp));
4159 SMARTLIST_FOREACH(sl2, const char *, cp, n += digestset_isin(ds, cp));
4161 tor_gettimeofday(&end);
4163 for (i = 0; i < fpostests; ++i) {
4164 crypto_rand(d, 20);
4165 if (digestset_isin(ds, d)) ++fp;
4168 printf("%ld\n",(unsigned long)tv_udiff(&start, &pt2));
4169 printf("%ld\n",(unsigned long)tv_udiff(&pt2, &pt3));
4170 printf("%ld\n",(unsigned long)tv_udiff(&pt3, &pt4));
4171 printf("%ld\n",(unsigned long)tv_udiff(&pt4, &end));
4172 printf("-- %d\n", n);
4173 printf("++ %f\n", fp/(double)fpostests);
4174 digestmap_free(dm, NULL);
4175 digestset_free(ds);
4176 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
4177 SMARTLIST_FOREACH(sl2, char *, cp, tor_free(cp));
4178 smartlist_free(sl);
4179 smartlist_free(sl2);
4182 /** Run unittests for memory pool allocator */
4183 static void
4184 test_util_mempool(void)
4186 mp_pool_t *pool = NULL;
4187 smartlist_t *allocated = NULL;
4188 int i;
4190 pool = mp_pool_new(1, 100);
4191 test_assert(pool);
4192 test_assert(pool->new_chunk_capacity >= 100);
4193 test_assert(pool->item_alloc_size >= sizeof(void*)+1);
4194 mp_pool_destroy(pool);
4195 pool = NULL;
4197 pool = mp_pool_new(241, 2500);
4198 test_assert(pool);
4199 test_assert(pool->new_chunk_capacity >= 10);
4200 test_assert(pool->item_alloc_size >= sizeof(void*)+241);
4201 test_eq(pool->item_alloc_size & 0x03, 0);
4202 test_assert(pool->new_chunk_capacity < 60);
4204 allocated = smartlist_create();
4205 for (i = 0; i < 20000; ++i) {
4206 if (smartlist_len(allocated) < 20 || crypto_rand_int(2)) {
4207 void *m = mp_pool_get(pool);
4208 memset(m, 0x09, 241);
4209 smartlist_add(allocated, m);
4210 //printf("%d: %p\n", i, m);
4211 //mp_pool_assert_ok(pool);
4212 } else {
4213 int idx = crypto_rand_int(smartlist_len(allocated));
4214 void *m = smartlist_get(allocated, idx);
4215 //printf("%d: free %p\n", i, m);
4216 smartlist_del(allocated, idx);
4217 mp_pool_release(m);
4218 //mp_pool_assert_ok(pool);
4220 if (crypto_rand_int(777)==0)
4221 mp_pool_clean(pool, 1, 1);
4223 if (i % 777)
4224 mp_pool_assert_ok(pool);
4227 done:
4228 if (allocated) {
4229 SMARTLIST_FOREACH(allocated, void *, m, mp_pool_release(m));
4230 mp_pool_assert_ok(pool);
4231 mp_pool_clean(pool, 0, 0);
4232 mp_pool_assert_ok(pool);
4233 smartlist_free(allocated);
4236 if (pool)
4237 mp_pool_destroy(pool);
4240 /** Run unittests for memory area allocator */
4241 static void
4242 test_util_memarea(void)
4244 memarea_t *area = memarea_new();
4245 char *p1, *p2, *p3, *p1_orig;
4246 void *malloced_ptr = NULL;
4247 int i;
4249 test_assert(area);
4251 p1_orig = p1 = memarea_alloc(area,64);
4252 p2 = memarea_alloc_zero(area,52);
4253 p3 = memarea_alloc(area,11);
4255 test_assert(memarea_owns_ptr(area, p1));
4256 test_assert(memarea_owns_ptr(area, p2));
4257 test_assert(memarea_owns_ptr(area, p3));
4258 /* Make sure we left enough space. */
4259 test_assert(p1+64 <= p2);
4260 test_assert(p2+52 <= p3);
4261 /* Make sure we aligned. */
4262 test_eq(((uintptr_t)p1) % sizeof(void*), 0);
4263 test_eq(((uintptr_t)p2) % sizeof(void*), 0);
4264 test_eq(((uintptr_t)p3) % sizeof(void*), 0);
4265 test_assert(!memarea_owns_ptr(area, p3+8192));
4266 test_assert(!memarea_owns_ptr(area, p3+30));
4267 test_assert(tor_mem_is_zero(p2, 52));
4268 /* Make sure we don't overalign. */
4269 p1 = memarea_alloc(area, 1);
4270 p2 = memarea_alloc(area, 1);
4271 test_eq(p1+sizeof(void*), p2);
4273 malloced_ptr = tor_malloc(64);
4274 test_assert(!memarea_owns_ptr(area, malloced_ptr));
4275 tor_free(malloced_ptr);
4278 /* memarea_memdup */
4280 malloced_ptr = tor_malloc(64);
4281 crypto_rand((char*)malloced_ptr, 64);
4282 p1 = memarea_memdup(area, malloced_ptr, 64);
4283 test_assert(p1 != malloced_ptr);
4284 test_memeq(p1, malloced_ptr, 64);
4285 tor_free(malloced_ptr);
4288 /* memarea_strdup. */
4289 p1 = memarea_strdup(area,"");
4290 p2 = memarea_strdup(area, "abcd");
4291 test_assert(p1);
4292 test_assert(p2);
4293 test_streq(p1, "");
4294 test_streq(p2, "abcd");
4296 /* memarea_strndup. */
4298 const char *s = "Ad ogni porta batte la morte e grida: il nome!";
4299 /* (From Turandot, act 3.) */
4300 size_t len = strlen(s);
4301 p1 = memarea_strndup(area, s, 1000);
4302 p2 = memarea_strndup(area, s, 10);
4303 test_streq(p1, s);
4304 test_assert(p2 >= p1 + len + 1);
4305 test_memeq(s, p2, 10);
4306 test_eq(p2[10], '\0');
4307 p3 = memarea_strndup(area, s, len);
4308 test_streq(p3, s);
4309 p3 = memarea_strndup(area, s, len-1);
4310 test_memeq(s, p3, len-1);
4311 test_eq(p3[len-1], '\0');
4314 memarea_clear(area);
4315 p1 = memarea_alloc(area, 1);
4316 test_eq(p1, p1_orig);
4317 memarea_clear(area);
4319 /* Check for running over an area's size. */
4320 for (i = 0; i < 512; ++i) {
4321 p1 = memarea_alloc(area, crypto_rand_int(5)+1);
4322 test_assert(memarea_owns_ptr(area, p1));
4324 memarea_assert_ok(area);
4325 /* Make sure we can allocate a too-big object. */
4326 p1 = memarea_alloc_zero(area, 9000);
4327 p2 = memarea_alloc_zero(area, 16);
4328 test_assert(memarea_owns_ptr(area, p1));
4329 test_assert(memarea_owns_ptr(area, p2));
4331 done:
4332 memarea_drop_all(area);
4333 tor_free(malloced_ptr);
4336 /** Run unit tests for utility functions to get file names relative to
4337 * the data directory. */
4338 static void
4339 test_util_datadir(void)
4341 char buf[1024];
4342 char *f = NULL;
4344 f = get_datadir_fname(NULL);
4345 test_streq(f, temp_dir);
4346 tor_free(f);
4347 f = get_datadir_fname("state");
4348 tor_snprintf(buf, sizeof(buf), "%s"PATH_SEPARATOR"state", temp_dir);
4349 test_streq(f, buf);
4350 tor_free(f);
4351 f = get_datadir_fname2("cache", "thingy");
4352 tor_snprintf(buf, sizeof(buf),
4353 "%s"PATH_SEPARATOR"cache"PATH_SEPARATOR"thingy", temp_dir);
4354 test_streq(f, buf);
4355 tor_free(f);
4356 f = get_datadir_fname2_suffix("cache", "thingy", ".foo");
4357 tor_snprintf(buf, sizeof(buf),
4358 "%s"PATH_SEPARATOR"cache"PATH_SEPARATOR"thingy.foo", temp_dir);
4359 test_streq(f, buf);
4360 tor_free(f);
4361 f = get_datadir_fname_suffix("cache", ".foo");
4362 tor_snprintf(buf, sizeof(buf), "%s"PATH_SEPARATOR"cache.foo",
4363 temp_dir);
4364 test_streq(f, buf);
4366 done:
4367 tor_free(f);
4370 /** Test AES-CTR encryption and decryption with IV. */
4371 static void
4372 test_crypto_aes_iv(void)
4374 crypto_cipher_env_t *cipher;
4375 char *plain, *encrypted1, *encrypted2, *decrypted1, *decrypted2;
4376 char plain_1[1], plain_15[15], plain_16[16], plain_17[17];
4377 char key1[16], key2[16];
4378 ssize_t encrypted_size, decrypted_size;
4380 plain = tor_malloc(4095);
4381 encrypted1 = tor_malloc(4095 + 1 + 16);
4382 encrypted2 = tor_malloc(4095 + 1 + 16);
4383 decrypted1 = tor_malloc(4095 + 1);
4384 decrypted2 = tor_malloc(4095 + 1);
4386 crypto_rand(plain, 4095);
4387 crypto_rand(key1, 16);
4388 crypto_rand(key2, 16);
4389 crypto_rand(plain_1, 1);
4390 crypto_rand(plain_15, 15);
4391 crypto_rand(plain_16, 16);
4392 crypto_rand(plain_17, 17);
4393 key1[0] = key2[0] + 128; /* Make sure that contents are different. */
4394 /* Encrypt and decrypt with the same key. */
4395 cipher = crypto_create_init_cipher(key1, 1);
4396 encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 4095,
4397 plain, 4095);
4398 crypto_free_cipher_env(cipher);
4399 cipher = NULL;
4400 test_eq(encrypted_size, 16 + 4095);
4401 tor_assert(encrypted_size > 0); /* This is obviously true, since 4111 is
4402 * greater than 0, but its truth is not
4403 * obvious to all analysis tools. */
4404 cipher = crypto_create_init_cipher(key1, 0);
4405 decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 4095,
4406 encrypted1, encrypted_size);
4407 crypto_free_cipher_env(cipher);
4408 cipher = NULL;
4409 test_eq(decrypted_size, 4095);
4410 tor_assert(decrypted_size > 0);
4411 test_memeq(plain, decrypted1, 4095);
4412 /* Encrypt a second time (with a new random initialization vector). */
4413 cipher = crypto_create_init_cipher(key1, 1);
4414 encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted2, 16 + 4095,
4415 plain, 4095);
4416 crypto_free_cipher_env(cipher);
4417 cipher = NULL;
4418 test_eq(encrypted_size, 16 + 4095);
4419 tor_assert(encrypted_size > 0);
4420 cipher = crypto_create_init_cipher(key1, 0);
4421 decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted2, 4095,
4422 encrypted2, encrypted_size);
4423 crypto_free_cipher_env(cipher);
4424 cipher = NULL;
4425 test_eq(decrypted_size, 4095);
4426 tor_assert(decrypted_size > 0);
4427 test_memeq(plain, decrypted2, 4095);
4428 test_memneq(encrypted1, encrypted2, encrypted_size);
4429 /* Decrypt with the wrong key. */
4430 cipher = crypto_create_init_cipher(key2, 0);
4431 decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted2, 4095,
4432 encrypted1, encrypted_size);
4433 crypto_free_cipher_env(cipher);
4434 cipher = NULL;
4435 test_memneq(plain, decrypted2, encrypted_size);
4436 /* Alter the initialization vector. */
4437 encrypted1[0] += 42;
4438 cipher = crypto_create_init_cipher(key1, 0);
4439 decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 4095,
4440 encrypted1, encrypted_size);
4441 crypto_free_cipher_env(cipher);
4442 cipher = NULL;
4443 test_memneq(plain, decrypted2, 4095);
4444 /* Special length case: 1. */
4445 cipher = crypto_create_init_cipher(key1, 1);
4446 encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 1,
4447 plain_1, 1);
4448 crypto_free_cipher_env(cipher);
4449 cipher = NULL;
4450 test_eq(encrypted_size, 16 + 1);
4451 tor_assert(encrypted_size > 0);
4452 cipher = crypto_create_init_cipher(key1, 0);
4453 decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 1,
4454 encrypted1, encrypted_size);
4455 crypto_free_cipher_env(cipher);
4456 cipher = NULL;
4457 test_eq(decrypted_size, 1);
4458 tor_assert(decrypted_size > 0);
4459 test_memeq(plain_1, decrypted1, 1);
4460 /* Special length case: 15. */
4461 cipher = crypto_create_init_cipher(key1, 1);
4462 encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 15,
4463 plain_15, 15);
4464 crypto_free_cipher_env(cipher);
4465 cipher = NULL;
4466 test_eq(encrypted_size, 16 + 15);
4467 tor_assert(encrypted_size > 0);
4468 cipher = crypto_create_init_cipher(key1, 0);
4469 decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 15,
4470 encrypted1, encrypted_size);
4471 crypto_free_cipher_env(cipher);
4472 cipher = NULL;
4473 test_eq(decrypted_size, 15);
4474 tor_assert(decrypted_size > 0);
4475 test_memeq(plain_15, decrypted1, 15);
4476 /* Special length case: 16. */
4477 cipher = crypto_create_init_cipher(key1, 1);
4478 encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 16,
4479 plain_16, 16);
4480 crypto_free_cipher_env(cipher);
4481 cipher = NULL;
4482 test_eq(encrypted_size, 16 + 16);
4483 tor_assert(encrypted_size > 0);
4484 cipher = crypto_create_init_cipher(key1, 0);
4485 decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 16,
4486 encrypted1, encrypted_size);
4487 crypto_free_cipher_env(cipher);
4488 cipher = NULL;
4489 test_eq(decrypted_size, 16);
4490 tor_assert(decrypted_size > 0);
4491 test_memeq(plain_16, decrypted1, 16);
4492 /* Special length case: 17. */
4493 cipher = crypto_create_init_cipher(key1, 1);
4494 encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 17,
4495 plain_17, 17);
4496 crypto_free_cipher_env(cipher);
4497 cipher = NULL;
4498 test_eq(encrypted_size, 16 + 17);
4499 tor_assert(encrypted_size > 0);
4500 cipher = crypto_create_init_cipher(key1, 0);
4501 decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 17,
4502 encrypted1, encrypted_size);
4503 test_eq(decrypted_size, 17);
4504 tor_assert(decrypted_size > 0);
4505 test_memeq(plain_17, decrypted1, 17);
4507 done:
4508 /* Free memory. */
4509 tor_free(plain);
4510 tor_free(encrypted1);
4511 tor_free(encrypted2);
4512 tor_free(decrypted1);
4513 tor_free(decrypted2);
4514 if (cipher)
4515 crypto_free_cipher_env(cipher);
4518 /** Test base32 decoding. */
4519 static void
4520 test_crypto_base32_decode(void)
4522 char plain[60], encoded[96 + 1], decoded[60];
4523 int res;
4524 crypto_rand(plain, 60);
4525 /* Encode and decode a random string. */
4526 base32_encode(encoded, 96 + 1, plain, 60);
4527 res = base32_decode(decoded, 60, encoded, 96);
4528 test_eq(res, 0);
4529 test_memeq(plain, decoded, 60);
4530 /* Encode, uppercase, and decode a random string. */
4531 base32_encode(encoded, 96 + 1, plain, 60);
4532 tor_strupper(encoded);
4533 res = base32_decode(decoded, 60, encoded, 96);
4534 test_eq(res, 0);
4535 test_memeq(plain, decoded, 60);
4536 /* Change encoded string and decode. */
4537 if (encoded[0] == 'A' || encoded[0] == 'a')
4538 encoded[0] = 'B';
4539 else
4540 encoded[0] = 'A';
4541 res = base32_decode(decoded, 60, encoded, 96);
4542 test_eq(res, 0);
4543 test_memneq(plain, decoded, 60);
4544 /* Bad encodings. */
4545 encoded[0] = '!';
4546 res = base32_decode(decoded, 60, encoded, 96);
4547 test_assert(res < 0);
4549 done:
4553 /** Test encoding and parsing of v2 rendezvous service descriptors. */
4554 static void
4555 test_rend_fns_v2(void)
4557 rend_service_descriptor_t *generated = NULL, *parsed = NULL;
4558 char service_id[DIGEST_LEN];
4559 char service_id_base32[REND_SERVICE_ID_LEN_BASE32+1];
4560 const char *next_desc;
4561 smartlist_t *descs = smartlist_create();
4562 char computed_desc_id[DIGEST_LEN];
4563 char parsed_desc_id[DIGEST_LEN];
4564 crypto_pk_env_t *pk1 = NULL, *pk2 = NULL;
4565 time_t now;
4566 char *intro_points_encrypted = NULL;
4567 size_t intro_points_size;
4568 size_t encoded_size;
4569 int i;
4570 pk1 = pk_generate(0);
4571 pk2 = pk_generate(1);
4572 generated = tor_malloc_zero(sizeof(rend_service_descriptor_t));
4573 generated->pk = crypto_pk_dup_key(pk1);
4574 crypto_pk_get_digest(generated->pk, service_id);
4575 base32_encode(service_id_base32, REND_SERVICE_ID_LEN_BASE32+1,
4576 service_id, REND_SERVICE_ID_LEN);
4577 now = time(NULL);
4578 generated->timestamp = now;
4579 generated->version = 2;
4580 generated->protocols = 42;
4581 generated->intro_nodes = smartlist_create();
4583 for (i = 0; i < 3; i++) {
4584 rend_intro_point_t *intro = tor_malloc_zero(sizeof(rend_intro_point_t));
4585 crypto_pk_env_t *okey = pk_generate(2 + i);
4586 intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
4587 intro->extend_info->onion_key = okey;
4588 crypto_pk_get_digest(intro->extend_info->onion_key,
4589 intro->extend_info->identity_digest);
4590 //crypto_rand(info->identity_digest, DIGEST_LEN); /* Would this work? */
4591 intro->extend_info->nickname[0] = '$';
4592 base16_encode(intro->extend_info->nickname + 1,
4593 sizeof(intro->extend_info->nickname) - 1,
4594 intro->extend_info->identity_digest, DIGEST_LEN);
4595 /* Does not cover all IP addresses. */
4596 tor_addr_from_ipv4h(&intro->extend_info->addr, crypto_rand_int(65536));
4597 intro->extend_info->port = crypto_rand_int(65536);
4598 intro->intro_key = crypto_pk_dup_key(pk2);
4599 smartlist_add(generated->intro_nodes, intro);
4601 test_assert(rend_encode_v2_descriptors(descs, generated, now, 0,
4602 REND_NO_AUTH, NULL, NULL) > 0);
4603 test_assert(rend_compute_v2_desc_id(computed_desc_id, service_id_base32,
4604 NULL, now, 0) == 0);
4605 test_memeq(((rend_encoded_v2_service_descriptor_t *)
4606 smartlist_get(descs, 0))->desc_id, computed_desc_id, DIGEST_LEN);
4607 test_assert(rend_parse_v2_service_descriptor(&parsed, parsed_desc_id,
4608 &intro_points_encrypted,
4609 &intro_points_size,
4610 &encoded_size,
4611 &next_desc,
4612 ((rend_encoded_v2_service_descriptor_t *)
4613 smartlist_get(descs, 0))->desc_str) == 0);
4614 test_assert(parsed);
4615 test_memeq(((rend_encoded_v2_service_descriptor_t *)
4616 smartlist_get(descs, 0))->desc_id, parsed_desc_id, DIGEST_LEN);
4617 test_eq(rend_parse_introduction_points(parsed, intro_points_encrypted,
4618 intro_points_size), 3);
4619 test_assert(!crypto_pk_cmp_keys(generated->pk, parsed->pk));
4620 test_eq(parsed->timestamp, now);
4621 test_eq(parsed->version, 2);
4622 test_eq(parsed->protocols, 42);
4623 test_eq(smartlist_len(parsed->intro_nodes), 3);
4624 for (i = 0; i < smartlist_len(parsed->intro_nodes); i++) {
4625 rend_intro_point_t *par_intro = smartlist_get(parsed->intro_nodes, i),
4626 *gen_intro = smartlist_get(generated->intro_nodes, i);
4627 extend_info_t *par_info = par_intro->extend_info;
4628 extend_info_t *gen_info = gen_intro->extend_info;
4629 test_assert(!crypto_pk_cmp_keys(gen_info->onion_key, par_info->onion_key));
4630 test_memeq(gen_info->identity_digest, par_info->identity_digest,
4631 DIGEST_LEN);
4632 test_streq(gen_info->nickname, par_info->nickname);
4633 test_assert(tor_addr_eq(&gen_info->addr, &par_info->addr));
4634 test_eq(gen_info->port, par_info->port);
4637 rend_service_descriptor_free(parsed);
4638 rend_service_descriptor_free(generated);
4639 parsed = generated = NULL;
4641 done:
4642 if (descs) {
4643 for (i = 0; i < smartlist_len(descs); i++)
4644 rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
4645 smartlist_free(descs);
4647 if (parsed)
4648 rend_service_descriptor_free(parsed);
4649 if (generated)
4650 rend_service_descriptor_free(generated);
4651 if (pk1)
4652 crypto_free_pk_env(pk1);
4653 if (pk2)
4654 crypto_free_pk_env(pk2);
4655 tor_free(intro_points_encrypted);
4658 /** Run unit tests for GeoIP code. */
4659 static void
4660 test_geoip(void)
4662 int i, j;
4663 time_t now = time(NULL);
4664 char *s = NULL;
4666 /* Populate the DB a bit. Add these in order, since we can't do the final
4667 * 'sort' step. These aren't very good IP addresses, but they're perfectly
4668 * fine uint32_t values. */
4669 test_eq(0, geoip_parse_entry("10,50,AB"));
4670 test_eq(0, geoip_parse_entry("52,90,XY"));
4671 test_eq(0, geoip_parse_entry("95,100,AB"));
4672 test_eq(0, geoip_parse_entry("\"105\",\"140\",\"ZZ\""));
4673 test_eq(0, geoip_parse_entry("\"150\",\"190\",\"XY\""));
4674 test_eq(0, geoip_parse_entry("\"200\",\"250\",\"AB\""));
4676 /* We should have 3 countries: ab, xy, zz. */
4677 test_eq(3, geoip_get_n_countries());
4678 /* Make sure that country ID actually works. */
4679 #define NAMEFOR(x) geoip_get_country_name(geoip_get_country_by_ip(x))
4680 test_streq("ab", NAMEFOR(32));
4681 test_streq("??", NAMEFOR(5));
4682 test_streq("??", NAMEFOR(51));
4683 test_streq("xy", NAMEFOR(150));
4684 test_streq("xy", NAMEFOR(190));
4685 test_streq("??", NAMEFOR(2000));
4686 #undef NAMEFOR
4688 get_options()->BridgeRelay = 1;
4689 get_options()->BridgeRecordUsageByCountry = 1;
4690 /* Put 9 observations in AB... */
4691 for (i=32; i < 40; ++i)
4692 geoip_note_client_seen(GEOIP_CLIENT_CONNECT, i, now-7200);
4693 geoip_note_client_seen(GEOIP_CLIENT_CONNECT, 225, now-7200);
4694 /* and 3 observations in XY, several times. */
4695 for (j=0; j < 10; ++j)
4696 for (i=52; i < 55; ++i)
4697 geoip_note_client_seen(GEOIP_CLIENT_CONNECT, i, now-3600);
4698 /* and 17 observations in ZZ... */
4699 for (i=110; i < 127; ++i)
4700 geoip_note_client_seen(GEOIP_CLIENT_CONNECT, i, now);
4701 s = geoip_get_client_history(now+5*24*60*60, GEOIP_CLIENT_CONNECT);
4702 test_assert(s);
4703 test_streq("zz=24,ab=16,xy=8", s);
4704 tor_free(s);
4706 /* Now clear out all the AB observations. */
4707 geoip_remove_old_clients(now-6000);
4708 s = geoip_get_client_history(now+5*24*60*60, GEOIP_CLIENT_CONNECT);
4709 test_assert(s);
4710 test_streq("zz=24,xy=8", s);
4712 done:
4713 tor_free(s);
4716 /** For test_array. Declare an CLI-invocable off-by-default function in the
4717 * unit tests, with function name and user-visible name <b>x</b>*/
4718 #define DISABLED(x) { #x, x, 0, 0, 0 }
4719 /** For test_array. Declare an CLI-invocable unit test function, with function
4720 * name test_<b>x</b>(), and user-visible name <b>x</b> */
4721 #define ENT(x) { #x, test_ ## x, 0, 0, 1 }
4722 /** For test_array. Declare an CLI-invocable unit test function, with function
4723 * name test_<b>x</b>_<b>y</b>(), and user-visible name
4724 * <b>x</b>/<b>y</b>. This function will be treated as a subentry of <b>x</b>,
4725 * so that invoking <b>x</b> from the CLI invokes this test too. */
4726 #define SUBENT(x,y) { #x "/" #y, test_ ## x ## _ ## y, 1, 0, 1 }
4728 /** An array of functions and information for all the unit tests we can run. */
4729 static struct {
4730 const char *test_name; /**< How does the user refer to this test from the
4731 * command line? */
4732 void (*test_fn)(void); /**< What function is called to run this test? */
4733 int is_subent; /**< Is this a subentry of a bigger set of related tests? */
4734 int selected; /**< Are we planning to run this one? */
4735 int is_default; /**< If the user doesn't say what tests they want, do they
4736 * get this function by default? */
4737 } test_array[] = {
4738 ENT(buffers),
4739 ENT(crypto),
4740 SUBENT(crypto, rng),
4741 SUBENT(crypto, aes),
4742 SUBENT(crypto, sha),
4743 SUBENT(crypto, pk),
4744 SUBENT(crypto, dh),
4745 SUBENT(crypto, s2k),
4746 SUBENT(crypto, aes_iv),
4747 SUBENT(crypto, base32_decode),
4748 ENT(util),
4749 SUBENT(util, ip6_helpers),
4750 SUBENT(util, gzip),
4751 SUBENT(util, datadir),
4752 SUBENT(util, smartlist_basic),
4753 SUBENT(util, smartlist_strings),
4754 SUBENT(util, smartlist_overlap),
4755 SUBENT(util, smartlist_digests),
4756 SUBENT(util, smartlist_join),
4757 SUBENT(util, bitarray),
4758 SUBENT(util, digestset),
4759 SUBENT(util, mempool),
4760 SUBENT(util, memarea),
4761 SUBENT(util, strmap),
4762 SUBENT(util, control_formats),
4763 SUBENT(util, pqueue),
4764 SUBENT(util, mmap),
4765 SUBENT(util, threads),
4766 SUBENT(util, order_functions),
4767 SUBENT(util, sscanf),
4768 ENT(onion_handshake),
4769 ENT(dir_format),
4770 ENT(dirutil),
4771 ENT(v3_networkstatus),
4772 ENT(policies),
4773 ENT(rend_fns),
4774 SUBENT(rend_fns, v2),
4775 ENT(geoip),
4777 DISABLED(bench_aes),
4778 DISABLED(bench_dmap),
4779 { NULL, NULL, 0, 0, 0 },
4782 static void syntax(void) ATTR_NORETURN;
4784 /** Print a syntax usage message, and exit.*/
4785 static void
4786 syntax(void)
4788 int i;
4789 printf("Syntax:\n"
4790 " test [-v|--verbose] [--warn|--notice|--info|--debug]\n"
4791 " [testname...]\n"
4792 "Recognized tests are:\n");
4793 for (i = 0; test_array[i].test_name; ++i) {
4794 printf(" %s\n", test_array[i].test_name);
4797 exit(0);
4800 /** Main entry point for unit test code: parse the command line, and run
4801 * some unit tests. */
4803 main(int c, char**v)
4805 or_options_t *options;
4806 char *errmsg = NULL;
4807 int i;
4808 int verbose = 0, any_selected = 0;
4809 int loglevel = LOG_ERR;
4811 #ifdef USE_DMALLOC
4813 int r = CRYPTO_set_mem_ex_functions(_tor_malloc, _tor_realloc, _tor_free);
4814 tor_assert(r);
4816 #endif
4818 update_approx_time(time(NULL));
4819 options = options_new();
4820 tor_threads_init();
4821 init_logging();
4823 for (i = 1; i < c; ++i) {
4824 if (!strcmp(v[i], "-v") || !strcmp(v[i], "--verbose"))
4825 verbose++;
4826 else if (!strcmp(v[i], "--warn"))
4827 loglevel = LOG_WARN;
4828 else if (!strcmp(v[i], "--notice"))
4829 loglevel = LOG_NOTICE;
4830 else if (!strcmp(v[i], "--info"))
4831 loglevel = LOG_INFO;
4832 else if (!strcmp(v[i], "--debug"))
4833 loglevel = LOG_DEBUG;
4834 else if (!strcmp(v[i], "--help") || !strcmp(v[i], "-h") || v[i][0] == '-')
4835 syntax();
4836 else {
4837 int j, found=0;
4838 for (j = 0; test_array[j].test_name; ++j) {
4839 if (!strcmp(v[i], test_array[j].test_name) ||
4840 (test_array[j].is_subent &&
4841 !strcmpstart(test_array[j].test_name, v[i]) &&
4842 test_array[j].test_name[strlen(v[i])] == '/') ||
4843 (v[i][0] == '=' && !strcmp(v[i]+1, test_array[j].test_name))) {
4844 test_array[j].selected = 1;
4845 any_selected = 1;
4846 found = 1;
4849 if (!found) {
4850 printf("Unknown test: %s\n", v[i]);
4851 syntax();
4856 if (!any_selected) {
4857 for (i = 0; test_array[i].test_name; ++i) {
4858 test_array[i].selected = test_array[i].is_default;
4863 log_severity_list_t s;
4864 memset(&s, 0, sizeof(s));
4865 set_log_severity_config(loglevel, LOG_ERR, &s);
4866 add_stream_log(&s, "", fileno(stdout));
4869 options->command = CMD_RUN_UNITTESTS;
4870 crypto_global_init(0);
4871 rep_hist_init();
4872 network_init();
4873 setup_directory();
4874 options_init(options);
4875 options->DataDirectory = tor_strdup(temp_dir);
4876 if (set_options(options, &errmsg) < 0) {
4877 printf("Failed to set initial options: %s\n", errmsg);
4878 tor_free(errmsg);
4879 return 1;
4882 crypto_seed_rng(1);
4884 atexit(remove_directory);
4886 printf("Running Tor unit tests on %s\n", get_uname());
4888 for (i = 0; test_array[i].test_name; ++i) {
4889 if (!test_array[i].selected)
4890 continue;
4891 if (!test_array[i].is_subent) {
4892 printf("\n============================== %s\n",test_array[i].test_name);
4893 } else if (test_array[i].is_subent && verbose) {
4894 printf("\n%s", test_array[i].test_name);
4896 test_array[i].test_fn();
4898 puts("");
4900 free_pregenerated_keys();
4901 #ifdef USE_DMALLOC
4902 tor_free_all(0);
4903 dmalloc_log_unfreed();
4904 #endif
4906 if (have_failed)
4907 return 1;
4908 else
4909 return 0;