Clean up a bit of C logic, and fix an erroneous warning.
[tor/rransom.git] / src / or / test.c
blob7b7411e2f85635003d92a49847b4dcc125e6269f
1 /* Copyright (c) 2001-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2009, 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 int 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 /* now make sure time works. */
1298 tor_gettimeofday(&end);
1299 /* We might've timewarped a little. */
1300 test_assert(tv_udiff(&start, &end) >= -5000);
1302 /* Test tor_log2(). */
1303 test_eq(tor_log2(64), 6);
1304 test_eq(tor_log2(65), 6);
1305 test_eq(tor_log2(63), 5);
1306 test_eq(tor_log2(1), 0);
1307 test_eq(tor_log2(2), 1);
1308 test_eq(tor_log2(3), 1);
1309 test_eq(tor_log2(4), 2);
1310 test_eq(tor_log2(5), 2);
1311 test_eq(tor_log2(U64_LITERAL(40000000000000000)), 55);
1312 test_eq(tor_log2(UINT64_MAX), 63);
1314 /* Test round_to_power_of_2 */
1315 test_eq(round_to_power_of_2(120), 128);
1316 test_eq(round_to_power_of_2(128), 128);
1317 test_eq(round_to_power_of_2(130), 128);
1318 test_eq(round_to_power_of_2(U64_LITERAL(40000000000000000)),
1319 U64_LITERAL(1)<<55);
1320 test_eq(round_to_power_of_2(0), 2);
1322 done:
1326 /** Helper: assert that IPv6 addresses <b>a</b> and <b>b</b> are the same. On
1327 * failure, reports an error, describing the addresses as <b>e1</b> and
1328 * <b>e2</b>, and reporting the line number as <b>line</b>. */
1329 static void
1330 _test_eq_ip6(struct in6_addr *a, struct in6_addr *b, const char *e1,
1331 const char *e2, int line)
1333 int i;
1334 int ok = 1;
1335 for (i = 0; i < 16; ++i) {
1336 if (a->s6_addr[i] != b->s6_addr[i]) {
1337 ok = 0;
1338 break;
1341 if (ok) {
1342 printf("."); fflush(stdout);
1343 } else {
1344 char buf1[128], *cp1;
1345 char buf2[128], *cp2;
1346 have_failed = 1;
1347 cp1 = buf1; cp2 = buf2;
1348 for (i=0; i<16; ++i) {
1349 tor_snprintf(cp1, sizeof(buf1)-(cp1-buf1), "%02x", a->s6_addr[i]);
1350 tor_snprintf(cp2, sizeof(buf2)-(cp2-buf2), "%02x", b->s6_addr[i]);
1351 cp1 += 2; cp2 += 2;
1352 if ((i%2)==1 && i != 15) {
1353 *cp1++ = ':';
1354 *cp2++ = ':';
1357 *cp1 = *cp2 = '\0';
1358 printf("Line %d: assertion failed: (%s == %s)\n"
1359 " %s != %s\n", line, e1, e2, buf1, buf2);
1360 fflush(stdout);
1364 /** Helper: Assert that two strings both decode as IPv6 addresses with
1365 * tor_inet_pton(), and both decode to the same address. */
1366 #define test_pton6_same(a,b) STMT_BEGIN \
1367 test_eq(tor_inet_pton(AF_INET6, a, &a1), 1); \
1368 test_eq(tor_inet_pton(AF_INET6, b, &a2), 1); \
1369 _test_eq_ip6(&a1,&a2,#a,#b,__LINE__); \
1370 STMT_END
1372 /** Helper: Assert that <b>a</b> is recognized as a bad IPv6 address by
1373 * tor_inet_pton(). */
1374 #define test_pton6_bad(a) \
1375 test_eq(0, tor_inet_pton(AF_INET6, a, &a1))
1377 /** Helper: assert that <b>a</b>, when parsed by tor_inet_pton() and displayed
1378 * with tor_inet_ntop(), yields <b>b</b>. Also assert that <b>b</b> parses to
1379 * the same value as <b>a</b>. */
1380 #define test_ntop6_reduces(a,b) STMT_BEGIN \
1381 test_eq(tor_inet_pton(AF_INET6, a, &a1), 1); \
1382 test_streq(tor_inet_ntop(AF_INET6, &a1, buf, sizeof(buf)), b); \
1383 test_eq(tor_inet_pton(AF_INET6, b, &a2), 1); \
1384 _test_eq_ip6(&a1, &a2, a, b, __LINE__); \
1385 STMT_END
1387 /** Helper: assert that <b>a</b> parses by tor_inet_pton() into a address that
1388 * passes tor_addr_is_internal() with <b>for_listening</b>. */
1389 #define test_internal_ip(a,for_listening) STMT_BEGIN \
1390 test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
1391 t1.family = AF_INET6; \
1392 if (!tor_addr_is_internal(&t1, for_listening)) \
1393 test_fail_msg( a "was not internal."); \
1394 STMT_END
1396 /** Helper: assert that <b>a</b> parses by tor_inet_pton() into a address that
1397 * does not pass tor_addr_is_internal() with <b>for_listening</b>. */
1398 #define test_external_ip(a,for_listening) STMT_BEGIN \
1399 test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
1400 t1.family = AF_INET6; \
1401 if (tor_addr_is_internal(&t1, for_listening)) \
1402 test_fail_msg(a "was not external."); \
1403 STMT_END
1405 /** Helper: Assert that <b>a</b> and <b>b</b>, when parsed by
1406 * tor_inet_pton(), give addresses that compare in the order defined by
1407 * <b>op</b> with tor_addr_compare(). */
1408 #define test_addr_compare(a, op, b) STMT_BEGIN \
1409 test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
1410 test_eq(tor_inet_pton(AF_INET6, b, &t2.addr.in6_addr), 1); \
1411 t1.family = t2.family = AF_INET6; \
1412 r = tor_addr_compare(&t1,&t2,CMP_SEMANTIC); \
1413 if (!(r op 0)) \
1414 test_fail_msg("failed: tor_addr_compare("a","b") "#op" 0"); \
1415 STMT_END
1417 /** Helper: Assert that <b>a</b> and <b>b</b>, when parsed by
1418 * tor_inet_pton(), give addresses that compare in the order defined by
1419 * <b>op</b> with tor_addr_compare_masked() with <b>m</b> masked. */
1420 #define test_addr_compare_masked(a, op, b, m) STMT_BEGIN \
1421 test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
1422 test_eq(tor_inet_pton(AF_INET6, b, &t2.addr.in6_addr), 1); \
1423 t1.family = t2.family = AF_INET6; \
1424 r = tor_addr_compare_masked(&t1,&t2,m,CMP_SEMANTIC); \
1425 if (!(r op 0)) \
1426 test_fail_msg("failed: tor_addr_compare_masked("a","b","#m") "#op" 0"); \
1427 STMT_END
1429 /** Helper: assert that <b>xx</b> is parseable as a masked IPv6 address with
1430 * ports by tor_parse_mask_addr_ports(), with family <b>f</b>, IP address
1431 * as 4 32-bit words <b>ip1...ip4</b>, mask bits as <b>mm</b>, and port range
1432 * as <b>pt1..pt2</b>. */
1433 #define test_addr_mask_ports_parse(xx, f, ip1, ip2, ip3, ip4, mm, pt1, pt2) \
1434 STMT_BEGIN \
1435 test_eq(tor_addr_parse_mask_ports(xx, &t1, &mask, &port1, &port2), f); \
1436 p1=tor_inet_ntop(AF_INET6, &t1.addr.in6_addr, bug, sizeof(bug)); \
1437 test_eq(htonl(ip1), tor_addr_to_in6_addr32(&t1)[0]); \
1438 test_eq(htonl(ip2), tor_addr_to_in6_addr32(&t1)[1]); \
1439 test_eq(htonl(ip3), tor_addr_to_in6_addr32(&t1)[2]); \
1440 test_eq(htonl(ip4), tor_addr_to_in6_addr32(&t1)[3]); \
1441 test_eq(mask, mm); \
1442 test_eq(port1, pt1); \
1443 test_eq(port2, pt2); \
1444 STMT_END
1446 /** Run unit tests for IPv6 encoding/decoding/manipulation functions. */
1447 static void
1448 test_util_ip6_helpers(void)
1450 char buf[TOR_ADDR_BUF_LEN], bug[TOR_ADDR_BUF_LEN];
1451 struct in6_addr a1, a2;
1452 tor_addr_t t1, t2;
1453 int r, i;
1454 uint16_t port1, port2;
1455 maskbits_t mask;
1456 const char *p1;
1457 struct sockaddr_storage sa_storage;
1458 struct sockaddr_in *sin;
1459 struct sockaddr_in6 *sin6;
1461 // struct in_addr b1, b2;
1462 /* Test tor_inet_ntop and tor_inet_pton: IPv6 */
1464 /* ==== Converting to and from sockaddr_t. */
1465 sin = (struct sockaddr_in *)&sa_storage;
1466 sin->sin_family = AF_INET;
1467 sin->sin_port = 9090;
1468 sin->sin_addr.s_addr = htonl(0x7f7f0102); /*127.127.1.2*/
1469 tor_addr_from_sockaddr(&t1, (struct sockaddr *)sin, NULL);
1470 test_eq(tor_addr_family(&t1), AF_INET);
1471 test_eq(tor_addr_to_ipv4h(&t1), 0x7f7f0102);
1473 memset(&sa_storage, 0, sizeof(sa_storage));
1474 test_eq(sizeof(struct sockaddr_in),
1475 tor_addr_to_sockaddr(&t1, 1234, (struct sockaddr *)&sa_storage,
1476 sizeof(sa_storage)));
1477 test_eq(1234, ntohs(sin->sin_port));
1478 test_eq(0x7f7f0102, ntohl(sin->sin_addr.s_addr));
1480 memset(&sa_storage, 0, sizeof(sa_storage));
1481 sin6 = (struct sockaddr_in6 *)&sa_storage;
1482 sin6->sin6_family = AF_INET6;
1483 sin6->sin6_port = htons(7070);
1484 sin6->sin6_addr.s6_addr[0] = 128;
1485 tor_addr_from_sockaddr(&t1, (struct sockaddr *)sin6, NULL);
1486 test_eq(tor_addr_family(&t1), AF_INET6);
1487 p1 = tor_addr_to_str(buf, &t1, sizeof(buf), 0);
1488 test_streq(p1, "8000::");
1490 memset(&sa_storage, 0, sizeof(sa_storage));
1491 test_eq(sizeof(struct sockaddr_in6),
1492 tor_addr_to_sockaddr(&t1, 9999, (struct sockaddr *)&sa_storage,
1493 sizeof(sa_storage)));
1494 test_eq(AF_INET6, sin6->sin6_family);
1495 test_eq(9999, ntohs(sin6->sin6_port));
1496 test_eq(0x80000000, ntohl(S6_ADDR32(sin6->sin6_addr)[0]));
1498 /* ==== tor_addr_lookup: static cases. (Can't test dns without knowing we
1499 * have a good resolver. */
1500 test_eq(0, tor_addr_lookup("127.128.129.130", AF_UNSPEC, &t1));
1501 test_eq(AF_INET, tor_addr_family(&t1));
1502 test_eq(tor_addr_to_ipv4h(&t1), 0x7f808182);
1504 test_eq(0, tor_addr_lookup("9000::5", AF_UNSPEC, &t1));
1505 test_eq(AF_INET6, tor_addr_family(&t1));
1506 test_eq(0x90, tor_addr_to_in6_addr8(&t1)[0]);
1507 test_assert(tor_mem_is_zero((char*)tor_addr_to_in6_addr8(&t1)+1, 14));
1508 test_eq(0x05, tor_addr_to_in6_addr8(&t1)[15]);
1510 /* === Test pton: valid af_inet6 */
1511 /* Simple, valid parsing. */
1512 r = tor_inet_pton(AF_INET6,
1513 "0102:0304:0506:0708:090A:0B0C:0D0E:0F10", &a1);
1514 test_assert(r==1);
1515 for (i=0;i<16;++i) { test_eq(i+1, (int)a1.s6_addr[i]); }
1516 /* ipv4 ending. */
1517 test_pton6_same("0102:0304:0506:0708:090A:0B0C:0D0E:0F10",
1518 "0102:0304:0506:0708:090A:0B0C:13.14.15.16");
1519 /* shortened words. */
1520 test_pton6_same("0001:0099:BEEF:0000:0123:FFFF:0001:0001",
1521 "1:99:BEEF:0:0123:FFFF:1:1");
1522 /* zeros at the beginning */
1523 test_pton6_same("0000:0000:0000:0000:0009:C0A8:0001:0001",
1524 "::9:c0a8:1:1");
1525 test_pton6_same("0000:0000:0000:0000:0009:C0A8:0001:0001",
1526 "::9:c0a8:0.1.0.1");
1527 /* zeros in the middle. */
1528 test_pton6_same("fe80:0000:0000:0000:0202:1111:0001:0001",
1529 "fe80::202:1111:1:1");
1530 /* zeros at the end. */
1531 test_pton6_same("1000:0001:0000:0007:0000:0000:0000:0000",
1532 "1000:1:0:7::");
1534 /* === Test ntop: af_inet6 */
1535 test_ntop6_reduces("0:0:0:0:0:0:0:0", "::");
1537 test_ntop6_reduces("0001:0099:BEEF:0006:0123:FFFF:0001:0001",
1538 "1:99:beef:6:123:ffff:1:1");
1540 //test_ntop6_reduces("0:0:0:0:0:0:c0a8:0101", "::192.168.1.1");
1541 test_ntop6_reduces("0:0:0:0:0:ffff:c0a8:0101", "::ffff:192.168.1.1");
1542 test_ntop6_reduces("002:0:0000:0:3::4", "2::3:0:0:4");
1543 test_ntop6_reduces("0:0::1:0:3", "::1:0:3");
1544 test_ntop6_reduces("008:0::0", "8::");
1545 test_ntop6_reduces("0:0:0:0:0:ffff::1", "::ffff:0.0.0.1");
1546 test_ntop6_reduces("abcd:0:0:0:0:0:7f00::", "abcd::7f00:0");
1547 test_ntop6_reduces("0000:0000:0000:0000:0009:C0A8:0001:0001",
1548 "::9:c0a8:1:1");
1549 test_ntop6_reduces("fe80:0000:0000:0000:0202:1111:0001:0001",
1550 "fe80::202:1111:1:1");
1551 test_ntop6_reduces("1000:0001:0000:0007:0000:0000:0000:0000",
1552 "1000:1:0:7::");
1554 /* === Test pton: invalid in6. */
1555 test_pton6_bad("foobar.");
1556 test_pton6_bad("55555::");
1557 test_pton6_bad("9:-60::");
1558 test_pton6_bad("1:2:33333:4:0002:3::");
1559 //test_pton6_bad("1:2:3333:4:00002:3::");// BAD, but glibc doesn't say so.
1560 test_pton6_bad("1:2:3333:4:fish:3::");
1561 test_pton6_bad("1:2:3:4:5:6:7:8:9");
1562 test_pton6_bad("1:2:3:4:5:6:7");
1563 test_pton6_bad("1:2:3:4:5:6:1.2.3.4.5");
1564 test_pton6_bad("1:2:3:4:5:6:1.2.3");
1565 test_pton6_bad("::1.2.3");
1566 test_pton6_bad("::1.2.3.4.5");
1567 test_pton6_bad("99");
1568 test_pton6_bad("");
1569 test_pton6_bad("1::2::3:4");
1570 test_pton6_bad("a:::b:c");
1571 test_pton6_bad(":::a:b:c");
1572 test_pton6_bad("a:b:c:::");
1574 /* test internal checking */
1575 test_external_ip("fbff:ffff::2:7", 0);
1576 test_internal_ip("fc01::2:7", 0);
1577 test_internal_ip("fdff:ffff::f:f", 0);
1578 test_external_ip("fe00::3:f", 0);
1580 test_external_ip("fe7f:ffff::2:7", 0);
1581 test_internal_ip("fe80::2:7", 0);
1582 test_internal_ip("febf:ffff::f:f", 0);
1584 test_internal_ip("fec0::2:7:7", 0);
1585 test_internal_ip("feff:ffff::e:7:7", 0);
1586 test_external_ip("ff00::e:7:7", 0);
1588 test_internal_ip("::", 0);
1589 test_internal_ip("::1", 0);
1590 test_internal_ip("::1", 1);
1591 test_internal_ip("::", 0);
1592 test_external_ip("::", 1);
1593 test_external_ip("::2", 0);
1594 test_external_ip("2001::", 0);
1595 test_external_ip("ffff::", 0);
1597 test_external_ip("::ffff:0.0.0.0", 1);
1598 test_internal_ip("::ffff:0.0.0.0", 0);
1599 test_internal_ip("::ffff:0.255.255.255", 0);
1600 test_external_ip("::ffff:1.0.0.0", 0);
1602 test_external_ip("::ffff:9.255.255.255", 0);
1603 test_internal_ip("::ffff:10.0.0.0", 0);
1604 test_internal_ip("::ffff:10.255.255.255", 0);
1605 test_external_ip("::ffff:11.0.0.0", 0);
1607 test_external_ip("::ffff:126.255.255.255", 0);
1608 test_internal_ip("::ffff:127.0.0.0", 0);
1609 test_internal_ip("::ffff:127.255.255.255", 0);
1610 test_external_ip("::ffff:128.0.0.0", 0);
1612 test_external_ip("::ffff:172.15.255.255", 0);
1613 test_internal_ip("::ffff:172.16.0.0", 0);
1614 test_internal_ip("::ffff:172.31.255.255", 0);
1615 test_external_ip("::ffff:172.32.0.0", 0);
1617 test_external_ip("::ffff:192.167.255.255", 0);
1618 test_internal_ip("::ffff:192.168.0.0", 0);
1619 test_internal_ip("::ffff:192.168.255.255", 0);
1620 test_external_ip("::ffff:192.169.0.0", 0);
1622 test_external_ip("::ffff:169.253.255.255", 0);
1623 test_internal_ip("::ffff:169.254.0.0", 0);
1624 test_internal_ip("::ffff:169.254.255.255", 0);
1625 test_external_ip("::ffff:169.255.0.0", 0);
1626 test_assert(is_internal_IP(0x7f000001, 0));
1628 /* tor_addr_compare(tor_addr_t x2) */
1629 test_addr_compare("ffff::", ==, "ffff::0");
1630 test_addr_compare("0::3:2:1", <, "0::ffff:0.3.2.1");
1631 test_addr_compare("0::2:2:1", <, "0::ffff:0.3.2.1");
1632 test_addr_compare("0::ffff:0.3.2.1", >, "0::0:0:0");
1633 test_addr_compare("0::ffff:5.2.2.1", <, "::ffff:6.0.0.0"); /* XXXX wrong. */
1634 tor_addr_parse_mask_ports("[::ffff:2.3.4.5]", &t1, NULL, NULL, NULL);
1635 tor_addr_parse_mask_ports("2.3.4.5", &t2, NULL, NULL, NULL);
1636 test_assert(tor_addr_compare(&t1, &t2, CMP_SEMANTIC) == 0);
1637 tor_addr_parse_mask_ports("[::ffff:2.3.4.4]", &t1, NULL, NULL, NULL);
1638 tor_addr_parse_mask_ports("2.3.4.5", &t2, NULL, NULL, NULL);
1639 test_assert(tor_addr_compare(&t1, &t2, CMP_SEMANTIC) < 0);
1641 /* test compare_masked */
1642 test_addr_compare_masked("ffff::", ==, "ffff::0", 128);
1643 test_addr_compare_masked("ffff::", ==, "ffff::0", 64);
1644 test_addr_compare_masked("0::2:2:1", <, "0::8000:2:1", 81);
1645 test_addr_compare_masked("0::2:2:1", ==, "0::8000:2:1", 80);
1647 /* Test decorated addr_to_string. */
1648 test_eq(AF_INET6, tor_addr_from_str(&t1, "[123:45:6789::5005:11]"));
1649 p1 = tor_addr_to_str(buf, &t1, sizeof(buf), 1);
1650 test_streq(p1, "[123:45:6789::5005:11]");
1651 test_eq(AF_INET, tor_addr_from_str(&t1, "18.0.0.1"));
1652 p1 = tor_addr_to_str(buf, &t1, sizeof(buf), 1);
1653 test_streq(p1, "18.0.0.1");
1655 /* Test tor_addr_parse_reverse_lookup_name */
1656 i = tor_addr_parse_reverse_lookup_name(&t1, "Foobar.baz", AF_UNSPEC, 0);
1657 test_eq(0, i);
1658 i = tor_addr_parse_reverse_lookup_name(&t1, "Foobar.baz", AF_UNSPEC, 1);
1659 test_eq(0, i);
1660 i = tor_addr_parse_reverse_lookup_name(&t1, "1.0.168.192.in-addr.arpa",
1661 AF_UNSPEC, 1);
1662 test_eq(1, i);
1663 test_eq(tor_addr_family(&t1), AF_INET);
1664 p1 = tor_addr_to_str(buf, &t1, sizeof(buf), 1);
1665 test_streq(p1, "192.168.0.1");
1666 i = tor_addr_parse_reverse_lookup_name(&t1, "192.168.0.99", AF_UNSPEC, 0);
1667 test_eq(0, i);
1668 i = tor_addr_parse_reverse_lookup_name(&t1, "192.168.0.99", AF_UNSPEC, 1);
1669 test_eq(1, i);
1670 p1 = tor_addr_to_str(buf, &t1, sizeof(buf), 1);
1671 test_streq(p1, "192.168.0.99");
1672 memset(&t1, 0, sizeof(t1));
1673 i = tor_addr_parse_reverse_lookup_name(&t1,
1674 "0.1.2.3.4.5.6.7.8.9.a.b.c.d.e.f."
1675 "f.e.e.b.1.e.b.e.e.f.f.e.e.e.d.9."
1676 "ip6.ARPA",
1677 AF_UNSPEC, 0);
1678 test_eq(1, i);
1679 p1 = tor_addr_to_str(buf, &t1, sizeof(buf), 1);
1680 test_streq(p1, "[9dee:effe:ebe1:beef:fedc:ba98:7654:3210]");
1681 /* Failing cases. */
1682 i = tor_addr_parse_reverse_lookup_name(&t1,
1683 "6.7.8.9.a.b.c.d.e.f."
1684 "f.e.e.b.1.e.b.e.e.f.f.e.e.e.d.9."
1685 "ip6.ARPA",
1686 AF_UNSPEC, 0);
1687 test_eq(i, -1);
1688 i = tor_addr_parse_reverse_lookup_name(&t1,
1689 "6.7.8.9.a.b.c.d.e.f.a.b.c.d.e.f.0."
1690 "f.e.e.b.1.e.b.e.e.f.f.e.e.e.d.9."
1691 "ip6.ARPA",
1692 AF_UNSPEC, 0);
1693 test_eq(i, -1);
1694 i = tor_addr_parse_reverse_lookup_name(&t1,
1695 "6.7.8.9.a.b.c.d.e.f.X.0.0.0.0.9."
1696 "f.e.e.b.1.e.b.e.e.f.f.e.e.e.d.9."
1697 "ip6.ARPA",
1698 AF_UNSPEC, 0);
1699 test_eq(i, -1);
1700 i = tor_addr_parse_reverse_lookup_name(&t1, "32.1.1.in-addr.arpa",
1701 AF_UNSPEC, 0);
1702 test_eq(i, -1);
1703 i = tor_addr_parse_reverse_lookup_name(&t1, ".in-addr.arpa",
1704 AF_UNSPEC, 0);
1705 test_eq(i, -1);
1706 i = tor_addr_parse_reverse_lookup_name(&t1, "1.2.3.4.5.in-addr.arpa",
1707 AF_UNSPEC, 0);
1708 test_eq(i, -1);
1709 i = tor_addr_parse_reverse_lookup_name(&t1, "1.2.3.4.5.in-addr.arpa",
1710 AF_INET6, 0);
1711 test_eq(i, -1);
1712 i = tor_addr_parse_reverse_lookup_name(&t1,
1713 "6.7.8.9.a.b.c.d.e.f.a.b.c.d.e.0."
1714 "f.e.e.b.1.e.b.e.e.f.f.e.e.e.d.9."
1715 "ip6.ARPA",
1716 AF_INET, 0);
1717 test_eq(i, -1);
1719 /* test tor_addr_parse_mask_ports */
1720 test_addr_mask_ports_parse("[::f]/17:47-95", AF_INET6,
1721 0, 0, 0, 0x0000000f, 17, 47, 95);
1722 //test_addr_parse("[::fefe:4.1.1.7/120]:999-1000");
1723 //test_addr_parse_check("::fefe:401:107", 120, 999, 1000);
1724 test_addr_mask_ports_parse("[::ffff:4.1.1.7]/120:443", AF_INET6,
1725 0, 0, 0x0000ffff, 0x04010107, 120, 443, 443);
1726 test_addr_mask_ports_parse("[abcd:2::44a:0]:2-65000", AF_INET6,
1727 0xabcd0002, 0, 0, 0x044a0000, 128, 2, 65000);
1729 r=tor_addr_parse_mask_ports("[fefef::]/112", &t1, NULL, NULL, NULL);
1730 test_assert(r == -1);
1731 r=tor_addr_parse_mask_ports("efef::/112", &t1, NULL, NULL, NULL);
1732 test_assert(r == -1);
1733 r=tor_addr_parse_mask_ports("[f:f:f:f:f:f:f:f::]", &t1, NULL, NULL, NULL);
1734 test_assert(r == -1);
1735 r=tor_addr_parse_mask_ports("[::f:f:f:f:f:f:f:f]", &t1, NULL, NULL, NULL);
1736 test_assert(r == -1);
1737 r=tor_addr_parse_mask_ports("[f:f:f:f:f:f:f:f:f]", &t1, NULL, NULL, NULL);
1738 test_assert(r == -1);
1739 /* Test for V4-mapped address with mask < 96. (arguably not valid) */
1740 r=tor_addr_parse_mask_ports("[::ffff:1.1.2.2/33]", &t1, &mask, NULL, NULL);
1741 test_assert(r == -1);
1742 r=tor_addr_parse_mask_ports("1.1.2.2/33", &t1, &mask, NULL, NULL);
1743 test_assert(r == -1);
1744 r=tor_addr_parse_mask_ports("1.1.2.2/31", &t1, &mask, NULL, NULL);
1745 test_assert(r == AF_INET);
1746 r=tor_addr_parse_mask_ports("[efef::]/112", &t1, &mask, &port1, &port2);
1747 test_assert(r == AF_INET6);
1748 test_assert(port1 == 1);
1749 test_assert(port2 == 65535);
1751 /* make sure inet address lengths >= max */
1752 test_assert(INET_NTOA_BUF_LEN >= sizeof("255.255.255.255"));
1753 test_assert(TOR_ADDR_BUF_LEN >=
1754 sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"));
1756 test_assert(sizeof(tor_addr_t) >= sizeof(struct in6_addr));
1758 /* get interface addresses */
1759 r = get_interface_address6(LOG_DEBUG, AF_INET, &t1);
1760 i = get_interface_address6(LOG_DEBUG, AF_INET6, &t2);
1761 #if 0
1762 tor_inet_ntop(AF_INET, &t1.sa.sin_addr, buf, sizeof(buf));
1763 printf("\nv4 address: %s (family=%i)", buf, IN_FAMILY(&t1));
1764 tor_inet_ntop(AF_INET6, &t2.sa6.sin6_addr, buf, sizeof(buf));
1765 printf("\nv6 address: %s (family=%i)", buf, IN_FAMILY(&t2));
1766 #endif
1768 done:
1772 /** Run unit tests for basic dynamic-sized array functionality. */
1773 static void
1774 test_util_smartlist_basic(void)
1776 smartlist_t *sl;
1778 /* XXXX test sort_digests, uniq_strings, uniq_digests */
1780 /* Test smartlist add, del_keeporder, insert, get. */
1781 sl = smartlist_create();
1782 smartlist_add(sl, (void*)1);
1783 smartlist_add(sl, (void*)2);
1784 smartlist_add(sl, (void*)3);
1785 smartlist_add(sl, (void*)4);
1786 smartlist_del_keeporder(sl, 1);
1787 smartlist_insert(sl, 1, (void*)22);
1788 smartlist_insert(sl, 0, (void*)0);
1789 smartlist_insert(sl, 5, (void*)555);
1790 test_eq_ptr((void*)0, smartlist_get(sl,0));
1791 test_eq_ptr((void*)1, smartlist_get(sl,1));
1792 test_eq_ptr((void*)22, smartlist_get(sl,2));
1793 test_eq_ptr((void*)3, smartlist_get(sl,3));
1794 test_eq_ptr((void*)4, smartlist_get(sl,4));
1795 test_eq_ptr((void*)555, smartlist_get(sl,5));
1796 /* Try deleting in the middle. */
1797 smartlist_del(sl, 1);
1798 test_eq_ptr((void*)555, smartlist_get(sl, 1));
1799 /* Try deleting at the end. */
1800 smartlist_del(sl, 4);
1801 test_eq(4, smartlist_len(sl));
1803 /* test isin. */
1804 test_assert(smartlist_isin(sl, (void*)3));
1805 test_assert(!smartlist_isin(sl, (void*)99));
1807 done:
1808 smartlist_free(sl);
1811 /** Run unit tests for smartlist-of-strings functionality. */
1812 static void
1813 test_util_smartlist_strings(void)
1815 smartlist_t *sl = smartlist_create();
1816 char *cp=NULL, *cp_alloc=NULL;
1817 size_t sz;
1819 /* Test split and join */
1820 test_eq(0, smartlist_len(sl));
1821 smartlist_split_string(sl, "abc", ":", 0, 0);
1822 test_eq(1, smartlist_len(sl));
1823 test_streq("abc", smartlist_get(sl, 0));
1824 smartlist_split_string(sl, "a::bc::", "::", 0, 0);
1825 test_eq(4, smartlist_len(sl));
1826 test_streq("a", smartlist_get(sl, 1));
1827 test_streq("bc", smartlist_get(sl, 2));
1828 test_streq("", smartlist_get(sl, 3));
1829 cp_alloc = smartlist_join_strings(sl, "", 0, NULL);
1830 test_streq(cp_alloc, "abcabc");
1831 tor_free(cp_alloc);
1832 cp_alloc = smartlist_join_strings(sl, "!", 0, NULL);
1833 test_streq(cp_alloc, "abc!a!bc!");
1834 tor_free(cp_alloc);
1835 cp_alloc = smartlist_join_strings(sl, "XY", 0, NULL);
1836 test_streq(cp_alloc, "abcXYaXYbcXY");
1837 tor_free(cp_alloc);
1838 cp_alloc = smartlist_join_strings(sl, "XY", 1, NULL);
1839 test_streq(cp_alloc, "abcXYaXYbcXYXY");
1840 tor_free(cp_alloc);
1841 cp_alloc = smartlist_join_strings(sl, "", 1, NULL);
1842 test_streq(cp_alloc, "abcabc");
1843 tor_free(cp_alloc);
1845 smartlist_split_string(sl, "/def/ /ghijk", "/", 0, 0);
1846 test_eq(8, smartlist_len(sl));
1847 test_streq("", smartlist_get(sl, 4));
1848 test_streq("def", smartlist_get(sl, 5));
1849 test_streq(" ", smartlist_get(sl, 6));
1850 test_streq("ghijk", smartlist_get(sl, 7));
1851 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1852 smartlist_clear(sl);
1854 smartlist_split_string(sl, "a,bbd,cdef", ",", SPLIT_SKIP_SPACE, 0);
1855 test_eq(3, smartlist_len(sl));
1856 test_streq("a", smartlist_get(sl,0));
1857 test_streq("bbd", smartlist_get(sl,1));
1858 test_streq("cdef", smartlist_get(sl,2));
1859 smartlist_split_string(sl, " z <> zhasd <> <> bnud<> ", "<>",
1860 SPLIT_SKIP_SPACE, 0);
1861 test_eq(8, smartlist_len(sl));
1862 test_streq("z", smartlist_get(sl,3));
1863 test_streq("zhasd", smartlist_get(sl,4));
1864 test_streq("", smartlist_get(sl,5));
1865 test_streq("bnud", smartlist_get(sl,6));
1866 test_streq("", smartlist_get(sl,7));
1868 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1869 smartlist_clear(sl);
1871 smartlist_split_string(sl, " ab\tc \td ef ", NULL,
1872 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1873 test_eq(4, smartlist_len(sl));
1874 test_streq("ab", smartlist_get(sl,0));
1875 test_streq("c", smartlist_get(sl,1));
1876 test_streq("d", smartlist_get(sl,2));
1877 test_streq("ef", smartlist_get(sl,3));
1878 smartlist_split_string(sl, "ghi\tj", NULL,
1879 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1880 test_eq(6, smartlist_len(sl));
1881 test_streq("ghi", smartlist_get(sl,4));
1882 test_streq("j", smartlist_get(sl,5));
1884 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1885 smartlist_clear(sl);
1887 cp_alloc = smartlist_join_strings(sl, "XY", 0, NULL);
1888 test_streq(cp_alloc, "");
1889 tor_free(cp_alloc);
1890 cp_alloc = smartlist_join_strings(sl, "XY", 1, NULL);
1891 test_streq(cp_alloc, "XY");
1892 tor_free(cp_alloc);
1894 smartlist_split_string(sl, " z <> zhasd <> <> bnud<> ", "<>",
1895 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1896 test_eq(3, smartlist_len(sl));
1897 test_streq("z", smartlist_get(sl, 0));
1898 test_streq("zhasd", smartlist_get(sl, 1));
1899 test_streq("bnud", smartlist_get(sl, 2));
1900 smartlist_split_string(sl, " z <> zhasd <> <> bnud<> ", "<>",
1901 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
1902 test_eq(5, smartlist_len(sl));
1903 test_streq("z", smartlist_get(sl, 3));
1904 test_streq("zhasd <> <> bnud<>", smartlist_get(sl, 4));
1905 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1906 smartlist_clear(sl);
1908 smartlist_split_string(sl, "abcd\n", "\n",
1909 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1910 test_eq(1, smartlist_len(sl));
1911 test_streq("abcd", smartlist_get(sl, 0));
1912 smartlist_split_string(sl, "efgh", "\n",
1913 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1914 test_eq(2, smartlist_len(sl));
1915 test_streq("efgh", smartlist_get(sl, 1));
1917 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1918 smartlist_clear(sl);
1920 /* Test swapping, shuffling, and sorting. */
1921 smartlist_split_string(sl, "the,onion,router,by,arma,and,nickm", ",", 0, 0);
1922 test_eq(7, smartlist_len(sl));
1923 smartlist_sort(sl, _compare_strs);
1924 cp_alloc = smartlist_join_strings(sl, ",", 0, NULL);
1925 test_streq(cp_alloc,"and,arma,by,nickm,onion,router,the");
1926 tor_free(cp_alloc);
1927 smartlist_swap(sl, 1, 5);
1928 cp_alloc = smartlist_join_strings(sl, ",", 0, NULL);
1929 test_streq(cp_alloc,"and,router,by,nickm,onion,arma,the");
1930 tor_free(cp_alloc);
1931 smartlist_shuffle(sl);
1932 test_eq(7, smartlist_len(sl));
1933 test_assert(smartlist_string_isin(sl, "and"));
1934 test_assert(smartlist_string_isin(sl, "router"));
1935 test_assert(smartlist_string_isin(sl, "by"));
1936 test_assert(smartlist_string_isin(sl, "nickm"));
1937 test_assert(smartlist_string_isin(sl, "onion"));
1938 test_assert(smartlist_string_isin(sl, "arma"));
1939 test_assert(smartlist_string_isin(sl, "the"));
1941 /* Test bsearch. */
1942 smartlist_sort(sl, _compare_strs);
1943 test_streq("nickm", smartlist_bsearch(sl, "zNicKM",
1944 _compare_without_first_ch));
1945 test_streq("and", smartlist_bsearch(sl, " AND", _compare_without_first_ch));
1946 test_eq_ptr(NULL, smartlist_bsearch(sl, " ANz", _compare_without_first_ch));
1948 /* Test bsearch_idx */
1950 int f;
1951 test_eq(0, smartlist_bsearch_idx(sl," aaa",_compare_without_first_ch,&f));
1952 test_eq(f, 0);
1953 test_eq(0, smartlist_bsearch_idx(sl," and",_compare_without_first_ch,&f));
1954 test_eq(f, 1);
1955 test_eq(1, smartlist_bsearch_idx(sl," arm",_compare_without_first_ch,&f));
1956 test_eq(f, 0);
1957 test_eq(1, smartlist_bsearch_idx(sl," arma",_compare_without_first_ch,&f));
1958 test_eq(f, 1);
1959 test_eq(2, smartlist_bsearch_idx(sl," armb",_compare_without_first_ch,&f));
1960 test_eq(f, 0);
1961 test_eq(7, smartlist_bsearch_idx(sl," zzzz",_compare_without_first_ch,&f));
1962 test_eq(f, 0);
1965 /* Test reverse() and pop_last() */
1966 smartlist_reverse(sl);
1967 cp_alloc = smartlist_join_strings(sl, ",", 0, NULL);
1968 test_streq(cp_alloc,"the,router,onion,nickm,by,arma,and");
1969 tor_free(cp_alloc);
1970 cp_alloc = smartlist_pop_last(sl);
1971 test_streq(cp_alloc, "and");
1972 tor_free(cp_alloc);
1973 test_eq(smartlist_len(sl), 6);
1974 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1975 smartlist_clear(sl);
1976 cp_alloc = smartlist_pop_last(sl);
1977 test_eq(cp_alloc, NULL);
1979 /* Test uniq() */
1980 smartlist_split_string(sl,
1981 "50,noon,radar,a,man,a,plan,a,canal,panama,radar,noon,50",
1982 ",", 0, 0);
1983 smartlist_sort(sl, _compare_strs);
1984 smartlist_uniq(sl, _compare_strs, _tor_free);
1985 cp_alloc = smartlist_join_strings(sl, ",", 0, NULL);
1986 test_streq(cp_alloc, "50,a,canal,man,noon,panama,plan,radar");
1987 tor_free(cp_alloc);
1989 /* Test string_isin and isin_case and num_isin */
1990 test_assert(smartlist_string_isin(sl, "noon"));
1991 test_assert(!smartlist_string_isin(sl, "noonoon"));
1992 test_assert(smartlist_string_isin_case(sl, "nOOn"));
1993 test_assert(!smartlist_string_isin_case(sl, "nooNooN"));
1994 test_assert(smartlist_string_num_isin(sl, 50));
1995 test_assert(!smartlist_string_num_isin(sl, 60));
1997 /* Test smartlist_choose */
1999 int i;
2000 int allsame = 1;
2001 int allin = 1;
2002 void *first = smartlist_choose(sl);
2003 test_assert(smartlist_isin(sl, first));
2004 for (i = 0; i < 100; ++i) {
2005 void *second = smartlist_choose(sl);
2006 if (second != first)
2007 allsame = 0;
2008 if (!smartlist_isin(sl, second))
2009 allin = 0;
2011 test_assert(!allsame);
2012 test_assert(allin);
2014 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
2015 smartlist_clear(sl);
2017 /* Test string_remove and remove and join_strings2 */
2018 smartlist_split_string(sl,
2019 "Some say the Earth will end in ice and some in fire",
2020 " ", 0, 0);
2021 cp = smartlist_get(sl, 4);
2022 test_streq(cp, "will");
2023 smartlist_add(sl, cp);
2024 smartlist_remove(sl, cp);
2025 tor_free(cp);
2026 cp_alloc = smartlist_join_strings(sl, ",", 0, NULL);
2027 test_streq(cp_alloc, "Some,say,the,Earth,fire,end,in,ice,and,some,in");
2028 tor_free(cp_alloc);
2029 smartlist_string_remove(sl, "in");
2030 cp_alloc = smartlist_join_strings2(sl, "+XX", 1, 0, &sz);
2031 test_streq(cp_alloc, "Some+say+the+Earth+fire+end+some+ice+and");
2032 test_eq((int)sz, 40);
2034 done:
2036 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
2037 smartlist_free(sl);
2038 tor_free(cp_alloc);
2041 /** Run unit tests for smartlist set manipulation functions. */
2042 static void
2043 test_util_smartlist_overlap(void)
2045 smartlist_t *sl = smartlist_create();
2046 smartlist_t *ints = smartlist_create();
2047 smartlist_t *odds = smartlist_create();
2048 smartlist_t *evens = smartlist_create();
2049 smartlist_t *primes = smartlist_create();
2050 int i;
2051 for (i=1; i < 10; i += 2)
2052 smartlist_add(odds, (void*)(uintptr_t)i);
2053 for (i=0; i < 10; i += 2)
2054 smartlist_add(evens, (void*)(uintptr_t)i);
2056 /* add_all */
2057 smartlist_add_all(ints, odds);
2058 smartlist_add_all(ints, evens);
2059 test_eq(smartlist_len(ints), 10);
2061 smartlist_add(primes, (void*)2);
2062 smartlist_add(primes, (void*)3);
2063 smartlist_add(primes, (void*)5);
2064 smartlist_add(primes, (void*)7);
2066 /* overlap */
2067 test_assert(smartlist_overlap(ints, odds));
2068 test_assert(smartlist_overlap(odds, primes));
2069 test_assert(smartlist_overlap(evens, primes));
2070 test_assert(!smartlist_overlap(odds, evens));
2072 /* intersect */
2073 smartlist_add_all(sl, odds);
2074 smartlist_intersect(sl, primes);
2075 test_eq(smartlist_len(sl), 3);
2076 test_assert(smartlist_isin(sl, (void*)3));
2077 test_assert(smartlist_isin(sl, (void*)5));
2078 test_assert(smartlist_isin(sl, (void*)7));
2080 /* subtract */
2081 smartlist_add_all(sl, primes);
2082 smartlist_subtract(sl, odds);
2083 test_eq(smartlist_len(sl), 1);
2084 test_assert(smartlist_isin(sl, (void*)2));
2086 done:
2087 smartlist_free(odds);
2088 smartlist_free(evens);
2089 smartlist_free(ints);
2090 smartlist_free(primes);
2091 smartlist_free(sl);
2094 /** Run unit tests for smartlist-of-digests functions. */
2095 static void
2096 test_util_smartlist_digests(void)
2098 smartlist_t *sl = smartlist_create();
2100 /* digest_isin. */
2101 smartlist_add(sl, tor_memdup("AAAAAAAAAAAAAAAAAAAA", DIGEST_LEN));
2102 smartlist_add(sl, tor_memdup("\00090AAB2AAAAaasdAAAAA", DIGEST_LEN));
2103 smartlist_add(sl, tor_memdup("\00090AAB2AAAAaasdAAAAA", DIGEST_LEN));
2104 test_eq(0, smartlist_digest_isin(NULL, "AAAAAAAAAAAAAAAAAAAA"));
2105 test_assert(smartlist_digest_isin(sl, "AAAAAAAAAAAAAAAAAAAA"));
2106 test_assert(smartlist_digest_isin(sl, "\00090AAB2AAAAaasdAAAAA"));
2107 test_eq(0, smartlist_digest_isin(sl, "\00090AAB2AAABaasdAAAAA"));
2109 /* sort digests */
2110 smartlist_sort_digests(sl);
2111 test_memeq(smartlist_get(sl, 0), "\00090AAB2AAAAaasdAAAAA", DIGEST_LEN);
2112 test_memeq(smartlist_get(sl, 1), "\00090AAB2AAAAaasdAAAAA", DIGEST_LEN);
2113 test_memeq(smartlist_get(sl, 2), "AAAAAAAAAAAAAAAAAAAA", DIGEST_LEN);
2114 test_eq(3, smartlist_len(sl));
2116 /* uniq_digests */
2117 smartlist_uniq_digests(sl);
2118 test_eq(2, smartlist_len(sl));
2119 test_memeq(smartlist_get(sl, 0), "\00090AAB2AAAAaasdAAAAA", DIGEST_LEN);
2120 test_memeq(smartlist_get(sl, 1), "AAAAAAAAAAAAAAAAAAAA", DIGEST_LEN);
2122 done:
2123 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
2124 smartlist_free(sl);
2127 /** Run unit tests for concatenate-a-smartlist-of-strings functions. */
2128 static void
2129 test_util_smartlist_join(void)
2131 smartlist_t *sl = smartlist_create();
2132 smartlist_t *sl2 = smartlist_create(), *sl3 = smartlist_create(),
2133 *sl4 = smartlist_create();
2134 char *joined=NULL;
2135 /* unique, sorted. */
2136 smartlist_split_string(sl,
2137 "Abashments Ambush Anchorman Bacon Banks Borscht "
2138 "Bunks Inhumane Insurance Knish Know Manners "
2139 "Maraschinos Stamina Sunbonnets Unicorns Wombats",
2140 " ", 0, 0);
2141 /* non-unique, sorted. */
2142 smartlist_split_string(sl2,
2143 "Ambush Anchorman Anchorman Anemias Anemias Bacon "
2144 "Crossbowmen Inhumane Insurance Knish Know Manners "
2145 "Manners Maraschinos Wombats Wombats Work",
2146 " ", 0, 0);
2147 SMARTLIST_FOREACH_JOIN(sl, char *, cp1,
2148 sl2, char *, cp2,
2149 strcmp(cp1,cp2),
2150 smartlist_add(sl3, cp2)) {
2151 test_streq(cp1, cp2);
2152 smartlist_add(sl4, cp1);
2153 } SMARTLIST_FOREACH_JOIN_END(cp1, cp2);
2155 SMARTLIST_FOREACH(sl3, const char *, cp,
2156 test_assert(smartlist_isin(sl2, cp) &&
2157 !smartlist_string_isin(sl, cp)));
2158 SMARTLIST_FOREACH(sl4, const char *, cp,
2159 test_assert(smartlist_isin(sl, cp) &&
2160 smartlist_string_isin(sl2, cp)));
2161 joined = smartlist_join_strings(sl3, ",", 0, NULL);
2162 test_streq(joined, "Anemias,Anemias,Crossbowmen,Work");
2163 tor_free(joined);
2164 joined = smartlist_join_strings(sl4, ",", 0, NULL);
2165 test_streq(joined, "Ambush,Anchorman,Anchorman,Bacon,Inhumane,Insurance,"
2166 "Knish,Know,Manners,Manners,Maraschinos,Wombats,Wombats");
2167 tor_free(joined);
2169 done:
2170 smartlist_free(sl4);
2171 smartlist_free(sl3);
2172 SMARTLIST_FOREACH(sl2, char *, cp, tor_free(cp));
2173 smartlist_free(sl2);
2174 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
2175 smartlist_free(sl);
2176 tor_free(joined);
2179 /** Run unit tests for bitarray code */
2180 static void
2181 test_util_bitarray(void)
2183 bitarray_t *ba = NULL;
2184 int i, j, ok=1;
2186 ba = bitarray_init_zero(1);
2187 test_assert(ba);
2188 test_assert(! bitarray_is_set(ba, 0));
2189 bitarray_set(ba, 0);
2190 test_assert(bitarray_is_set(ba, 0));
2191 bitarray_clear(ba, 0);
2192 test_assert(! bitarray_is_set(ba, 0));
2193 bitarray_free(ba);
2195 ba = bitarray_init_zero(1023);
2196 for (i = 1; i < 64; ) {
2197 for (j = 0; j < 1023; ++j) {
2198 if (j % i)
2199 bitarray_set(ba, j);
2200 else
2201 bitarray_clear(ba, j);
2203 for (j = 0; j < 1023; ++j) {
2204 if (!bool_eq(bitarray_is_set(ba, j), j%i))
2205 ok = 0;
2207 test_assert(ok);
2208 if (i < 7)
2209 ++i;
2210 else if (i == 28)
2211 i = 32;
2212 else
2213 i += 7;
2216 done:
2217 if (ba)
2218 bitarray_free(ba);
2221 /** Run unit tests for digest set code (implemented as a hashtable or as a
2222 * bloom filter) */
2223 static void
2224 test_util_digestset(void)
2226 smartlist_t *included = smartlist_create();
2227 char d[DIGEST_LEN];
2228 int i;
2229 int ok = 1;
2230 int false_positives = 0;
2231 digestset_t *set = NULL;
2233 for (i = 0; i < 1000; ++i) {
2234 crypto_rand(d, DIGEST_LEN);
2235 smartlist_add(included, tor_memdup(d, DIGEST_LEN));
2237 set = digestset_new(1000);
2238 SMARTLIST_FOREACH(included, const char *, cp,
2239 if (digestset_isin(set, cp))
2240 ok = 0);
2241 test_assert(ok);
2242 SMARTLIST_FOREACH(included, const char *, cp,
2243 digestset_add(set, cp));
2244 SMARTLIST_FOREACH(included, const char *, cp,
2245 if (!digestset_isin(set, cp))
2246 ok = 0);
2247 test_assert(ok);
2248 for (i = 0; i < 1000; ++i) {
2249 crypto_rand(d, DIGEST_LEN);
2250 if (digestset_isin(set, d))
2251 ++false_positives;
2253 test_assert(false_positives < 50); /* Should be far lower. */
2255 done:
2256 if (set)
2257 digestset_free(set);
2258 SMARTLIST_FOREACH(included, char *, cp, tor_free(cp));
2259 smartlist_free(included);
2262 /** mutex for thread test to stop the threads hitting data at the same time. */
2263 static tor_mutex_t *_thread_test_mutex = NULL;
2264 /** mutexes for the thread test to make sure that the threads have to
2265 * interleave somewhat. */
2266 static tor_mutex_t *_thread_test_start1 = NULL,
2267 *_thread_test_start2 = NULL;
2268 /** Shared strmap for the thread test. */
2269 static strmap_t *_thread_test_strmap = NULL;
2270 /** The name of thread1 for the thread test */
2271 static char *_thread1_name = NULL;
2272 /** The name of thread2 for the thread test */
2273 static char *_thread2_name = NULL;
2275 static void _thread_test_func(void* _s) ATTR_NORETURN;
2277 /** How many iterations have the threads in the unit test run? */
2278 static int t1_count = 0, t2_count = 0;
2280 /** Helper function for threading unit tests: This function runs in a
2281 * subthread. It grabs its own mutex (start1 or start2) to make sure that it
2282 * should start, then it repeatedly alters _test_thread_strmap protected by
2283 * _thread_test_mutex. */
2284 static void
2285 _thread_test_func(void* _s)
2287 char *s = _s;
2288 int i, *count;
2289 tor_mutex_t *m;
2290 char buf[64];
2291 char **cp;
2292 if (!strcmp(s, "thread 1")) {
2293 m = _thread_test_start1;
2294 cp = &_thread1_name;
2295 count = &t1_count;
2296 } else {
2297 m = _thread_test_start2;
2298 cp = &_thread2_name;
2299 count = &t2_count;
2301 tor_mutex_acquire(m);
2303 tor_snprintf(buf, sizeof(buf), "%lu", tor_get_thread_id());
2304 *cp = tor_strdup(buf);
2306 for (i=0; i<10000; ++i) {
2307 tor_mutex_acquire(_thread_test_mutex);
2308 strmap_set(_thread_test_strmap, "last to run", *cp);
2309 ++*count;
2310 tor_mutex_release(_thread_test_mutex);
2312 tor_mutex_acquire(_thread_test_mutex);
2313 strmap_set(_thread_test_strmap, s, *cp);
2314 tor_mutex_release(_thread_test_mutex);
2316 tor_mutex_release(m);
2318 spawn_exit();
2321 /** Run unit tests for threading logic. */
2322 static void
2323 test_util_threads(void)
2325 char *s1 = NULL, *s2 = NULL;
2326 int done = 0, timedout = 0;
2327 time_t started;
2328 #ifndef TOR_IS_MULTITHREADED
2329 /* Skip this test if we aren't threading. We should be threading most
2330 * everywhere by now. */
2331 if (1)
2332 return;
2333 #endif
2334 _thread_test_mutex = tor_mutex_new();
2335 _thread_test_start1 = tor_mutex_new();
2336 _thread_test_start2 = tor_mutex_new();
2337 _thread_test_strmap = strmap_new();
2338 s1 = tor_strdup("thread 1");
2339 s2 = tor_strdup("thread 2");
2340 tor_mutex_acquire(_thread_test_start1);
2341 tor_mutex_acquire(_thread_test_start2);
2342 spawn_func(_thread_test_func, s1);
2343 spawn_func(_thread_test_func, s2);
2344 tor_mutex_release(_thread_test_start2);
2345 tor_mutex_release(_thread_test_start1);
2346 started = time(NULL);
2347 while (!done) {
2348 tor_mutex_acquire(_thread_test_mutex);
2349 strmap_assert_ok(_thread_test_strmap);
2350 if (strmap_get(_thread_test_strmap, "thread 1") &&
2351 strmap_get(_thread_test_strmap, "thread 2")) {
2352 done = 1;
2353 } else if (time(NULL) > started + 25) {
2354 timedout = done = 1;
2356 tor_mutex_release(_thread_test_mutex);
2358 tor_mutex_free(_thread_test_mutex);
2360 tor_mutex_acquire(_thread_test_start1);
2361 tor_mutex_release(_thread_test_start1);
2362 tor_mutex_acquire(_thread_test_start2);
2363 tor_mutex_release(_thread_test_start2);
2365 if (timedout) {
2366 printf("\nTimed out: %d %d", t1_count, t2_count);
2367 test_assert(strmap_get(_thread_test_strmap, "thread 1"));
2368 test_assert(strmap_get(_thread_test_strmap, "thread 2"));
2369 test_assert(!timedout);
2372 /* different thread IDs. */
2373 test_assert(strcmp(strmap_get(_thread_test_strmap, "thread 1"),
2374 strmap_get(_thread_test_strmap, "thread 2")));
2375 test_assert(!strcmp(strmap_get(_thread_test_strmap, "thread 1"),
2376 strmap_get(_thread_test_strmap, "last to run")) ||
2377 !strcmp(strmap_get(_thread_test_strmap, "thread 2"),
2378 strmap_get(_thread_test_strmap, "last to run")));
2380 done:
2381 tor_free(s1);
2382 tor_free(s2);
2383 tor_free(_thread1_name);
2384 tor_free(_thread2_name);
2385 if (_thread_test_strmap)
2386 strmap_free(_thread_test_strmap, NULL);
2387 if (_thread_test_start1)
2388 tor_mutex_free(_thread_test_start1);
2389 if (_thread_test_start2)
2390 tor_mutex_free(_thread_test_start2);
2393 /** Helper: return a tristate based on comparing two strings. */
2394 static int
2395 _compare_strings_for_pqueue(const void *s1, const void *s2)
2397 return strcmp((const char*)s1, (const char*)s2);
2400 /** Run unit tests for heap-based priority queue functions. */
2401 static void
2402 test_util_pqueue(void)
2404 smartlist_t *sl = smartlist_create();
2405 int (*cmp)(const void *, const void*);
2406 #define OK() smartlist_pqueue_assert_ok(sl, cmp)
2408 cmp = _compare_strings_for_pqueue;
2410 smartlist_pqueue_add(sl, cmp, (char*)"cows");
2411 smartlist_pqueue_add(sl, cmp, (char*)"zebras");
2412 smartlist_pqueue_add(sl, cmp, (char*)"fish");
2413 smartlist_pqueue_add(sl, cmp, (char*)"frogs");
2414 smartlist_pqueue_add(sl, cmp, (char*)"apples");
2415 smartlist_pqueue_add(sl, cmp, (char*)"squid");
2416 smartlist_pqueue_add(sl, cmp, (char*)"daschunds");
2417 smartlist_pqueue_add(sl, cmp, (char*)"eggplants");
2418 smartlist_pqueue_add(sl, cmp, (char*)"weissbier");
2419 smartlist_pqueue_add(sl, cmp, (char*)"lobsters");
2420 smartlist_pqueue_add(sl, cmp, (char*)"roquefort");
2422 OK();
2424 test_eq(smartlist_len(sl), 11);
2425 test_streq(smartlist_get(sl, 0), "apples");
2426 test_streq(smartlist_pqueue_pop(sl, cmp), "apples");
2427 test_eq(smartlist_len(sl), 10);
2428 OK();
2429 test_streq(smartlist_pqueue_pop(sl, cmp), "cows");
2430 test_streq(smartlist_pqueue_pop(sl, cmp), "daschunds");
2431 smartlist_pqueue_add(sl, cmp, (char*)"chinchillas");
2432 OK();
2433 smartlist_pqueue_add(sl, cmp, (char*)"fireflies");
2434 OK();
2435 test_streq(smartlist_pqueue_pop(sl, cmp), "chinchillas");
2436 test_streq(smartlist_pqueue_pop(sl, cmp), "eggplants");
2437 test_streq(smartlist_pqueue_pop(sl, cmp), "fireflies");
2438 OK();
2439 test_streq(smartlist_pqueue_pop(sl, cmp), "fish");
2440 test_streq(smartlist_pqueue_pop(sl, cmp), "frogs");
2441 test_streq(smartlist_pqueue_pop(sl, cmp), "lobsters");
2442 test_streq(smartlist_pqueue_pop(sl, cmp), "roquefort");
2443 OK();
2444 test_eq(smartlist_len(sl), 3);
2445 test_streq(smartlist_pqueue_pop(sl, cmp), "squid");
2446 test_streq(smartlist_pqueue_pop(sl, cmp), "weissbier");
2447 test_streq(smartlist_pqueue_pop(sl, cmp), "zebras");
2448 test_eq(smartlist_len(sl), 0);
2449 OK();
2450 #undef OK
2452 done:
2454 smartlist_free(sl);
2457 /** Run unit tests for compression functions */
2458 static void
2459 test_util_gzip(void)
2461 char *buf1=NULL, *buf2=NULL, *buf3=NULL, *cp1, *cp2;
2462 const char *ccp2;
2463 size_t len1, len2;
2464 tor_zlib_state_t *state = NULL;
2466 buf1 = tor_strdup("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ");
2467 test_assert(detect_compression_method(buf1, strlen(buf1)) == UNKNOWN_METHOD);
2468 if (is_gzip_supported()) {
2469 test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
2470 GZIP_METHOD));
2471 test_assert(buf2);
2472 test_assert(!memcmp(buf2, "\037\213", 2)); /* Gzip magic. */
2473 test_assert(detect_compression_method(buf2, len1) == GZIP_METHOD);
2475 test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1,
2476 GZIP_METHOD, 1, LOG_INFO));
2477 test_assert(buf3);
2478 test_streq(buf1,buf3);
2480 tor_free(buf2);
2481 tor_free(buf3);
2484 test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
2485 ZLIB_METHOD));
2486 test_assert(buf2);
2487 test_assert(!memcmp(buf2, "\x78\xDA", 2)); /* deflate magic. */
2488 test_assert(detect_compression_method(buf2, len1) == ZLIB_METHOD);
2490 test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1,
2491 ZLIB_METHOD, 1, LOG_INFO));
2492 test_assert(buf3);
2493 test_streq(buf1,buf3);
2495 /* Check whether we can uncompress concatenated, compressed strings. */
2496 tor_free(buf3);
2497 buf2 = tor_realloc(buf2, len1*2);
2498 memcpy(buf2+len1, buf2, len1);
2499 test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1*2,
2500 ZLIB_METHOD, 1, LOG_INFO));
2501 test_eq(len2, (strlen(buf1)+1)*2);
2502 test_memeq(buf3,
2503 "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ\0"
2504 "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ\0",
2505 (strlen(buf1)+1)*2);
2507 tor_free(buf1);
2508 tor_free(buf2);
2509 tor_free(buf3);
2511 /* Check whether we can uncompress partial strings. */
2512 buf1 =
2513 tor_strdup("String with low redundancy that won't be compressed much.");
2514 test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
2515 ZLIB_METHOD));
2516 tor_assert(len1>16);
2517 /* when we allow an incomplete string, we should succeed.*/
2518 tor_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1-16,
2519 ZLIB_METHOD, 0, LOG_INFO));
2520 buf3[len2]='\0';
2521 tor_assert(len2 > 5);
2522 tor_assert(!strcmpstart(buf1, buf3));
2524 /* when we demand a complete string, this must fail. */
2525 tor_free(buf3);
2526 tor_assert(tor_gzip_uncompress(&buf3, &len2, buf2, len1-16,
2527 ZLIB_METHOD, 1, LOG_INFO));
2528 tor_assert(!buf3);
2530 /* Now, try streaming compression. */
2531 tor_free(buf1);
2532 tor_free(buf2);
2533 tor_free(buf3);
2534 state = tor_zlib_new(1, ZLIB_METHOD);
2535 tor_assert(state);
2536 cp1 = buf1 = tor_malloc(1024);
2537 len1 = 1024;
2538 ccp2 = "ABCDEFGHIJABCDEFGHIJ";
2539 len2 = 21;
2540 test_assert(tor_zlib_process(state, &cp1, &len1, &ccp2, &len2, 0)
2541 == TOR_ZLIB_OK);
2542 test_eq(len2, 0); /* Make sure we compressed it all. */
2543 test_assert(cp1 > buf1);
2545 len2 = 0;
2546 cp2 = cp1;
2547 test_assert(tor_zlib_process(state, &cp1, &len1, &ccp2, &len2, 1)
2548 == TOR_ZLIB_DONE);
2549 test_eq(len2, 0);
2550 test_assert(cp1 > cp2); /* Make sure we really added something. */
2552 tor_assert(!tor_gzip_uncompress(&buf3, &len2, buf1, 1024-len1,
2553 ZLIB_METHOD, 1, LOG_WARN));
2554 test_streq(buf3, "ABCDEFGHIJABCDEFGHIJ"); /*Make sure it compressed right.*/
2556 done:
2557 if (state)
2558 tor_zlib_free(state);
2559 tor_free(buf2);
2560 tor_free(buf3);
2561 tor_free(buf1);
2564 /** Run unit tests for string-to-void* map functions */
2565 static void
2566 test_util_strmap(void)
2568 strmap_t *map;
2569 strmap_iter_t *iter;
2570 const char *k;
2571 void *v;
2572 char *visited = NULL;
2573 smartlist_t *found_keys = NULL;
2575 map = strmap_new();
2576 test_assert(map);
2577 test_eq(strmap_size(map), 0);
2578 test_assert(strmap_isempty(map));
2579 v = strmap_set(map, "K1", (void*)99);
2580 test_eq(v, NULL);
2581 test_assert(!strmap_isempty(map));
2582 v = strmap_set(map, "K2", (void*)101);
2583 test_eq(v, NULL);
2584 v = strmap_set(map, "K1", (void*)100);
2585 test_eq(v, (void*)99);
2586 test_eq_ptr(strmap_get(map,"K1"), (void*)100);
2587 test_eq_ptr(strmap_get(map,"K2"), (void*)101);
2588 test_eq_ptr(strmap_get(map,"K-not-there"), NULL);
2589 strmap_assert_ok(map);
2591 v = strmap_remove(map,"K2");
2592 strmap_assert_ok(map);
2593 test_eq_ptr(v, (void*)101);
2594 test_eq_ptr(strmap_get(map,"K2"), NULL);
2595 test_eq_ptr(strmap_remove(map,"K2"), NULL);
2597 strmap_set(map, "K2", (void*)101);
2598 strmap_set(map, "K3", (void*)102);
2599 strmap_set(map, "K4", (void*)103);
2600 test_eq(strmap_size(map), 4);
2601 strmap_assert_ok(map);
2602 strmap_set(map, "K5", (void*)104);
2603 strmap_set(map, "K6", (void*)105);
2604 strmap_assert_ok(map);
2606 /* Test iterator. */
2607 iter = strmap_iter_init(map);
2608 found_keys = smartlist_create();
2609 while (!strmap_iter_done(iter)) {
2610 strmap_iter_get(iter,&k,&v);
2611 smartlist_add(found_keys, tor_strdup(k));
2612 test_eq_ptr(v, strmap_get(map, k));
2614 if (!strcmp(k, "K2")) {
2615 iter = strmap_iter_next_rmv(map,iter);
2616 } else {
2617 iter = strmap_iter_next(map,iter);
2621 /* Make sure we removed K2, but not the others. */
2622 test_eq_ptr(strmap_get(map, "K2"), NULL);
2623 test_eq_ptr(strmap_get(map, "K5"), (void*)104);
2624 /* Make sure we visited everyone once */
2625 smartlist_sort_strings(found_keys);
2626 visited = smartlist_join_strings(found_keys, ":", 0, NULL);
2627 test_streq(visited, "K1:K2:K3:K4:K5:K6");
2629 strmap_assert_ok(map);
2630 /* Clean up after ourselves. */
2631 strmap_free(map, NULL);
2632 map = NULL;
2634 /* Now try some lc functions. */
2635 map = strmap_new();
2636 strmap_set_lc(map,"Ab.C", (void*)1);
2637 test_eq_ptr(strmap_get(map,"ab.c"), (void*)1);
2638 strmap_assert_ok(map);
2639 test_eq_ptr(strmap_get_lc(map,"AB.C"), (void*)1);
2640 test_eq_ptr(strmap_get(map,"AB.C"), NULL);
2641 test_eq_ptr(strmap_remove_lc(map,"aB.C"), (void*)1);
2642 strmap_assert_ok(map);
2643 test_eq_ptr(strmap_get_lc(map,"AB.C"), NULL);
2645 done:
2646 if (map)
2647 strmap_free(map,NULL);
2648 if (found_keys) {
2649 SMARTLIST_FOREACH(found_keys, char *, cp, tor_free(cp));
2650 smartlist_free(found_keys);
2652 tor_free(visited);
2655 /** Run unit tests for mmap() wrapper functionality. */
2656 static void
2657 test_util_mmap(void)
2659 char *fname1 = tor_strdup(get_fname("mapped_1"));
2660 char *fname2 = tor_strdup(get_fname("mapped_2"));
2661 char *fname3 = tor_strdup(get_fname("mapped_3"));
2662 const size_t buflen = 17000;
2663 char *buf = tor_malloc(17000);
2664 tor_mmap_t *mapping = NULL;
2666 crypto_rand(buf, buflen);
2668 mapping = tor_mmap_file(fname1);
2669 test_assert(! mapping);
2671 write_str_to_file(fname1, "Short file.", 1);
2672 write_bytes_to_file(fname2, buf, buflen, 1);
2673 write_bytes_to_file(fname3, buf, 16384, 1);
2675 mapping = tor_mmap_file(fname1);
2676 test_assert(mapping);
2677 test_eq(mapping->size, strlen("Short file."));
2678 test_streq(mapping->data, "Short file.");
2679 #ifdef MS_WINDOWS
2680 tor_munmap_file(mapping);
2681 mapping = NULL;
2682 test_assert(unlink(fname1) == 0);
2683 #else
2684 /* make sure we can unlink. */
2685 test_assert(unlink(fname1) == 0);
2686 test_streq(mapping->data, "Short file.");
2687 tor_munmap_file(mapping);
2688 mapping = NULL;
2689 #endif
2691 /* Now a zero-length file. */
2692 write_str_to_file(fname1, "", 1);
2693 mapping = tor_mmap_file(fname1);
2694 test_eq(mapping, NULL);
2695 test_eq(ERANGE, errno);
2696 unlink(fname1);
2698 /* Make sure that we fail to map a no-longer-existent file. */
2699 mapping = tor_mmap_file(fname1);
2700 test_assert(mapping == NULL);
2702 /* Now try a big file that stretches across a few pages and isn't aligned */
2703 mapping = tor_mmap_file(fname2);
2704 test_assert(mapping);
2705 test_eq(mapping->size, buflen);
2706 test_memeq(mapping->data, buf, buflen);
2707 tor_munmap_file(mapping);
2708 mapping = NULL;
2710 /* Now try a big aligned file. */
2711 mapping = tor_mmap_file(fname3);
2712 test_assert(mapping);
2713 test_eq(mapping->size, 16384);
2714 test_memeq(mapping->data, buf, 16384);
2715 tor_munmap_file(mapping);
2716 mapping = NULL;
2718 done:
2719 unlink(fname1);
2720 unlink(fname2);
2721 unlink(fname3);
2723 tor_free(fname1);
2724 tor_free(fname2);
2725 tor_free(fname3);
2726 tor_free(buf);
2728 if (mapping)
2729 tor_munmap_file(mapping);
2732 /** Run unit tests for escaping/unescaping data for use by controllers. */
2733 static void
2734 test_util_control_formats(void)
2736 char *out = NULL;
2737 const char *inp =
2738 "..This is a test\r\nof the emergency \nbroadcast\r\n..system.\r\nZ.\r\n";
2739 size_t sz;
2741 sz = read_escaped_data(inp, strlen(inp), &out);
2742 test_streq(out,
2743 ".This is a test\nof the emergency \nbroadcast\n.system.\nZ.\n");
2744 test_eq(sz, strlen(out));
2746 done:
2747 tor_free(out);
2750 static void
2751 test_util_sscanf(void)
2753 unsigned u1, u2, u3;
2754 char s1[10], s2[10], s3[10], ch;
2755 int r;
2757 r = tor_sscanf("hello world", "hello world"); /* String match: success */
2758 test_eq(r, 0);
2759 r = tor_sscanf("hello world 3", "hello worlb %u", &u1); /* String fail */
2760 test_eq(r, 0);
2761 r = tor_sscanf("12345", "%u", &u1); /* Simple number */
2762 test_eq(r, 1);
2763 test_eq(u1, 12345u);
2764 r = tor_sscanf("", "%u", &u1); /* absent number */
2765 test_eq(r, 0);
2766 r = tor_sscanf("A", "%u", &u1); /* bogus number */
2767 test_eq(r, 0);
2768 r = tor_sscanf("4294967295", "%u", &u1); /* UINT32_MAX should work. */
2769 test_eq(r, 1);
2770 test_eq(u1, 4294967295u);
2771 r = tor_sscanf("4294967296", "%u", &u1); /* Always say -1 at 32 bits. */
2772 test_eq(r, 0);
2773 r = tor_sscanf("123456", "%2u%u", &u1, &u2); /* Width */
2774 test_eq(r, 2);
2775 test_eq(u1, 12u);
2776 test_eq(u2, 3456u);
2777 r = tor_sscanf("!12:3:456", "!%2u:%2u:%3u", &u1, &u2, &u3); /* separators */
2778 test_eq(r, 3);
2779 test_eq(u1, 12u);
2780 test_eq(u2, 3u);
2781 test_eq(u3, 456u);
2782 r = tor_sscanf("12:3:045", "%2u:%2u:%3u", &u1, &u2, &u3); /* 0s */
2783 test_eq(r, 3);
2784 test_eq(u1, 12u);
2785 test_eq(u2, 3u);
2786 test_eq(u3, 45u);
2787 /* %u does not match space.*/
2788 r = tor_sscanf("12:3: 45", "%2u:%2u:%3u", &u1, &u2, &u3);
2789 test_eq(r, 2);
2790 /* %u does not match negative numbers. */
2791 r = tor_sscanf("12:3:-4", "%2u:%2u:%3u", &u1, &u2, &u3);
2792 test_eq(r, 2);
2793 /* Arbitrary amounts of 0-padding are okay */
2794 r = tor_sscanf("12:03:000000000000000099", "%2u:%2u:%u", &u1, &u2, &u3);
2795 test_eq(r, 3);
2796 test_eq(u1, 12u);
2797 test_eq(u2, 3u);
2798 test_eq(u3, 99u);
2800 r = tor_sscanf("99% fresh", "%3u%% fresh", &u1); /* percents are scannable.*/
2801 test_eq(r, 1);
2802 test_eq(u1, 99);
2804 r = tor_sscanf("hello", "%s", s1); /* %s needs a number. */
2805 test_eq(r, -1);
2807 r = tor_sscanf("hello", "%3s%7s", s1, s2); /* %s matches characters. */
2808 test_eq(r, 2);
2809 test_streq(s1, "hel");
2810 test_streq(s2, "lo");
2811 r = tor_sscanf("WD40", "%2s%u", s3, &u1); /* %s%u */
2812 test_eq(r, 2);
2813 test_streq(s3, "WD");
2814 test_eq(u1, 40);
2815 r = tor_sscanf("76trombones", "%6u%9s", &u1, s1); /* %u%s */
2816 test_eq(r, 2);
2817 test_eq(u1, 76);
2818 test_streq(s1, "trombones");
2819 r = tor_sscanf("hello world", "%9s %9s", s1, s2); /* %s doesn't eat space. */
2820 test_eq(r, 2);
2821 test_streq(s1, "hello");
2822 test_streq(s2, "world");
2823 r = tor_sscanf("hi", "%9s%9s%3s", s1, s2, s3); /* %s can be empty. */
2824 test_eq(r, 3);
2825 test_streq(s1, "hi");
2826 test_streq(s2, "");
2827 test_streq(s3, "");
2829 r = tor_sscanf("1.2.3", "%u.%u.%u%c", &u1, &u2, &u3, &ch);
2830 test_eq(r, 3);
2831 r = tor_sscanf("1.2.3 foobar", "%u.%u.%u%c", &u1, &u2, &u3, &ch);
2832 test_eq(r, 4);
2834 done:
2838 /** Run unit tests for the onion handshake code. */
2839 static void
2840 test_onion_handshake(void)
2842 /* client-side */
2843 crypto_dh_env_t *c_dh = NULL;
2844 char c_buf[ONIONSKIN_CHALLENGE_LEN];
2845 char c_keys[40];
2847 /* server-side */
2848 char s_buf[ONIONSKIN_REPLY_LEN];
2849 char s_keys[40];
2851 /* shared */
2852 crypto_pk_env_t *pk = NULL;
2854 pk = pk_generate(0);
2856 /* client handshake 1. */
2857 memset(c_buf, 0, ONIONSKIN_CHALLENGE_LEN);
2858 test_assert(! onion_skin_create(pk, &c_dh, c_buf));
2860 /* server handshake */
2861 memset(s_buf, 0, ONIONSKIN_REPLY_LEN);
2862 memset(s_keys, 0, 40);
2863 test_assert(! onion_skin_server_handshake(c_buf, pk, NULL,
2864 s_buf, s_keys, 40));
2866 /* client handshake 2 */
2867 memset(c_keys, 0, 40);
2868 test_assert(! onion_skin_client_handshake(c_dh, s_buf, c_keys, 40));
2870 if (memcmp(c_keys, s_keys, 40)) {
2871 puts("Aiiiie");
2872 exit(1);
2874 test_memeq(c_keys, s_keys, 40);
2875 memset(s_buf, 0, 40);
2876 test_memneq(c_keys, s_buf, 40);
2878 done:
2879 if (c_dh)
2880 crypto_dh_free(c_dh);
2881 if (pk)
2882 crypto_free_pk_env(pk);
2885 /** Run unit tests for router descriptor generation logic. */
2886 static void
2887 test_dir_format(void)
2889 char buf[8192], buf2[8192];
2890 char platform[256];
2891 char fingerprint[FINGERPRINT_LEN+1];
2892 char *pk1_str = NULL, *pk2_str = NULL, *pk3_str = NULL, *cp;
2893 size_t pk1_str_len, pk2_str_len, pk3_str_len;
2894 routerinfo_t *r1=NULL, *r2=NULL;
2895 crypto_pk_env_t *pk1 = NULL, *pk2 = NULL, *pk3 = NULL;
2896 routerinfo_t *rp1 = NULL;
2897 addr_policy_t *ex1, *ex2;
2898 routerlist_t *dir1 = NULL, *dir2 = NULL;
2899 tor_version_t ver1;
2901 pk1 = pk_generate(0);
2902 pk2 = pk_generate(1);
2903 pk3 = pk_generate(2);
2905 test_assert( is_legal_nickname("a"));
2906 test_assert(!is_legal_nickname(""));
2907 test_assert(!is_legal_nickname("abcdefghijklmnopqrst")); /* 20 chars */
2908 test_assert(!is_legal_nickname("hyphen-")); /* bad char */
2909 test_assert( is_legal_nickname("abcdefghijklmnopqrs")); /* 19 chars */
2910 test_assert(!is_legal_nickname("$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2911 /* valid */
2912 test_assert( is_legal_nickname_or_hexdigest(
2913 "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2914 test_assert( is_legal_nickname_or_hexdigest(
2915 "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA=fred"));
2916 test_assert( is_legal_nickname_or_hexdigest(
2917 "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA~fred"));
2918 /* too short */
2919 test_assert(!is_legal_nickname_or_hexdigest(
2920 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2921 /* illegal char */
2922 test_assert(!is_legal_nickname_or_hexdigest(
2923 "$AAAAAAzAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2924 /* hex part too long */
2925 test_assert(!is_legal_nickname_or_hexdigest(
2926 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2927 test_assert(!is_legal_nickname_or_hexdigest(
2928 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=fred"));
2929 /* Bad nickname */
2930 test_assert(!is_legal_nickname_or_hexdigest(
2931 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="));
2932 test_assert(!is_legal_nickname_or_hexdigest(
2933 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~"));
2934 test_assert(!is_legal_nickname_or_hexdigest(
2935 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~hyphen-"));
2936 test_assert(!is_legal_nickname_or_hexdigest(
2937 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~"
2938 "abcdefghijklmnoppqrst"));
2939 /* Bad extra char. */
2940 test_assert(!is_legal_nickname_or_hexdigest(
2941 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA!"));
2942 test_assert(is_legal_nickname_or_hexdigest("xyzzy"));
2943 test_assert(is_legal_nickname_or_hexdigest("abcdefghijklmnopqrs"));
2944 test_assert(!is_legal_nickname_or_hexdigest("abcdefghijklmnopqrst"));
2946 get_platform_str(platform, sizeof(platform));
2947 r1 = tor_malloc_zero(sizeof(routerinfo_t));
2948 r1->address = tor_strdup("18.244.0.1");
2949 r1->addr = 0xc0a80001u; /* 192.168.0.1 */
2950 r1->cache_info.published_on = 0;
2951 r1->or_port = 9000;
2952 r1->dir_port = 9003;
2953 r1->onion_pkey = crypto_pk_dup_key(pk1);
2954 r1->identity_pkey = crypto_pk_dup_key(pk2);
2955 r1->bandwidthrate = 1000;
2956 r1->bandwidthburst = 5000;
2957 r1->bandwidthcapacity = 10000;
2958 r1->exit_policy = NULL;
2959 r1->nickname = tor_strdup("Magri");
2960 r1->platform = tor_strdup(platform);
2962 ex1 = tor_malloc_zero(sizeof(addr_policy_t));
2963 ex2 = tor_malloc_zero(sizeof(addr_policy_t));
2964 ex1->policy_type = ADDR_POLICY_ACCEPT;
2965 tor_addr_from_ipv4h(&ex1->addr, 0);
2966 ex1->maskbits = 0;
2967 ex1->prt_min = ex1->prt_max = 80;
2968 ex2->policy_type = ADDR_POLICY_REJECT;
2969 tor_addr_from_ipv4h(&ex2->addr, 18<<24);
2970 ex2->maskbits = 8;
2971 ex2->prt_min = ex2->prt_max = 24;
2972 r2 = tor_malloc_zero(sizeof(routerinfo_t));
2973 r2->address = tor_strdup("1.1.1.1");
2974 r2->addr = 0x0a030201u; /* 10.3.2.1 */
2975 r2->platform = tor_strdup(platform);
2976 r2->cache_info.published_on = 5;
2977 r2->or_port = 9005;
2978 r2->dir_port = 0;
2979 r2->onion_pkey = crypto_pk_dup_key(pk2);
2980 r2->identity_pkey = crypto_pk_dup_key(pk1);
2981 r2->bandwidthrate = r2->bandwidthburst = r2->bandwidthcapacity = 3000;
2982 r2->exit_policy = smartlist_create();
2983 smartlist_add(r2->exit_policy, ex2);
2984 smartlist_add(r2->exit_policy, ex1);
2985 r2->nickname = tor_strdup("Fred");
2987 test_assert(!crypto_pk_write_public_key_to_string(pk1, &pk1_str,
2988 &pk1_str_len));
2989 test_assert(!crypto_pk_write_public_key_to_string(pk2 , &pk2_str,
2990 &pk2_str_len));
2991 test_assert(!crypto_pk_write_public_key_to_string(pk3 , &pk3_str,
2992 &pk3_str_len));
2994 memset(buf, 0, 2048);
2995 test_assert(router_dump_router_to_string(buf, 2048, r1, pk2)>0);
2997 strlcpy(buf2, "router Magri 18.244.0.1 9000 0 9003\n"
2998 "platform Tor "VERSION" on ", sizeof(buf2));
2999 strlcat(buf2, get_uname(), sizeof(buf2));
3000 strlcat(buf2, "\n"
3001 "opt protocols Link 1 2 Circuit 1\n"
3002 "published 1970-01-01 00:00:00\n"
3003 "opt fingerprint ", sizeof(buf2));
3004 test_assert(!crypto_pk_get_fingerprint(pk2, fingerprint, 1));
3005 strlcat(buf2, fingerprint, sizeof(buf2));
3006 strlcat(buf2, "\nuptime 0\n"
3007 /* XXX the "0" above is hard-coded, but even if we made it reflect
3008 * uptime, that still wouldn't make it right, because the two
3009 * descriptors might be made on different seconds... hm. */
3010 "bandwidth 1000 5000 10000\n"
3011 "opt extra-info-digest 0000000000000000000000000000000000000000\n"
3012 "onion-key\n", sizeof(buf2));
3013 strlcat(buf2, pk1_str, sizeof(buf2));
3014 strlcat(buf2, "signing-key\n", sizeof(buf2));
3015 strlcat(buf2, pk2_str, sizeof(buf2));
3016 strlcat(buf2, "opt hidden-service-dir\n", sizeof(buf2));
3017 strlcat(buf2, "reject *:*\nrouter-signature\n", sizeof(buf2));
3018 buf[strlen(buf2)] = '\0'; /* Don't compare the sig; it's never the same
3019 * twice */
3021 test_streq(buf, buf2);
3023 test_assert(router_dump_router_to_string(buf, 2048, r1, pk2)>0);
3024 cp = buf;
3025 rp1 = router_parse_entry_from_string((const char*)cp,NULL,1,0,NULL);
3026 test_assert(rp1);
3027 test_streq(rp1->address, r1->address);
3028 test_eq(rp1->or_port, r1->or_port);
3029 //test_eq(rp1->dir_port, r1->dir_port);
3030 test_eq(rp1->bandwidthrate, r1->bandwidthrate);
3031 test_eq(rp1->bandwidthburst, r1->bandwidthburst);
3032 test_eq(rp1->bandwidthcapacity, r1->bandwidthcapacity);
3033 test_assert(crypto_pk_cmp_keys(rp1->onion_pkey, pk1) == 0);
3034 test_assert(crypto_pk_cmp_keys(rp1->identity_pkey, pk2) == 0);
3035 //test_assert(rp1->exit_policy == NULL);
3037 #if 0
3038 /* XXX Once we have exit policies, test this again. XXX */
3039 strlcpy(buf2, "router tor.tor.tor 9005 0 0 3000\n", sizeof(buf2));
3040 strlcat(buf2, pk2_str, sizeof(buf2));
3041 strlcat(buf2, "signing-key\n", sizeof(buf2));
3042 strlcat(buf2, pk1_str, sizeof(buf2));
3043 strlcat(buf2, "accept *:80\nreject 18.*:24\n\n", sizeof(buf2));
3044 test_assert(router_dump_router_to_string(buf, 2048, &r2, pk2)>0);
3045 test_streq(buf, buf2);
3047 cp = buf;
3048 rp2 = router_parse_entry_from_string(&cp,1);
3049 test_assert(rp2);
3050 test_streq(rp2->address, r2.address);
3051 test_eq(rp2->or_port, r2.or_port);
3052 test_eq(rp2->dir_port, r2.dir_port);
3053 test_eq(rp2->bandwidth, r2.bandwidth);
3054 test_assert(crypto_pk_cmp_keys(rp2->onion_pkey, pk2) == 0);
3055 test_assert(crypto_pk_cmp_keys(rp2->identity_pkey, pk1) == 0);
3056 test_eq(rp2->exit_policy->policy_type, EXIT_POLICY_ACCEPT);
3057 test_streq(rp2->exit_policy->string, "accept *:80");
3058 test_streq(rp2->exit_policy->address, "*");
3059 test_streq(rp2->exit_policy->port, "80");
3060 test_eq(rp2->exit_policy->next->policy_type, EXIT_POLICY_REJECT);
3061 test_streq(rp2->exit_policy->next->string, "reject 18.*:24");
3062 test_streq(rp2->exit_policy->next->address, "18.*");
3063 test_streq(rp2->exit_policy->next->port, "24");
3064 test_assert(rp2->exit_policy->next->next == NULL);
3066 /* Okay, now for the directories. */
3068 fingerprint_list = smartlist_create();
3069 crypto_pk_get_fingerprint(pk2, buf, 1);
3070 add_fingerprint_to_dir("Magri", buf, fingerprint_list);
3071 crypto_pk_get_fingerprint(pk1, buf, 1);
3072 add_fingerprint_to_dir("Fred", buf, fingerprint_list);
3076 char d[DIGEST_LEN];
3077 const char *m;
3078 /* XXXX NM re-enable. */
3079 /* Make sure routers aren't too far in the past any more. */
3080 r1->cache_info.published_on = time(NULL);
3081 r2->cache_info.published_on = time(NULL)-3*60*60;
3082 test_assert(router_dump_router_to_string(buf, 2048, r1, pk2)>0);
3083 test_eq(dirserv_add_descriptor(buf,&m,""), ROUTER_ADDED_NOTIFY_GENERATOR);
3084 test_assert(router_dump_router_to_string(buf, 2048, r2, pk1)>0);
3085 test_eq(dirserv_add_descriptor(buf,&m,""), ROUTER_ADDED_NOTIFY_GENERATOR);
3086 get_options()->Nickname = tor_strdup("DirServer");
3087 test_assert(!dirserv_dump_directory_to_string(&cp,pk3, 0));
3088 crypto_pk_get_digest(pk3, d);
3089 test_assert(!router_parse_directory(cp));
3090 test_eq(2, smartlist_len(dir1->routers));
3091 tor_free(cp);
3093 #endif
3094 dirserv_free_fingerprint_list();
3096 /* Try out version parsing functionality */
3097 test_eq(0, tor_version_parse("0.3.4pre2-cvs", &ver1));
3098 test_eq(0, ver1.major);
3099 test_eq(3, ver1.minor);
3100 test_eq(4, ver1.micro);
3101 test_eq(VER_PRE, ver1.status);
3102 test_eq(2, ver1.patchlevel);
3103 test_eq(0, tor_version_parse("0.3.4rc1", &ver1));
3104 test_eq(0, ver1.major);
3105 test_eq(3, ver1.minor);
3106 test_eq(4, ver1.micro);
3107 test_eq(VER_RC, ver1.status);
3108 test_eq(1, ver1.patchlevel);
3109 test_eq(0, tor_version_parse("1.3.4", &ver1));
3110 test_eq(1, ver1.major);
3111 test_eq(3, ver1.minor);
3112 test_eq(4, ver1.micro);
3113 test_eq(VER_RELEASE, ver1.status);
3114 test_eq(0, ver1.patchlevel);
3115 test_eq(0, tor_version_parse("1.3.4.999", &ver1));
3116 test_eq(1, ver1.major);
3117 test_eq(3, ver1.minor);
3118 test_eq(4, ver1.micro);
3119 test_eq(VER_RELEASE, ver1.status);
3120 test_eq(999, ver1.patchlevel);
3121 test_eq(0, tor_version_parse("0.1.2.4-alpha", &ver1));
3122 test_eq(0, ver1.major);
3123 test_eq(1, ver1.minor);
3124 test_eq(2, ver1.micro);
3125 test_eq(4, ver1.patchlevel);
3126 test_eq(VER_RELEASE, ver1.status);
3127 test_streq("alpha", ver1.status_tag);
3128 test_eq(0, tor_version_parse("0.1.2.4", &ver1));
3129 test_eq(0, ver1.major);
3130 test_eq(1, ver1.minor);
3131 test_eq(2, ver1.micro);
3132 test_eq(4, ver1.patchlevel);
3133 test_eq(VER_RELEASE, ver1.status);
3134 test_streq("", ver1.status_tag);
3136 #define test_eq_vs(vs1, vs2) test_eq_type(version_status_t, "%d", (vs1), (vs2))
3137 #define test_v_i_o(val, ver, lst) \
3138 test_eq_vs(val, tor_version_is_obsolete(ver, lst))
3140 /* make sure tor_version_is_obsolete() works */
3141 test_v_i_o(VS_OLD, "0.0.1", "Tor 0.0.2");
3142 test_v_i_o(VS_OLD, "0.0.1", "0.0.2, Tor 0.0.3");
3143 test_v_i_o(VS_OLD, "0.0.1", "0.0.2,Tor 0.0.3");
3144 test_v_i_o(VS_OLD, "0.0.1","0.0.3,BetterTor 0.0.1");
3145 test_v_i_o(VS_RECOMMENDED, "0.0.2", "Tor 0.0.2,Tor 0.0.3");
3146 test_v_i_o(VS_NEW_IN_SERIES, "0.0.2", "Tor 0.0.2pre1,Tor 0.0.3");
3147 test_v_i_o(VS_OLD, "0.0.2", "Tor 0.0.2.1,Tor 0.0.3");
3148 test_v_i_o(VS_NEW, "0.1.0", "Tor 0.0.2,Tor 0.0.3");
3149 test_v_i_o(VS_RECOMMENDED, "0.0.7rc2", "0.0.7,Tor 0.0.7rc2,Tor 0.0.8");
3150 test_v_i_o(VS_OLD, "0.0.5.0", "0.0.5.1-cvs");
3151 test_v_i_o(VS_NEW_IN_SERIES, "0.0.5.1-cvs", "0.0.5, 0.0.6");
3152 /* Not on list, but newer than any in same series. */
3153 test_v_i_o(VS_NEW_IN_SERIES, "0.1.0.3",
3154 "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
3155 /* Series newer than any on list. */
3156 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");
3157 /* Series older than any on list. */
3158 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");
3159 /* Not on list, not newer than any on same series. */
3160 test_v_i_o(VS_UNRECOMMENDED, "0.1.0.1",
3161 "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
3162 /* On list, not newer than any on same series. */
3163 test_v_i_o(VS_UNRECOMMENDED,
3164 "0.1.0.1", "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
3165 test_eq(0, tor_version_as_new_as("Tor 0.0.5", "0.0.9pre1-cvs"));
3166 test_eq(1, tor_version_as_new_as(
3167 "Tor 0.0.8 on Darwin 64-121-192-100.c3-0."
3168 "sfpo-ubr1.sfrn-sfpo.ca.cable.rcn.com Power Macintosh",
3169 "0.0.8rc2"));
3170 test_eq(0, tor_version_as_new_as(
3171 "Tor 0.0.8 on Darwin 64-121-192-100.c3-0."
3172 "sfpo-ubr1.sfrn-sfpo.ca.cable.rcn.com Power Macintosh", "0.0.8.2"));
3174 /* Now try svn revisions. */
3175 test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100)",
3176 "Tor 0.2.1.0-dev (r99)"));
3177 test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100) on Banana Jr",
3178 "Tor 0.2.1.0-dev (r99) on Hal 9000"));
3179 test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100)",
3180 "Tor 0.2.1.0-dev on Colossus"));
3181 test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev (r99)",
3182 "Tor 0.2.1.0-dev (r100)"));
3183 test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev (r99) on MCP",
3184 "Tor 0.2.1.0-dev (r100) on AM"));
3185 test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev",
3186 "Tor 0.2.1.0-dev (r99)"));
3187 test_eq(1, tor_version_as_new_as("Tor 0.2.1.1",
3188 "Tor 0.2.1.0-dev (r99)"));
3189 done:
3190 if (r1)
3191 routerinfo_free(r1);
3192 if (r2)
3193 routerinfo_free(r2);
3195 tor_free(pk1_str);
3196 tor_free(pk2_str);
3197 tor_free(pk3_str);
3198 if (pk1) crypto_free_pk_env(pk1);
3199 if (pk2) crypto_free_pk_env(pk2);
3200 if (pk3) crypto_free_pk_env(pk3);
3201 if (rp1) routerinfo_free(rp1);
3202 tor_free(dir1); /* XXXX And more !*/
3203 tor_free(dir2); /* And more !*/
3206 /** Run unit tests for misc directory functions. */
3207 static void
3208 test_dirutil(void)
3210 smartlist_t *sl = smartlist_create();
3211 fp_pair_t *pair;
3213 dir_split_resource_into_fingerprint_pairs(
3214 /* Two pairs, out of order, with one duplicate. */
3215 "73656372657420646174612E0000000000FFFFFF-"
3216 "557365204145532d32353620696e73746561642e+"
3217 "73656372657420646174612E0000000000FFFFFF-"
3218 "557365204145532d32353620696e73746561642e+"
3219 "48657861646563696d616c2069736e277420736f-"
3220 "676f6f6420666f7220686964696e6720796f7572.z", sl);
3222 test_eq(smartlist_len(sl), 2);
3223 pair = smartlist_get(sl, 0);
3224 test_memeq(pair->first, "Hexadecimal isn't so", DIGEST_LEN);
3225 test_memeq(pair->second, "good for hiding your", DIGEST_LEN);
3226 pair = smartlist_get(sl, 1);
3227 test_memeq(pair->first, "secret data.\0\0\0\0\0\xff\xff\xff", DIGEST_LEN);
3228 test_memeq(pair->second, "Use AES-256 instead.", DIGEST_LEN);
3230 done:
3231 SMARTLIST_FOREACH(sl, fp_pair_t *, pair, tor_free(pair));
3232 smartlist_free(sl);
3235 extern const char AUTHORITY_CERT_1[];
3236 extern const char AUTHORITY_SIGNKEY_1[];
3237 extern const char AUTHORITY_CERT_2[];
3238 extern const char AUTHORITY_SIGNKEY_2[];
3239 extern const char AUTHORITY_CERT_3[];
3240 extern const char AUTHORITY_SIGNKEY_3[];
3242 /** Helper: Test that two networkstatus_voter_info_t do in fact represent the
3243 * same voting authority, and that they do in fact have all the same
3244 * information. */
3245 static void
3246 test_same_voter(networkstatus_voter_info_t *v1,
3247 networkstatus_voter_info_t *v2)
3249 test_streq(v1->nickname, v2->nickname);
3250 test_memeq(v1->identity_digest, v2->identity_digest, DIGEST_LEN);
3251 test_streq(v1->address, v2->address);
3252 test_eq(v1->addr, v2->addr);
3253 test_eq(v1->dir_port, v2->dir_port);
3254 test_eq(v1->or_port, v2->or_port);
3255 test_streq(v1->contact, v2->contact);
3256 test_memeq(v1->vote_digest, v2->vote_digest, DIGEST_LEN);
3257 done:
3261 /** Run unit tests for getting the median of a list. */
3262 static void
3263 test_util_order_functions(void)
3265 int lst[25], n = 0;
3266 // int a=12,b=24,c=25,d=60,e=77;
3268 #define median() median_int(lst, n)
3270 lst[n++] = 12;
3271 test_eq(12, median()); /* 12 */
3272 lst[n++] = 77;
3273 //smartlist_shuffle(sl);
3274 test_eq(12, median()); /* 12, 77 */
3275 lst[n++] = 77;
3276 //smartlist_shuffle(sl);
3277 test_eq(77, median()); /* 12, 77, 77 */
3278 lst[n++] = 24;
3279 test_eq(24, median()); /* 12,24,77,77 */
3280 lst[n++] = 60;
3281 lst[n++] = 12;
3282 lst[n++] = 25;
3283 //smartlist_shuffle(sl);
3284 test_eq(25, median()); /* 12,12,24,25,60,77,77 */
3285 #undef median
3287 done:
3291 /** Helper: Make a new routerinfo containing the right information for a
3292 * given vote_routerstatus_t. */
3293 static routerinfo_t *
3294 generate_ri_from_rs(const vote_routerstatus_t *vrs)
3296 routerinfo_t *r;
3297 const routerstatus_t *rs = &vrs->status;
3298 static time_t published = 0;
3300 r = tor_malloc_zero(sizeof(routerinfo_t));
3301 memcpy(r->cache_info.identity_digest, rs->identity_digest, DIGEST_LEN);
3302 memcpy(r->cache_info.signed_descriptor_digest, rs->descriptor_digest,
3303 DIGEST_LEN);
3304 r->cache_info.do_not_cache = 1;
3305 r->cache_info.routerlist_index = -1;
3306 r->cache_info.signed_descriptor_body =
3307 tor_strdup("123456789012345678901234567890123");
3308 r->cache_info.signed_descriptor_len =
3309 strlen(r->cache_info.signed_descriptor_body);
3310 r->exit_policy = smartlist_create();
3311 r->cache_info.published_on = ++published + time(NULL);
3312 return r;
3315 /** Run unit tests for generating and parsing V3 consensus networkstatus
3316 * documents. */
3317 static void
3318 test_v3_networkstatus(void)
3320 authority_cert_t *cert1=NULL, *cert2=NULL, *cert3=NULL;
3321 crypto_pk_env_t *sign_skey_1=NULL, *sign_skey_2=NULL, *sign_skey_3=NULL;
3322 crypto_pk_env_t *sign_skey_leg1=NULL;
3323 const char *msg=NULL;
3325 time_t now = time(NULL);
3326 networkstatus_voter_info_t *voter;
3327 networkstatus_t *vote=NULL, *v1=NULL, *v2=NULL, *v3=NULL, *con=NULL;
3328 vote_routerstatus_t *vrs;
3329 routerstatus_t *rs;
3330 char *v1_text=NULL, *v2_text=NULL, *v3_text=NULL, *consensus_text=NULL, *cp;
3331 smartlist_t *votes = smartlist_create();
3333 /* For generating the two other consensuses. */
3334 char *detached_text1=NULL, *detached_text2=NULL;
3335 char *consensus_text2=NULL, *consensus_text3=NULL;
3336 networkstatus_t *con2=NULL, *con3=NULL;
3337 ns_detached_signatures_t *dsig1=NULL, *dsig2=NULL;
3339 /* Parse certificates and keys. */
3340 cert1 = authority_cert_parse_from_string(AUTHORITY_CERT_1, NULL);
3341 test_assert(cert1);
3342 test_assert(cert1->is_cross_certified);
3343 cert2 = authority_cert_parse_from_string(AUTHORITY_CERT_2, NULL);
3344 test_assert(cert2);
3345 cert3 = authority_cert_parse_from_string(AUTHORITY_CERT_3, NULL);
3346 test_assert(cert3);
3347 sign_skey_1 = crypto_new_pk_env();
3348 sign_skey_2 = crypto_new_pk_env();
3349 sign_skey_3 = crypto_new_pk_env();
3350 sign_skey_leg1 = pk_generate(4);
3352 test_assert(!crypto_pk_read_private_key_from_string(sign_skey_1,
3353 AUTHORITY_SIGNKEY_1));
3354 test_assert(!crypto_pk_read_private_key_from_string(sign_skey_2,
3355 AUTHORITY_SIGNKEY_2));
3356 test_assert(!crypto_pk_read_private_key_from_string(sign_skey_3,
3357 AUTHORITY_SIGNKEY_3));
3359 test_assert(!crypto_pk_cmp_keys(sign_skey_1, cert1->signing_key));
3360 test_assert(!crypto_pk_cmp_keys(sign_skey_2, cert2->signing_key));
3363 * Set up a vote; generate it; try to parse it.
3365 vote = tor_malloc_zero(sizeof(networkstatus_t));
3366 vote->type = NS_TYPE_VOTE;
3367 vote->published = now;
3368 vote->valid_after = now+1000;
3369 vote->fresh_until = now+2000;
3370 vote->valid_until = now+3000;
3371 vote->vote_seconds = 100;
3372 vote->dist_seconds = 200;
3373 vote->supported_methods = smartlist_create();
3374 smartlist_split_string(vote->supported_methods, "1 2 3", NULL, 0, -1);
3375 vote->client_versions = tor_strdup("0.1.2.14,0.1.2.15");
3376 vote->server_versions = tor_strdup("0.1.2.14,0.1.2.15,0.1.2.16");
3377 vote->known_flags = smartlist_create();
3378 smartlist_split_string(vote->known_flags,
3379 "Authority Exit Fast Guard Running Stable V2Dir Valid",
3380 0, SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
3381 vote->voters = smartlist_create();
3382 voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
3383 voter->nickname = tor_strdup("Voter1");
3384 voter->address = tor_strdup("1.2.3.4");
3385 voter->addr = 0x01020304;
3386 voter->dir_port = 80;
3387 voter->or_port = 9000;
3388 voter->contact = tor_strdup("voter@example.com");
3389 crypto_pk_get_digest(cert1->identity_key, voter->identity_digest);
3390 smartlist_add(vote->voters, voter);
3391 vote->cert = authority_cert_dup(cert1);
3392 vote->routerstatus_list = smartlist_create();
3393 /* add the first routerstatus. */
3394 vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
3395 rs = &vrs->status;
3396 vrs->version = tor_strdup("0.1.2.14");
3397 rs->published_on = now-1500;
3398 strlcpy(rs->nickname, "router2", sizeof(rs->nickname));
3399 memset(rs->identity_digest, 3, DIGEST_LEN);
3400 memset(rs->descriptor_digest, 78, DIGEST_LEN);
3401 rs->addr = 0x99008801;
3402 rs->or_port = 443;
3403 rs->dir_port = 8000;
3404 /* all flags but running cleared */
3405 rs->is_running = 1;
3406 smartlist_add(vote->routerstatus_list, vrs);
3407 test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs), &msg,0,0)>=0);
3409 /* add the second routerstatus. */
3410 vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
3411 rs = &vrs->status;
3412 vrs->version = tor_strdup("0.2.0.5");
3413 rs->published_on = now-1000;
3414 strlcpy(rs->nickname, "router1", sizeof(rs->nickname));
3415 memset(rs->identity_digest, 5, DIGEST_LEN);
3416 memset(rs->descriptor_digest, 77, DIGEST_LEN);
3417 rs->addr = 0x99009901;
3418 rs->or_port = 443;
3419 rs->dir_port = 0;
3420 rs->is_exit = rs->is_stable = rs->is_fast = rs->is_running =
3421 rs->is_valid = rs->is_v2_dir = rs->is_possible_guard = 1;
3422 smartlist_add(vote->routerstatus_list, vrs);
3423 test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs), &msg,0,0)>=0);
3425 /* add the third routerstatus. */
3426 vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
3427 rs = &vrs->status;
3428 vrs->version = tor_strdup("0.1.0.3");
3429 rs->published_on = now-1000;
3430 strlcpy(rs->nickname, "router3", sizeof(rs->nickname));
3431 memset(rs->identity_digest, 33, DIGEST_LEN);
3432 memset(rs->descriptor_digest, 79, DIGEST_LEN);
3433 rs->addr = 0xAA009901;
3434 rs->or_port = 400;
3435 rs->dir_port = 9999;
3436 rs->is_authority = rs->is_exit = rs->is_stable = rs->is_fast =
3437 rs->is_running = rs->is_valid = rs->is_v2_dir = rs->is_possible_guard = 1;
3438 smartlist_add(vote->routerstatus_list, vrs);
3439 test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs), &msg,0,0)>=0);
3441 /* add a fourth routerstatus that is not running. */
3442 vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
3443 rs = &vrs->status;
3444 vrs->version = tor_strdup("0.1.6.3");
3445 rs->published_on = now-1000;
3446 strlcpy(rs->nickname, "router4", sizeof(rs->nickname));
3447 memset(rs->identity_digest, 34, DIGEST_LEN);
3448 memset(rs->descriptor_digest, 48, DIGEST_LEN);
3449 rs->addr = 0xC0000203;
3450 rs->or_port = 500;
3451 rs->dir_port = 1999;
3452 /* Running flag (and others) cleared */
3453 smartlist_add(vote->routerstatus_list, vrs);
3454 test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs), &msg,0,0)>=0);
3456 /* dump the vote and try to parse it. */
3457 v1_text = format_networkstatus_vote(sign_skey_1, vote);
3458 test_assert(v1_text);
3459 v1 = networkstatus_parse_vote_from_string(v1_text, NULL, NS_TYPE_VOTE);
3460 test_assert(v1);
3462 /* Make sure the parsed thing was right. */
3463 test_eq(v1->type, NS_TYPE_VOTE);
3464 test_eq(v1->published, vote->published);
3465 test_eq(v1->valid_after, vote->valid_after);
3466 test_eq(v1->fresh_until, vote->fresh_until);
3467 test_eq(v1->valid_until, vote->valid_until);
3468 test_eq(v1->vote_seconds, vote->vote_seconds);
3469 test_eq(v1->dist_seconds, vote->dist_seconds);
3470 test_streq(v1->client_versions, vote->client_versions);
3471 test_streq(v1->server_versions, vote->server_versions);
3472 test_assert(v1->voters && smartlist_len(v1->voters));
3473 voter = smartlist_get(v1->voters, 0);
3474 test_streq(voter->nickname, "Voter1");
3475 test_streq(voter->address, "1.2.3.4");
3476 test_eq(voter->addr, 0x01020304);
3477 test_eq(voter->dir_port, 80);
3478 test_eq(voter->or_port, 9000);
3479 test_streq(voter->contact, "voter@example.com");
3480 test_assert(v1->cert);
3481 test_assert(!crypto_pk_cmp_keys(sign_skey_1, v1->cert->signing_key));
3482 cp = smartlist_join_strings(v1->known_flags, ":", 0, NULL);
3483 test_streq(cp, "Authority:Exit:Fast:Guard:Running:Stable:V2Dir:Valid");
3484 tor_free(cp);
3485 test_eq(smartlist_len(v1->routerstatus_list), 4);
3486 /* Check the first routerstatus. */
3487 vrs = smartlist_get(v1->routerstatus_list, 0);
3488 rs = &vrs->status;
3489 test_streq(vrs->version, "0.1.2.14");
3490 test_eq(rs->published_on, now-1500);
3491 test_streq(rs->nickname, "router2");
3492 test_memeq(rs->identity_digest,
3493 "\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3",
3494 DIGEST_LEN);
3495 test_memeq(rs->descriptor_digest, "NNNNNNNNNNNNNNNNNNNN", DIGEST_LEN);
3496 test_eq(rs->addr, 0x99008801);
3497 test_eq(rs->or_port, 443);
3498 test_eq(rs->dir_port, 8000);
3499 test_eq(vrs->flags, U64_LITERAL(16)); // no flags except "running"
3500 /* Check the second routerstatus. */
3501 vrs = smartlist_get(v1->routerstatus_list, 1);
3502 rs = &vrs->status;
3503 test_streq(vrs->version, "0.2.0.5");
3504 test_eq(rs->published_on, now-1000);
3505 test_streq(rs->nickname, "router1");
3506 test_memeq(rs->identity_digest,
3507 "\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5",
3508 DIGEST_LEN);
3509 test_memeq(rs->descriptor_digest, "MMMMMMMMMMMMMMMMMMMM", DIGEST_LEN);
3510 test_eq(rs->addr, 0x99009901);
3511 test_eq(rs->or_port, 443);
3512 test_eq(rs->dir_port, 0);
3513 test_eq(vrs->flags, U64_LITERAL(254)); // all flags except "authority."
3515 /* Generate second vote. It disagrees on some of the times,
3516 * and doesn't list versions, and knows some crazy flags */
3517 vote->published = now+1;
3518 vote->fresh_until = now+3005;
3519 vote->dist_seconds = 300;
3520 authority_cert_free(vote->cert);
3521 vote->cert = authority_cert_dup(cert2);
3522 tor_free(vote->client_versions);
3523 tor_free(vote->server_versions);
3524 voter = smartlist_get(vote->voters, 0);
3525 tor_free(voter->nickname);
3526 tor_free(voter->address);
3527 voter->nickname = tor_strdup("Voter2");
3528 voter->address = tor_strdup("2.3.4.5");
3529 voter->addr = 0x02030405;
3530 crypto_pk_get_digest(cert2->identity_key, voter->identity_digest);
3531 smartlist_add(vote->known_flags, tor_strdup("MadeOfCheese"));
3532 smartlist_add(vote->known_flags, tor_strdup("MadeOfTin"));
3533 smartlist_sort_strings(vote->known_flags);
3534 vrs = smartlist_get(vote->routerstatus_list, 2);
3535 smartlist_del_keeporder(vote->routerstatus_list, 2);
3536 tor_free(vrs->version);
3537 tor_free(vrs);
3538 vrs = smartlist_get(vote->routerstatus_list, 0);
3539 vrs->status.is_fast = 1;
3540 /* generate and parse. */
3541 v2_text = format_networkstatus_vote(sign_skey_2, vote);
3542 test_assert(v2_text);
3543 v2 = networkstatus_parse_vote_from_string(v2_text, NULL, NS_TYPE_VOTE);
3544 test_assert(v2);
3545 /* Check that flags come out right.*/
3546 cp = smartlist_join_strings(v2->known_flags, ":", 0, NULL);
3547 test_streq(cp, "Authority:Exit:Fast:Guard:MadeOfCheese:MadeOfTin:"
3548 "Running:Stable:V2Dir:Valid");
3549 tor_free(cp);
3550 vrs = smartlist_get(v2->routerstatus_list, 1);
3551 /* 1023 - authority(1) - madeofcheese(16) - madeoftin(32) */
3552 test_eq(vrs->flags, U64_LITERAL(974));
3554 /* Generate the third vote. */
3555 vote->published = now;
3556 vote->fresh_until = now+2003;
3557 vote->dist_seconds = 250;
3558 authority_cert_free(vote->cert);
3559 vote->cert = authority_cert_dup(cert3);
3560 smartlist_add(vote->supported_methods, tor_strdup("4"));
3561 vote->client_versions = tor_strdup("0.1.2.14,0.1.2.17");
3562 vote->server_versions = tor_strdup("0.1.2.10,0.1.2.15,0.1.2.16");
3563 voter = smartlist_get(vote->voters, 0);
3564 tor_free(voter->nickname);
3565 tor_free(voter->address);
3566 voter->nickname = tor_strdup("Voter3");
3567 voter->address = tor_strdup("3.4.5.6");
3568 voter->addr = 0x03040506;
3569 crypto_pk_get_digest(cert3->identity_key, voter->identity_digest);
3570 /* This one has a legacy id. */
3571 memset(voter->legacy_id_digest, (int)'A', DIGEST_LEN);
3572 vrs = smartlist_get(vote->routerstatus_list, 0);
3573 smartlist_del_keeporder(vote->routerstatus_list, 0);
3574 tor_free(vrs->version);
3575 tor_free(vrs);
3576 vrs = smartlist_get(vote->routerstatus_list, 0);
3577 memset(vrs->status.descriptor_digest, (int)'Z', DIGEST_LEN);
3578 test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs), &msg,0,0)>=0);
3580 v3_text = format_networkstatus_vote(sign_skey_3, vote);
3581 test_assert(v3_text);
3583 v3 = networkstatus_parse_vote_from_string(v3_text, NULL, NS_TYPE_VOTE);
3584 test_assert(v3);
3586 /* Compute a consensus as voter 3. */
3587 smartlist_add(votes, v3);
3588 smartlist_add(votes, v1);
3589 smartlist_add(votes, v2);
3590 consensus_text = networkstatus_compute_consensus(votes, 3,
3591 cert3->identity_key,
3592 sign_skey_3,
3593 "AAAAAAAAAAAAAAAAAAAA",
3594 sign_skey_leg1);
3595 test_assert(consensus_text);
3596 con = networkstatus_parse_vote_from_string(consensus_text, NULL,
3597 NS_TYPE_CONSENSUS);
3598 test_assert(con);
3599 //log_notice(LD_GENERAL, "<<%s>>\n<<%s>>\n<<%s>>\n",
3600 // v1_text, v2_text, v3_text);
3602 /* Check consensus contents. */
3603 test_assert(con->type == NS_TYPE_CONSENSUS);
3604 test_eq(con->published, 0); /* this field only appears in votes. */
3605 test_eq(con->valid_after, now+1000);
3606 test_eq(con->fresh_until, now+2003); /* median */
3607 test_eq(con->valid_until, now+3000);
3608 test_eq(con->vote_seconds, 100);
3609 test_eq(con->dist_seconds, 250); /* median */
3610 test_streq(con->client_versions, "0.1.2.14");
3611 test_streq(con->server_versions, "0.1.2.15,0.1.2.16");
3612 cp = smartlist_join_strings(v2->known_flags, ":", 0, NULL);
3613 test_streq(cp, "Authority:Exit:Fast:Guard:MadeOfCheese:MadeOfTin:"
3614 "Running:Stable:V2Dir:Valid");
3615 tor_free(cp);
3616 test_eq(4, smartlist_len(con->voters)); /*3 voters, 1 legacy key.*/
3617 /* The voter id digests should be in this order. */
3618 test_assert(memcmp(cert2->cache_info.identity_digest,
3619 cert1->cache_info.identity_digest,DIGEST_LEN)<0);
3620 test_assert(memcmp(cert1->cache_info.identity_digest,
3621 cert3->cache_info.identity_digest,DIGEST_LEN)<0);
3622 test_same_voter(smartlist_get(con->voters, 1),
3623 smartlist_get(v2->voters, 0));
3624 test_same_voter(smartlist_get(con->voters, 2),
3625 smartlist_get(v1->voters, 0));
3626 test_same_voter(smartlist_get(con->voters, 3),
3627 smartlist_get(v3->voters, 0));
3629 test_assert(!con->cert);
3630 test_eq(2, smartlist_len(con->routerstatus_list));
3631 /* There should be two listed routers: one with identity 3, one with
3632 * identity 5. */
3633 /* This one showed up in 2 digests. */
3634 rs = smartlist_get(con->routerstatus_list, 0);
3635 test_memeq(rs->identity_digest,
3636 "\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3",
3637 DIGEST_LEN);
3638 test_memeq(rs->descriptor_digest, "NNNNNNNNNNNNNNNNNNNN", DIGEST_LEN);
3639 test_assert(!rs->is_authority);
3640 test_assert(!rs->is_exit);
3641 test_assert(!rs->is_fast);
3642 test_assert(!rs->is_possible_guard);
3643 test_assert(!rs->is_stable);
3644 test_assert(rs->is_running); /* If it wasn't running it wouldn't be here */
3645 test_assert(!rs->is_v2_dir);
3646 test_assert(!rs->is_valid);
3647 test_assert(!rs->is_named);
3648 /* XXXX check version */
3650 rs = smartlist_get(con->routerstatus_list, 1);
3651 /* This one showed up in 3 digests. Twice with ID 'M', once with 'Z'. */
3652 test_memeq(rs->identity_digest,
3653 "\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5",
3654 DIGEST_LEN);
3655 test_streq(rs->nickname, "router1");
3656 test_memeq(rs->descriptor_digest, "MMMMMMMMMMMMMMMMMMMM", DIGEST_LEN);
3657 test_eq(rs->published_on, now-1000);
3658 test_eq(rs->addr, 0x99009901);
3659 test_eq(rs->or_port, 443);
3660 test_eq(rs->dir_port, 0);
3661 test_assert(!rs->is_authority);
3662 test_assert(rs->is_exit);
3663 test_assert(rs->is_fast);
3664 test_assert(rs->is_possible_guard);
3665 test_assert(rs->is_stable);
3666 test_assert(rs->is_running);
3667 test_assert(rs->is_v2_dir);
3668 test_assert(rs->is_valid);
3669 test_assert(!rs->is_named);
3670 /* XXXX check version */
3671 // x231
3672 // x213
3674 /* Check signatures. the first voter is a pseudo-entry with a legacy key.
3675 * The second one hasn't signed. The fourth one has signed: validate it. */
3676 voter = smartlist_get(con->voters, 1);
3677 test_assert(!voter->signature);
3678 test_assert(!voter->good_signature);
3679 test_assert(!voter->bad_signature);
3681 voter = smartlist_get(con->voters, 3);
3682 test_assert(voter->signature);
3683 test_assert(!voter->good_signature);
3684 test_assert(!voter->bad_signature);
3685 test_assert(!networkstatus_check_voter_signature(con,
3686 smartlist_get(con->voters, 3),
3687 cert3));
3688 test_assert(voter->signature);
3689 test_assert(voter->good_signature);
3690 test_assert(!voter->bad_signature);
3693 const char *msg=NULL;
3694 /* Compute the other two signed consensuses. */
3695 smartlist_shuffle(votes);
3696 consensus_text2 = networkstatus_compute_consensus(votes, 3,
3697 cert2->identity_key,
3698 sign_skey_2, NULL,NULL);
3699 smartlist_shuffle(votes);
3700 consensus_text3 = networkstatus_compute_consensus(votes, 3,
3701 cert1->identity_key,
3702 sign_skey_1, NULL,NULL);
3703 test_assert(consensus_text2);
3704 test_assert(consensus_text3);
3705 con2 = networkstatus_parse_vote_from_string(consensus_text2, NULL,
3706 NS_TYPE_CONSENSUS);
3707 con3 = networkstatus_parse_vote_from_string(consensus_text3, NULL,
3708 NS_TYPE_CONSENSUS);
3709 test_assert(con2);
3710 test_assert(con3);
3712 /* All three should have the same digest. */
3713 test_memeq(con->networkstatus_digest, con2->networkstatus_digest,
3714 DIGEST_LEN);
3715 test_memeq(con->networkstatus_digest, con3->networkstatus_digest,
3716 DIGEST_LEN);
3718 /* Extract a detached signature from con3. */
3719 detached_text1 = networkstatus_get_detached_signatures(con3);
3720 tor_assert(detached_text1);
3721 /* Try to parse it. */
3722 dsig1 = networkstatus_parse_detached_signatures(detached_text1, NULL);
3723 tor_assert(dsig1);
3725 /* Are parsed values as expected? */
3726 test_eq(dsig1->valid_after, con3->valid_after);
3727 test_eq(dsig1->fresh_until, con3->fresh_until);
3728 test_eq(dsig1->valid_until, con3->valid_until);
3729 test_memeq(dsig1->networkstatus_digest, con3->networkstatus_digest,
3730 DIGEST_LEN);
3731 test_eq(1, smartlist_len(dsig1->signatures));
3732 voter = smartlist_get(dsig1->signatures, 0);
3733 test_memeq(voter->identity_digest, cert1->cache_info.identity_digest,
3734 DIGEST_LEN);
3736 /* Try adding it to con2. */
3737 detached_text2 = networkstatus_get_detached_signatures(con2);
3738 test_eq(1, networkstatus_add_detached_signatures(con2, dsig1, &msg));
3739 tor_free(detached_text2);
3740 detached_text2 = networkstatus_get_detached_signatures(con2);
3741 //printf("\n<%s>\n", detached_text2);
3742 dsig2 = networkstatus_parse_detached_signatures(detached_text2, NULL);
3743 test_assert(dsig2);
3745 printf("\n");
3746 SMARTLIST_FOREACH(dsig2->signatures, networkstatus_voter_info_t *, vi, {
3747 char hd[64];
3748 base16_encode(hd, sizeof(hd), vi->identity_digest, DIGEST_LEN);
3749 printf("%s\n", hd);
3752 test_eq(2, smartlist_len(dsig2->signatures));
3754 /* Try adding to con2 twice; verify that nothing changes. */
3755 test_eq(0, networkstatus_add_detached_signatures(con2, dsig1, &msg));
3757 /* Add to con. */
3758 test_eq(2, networkstatus_add_detached_signatures(con, dsig2, &msg));
3759 /* Check signatures */
3760 test_assert(!networkstatus_check_voter_signature(con,
3761 smartlist_get(con->voters, 1),
3762 cert2));
3763 test_assert(!networkstatus_check_voter_signature(con,
3764 smartlist_get(con->voters, 2),
3765 cert1));
3769 done:
3770 smartlist_free(votes);
3771 tor_free(v1_text);
3772 tor_free(v2_text);
3773 tor_free(v3_text);
3774 tor_free(consensus_text);
3776 if (vote)
3777 networkstatus_vote_free(vote);
3778 if (v1)
3779 networkstatus_vote_free(v1);
3780 if (v2)
3781 networkstatus_vote_free(v2);
3782 if (v3)
3783 networkstatus_vote_free(v3);
3784 if (con)
3785 networkstatus_vote_free(con);
3786 if (sign_skey_1)
3787 crypto_free_pk_env(sign_skey_1);
3788 if (sign_skey_2)
3789 crypto_free_pk_env(sign_skey_2);
3790 if (sign_skey_3)
3791 crypto_free_pk_env(sign_skey_3);
3792 if (sign_skey_leg1)
3793 crypto_free_pk_env(sign_skey_leg1);
3794 if (cert1)
3795 authority_cert_free(cert1);
3796 if (cert2)
3797 authority_cert_free(cert2);
3798 if (cert3)
3799 authority_cert_free(cert3);
3801 tor_free(consensus_text2);
3802 tor_free(consensus_text3);
3803 tor_free(detached_text1);
3804 tor_free(detached_text2);
3805 if (con2)
3806 networkstatus_vote_free(con2);
3807 if (con3)
3808 networkstatus_vote_free(con3);
3809 if (dsig1)
3810 ns_detached_signatures_free(dsig1);
3811 if (dsig2)
3812 ns_detached_signatures_free(dsig2);
3815 /** Helper: Parse the exit policy string in <b>policy_str</b>, and make sure
3816 * that policies_summarize() produces the string <b>expected_summary</b> from
3817 * it. */
3818 static void
3819 test_policy_summary_helper(const char *policy_str,
3820 const char *expected_summary)
3822 config_line_t line;
3823 smartlist_t *policy = smartlist_create();
3824 char *summary = NULL;
3825 int r;
3827 line.key = (char*)"foo";
3828 line.value = (char *)policy_str;
3829 line.next = NULL;
3831 r = policies_parse_exit_policy(&line, &policy, 0, NULL);
3832 test_eq(r, 0);
3833 summary = policy_summarize(policy);
3835 test_assert(summary != NULL);
3836 test_streq(summary, expected_summary);
3838 done:
3839 tor_free(summary);
3840 if (policy)
3841 addr_policy_list_free(policy);
3844 /** Run unit tests for generating summary lines of exit policies */
3845 static void
3846 test_policies(void)
3848 int i;
3849 smartlist_t *policy = NULL, *policy2 = NULL;
3850 addr_policy_t *p;
3851 tor_addr_t tar;
3852 config_line_t line;
3853 smartlist_t *sm = NULL;
3854 char *policy_str = NULL;
3856 policy = smartlist_create();
3858 p = router_parse_addr_policy_item_from_string("reject 192.168.0.0/16:*",-1);
3859 test_assert(p != NULL);
3860 test_eq(ADDR_POLICY_REJECT, p->policy_type);
3861 tor_addr_from_ipv4h(&tar, 0xc0a80000u);
3862 test_eq(0, tor_addr_compare(&p->addr, &tar, CMP_EXACT));
3863 test_eq(16, p->maskbits);
3864 test_eq(1, p->prt_min);
3865 test_eq(65535, p->prt_max);
3867 smartlist_add(policy, p);
3869 test_assert(ADDR_POLICY_ACCEPTED ==
3870 compare_addr_to_addr_policy(0x01020304u, 2, policy));
3871 test_assert(ADDR_POLICY_PROBABLY_ACCEPTED ==
3872 compare_addr_to_addr_policy(0, 2, policy));
3873 test_assert(ADDR_POLICY_REJECTED ==
3874 compare_addr_to_addr_policy(0xc0a80102, 2, policy));
3876 policy2 = NULL;
3877 test_assert(0 == policies_parse_exit_policy(NULL, &policy2, 1, NULL));
3878 test_assert(policy2);
3880 test_assert(!exit_policy_is_general_exit(policy));
3881 test_assert(exit_policy_is_general_exit(policy2));
3882 test_assert(!exit_policy_is_general_exit(NULL));
3884 test_assert(cmp_addr_policies(policy, policy2));
3885 test_assert(cmp_addr_policies(policy, NULL));
3886 test_assert(!cmp_addr_policies(policy2, policy2));
3887 test_assert(!cmp_addr_policies(NULL, NULL));
3889 test_assert(!policy_is_reject_star(policy2));
3890 test_assert(policy_is_reject_star(policy));
3891 test_assert(policy_is_reject_star(NULL));
3893 addr_policy_list_free(policy);
3894 policy = NULL;
3896 /* make sure compacting logic works. */
3897 policy = NULL;
3898 line.key = (char*)"foo";
3899 line.value = (char*)"accept *:80,reject private:*,reject *:*";
3900 line.next = NULL;
3901 test_assert(0 == policies_parse_exit_policy(&line, &policy, 0, NULL));
3902 test_assert(policy);
3903 //test_streq(policy->string, "accept *:80");
3904 //test_streq(policy->next->string, "reject *:*");
3905 test_eq(smartlist_len(policy), 2);
3907 /* test policy summaries */
3908 /* check if we properly ignore private IP addresses */
3909 test_policy_summary_helper("reject 192.168.0.0/16:*,"
3910 "reject 0.0.0.0/8:*,"
3911 "reject 10.0.0.0/8:*,"
3912 "accept *:10-30,"
3913 "accept *:90,"
3914 "reject *:*",
3915 "accept 10-30,90");
3916 /* check all accept policies, and proper counting of rejects */
3917 test_policy_summary_helper("reject 11.0.0.0/9:80,"
3918 "reject 12.0.0.0/9:80,"
3919 "reject 13.0.0.0/9:80,"
3920 "reject 14.0.0.0/9:80,"
3921 "accept *:*", "accept 1-65535");
3922 test_policy_summary_helper("reject 11.0.0.0/9:80,"
3923 "reject 12.0.0.0/9:80,"
3924 "reject 13.0.0.0/9:80,"
3925 "reject 14.0.0.0/9:80,"
3926 "reject 15.0.0.0:81,"
3927 "accept *:*", "accept 1-65535");
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 "reject 15.0.0.0:80,"
3933 "accept *:*",
3934 "reject 80");
3935 /* no exits */
3936 test_policy_summary_helper("accept 11.0.0.0/9:80,"
3937 "reject *:*",
3938 "reject 1-65535");
3939 /* port merging */
3940 test_policy_summary_helper("accept *:80,"
3941 "accept *:81,"
3942 "accept *:100-110,"
3943 "accept *:111,"
3944 "reject *:*",
3945 "accept 80-81,100-111");
3946 /* border ports */
3947 test_policy_summary_helper("accept *:1,"
3948 "accept *:3,"
3949 "accept *:65535,"
3950 "reject *:*",
3951 "accept 1,3,65535");
3952 /* holes */
3953 test_policy_summary_helper("accept *:1,"
3954 "accept *:3,"
3955 "accept *:5,"
3956 "accept *:7,"
3957 "reject *:*",
3958 "accept 1,3,5,7");
3959 test_policy_summary_helper("reject *:1,"
3960 "reject *:3,"
3961 "reject *:5,"
3962 "reject *:7,"
3963 "accept *:*",
3964 "reject 1,3,5,7");
3966 /* truncation ports */
3967 sm = smartlist_create();
3968 for (i=1; i<2000; i+=2) {
3969 char buf[POLICY_BUF_LEN];
3970 tor_snprintf(buf, sizeof(buf), "reject *:%d", i);
3971 smartlist_add(sm, tor_strdup(buf));
3973 smartlist_add(sm, tor_strdup("accept *:*"));
3974 policy_str = smartlist_join_strings(sm, ",", 0, NULL);
3975 test_policy_summary_helper( policy_str,
3976 "accept 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,"
3977 "46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,"
3978 "92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,"
3979 "130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,"
3980 "166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198,200,"
3981 "202,204,206,208,210,212,214,216,218,220,222,224,226,228,230,232,234,236,"
3982 "238,240,242,244,246,248,250,252,254,256,258,260,262,264,266,268,270,272,"
3983 "274,276,278,280,282,284,286,288,290,292,294,296,298,300,302,304,306,308,"
3984 "310,312,314,316,318,320,322,324,326,328,330,332,334,336,338,340,342,344,"
3985 "346,348,350,352,354,356,358,360,362,364,366,368,370,372,374,376,378,380,"
3986 "382,384,386,388,390,392,394,396,398,400,402,404,406,408,410,412,414,416,"
3987 "418,420,422,424,426,428,430,432,434,436,438,440,442,444,446,448,450,452,"
3988 "454,456,458,460,462,464,466,468,470,472,474,476,478,480,482,484,486,488,"
3989 "490,492,494,496,498,500,502,504,506,508,510,512,514,516,518,520,522");
3991 done:
3992 if (policy)
3993 addr_policy_list_free(policy);
3994 if (policy2)
3995 addr_policy_list_free(policy2);
3996 tor_free(policy_str);
3997 if (sm) {
3998 SMARTLIST_FOREACH(sm, char *, s, tor_free(s));
3999 smartlist_free(sm);
4003 /** Run unit tests for basic rendezvous functions. */
4004 static void
4005 test_rend_fns(void)
4007 char address1[] = "fooaddress.onion";
4008 char address2[] = "aaaaaaaaaaaaaaaa.onion";
4009 char address3[] = "fooaddress.exit";
4010 char address4[] = "www.torproject.org";
4011 rend_service_descriptor_t *d1 =
4012 tor_malloc_zero(sizeof(rend_service_descriptor_t));
4013 rend_service_descriptor_t *d2 = NULL;
4014 char *encoded = NULL;
4015 size_t len;
4016 time_t now;
4017 int i;
4018 crypto_pk_env_t *pk1 = pk_generate(0), *pk2 = pk_generate(1);
4020 /* Test unversioned (v0) descriptor */
4021 d1->pk = crypto_pk_dup_key(pk1);
4022 now = time(NULL);
4023 d1->timestamp = now;
4024 d1->version = 0;
4025 d1->intro_nodes = smartlist_create();
4026 for (i = 0; i < 3; i++) {
4027 rend_intro_point_t *intro = tor_malloc_zero(sizeof(rend_intro_point_t));
4028 intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
4029 crypto_rand(intro->extend_info->identity_digest, DIGEST_LEN);
4030 intro->extend_info->nickname[0] = '$';
4031 base16_encode(intro->extend_info->nickname+1, HEX_DIGEST_LEN+1,
4032 intro->extend_info->identity_digest, DIGEST_LEN);
4033 smartlist_add(d1->intro_nodes, intro);
4035 test_assert(! rend_encode_service_descriptor(d1, pk1, &encoded, &len));
4036 d2 = rend_parse_service_descriptor(encoded, len);
4037 test_assert(d2);
4039 test_assert(!crypto_pk_cmp_keys(d1->pk, d2->pk));
4040 test_eq(d2->timestamp, now);
4041 test_eq(d2->version, 0);
4042 test_eq(d2->protocols, 1<<2);
4043 test_eq(smartlist_len(d2->intro_nodes), 3);
4044 for (i = 0; i < 3; i++) {
4045 rend_intro_point_t *intro1 = smartlist_get(d1->intro_nodes, i);
4046 rend_intro_point_t *intro2 = smartlist_get(d2->intro_nodes, i);
4047 test_streq(intro1->extend_info->nickname,
4048 intro2->extend_info->nickname);
4051 test_assert(BAD_HOSTNAME == parse_extended_hostname(address1));
4052 test_assert(ONION_HOSTNAME == parse_extended_hostname(address2));
4053 test_assert(EXIT_HOSTNAME == parse_extended_hostname(address3));
4054 test_assert(NORMAL_HOSTNAME == parse_extended_hostname(address4));
4056 crypto_free_pk_env(pk1);
4057 crypto_free_pk_env(pk2);
4058 pk1 = pk2 = NULL;
4059 rend_service_descriptor_free(d1);
4060 rend_service_descriptor_free(d2);
4061 d1 = d2 = NULL;
4063 done:
4064 if (pk1)
4065 crypto_free_pk_env(pk1);
4066 if (pk2)
4067 crypto_free_pk_env(pk2);
4068 if (d1)
4069 rend_service_descriptor_free(d1);
4070 if (d2)
4071 rend_service_descriptor_free(d2);
4072 tor_free(encoded);
4075 /** Run AES performance benchmarks. */
4076 static void
4077 bench_aes(void)
4079 int len, i;
4080 char *b1, *b2;
4081 crypto_cipher_env_t *c;
4082 struct timeval start, end;
4083 const int iters = 100000;
4084 uint64_t nsec;
4085 c = crypto_new_cipher_env();
4086 crypto_cipher_generate_key(c);
4087 crypto_cipher_encrypt_init_cipher(c);
4088 for (len = 1; len <= 8192; len *= 2) {
4089 b1 = tor_malloc_zero(len);
4090 b2 = tor_malloc_zero(len);
4091 tor_gettimeofday(&start);
4092 for (i = 0; i < iters; ++i) {
4093 crypto_cipher_encrypt(c, b1, b2, len);
4095 tor_gettimeofday(&end);
4096 tor_free(b1);
4097 tor_free(b2);
4098 nsec = (uint64_t) tv_udiff(&start,&end);
4099 nsec *= 1000;
4100 nsec /= (iters*len);
4101 printf("%d bytes: "U64_FORMAT" nsec per byte\n", len,
4102 U64_PRINTF_ARG(nsec));
4104 crypto_free_cipher_env(c);
4107 /** Run digestmap_t performance benchmarks. */
4108 static void
4109 bench_dmap(void)
4111 smartlist_t *sl = smartlist_create();
4112 smartlist_t *sl2 = smartlist_create();
4113 struct timeval start, end, pt2, pt3, pt4;
4114 const int iters = 10000;
4115 const int elts = 4000;
4116 const int fpostests = 1000000;
4117 char d[20];
4118 int i,n=0, fp = 0;
4119 digestmap_t *dm = digestmap_new();
4120 digestset_t *ds = digestset_new(elts);
4122 for (i = 0; i < elts; ++i) {
4123 crypto_rand(d, 20);
4124 smartlist_add(sl, tor_memdup(d, 20));
4126 for (i = 0; i < elts; ++i) {
4127 crypto_rand(d, 20);
4128 smartlist_add(sl2, tor_memdup(d, 20));
4130 printf("nbits=%d\n", ds->mask+1);
4132 tor_gettimeofday(&start);
4133 for (i = 0; i < iters; ++i) {
4134 SMARTLIST_FOREACH(sl, const char *, cp, digestmap_set(dm, cp, (void*)1));
4136 tor_gettimeofday(&pt2);
4137 for (i = 0; i < iters; ++i) {
4138 SMARTLIST_FOREACH(sl, const char *, cp, digestmap_get(dm, cp));
4139 SMARTLIST_FOREACH(sl2, const char *, cp, digestmap_get(dm, cp));
4141 tor_gettimeofday(&pt3);
4142 for (i = 0; i < iters; ++i) {
4143 SMARTLIST_FOREACH(sl, const char *, cp, digestset_add(ds, cp));
4145 tor_gettimeofday(&pt4);
4146 for (i = 0; i < iters; ++i) {
4147 SMARTLIST_FOREACH(sl, const char *, cp, n += digestset_isin(ds, cp));
4148 SMARTLIST_FOREACH(sl2, const char *, cp, n += digestset_isin(ds, cp));
4150 tor_gettimeofday(&end);
4152 for (i = 0; i < fpostests; ++i) {
4153 crypto_rand(d, 20);
4154 if (digestset_isin(ds, d)) ++fp;
4157 printf("%ld\n",(unsigned long)tv_udiff(&start, &pt2));
4158 printf("%ld\n",(unsigned long)tv_udiff(&pt2, &pt3));
4159 printf("%ld\n",(unsigned long)tv_udiff(&pt3, &pt4));
4160 printf("%ld\n",(unsigned long)tv_udiff(&pt4, &end));
4161 printf("-- %d\n", n);
4162 printf("++ %f\n", fp/(double)fpostests);
4163 digestmap_free(dm, NULL);
4164 digestset_free(ds);
4165 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
4166 SMARTLIST_FOREACH(sl2, char *, cp, tor_free(cp));
4167 smartlist_free(sl);
4168 smartlist_free(sl2);
4171 /** Run unittests for memory pool allocator */
4172 static void
4173 test_util_mempool(void)
4175 mp_pool_t *pool = NULL;
4176 smartlist_t *allocated = NULL;
4177 int i;
4179 pool = mp_pool_new(1, 100);
4180 test_assert(pool);
4181 test_assert(pool->new_chunk_capacity >= 100);
4182 test_assert(pool->item_alloc_size >= sizeof(void*)+1);
4183 mp_pool_destroy(pool);
4184 pool = NULL;
4186 pool = mp_pool_new(241, 2500);
4187 test_assert(pool);
4188 test_assert(pool->new_chunk_capacity >= 10);
4189 test_assert(pool->item_alloc_size >= sizeof(void*)+241);
4190 test_eq(pool->item_alloc_size & 0x03, 0);
4191 test_assert(pool->new_chunk_capacity < 60);
4193 allocated = smartlist_create();
4194 for (i = 0; i < 20000; ++i) {
4195 if (smartlist_len(allocated) < 20 || crypto_rand_int(2)) {
4196 void *m = mp_pool_get(pool);
4197 memset(m, 0x09, 241);
4198 smartlist_add(allocated, m);
4199 //printf("%d: %p\n", i, m);
4200 //mp_pool_assert_ok(pool);
4201 } else {
4202 int idx = crypto_rand_int(smartlist_len(allocated));
4203 void *m = smartlist_get(allocated, idx);
4204 //printf("%d: free %p\n", i, m);
4205 smartlist_del(allocated, idx);
4206 mp_pool_release(m);
4207 //mp_pool_assert_ok(pool);
4209 if (crypto_rand_int(777)==0)
4210 mp_pool_clean(pool, 1, 1);
4212 if (i % 777)
4213 mp_pool_assert_ok(pool);
4216 done:
4217 if (allocated) {
4218 SMARTLIST_FOREACH(allocated, void *, m, mp_pool_release(m));
4219 mp_pool_assert_ok(pool);
4220 mp_pool_clean(pool, 0, 0);
4221 mp_pool_assert_ok(pool);
4222 smartlist_free(allocated);
4225 if (pool)
4226 mp_pool_destroy(pool);
4229 /** Run unittests for memory area allocator */
4230 static void
4231 test_util_memarea(void)
4233 memarea_t *area = memarea_new();
4234 char *p1, *p2, *p3, *p1_orig;
4235 void *malloced_ptr = NULL;
4236 int i;
4238 test_assert(area);
4240 p1_orig = p1 = memarea_alloc(area,64);
4241 p2 = memarea_alloc_zero(area,52);
4242 p3 = memarea_alloc(area,11);
4244 test_assert(memarea_owns_ptr(area, p1));
4245 test_assert(memarea_owns_ptr(area, p2));
4246 test_assert(memarea_owns_ptr(area, p3));
4247 /* Make sure we left enough space. */
4248 test_assert(p1+64 <= p2);
4249 test_assert(p2+52 <= p3);
4250 /* Make sure we aligned. */
4251 test_eq(((uintptr_t)p1) % sizeof(void*), 0);
4252 test_eq(((uintptr_t)p2) % sizeof(void*), 0);
4253 test_eq(((uintptr_t)p3) % sizeof(void*), 0);
4254 test_assert(!memarea_owns_ptr(area, p3+8192));
4255 test_assert(!memarea_owns_ptr(area, p3+30));
4256 test_assert(tor_mem_is_zero(p2, 52));
4257 /* Make sure we don't overalign. */
4258 p1 = memarea_alloc(area, 1);
4259 p2 = memarea_alloc(area, 1);
4260 test_eq(p1+sizeof(void*), p2);
4262 malloced_ptr = tor_malloc(64);
4263 test_assert(!memarea_owns_ptr(area, malloced_ptr));
4264 tor_free(malloced_ptr);
4267 /* memarea_memdup */
4269 malloced_ptr = tor_malloc(64);
4270 crypto_rand((char*)malloced_ptr, 64);
4271 p1 = memarea_memdup(area, malloced_ptr, 64);
4272 test_assert(p1 != malloced_ptr);
4273 test_memeq(p1, malloced_ptr, 64);
4274 tor_free(malloced_ptr);
4277 /* memarea_strdup. */
4278 p1 = memarea_strdup(area,"");
4279 p2 = memarea_strdup(area, "abcd");
4280 test_assert(p1);
4281 test_assert(p2);
4282 test_streq(p1, "");
4283 test_streq(p2, "abcd");
4285 /* memarea_strndup. */
4287 const char *s = "Ad ogni porta batte la morte e grida: il nome!";
4288 /* (From Turandot, act 3.) */
4289 size_t len = strlen(s);
4290 p1 = memarea_strndup(area, s, 1000);
4291 p2 = memarea_strndup(area, s, 10);
4292 test_streq(p1, s);
4293 test_assert(p2 >= p1 + len + 1);
4294 test_memeq(s, p2, 10);
4295 test_eq(p2[10], '\0');
4296 p3 = memarea_strndup(area, s, len);
4297 test_streq(p3, s);
4298 p3 = memarea_strndup(area, s, len-1);
4299 test_memeq(s, p3, len-1);
4300 test_eq(p3[len-1], '\0');
4303 memarea_clear(area);
4304 p1 = memarea_alloc(area, 1);
4305 test_eq(p1, p1_orig);
4306 memarea_clear(area);
4308 /* Check for running over an area's size. */
4309 for (i = 0; i < 512; ++i) {
4310 p1 = memarea_alloc(area, crypto_rand_int(5)+1);
4311 test_assert(memarea_owns_ptr(area, p1));
4313 memarea_assert_ok(area);
4314 /* Make sure we can allocate a too-big object. */
4315 p1 = memarea_alloc_zero(area, 9000);
4316 p2 = memarea_alloc_zero(area, 16);
4317 test_assert(memarea_owns_ptr(area, p1));
4318 test_assert(memarea_owns_ptr(area, p2));
4320 done:
4321 memarea_drop_all(area);
4322 tor_free(malloced_ptr);
4325 /** Run unit tests for utility functions to get file names relative to
4326 * the data directory. */
4327 static void
4328 test_util_datadir(void)
4330 char buf[1024];
4331 char *f = NULL;
4333 f = get_datadir_fname(NULL);
4334 test_streq(f, temp_dir);
4335 tor_free(f);
4336 f = get_datadir_fname("state");
4337 tor_snprintf(buf, sizeof(buf), "%s"PATH_SEPARATOR"state", temp_dir);
4338 test_streq(f, buf);
4339 tor_free(f);
4340 f = get_datadir_fname2("cache", "thingy");
4341 tor_snprintf(buf, sizeof(buf),
4342 "%s"PATH_SEPARATOR"cache"PATH_SEPARATOR"thingy", temp_dir);
4343 test_streq(f, buf);
4344 tor_free(f);
4345 f = get_datadir_fname2_suffix("cache", "thingy", ".foo");
4346 tor_snprintf(buf, sizeof(buf),
4347 "%s"PATH_SEPARATOR"cache"PATH_SEPARATOR"thingy.foo", temp_dir);
4348 test_streq(f, buf);
4349 tor_free(f);
4350 f = get_datadir_fname_suffix("cache", ".foo");
4351 tor_snprintf(buf, sizeof(buf), "%s"PATH_SEPARATOR"cache.foo",
4352 temp_dir);
4353 test_streq(f, buf);
4355 done:
4356 tor_free(f);
4359 /** Test AES-CTR encryption and decryption with IV. */
4360 static void
4361 test_crypto_aes_iv(void)
4363 crypto_cipher_env_t *cipher;
4364 char *plain, *encrypted1, *encrypted2, *decrypted1, *decrypted2;
4365 char plain_1[1], plain_15[15], plain_16[16], plain_17[17];
4366 char key1[16], key2[16];
4367 ssize_t encrypted_size, decrypted_size;
4369 plain = tor_malloc(4095);
4370 encrypted1 = tor_malloc(4095 + 1 + 16);
4371 encrypted2 = tor_malloc(4095 + 1 + 16);
4372 decrypted1 = tor_malloc(4095 + 1);
4373 decrypted2 = tor_malloc(4095 + 1);
4375 crypto_rand(plain, 4095);
4376 crypto_rand(key1, 16);
4377 crypto_rand(key2, 16);
4378 crypto_rand(plain_1, 1);
4379 crypto_rand(plain_15, 15);
4380 crypto_rand(plain_16, 16);
4381 crypto_rand(plain_17, 17);
4382 key1[0] = key2[0] + 128; /* Make sure that contents are different. */
4383 /* Encrypt and decrypt with the same key. */
4384 cipher = crypto_create_init_cipher(key1, 1);
4385 encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 4095,
4386 plain, 4095);
4387 crypto_free_cipher_env(cipher);
4388 cipher = NULL;
4389 test_eq(encrypted_size, 16 + 4095);
4390 tor_assert(encrypted_size > 0); /* This is obviously true, since 4111 is
4391 * greater than 0, but its truth is not
4392 * obvious to all analysis tools. */
4393 cipher = crypto_create_init_cipher(key1, 0);
4394 decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 4095,
4395 encrypted1, encrypted_size);
4396 crypto_free_cipher_env(cipher);
4397 cipher = NULL;
4398 test_eq(decrypted_size, 4095);
4399 tor_assert(decrypted_size > 0);
4400 test_memeq(plain, decrypted1, 4095);
4401 /* Encrypt a second time (with a new random initialization vector). */
4402 cipher = crypto_create_init_cipher(key1, 1);
4403 encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted2, 16 + 4095,
4404 plain, 4095);
4405 crypto_free_cipher_env(cipher);
4406 cipher = NULL;
4407 test_eq(encrypted_size, 16 + 4095);
4408 tor_assert(encrypted_size > 0);
4409 cipher = crypto_create_init_cipher(key1, 0);
4410 decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted2, 4095,
4411 encrypted2, encrypted_size);
4412 crypto_free_cipher_env(cipher);
4413 cipher = NULL;
4414 test_eq(decrypted_size, 4095);
4415 tor_assert(decrypted_size > 0);
4416 test_memeq(plain, decrypted2, 4095);
4417 test_memneq(encrypted1, encrypted2, encrypted_size);
4418 /* Decrypt with the wrong key. */
4419 cipher = crypto_create_init_cipher(key2, 0);
4420 decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted2, 4095,
4421 encrypted1, encrypted_size);
4422 crypto_free_cipher_env(cipher);
4423 cipher = NULL;
4424 test_memneq(plain, decrypted2, encrypted_size);
4425 /* Alter the initialization vector. */
4426 encrypted1[0] += 42;
4427 cipher = crypto_create_init_cipher(key1, 0);
4428 decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 4095,
4429 encrypted1, encrypted_size);
4430 crypto_free_cipher_env(cipher);
4431 cipher = NULL;
4432 test_memneq(plain, decrypted2, 4095);
4433 /* Special length case: 1. */
4434 cipher = crypto_create_init_cipher(key1, 1);
4435 encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 1,
4436 plain_1, 1);
4437 crypto_free_cipher_env(cipher);
4438 cipher = NULL;
4439 test_eq(encrypted_size, 16 + 1);
4440 tor_assert(encrypted_size > 0);
4441 cipher = crypto_create_init_cipher(key1, 0);
4442 decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 1,
4443 encrypted1, encrypted_size);
4444 crypto_free_cipher_env(cipher);
4445 cipher = NULL;
4446 test_eq(decrypted_size, 1);
4447 tor_assert(decrypted_size > 0);
4448 test_memeq(plain_1, decrypted1, 1);
4449 /* Special length case: 15. */
4450 cipher = crypto_create_init_cipher(key1, 1);
4451 encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 15,
4452 plain_15, 15);
4453 crypto_free_cipher_env(cipher);
4454 cipher = NULL;
4455 test_eq(encrypted_size, 16 + 15);
4456 tor_assert(encrypted_size > 0);
4457 cipher = crypto_create_init_cipher(key1, 0);
4458 decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 15,
4459 encrypted1, encrypted_size);
4460 crypto_free_cipher_env(cipher);
4461 cipher = NULL;
4462 test_eq(decrypted_size, 15);
4463 tor_assert(decrypted_size > 0);
4464 test_memeq(plain_15, decrypted1, 15);
4465 /* Special length case: 16. */
4466 cipher = crypto_create_init_cipher(key1, 1);
4467 encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 16,
4468 plain_16, 16);
4469 crypto_free_cipher_env(cipher);
4470 cipher = NULL;
4471 test_eq(encrypted_size, 16 + 16);
4472 tor_assert(encrypted_size > 0);
4473 cipher = crypto_create_init_cipher(key1, 0);
4474 decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 16,
4475 encrypted1, encrypted_size);
4476 crypto_free_cipher_env(cipher);
4477 cipher = NULL;
4478 test_eq(decrypted_size, 16);
4479 tor_assert(decrypted_size > 0);
4480 test_memeq(plain_16, decrypted1, 16);
4481 /* Special length case: 17. */
4482 cipher = crypto_create_init_cipher(key1, 1);
4483 encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 17,
4484 plain_17, 17);
4485 crypto_free_cipher_env(cipher);
4486 cipher = NULL;
4487 test_eq(encrypted_size, 16 + 17);
4488 tor_assert(encrypted_size > 0);
4489 cipher = crypto_create_init_cipher(key1, 0);
4490 decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 17,
4491 encrypted1, encrypted_size);
4492 test_eq(decrypted_size, 17);
4493 tor_assert(decrypted_size > 0);
4494 test_memeq(plain_17, decrypted1, 17);
4496 done:
4497 /* Free memory. */
4498 tor_free(plain);
4499 tor_free(encrypted1);
4500 tor_free(encrypted2);
4501 tor_free(decrypted1);
4502 tor_free(decrypted2);
4503 if (cipher)
4504 crypto_free_cipher_env(cipher);
4507 /** Test base32 decoding. */
4508 static void
4509 test_crypto_base32_decode(void)
4511 char plain[60], encoded[96 + 1], decoded[60];
4512 int res;
4513 crypto_rand(plain, 60);
4514 /* Encode and decode a random string. */
4515 base32_encode(encoded, 96 + 1, plain, 60);
4516 res = base32_decode(decoded, 60, encoded, 96);
4517 test_eq(res, 0);
4518 test_memeq(plain, decoded, 60);
4519 /* Encode, uppercase, and decode a random string. */
4520 base32_encode(encoded, 96 + 1, plain, 60);
4521 tor_strupper(encoded);
4522 res = base32_decode(decoded, 60, encoded, 96);
4523 test_eq(res, 0);
4524 test_memeq(plain, decoded, 60);
4525 /* Change encoded string and decode. */
4526 if (encoded[0] == 'A' || encoded[0] == 'a')
4527 encoded[0] = 'B';
4528 else
4529 encoded[0] = 'A';
4530 res = base32_decode(decoded, 60, encoded, 96);
4531 test_eq(res, 0);
4532 test_memneq(plain, decoded, 60);
4533 /* Bad encodings. */
4534 encoded[0] = '!';
4535 res = base32_decode(decoded, 60, encoded, 96);
4536 test_assert(res < 0);
4538 done:
4542 /** Test encoding and parsing of v2 rendezvous service descriptors. */
4543 static void
4544 test_rend_fns_v2(void)
4546 rend_service_descriptor_t *generated = NULL, *parsed = NULL;
4547 char service_id[DIGEST_LEN];
4548 char service_id_base32[REND_SERVICE_ID_LEN_BASE32+1];
4549 const char *next_desc;
4550 smartlist_t *descs = smartlist_create();
4551 char computed_desc_id[DIGEST_LEN];
4552 char parsed_desc_id[DIGEST_LEN];
4553 crypto_pk_env_t *pk1 = NULL, *pk2 = NULL;
4554 time_t now;
4555 char *intro_points_encrypted = NULL;
4556 size_t intro_points_size;
4557 size_t encoded_size;
4558 int i;
4559 pk1 = pk_generate(0);
4560 pk2 = pk_generate(1);
4561 generated = tor_malloc_zero(sizeof(rend_service_descriptor_t));
4562 generated->pk = crypto_pk_dup_key(pk1);
4563 crypto_pk_get_digest(generated->pk, service_id);
4564 base32_encode(service_id_base32, REND_SERVICE_ID_LEN_BASE32+1,
4565 service_id, REND_SERVICE_ID_LEN);
4566 now = time(NULL);
4567 generated->timestamp = now;
4568 generated->version = 2;
4569 generated->protocols = 42;
4570 generated->intro_nodes = smartlist_create();
4572 for (i = 0; i < 3; i++) {
4573 rend_intro_point_t *intro = tor_malloc_zero(sizeof(rend_intro_point_t));
4574 crypto_pk_env_t *okey = pk_generate(2 + i);
4575 intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
4576 intro->extend_info->onion_key = okey;
4577 crypto_pk_get_digest(intro->extend_info->onion_key,
4578 intro->extend_info->identity_digest);
4579 //crypto_rand(info->identity_digest, DIGEST_LEN); /* Would this work? */
4580 intro->extend_info->nickname[0] = '$';
4581 base16_encode(intro->extend_info->nickname + 1,
4582 sizeof(intro->extend_info->nickname) - 1,
4583 intro->extend_info->identity_digest, DIGEST_LEN);
4584 /* Does not cover all IP addresses. */
4585 tor_addr_from_ipv4h(&intro->extend_info->addr, crypto_rand_int(65536));
4586 intro->extend_info->port = crypto_rand_int(65536);
4587 intro->intro_key = crypto_pk_dup_key(pk2);
4588 smartlist_add(generated->intro_nodes, intro);
4590 test_assert(rend_encode_v2_descriptors(descs, generated, now, 0,
4591 REND_NO_AUTH, NULL, NULL) > 0);
4592 test_assert(rend_compute_v2_desc_id(computed_desc_id, service_id_base32,
4593 NULL, now, 0) == 0);
4594 test_memeq(((rend_encoded_v2_service_descriptor_t *)
4595 smartlist_get(descs, 0))->desc_id, computed_desc_id, DIGEST_LEN);
4596 test_assert(rend_parse_v2_service_descriptor(&parsed, parsed_desc_id,
4597 &intro_points_encrypted,
4598 &intro_points_size,
4599 &encoded_size,
4600 &next_desc,
4601 ((rend_encoded_v2_service_descriptor_t *)
4602 smartlist_get(descs, 0))->desc_str) == 0);
4603 test_assert(parsed);
4604 test_memeq(((rend_encoded_v2_service_descriptor_t *)
4605 smartlist_get(descs, 0))->desc_id, parsed_desc_id, DIGEST_LEN);
4606 test_eq(rend_parse_introduction_points(parsed, intro_points_encrypted,
4607 intro_points_size), 3);
4608 test_assert(!crypto_pk_cmp_keys(generated->pk, parsed->pk));
4609 test_eq(parsed->timestamp, now);
4610 test_eq(parsed->version, 2);
4611 test_eq(parsed->protocols, 42);
4612 test_eq(smartlist_len(parsed->intro_nodes), 3);
4613 for (i = 0; i < smartlist_len(parsed->intro_nodes); i++) {
4614 rend_intro_point_t *par_intro = smartlist_get(parsed->intro_nodes, i),
4615 *gen_intro = smartlist_get(generated->intro_nodes, i);
4616 extend_info_t *par_info = par_intro->extend_info;
4617 extend_info_t *gen_info = gen_intro->extend_info;
4618 test_assert(!crypto_pk_cmp_keys(gen_info->onion_key, par_info->onion_key));
4619 test_memeq(gen_info->identity_digest, par_info->identity_digest,
4620 DIGEST_LEN);
4621 test_streq(gen_info->nickname, par_info->nickname);
4622 test_assert(tor_addr_eq(&gen_info->addr, &par_info->addr));
4623 test_eq(gen_info->port, par_info->port);
4626 rend_service_descriptor_free(parsed);
4627 rend_service_descriptor_free(generated);
4628 parsed = generated = NULL;
4630 done:
4631 if (descs) {
4632 for (i = 0; i < smartlist_len(descs); i++)
4633 rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
4634 smartlist_free(descs);
4636 if (parsed)
4637 rend_service_descriptor_free(parsed);
4638 if (generated)
4639 rend_service_descriptor_free(generated);
4640 if (pk1)
4641 crypto_free_pk_env(pk1);
4642 if (pk2)
4643 crypto_free_pk_env(pk2);
4644 tor_free(intro_points_encrypted);
4647 /** Run unit tests for GeoIP code. */
4648 static void
4649 test_geoip(void)
4651 int i, j;
4652 time_t now = time(NULL);
4653 char *s = NULL;
4655 /* Populate the DB a bit. Add these in order, since we can't do the final
4656 * 'sort' step. These aren't very good IP addresses, but they're perfectly
4657 * fine uint32_t values. */
4658 test_eq(0, geoip_parse_entry("10,50,AB"));
4659 test_eq(0, geoip_parse_entry("52,90,XY"));
4660 test_eq(0, geoip_parse_entry("95,100,AB"));
4661 test_eq(0, geoip_parse_entry("\"105\",\"140\",\"ZZ\""));
4662 test_eq(0, geoip_parse_entry("\"150\",\"190\",\"XY\""));
4663 test_eq(0, geoip_parse_entry("\"200\",\"250\",\"AB\""));
4665 /* We should have 3 countries: ab, xy, zz. */
4666 test_eq(3, geoip_get_n_countries());
4667 /* Make sure that country ID actually works. */
4668 #define NAMEFOR(x) geoip_get_country_name(geoip_get_country_by_ip(x))
4669 test_streq("ab", NAMEFOR(32));
4670 test_streq("??", NAMEFOR(5));
4671 test_streq("??", NAMEFOR(51));
4672 test_streq("xy", NAMEFOR(150));
4673 test_streq("xy", NAMEFOR(190));
4674 test_streq("??", NAMEFOR(2000));
4675 #undef NAMEFOR
4677 get_options()->BridgeRelay = 1;
4678 get_options()->BridgeRecordUsageByCountry = 1;
4679 /* Put 9 observations in AB... */
4680 for (i=32; i < 40; ++i)
4681 geoip_note_client_seen(GEOIP_CLIENT_CONNECT, i, now-7200);
4682 geoip_note_client_seen(GEOIP_CLIENT_CONNECT, 225, now-7200);
4683 /* and 3 observations in XY, several times. */
4684 for (j=0; j < 10; ++j)
4685 for (i=52; i < 55; ++i)
4686 geoip_note_client_seen(GEOIP_CLIENT_CONNECT, i, now-3600);
4687 /* and 17 observations in ZZ... */
4688 for (i=110; i < 127; ++i)
4689 geoip_note_client_seen(GEOIP_CLIENT_CONNECT, i, now);
4690 s = geoip_get_client_history(now+5*24*60*60, GEOIP_CLIENT_CONNECT);
4691 test_assert(s);
4692 test_streq("zz=24,ab=16,xy=8", s);
4693 tor_free(s);
4695 /* Now clear out all the AB observations. */
4696 geoip_remove_old_clients(now-6000);
4697 s = geoip_get_client_history(now+5*24*60*60, GEOIP_CLIENT_CONNECT);
4698 test_assert(s);
4699 test_streq("zz=24,xy=8", s);
4701 done:
4702 tor_free(s);
4705 /** For test_array. Declare an CLI-invocable off-by-default function in the
4706 * unit tests, with function name and user-visible name <b>x</b>*/
4707 #define DISABLED(x) { #x, x, 0, 0, 0 }
4708 /** For test_array. Declare an CLI-invocable unit test function, with function
4709 * name test_<b>x</b>(), and user-visible name <b>x</b> */
4710 #define ENT(x) { #x, test_ ## x, 0, 0, 1 }
4711 /** For test_array. Declare an CLI-invocable unit test function, with function
4712 * name test_<b>x</b>_<b>y</b>(), and user-visible name
4713 * <b>x</b>/<b>y</b>. This function will be treated as a subentry of <b>x</b>,
4714 * so that invoking <b>x</b> from the CLI invokes this test too. */
4715 #define SUBENT(x,y) { #x "/" #y, test_ ## x ## _ ## y, 1, 0, 1 }
4717 /** An array of functions and information for all the unit tests we can run. */
4718 static struct {
4719 const char *test_name; /**< How does the user refer to this test from the
4720 * command line? */
4721 void (*test_fn)(void); /**< What function is called to run this test? */
4722 int is_subent; /**< Is this a subentry of a bigger set of related tests? */
4723 int selected; /**< Are we planning to run this one? */
4724 int is_default; /**< If the user doesn't say what tests they want, do they
4725 * get this function by default? */
4726 } test_array[] = {
4727 ENT(buffers),
4728 ENT(crypto),
4729 SUBENT(crypto, rng),
4730 SUBENT(crypto, aes),
4731 SUBENT(crypto, sha),
4732 SUBENT(crypto, pk),
4733 SUBENT(crypto, dh),
4734 SUBENT(crypto, s2k),
4735 SUBENT(crypto, aes_iv),
4736 SUBENT(crypto, base32_decode),
4737 ENT(util),
4738 SUBENT(util, ip6_helpers),
4739 SUBENT(util, gzip),
4740 SUBENT(util, datadir),
4741 SUBENT(util, smartlist_basic),
4742 SUBENT(util, smartlist_strings),
4743 SUBENT(util, smartlist_overlap),
4744 SUBENT(util, smartlist_digests),
4745 SUBENT(util, smartlist_join),
4746 SUBENT(util, bitarray),
4747 SUBENT(util, digestset),
4748 SUBENT(util, mempool),
4749 SUBENT(util, memarea),
4750 SUBENT(util, strmap),
4751 SUBENT(util, control_formats),
4752 SUBENT(util, pqueue),
4753 SUBENT(util, mmap),
4754 SUBENT(util, threads),
4755 SUBENT(util, order_functions),
4756 SUBENT(util, sscanf),
4757 ENT(onion_handshake),
4758 ENT(dir_format),
4759 ENT(dirutil),
4760 ENT(v3_networkstatus),
4761 ENT(policies),
4762 ENT(rend_fns),
4763 SUBENT(rend_fns, v2),
4764 ENT(geoip),
4766 DISABLED(bench_aes),
4767 DISABLED(bench_dmap),
4768 { NULL, NULL, 0, 0, 0 },
4771 static void syntax(void) ATTR_NORETURN;
4773 /** Print a syntax usage message, and exit.*/
4774 static void
4775 syntax(void)
4777 int i;
4778 printf("Syntax:\n"
4779 " test [-v|--verbose] [--warn|--notice|--info|--debug]\n"
4780 " [testname...]\n"
4781 "Recognized tests are:\n");
4782 for (i = 0; test_array[i].test_name; ++i) {
4783 printf(" %s\n", test_array[i].test_name);
4786 exit(0);
4789 /** Main entry point for unit test code: parse the command line, and run
4790 * some unit tests. */
4792 main(int c, char**v)
4794 or_options_t *options;
4795 char *errmsg = NULL;
4796 int i;
4797 int verbose = 0, any_selected = 0;
4798 int loglevel = LOG_ERR;
4800 #ifdef USE_DMALLOC
4802 int r = CRYPTO_set_mem_ex_functions(_tor_malloc, _tor_realloc, _tor_free);
4803 tor_assert(r);
4805 #endif
4807 update_approx_time(time(NULL));
4808 options = options_new();
4809 tor_threads_init();
4810 init_logging();
4812 for (i = 1; i < c; ++i) {
4813 if (!strcmp(v[i], "-v") || !strcmp(v[i], "--verbose"))
4814 verbose++;
4815 else if (!strcmp(v[i], "--warn"))
4816 loglevel = LOG_WARN;
4817 else if (!strcmp(v[i], "--notice"))
4818 loglevel = LOG_NOTICE;
4819 else if (!strcmp(v[i], "--info"))
4820 loglevel = LOG_INFO;
4821 else if (!strcmp(v[i], "--debug"))
4822 loglevel = LOG_DEBUG;
4823 else if (!strcmp(v[i], "--help") || !strcmp(v[i], "-h") || v[i][0] == '-')
4824 syntax();
4825 else {
4826 int j, found=0;
4827 for (j = 0; test_array[j].test_name; ++j) {
4828 if (!strcmp(v[i], test_array[j].test_name) ||
4829 (test_array[j].is_subent &&
4830 !strcmpstart(test_array[j].test_name, v[i]) &&
4831 test_array[j].test_name[strlen(v[i])] == '/') ||
4832 (v[i][0] == '=' && !strcmp(v[i]+1, test_array[j].test_name))) {
4833 test_array[j].selected = 1;
4834 any_selected = 1;
4835 found = 1;
4838 if (!found) {
4839 printf("Unknown test: %s\n", v[i]);
4840 syntax();
4845 if (!any_selected) {
4846 for (i = 0; test_array[i].test_name; ++i) {
4847 test_array[i].selected = test_array[i].is_default;
4852 log_severity_list_t s;
4853 memset(&s, 0, sizeof(s));
4854 set_log_severity_config(loglevel, LOG_ERR, &s);
4855 add_stream_log(&s, "", fileno(stdout));
4858 options->command = CMD_RUN_UNITTESTS;
4859 crypto_global_init(0);
4860 rep_hist_init();
4861 network_init();
4862 setup_directory();
4863 options_init(options);
4864 options->DataDirectory = tor_strdup(temp_dir);
4865 if (set_options(options, &errmsg) < 0) {
4866 printf("Failed to set initial options: %s\n", errmsg);
4867 tor_free(errmsg);
4868 return 1;
4871 crypto_seed_rng(1);
4873 atexit(remove_directory);
4875 printf("Running Tor unit tests on %s\n", get_uname());
4877 for (i = 0; test_array[i].test_name; ++i) {
4878 if (!test_array[i].selected)
4879 continue;
4880 if (!test_array[i].is_subent) {
4881 printf("\n============================== %s\n",test_array[i].test_name);
4882 } else if (test_array[i].is_subent && verbose) {
4883 printf("\n%s", test_array[i].test_name);
4885 test_array[i].test_fn();
4887 puts("");
4889 free_pregenerated_keys();
4890 #ifdef USE_DMALLOC
4891 tor_free_all(0);
4892 dmalloc_log_unfreed();
4893 #endif
4895 if (have_failed)
4896 return 1;
4897 else
4898 return 0;