Clean up (and mark for 0.2.2.) comments relating to non-beauty of current bug-743...
[tor/rransom.git] / src / or / test.c
blob511e8c2329effcd033dc00010648cf1dc8cc6621
1 /* Copyright (c) 2001-2004, Roger Dingledine.
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2008, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
6 /* 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 = NULL;
2405 int (*cmp)(const void *, const void*);
2406 #define OK() smartlist_pqueue_assert_ok(sl, cmp)
2408 cmp = _compare_strings_for_pqueue;
2410 sl = smartlist_create();
2411 smartlist_pqueue_add(sl, cmp, (char*)"cows");
2412 smartlist_pqueue_add(sl, cmp, (char*)"zebras");
2413 smartlist_pqueue_add(sl, cmp, (char*)"fish");
2414 smartlist_pqueue_add(sl, cmp, (char*)"frogs");
2415 smartlist_pqueue_add(sl, cmp, (char*)"apples");
2416 smartlist_pqueue_add(sl, cmp, (char*)"squid");
2417 smartlist_pqueue_add(sl, cmp, (char*)"daschunds");
2418 smartlist_pqueue_add(sl, cmp, (char*)"eggplants");
2419 smartlist_pqueue_add(sl, cmp, (char*)"weissbier");
2420 smartlist_pqueue_add(sl, cmp, (char*)"lobsters");
2421 smartlist_pqueue_add(sl, cmp, (char*)"roquefort");
2423 OK();
2425 test_eq(smartlist_len(sl), 11);
2426 test_streq(smartlist_get(sl, 0), "apples");
2427 test_streq(smartlist_pqueue_pop(sl, cmp), "apples");
2428 test_eq(smartlist_len(sl), 10);
2429 OK();
2430 test_streq(smartlist_pqueue_pop(sl, cmp), "cows");
2431 test_streq(smartlist_pqueue_pop(sl, cmp), "daschunds");
2432 smartlist_pqueue_add(sl, cmp, (char*)"chinchillas");
2433 OK();
2434 smartlist_pqueue_add(sl, cmp, (char*)"fireflies");
2435 OK();
2436 test_streq(smartlist_pqueue_pop(sl, cmp), "chinchillas");
2437 test_streq(smartlist_pqueue_pop(sl, cmp), "eggplants");
2438 test_streq(smartlist_pqueue_pop(sl, cmp), "fireflies");
2439 OK();
2440 test_streq(smartlist_pqueue_pop(sl, cmp), "fish");
2441 test_streq(smartlist_pqueue_pop(sl, cmp), "frogs");
2442 test_streq(smartlist_pqueue_pop(sl, cmp), "lobsters");
2443 test_streq(smartlist_pqueue_pop(sl, cmp), "roquefort");
2444 OK();
2445 test_eq(smartlist_len(sl), 3);
2446 test_streq(smartlist_pqueue_pop(sl, cmp), "squid");
2447 test_streq(smartlist_pqueue_pop(sl, cmp), "weissbier");
2448 test_streq(smartlist_pqueue_pop(sl, cmp), "zebras");
2449 test_eq(smartlist_len(sl), 0);
2450 OK();
2451 #undef OK
2453 done:
2454 if (sl)
2455 smartlist_free(sl);
2458 /** Run unit tests for compression functions */
2459 static void
2460 test_util_gzip(void)
2462 char *buf1=NULL, *buf2=NULL, *buf3=NULL, *cp1, *cp2;
2463 const char *ccp2;
2464 size_t len1, len2;
2465 tor_zlib_state_t *state = NULL;
2467 buf1 = tor_strdup("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ");
2468 test_assert(detect_compression_method(buf1, strlen(buf1)) == UNKNOWN_METHOD);
2469 if (is_gzip_supported()) {
2470 test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
2471 GZIP_METHOD));
2472 test_assert(buf2);
2473 test_assert(!memcmp(buf2, "\037\213", 2)); /* Gzip magic. */
2474 test_assert(detect_compression_method(buf2, len1) == GZIP_METHOD);
2476 test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1,
2477 GZIP_METHOD, 1, LOG_INFO));
2478 test_assert(buf3);
2479 test_streq(buf1,buf3);
2481 tor_free(buf2);
2482 tor_free(buf3);
2485 test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
2486 ZLIB_METHOD));
2487 test_assert(buf2);
2488 test_assert(!memcmp(buf2, "\x78\xDA", 2)); /* deflate magic. */
2489 test_assert(detect_compression_method(buf2, len1) == ZLIB_METHOD);
2491 test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1,
2492 ZLIB_METHOD, 1, LOG_INFO));
2493 test_assert(buf3);
2494 test_streq(buf1,buf3);
2496 /* Check whether we can uncompress concatenated, compresed strings. */
2497 tor_free(buf3);
2498 buf2 = tor_realloc(buf2, len1*2);
2499 memcpy(buf2+len1, buf2, len1);
2500 test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1*2,
2501 ZLIB_METHOD, 1, LOG_INFO));
2502 test_eq(len2, (strlen(buf1)+1)*2);
2503 test_memeq(buf3,
2504 "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ\0"
2505 "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ\0",
2506 (strlen(buf1)+1)*2);
2508 tor_free(buf1);
2509 tor_free(buf2);
2510 tor_free(buf3);
2512 /* Check whether we can uncompress partial strings. */
2513 buf1 =
2514 tor_strdup("String with low redundancy that won't be compressed much.");
2515 test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
2516 ZLIB_METHOD));
2517 tor_assert(len1>16);
2518 /* when we allow an uncomplete string, we should succeed.*/
2519 tor_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1-16,
2520 ZLIB_METHOD, 0, LOG_INFO));
2521 buf3[len2]='\0';
2522 tor_assert(len2 > 5);
2523 tor_assert(!strcmpstart(buf1, buf3));
2525 /* when we demand a complete string, this must fail. */
2526 tor_free(buf3);
2527 tor_assert(tor_gzip_uncompress(&buf3, &len2, buf2, len1-16,
2528 ZLIB_METHOD, 1, LOG_INFO));
2529 tor_assert(!buf3);
2531 /* Now, try streaming compression. */
2532 tor_free(buf1);
2533 tor_free(buf2);
2534 tor_free(buf3);
2535 state = tor_zlib_new(1, ZLIB_METHOD);
2536 tor_assert(state);
2537 cp1 = buf1 = tor_malloc(1024);
2538 len1 = 1024;
2539 ccp2 = "ABCDEFGHIJABCDEFGHIJ";
2540 len2 = 21;
2541 test_assert(tor_zlib_process(state, &cp1, &len1, &ccp2, &len2, 0)
2542 == TOR_ZLIB_OK);
2543 test_eq(len2, 0); /* Make sure we compressed it all. */
2544 test_assert(cp1 > buf1);
2546 len2 = 0;
2547 cp2 = cp1;
2548 test_assert(tor_zlib_process(state, &cp1, &len1, &ccp2, &len2, 1)
2549 == TOR_ZLIB_DONE);
2550 test_eq(len2, 0);
2551 test_assert(cp1 > cp2); /* Make sure we really added something. */
2553 tor_assert(!tor_gzip_uncompress(&buf3, &len2, buf1, 1024-len1,
2554 ZLIB_METHOD, 1, LOG_WARN));
2555 test_streq(buf3, "ABCDEFGHIJABCDEFGHIJ"); /*Make sure it compressed right.*/
2557 done:
2558 if (state)
2559 tor_zlib_free(state);
2560 tor_free(buf2);
2561 tor_free(buf3);
2562 tor_free(buf1);
2565 /** Run unit tests for string-to-void* map functions */
2566 static void
2567 test_util_strmap(void)
2569 strmap_t *map;
2570 strmap_iter_t *iter;
2571 const char *k;
2572 void *v;
2573 char *visited = NULL;
2574 smartlist_t *found_keys = NULL;
2576 map = strmap_new();
2577 test_assert(map);
2578 test_eq(strmap_size(map), 0);
2579 test_assert(strmap_isempty(map));
2580 v = strmap_set(map, "K1", (void*)99);
2581 test_eq(v, NULL);
2582 test_assert(!strmap_isempty(map));
2583 v = strmap_set(map, "K2", (void*)101);
2584 test_eq(v, NULL);
2585 v = strmap_set(map, "K1", (void*)100);
2586 test_eq(v, (void*)99);
2587 test_eq_ptr(strmap_get(map,"K1"), (void*)100);
2588 test_eq_ptr(strmap_get(map,"K2"), (void*)101);
2589 test_eq_ptr(strmap_get(map,"K-not-there"), NULL);
2590 strmap_assert_ok(map);
2592 v = strmap_remove(map,"K2");
2593 strmap_assert_ok(map);
2594 test_eq_ptr(v, (void*)101);
2595 test_eq_ptr(strmap_get(map,"K2"), NULL);
2596 test_eq_ptr(strmap_remove(map,"K2"), NULL);
2598 strmap_set(map, "K2", (void*)101);
2599 strmap_set(map, "K3", (void*)102);
2600 strmap_set(map, "K4", (void*)103);
2601 test_eq(strmap_size(map), 4);
2602 strmap_assert_ok(map);
2603 strmap_set(map, "K5", (void*)104);
2604 strmap_set(map, "K6", (void*)105);
2605 strmap_assert_ok(map);
2607 /* Test iterator. */
2608 iter = strmap_iter_init(map);
2609 found_keys = smartlist_create();
2610 while (!strmap_iter_done(iter)) {
2611 strmap_iter_get(iter,&k,&v);
2612 smartlist_add(found_keys, tor_strdup(k));
2613 test_eq_ptr(v, strmap_get(map, k));
2615 if (!strcmp(k, "K2")) {
2616 iter = strmap_iter_next_rmv(map,iter);
2617 } else {
2618 iter = strmap_iter_next(map,iter);
2622 /* Make sure we removed K2, but not the others. */
2623 test_eq_ptr(strmap_get(map, "K2"), NULL);
2624 test_eq_ptr(strmap_get(map, "K5"), (void*)104);
2625 /* Make sure we visited everyone once */
2626 smartlist_sort_strings(found_keys);
2627 visited = smartlist_join_strings(found_keys, ":", 0, NULL);
2628 test_streq(visited, "K1:K2:K3:K4:K5:K6");
2630 strmap_assert_ok(map);
2631 /* Clean up after ourselves. */
2632 strmap_free(map, NULL);
2633 map = NULL;
2635 /* Now try some lc functions. */
2636 map = strmap_new();
2637 strmap_set_lc(map,"Ab.C", (void*)1);
2638 test_eq_ptr(strmap_get(map,"ab.c"), (void*)1);
2639 strmap_assert_ok(map);
2640 test_eq_ptr(strmap_get_lc(map,"AB.C"), (void*)1);
2641 test_eq_ptr(strmap_get(map,"AB.C"), NULL);
2642 test_eq_ptr(strmap_remove_lc(map,"aB.C"), (void*)1);
2643 strmap_assert_ok(map);
2644 test_eq_ptr(strmap_get_lc(map,"AB.C"), NULL);
2646 done:
2647 if (map)
2648 strmap_free(map,NULL);
2649 if (found_keys) {
2650 SMARTLIST_FOREACH(found_keys, char *, cp, tor_free(cp));
2651 smartlist_free(found_keys);
2653 tor_free(visited);
2656 /** Run unit tests for mmap() wrapper functionality. */
2657 static void
2658 test_util_mmap(void)
2660 char *fname1 = tor_strdup(get_fname("mapped_1"));
2661 char *fname2 = tor_strdup(get_fname("mapped_2"));
2662 char *fname3 = tor_strdup(get_fname("mapped_3"));
2663 const size_t buflen = 17000;
2664 char *buf = tor_malloc(17000);
2665 tor_mmap_t *mapping = NULL;
2667 crypto_rand(buf, buflen);
2669 mapping = tor_mmap_file(fname1);
2670 test_assert(! mapping);
2672 write_str_to_file(fname1, "Short file.", 1);
2673 write_bytes_to_file(fname2, buf, buflen, 1);
2674 write_bytes_to_file(fname3, buf, 16384, 1);
2676 mapping = tor_mmap_file(fname1);
2677 test_assert(mapping);
2678 test_eq(mapping->size, strlen("Short file."));
2679 test_streq(mapping->data, "Short file.");
2680 #ifdef MS_WINDOWS
2681 tor_munmap_file(mapping);
2682 mapping = NULL;
2683 test_assert(unlink(fname1) == 0);
2684 #else
2685 /* make sure we can unlink. */
2686 test_assert(unlink(fname1) == 0);
2687 test_streq(mapping->data, "Short file.");
2688 tor_munmap_file(mapping);
2689 mapping = NULL;
2690 #endif
2692 /* Now a zero-length file. */
2693 write_str_to_file(fname1, "", 1);
2694 mapping = tor_mmap_file(fname1);
2695 test_eq(mapping, NULL);
2696 test_eq(ERANGE, errno);
2697 unlink(fname1);
2699 /* Make sure that we fail to map a no-longer-existent file. */
2700 mapping = tor_mmap_file(fname1);
2701 test_assert(mapping == NULL);
2703 /* Now try a big file that stretches across a few pages and isn't aligned */
2704 mapping = tor_mmap_file(fname2);
2705 test_assert(mapping);
2706 test_eq(mapping->size, buflen);
2707 test_memeq(mapping->data, buf, buflen);
2708 tor_munmap_file(mapping);
2709 mapping = NULL;
2711 /* Now try a big aligned file. */
2712 mapping = tor_mmap_file(fname3);
2713 test_assert(mapping);
2714 test_eq(mapping->size, 16384);
2715 test_memeq(mapping->data, buf, 16384);
2716 tor_munmap_file(mapping);
2717 mapping = NULL;
2719 done:
2720 unlink(fname1);
2721 unlink(fname2);
2722 unlink(fname3);
2724 tor_free(fname1);
2725 tor_free(fname2);
2726 tor_free(fname3);
2727 tor_free(buf);
2729 if (mapping)
2730 tor_munmap_file(mapping);
2733 /** Run unit tests for escaping/unescaping data for use by controllers. */
2734 static void
2735 test_util_control_formats(void)
2737 char *out = NULL;
2738 const char *inp =
2739 "..This is a test\r\nof the emergency \nbroadcast\r\n..system.\r\nZ.\r\n";
2740 size_t sz;
2742 sz = read_escaped_data(inp, strlen(inp), &out);
2743 test_streq(out,
2744 ".This is a test\nof the emergency \nbroadcast\n.system.\nZ.\n");
2745 test_eq(sz, strlen(out));
2747 done:
2748 tor_free(out);
2751 /** Run unit tests for the onion handshake code. */
2752 static void
2753 test_onion_handshake(void)
2755 /* client-side */
2756 crypto_dh_env_t *c_dh = NULL;
2757 char c_buf[ONIONSKIN_CHALLENGE_LEN];
2758 char c_keys[40];
2760 /* server-side */
2761 char s_buf[ONIONSKIN_REPLY_LEN];
2762 char s_keys[40];
2764 /* shared */
2765 crypto_pk_env_t *pk = NULL;
2767 pk = pk_generate(0);
2769 /* client handshake 1. */
2770 memset(c_buf, 0, ONIONSKIN_CHALLENGE_LEN);
2771 test_assert(! onion_skin_create(pk, &c_dh, c_buf));
2773 /* server handshake */
2774 memset(s_buf, 0, ONIONSKIN_REPLY_LEN);
2775 memset(s_keys, 0, 40);
2776 test_assert(! onion_skin_server_handshake(c_buf, pk, NULL,
2777 s_buf, s_keys, 40));
2779 /* client handshake 2 */
2780 memset(c_keys, 0, 40);
2781 test_assert(! onion_skin_client_handshake(c_dh, s_buf, c_keys, 40));
2783 if (memcmp(c_keys, s_keys, 40)) {
2784 puts("Aiiiie");
2785 exit(1);
2787 test_memeq(c_keys, s_keys, 40);
2788 memset(s_buf, 0, 40);
2789 test_memneq(c_keys, s_buf, 40);
2791 done:
2792 if (c_dh)
2793 crypto_dh_free(c_dh);
2794 if (pk)
2795 crypto_free_pk_env(pk);
2798 /** Run unit tests for router descriptor generation logic. */
2799 static void
2800 test_dir_format(void)
2802 char buf[8192], buf2[8192];
2803 char platform[256];
2804 char fingerprint[FINGERPRINT_LEN+1];
2805 char *pk1_str = NULL, *pk2_str = NULL, *pk3_str = NULL, *cp;
2806 size_t pk1_str_len, pk2_str_len, pk3_str_len;
2807 routerinfo_t *r1=NULL, *r2=NULL;
2808 crypto_pk_env_t *pk1 = NULL, *pk2 = NULL, *pk3 = NULL;
2809 routerinfo_t *rp1 = NULL;
2810 addr_policy_t *ex1, *ex2;
2811 routerlist_t *dir1 = NULL, *dir2 = NULL;
2812 tor_version_t ver1;
2814 pk1 = pk_generate(0);
2815 pk2 = pk_generate(1);
2816 pk3 = pk_generate(2);
2818 test_assert( is_legal_nickname("a"));
2819 test_assert(!is_legal_nickname(""));
2820 test_assert(!is_legal_nickname("abcdefghijklmnopqrst")); /* 20 chars */
2821 test_assert(!is_legal_nickname("hyphen-")); /* bad char */
2822 test_assert( is_legal_nickname("abcdefghijklmnopqrs")); /* 19 chars */
2823 test_assert(!is_legal_nickname("$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2824 /* valid */
2825 test_assert( is_legal_nickname_or_hexdigest(
2826 "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2827 test_assert( is_legal_nickname_or_hexdigest(
2828 "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA=fred"));
2829 test_assert( is_legal_nickname_or_hexdigest(
2830 "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA~fred"));
2831 /* too short */
2832 test_assert(!is_legal_nickname_or_hexdigest(
2833 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2834 /* illegal char */
2835 test_assert(!is_legal_nickname_or_hexdigest(
2836 "$AAAAAAzAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2837 /* hex part too long */
2838 test_assert(!is_legal_nickname_or_hexdigest(
2839 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2840 test_assert(!is_legal_nickname_or_hexdigest(
2841 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=fred"));
2842 /* Bad nickname */
2843 test_assert(!is_legal_nickname_or_hexdigest(
2844 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="));
2845 test_assert(!is_legal_nickname_or_hexdigest(
2846 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~"));
2847 test_assert(!is_legal_nickname_or_hexdigest(
2848 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~hyphen-"));
2849 test_assert(!is_legal_nickname_or_hexdigest(
2850 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~"
2851 "abcdefghijklmnoppqrst"));
2852 /* Bad extra char. */
2853 test_assert(!is_legal_nickname_or_hexdigest(
2854 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA!"));
2855 test_assert(is_legal_nickname_or_hexdigest("xyzzy"));
2856 test_assert(is_legal_nickname_or_hexdigest("abcdefghijklmnopqrs"));
2857 test_assert(!is_legal_nickname_or_hexdigest("abcdefghijklmnopqrst"));
2859 get_platform_str(platform, sizeof(platform));
2860 r1 = tor_malloc_zero(sizeof(routerinfo_t));
2861 r1->address = tor_strdup("18.244.0.1");
2862 r1->addr = 0xc0a80001u; /* 192.168.0.1 */
2863 r1->cache_info.published_on = 0;
2864 r1->or_port = 9000;
2865 r1->dir_port = 9003;
2866 r1->onion_pkey = crypto_pk_dup_key(pk1);
2867 r1->identity_pkey = crypto_pk_dup_key(pk2);
2868 r1->bandwidthrate = 1000;
2869 r1->bandwidthburst = 5000;
2870 r1->bandwidthcapacity = 10000;
2871 r1->exit_policy = NULL;
2872 r1->nickname = tor_strdup("Magri");
2873 r1->platform = tor_strdup(platform);
2875 ex1 = tor_malloc_zero(sizeof(addr_policy_t));
2876 ex2 = tor_malloc_zero(sizeof(addr_policy_t));
2877 ex1->policy_type = ADDR_POLICY_ACCEPT;
2878 tor_addr_from_ipv4h(&ex1->addr, 0);
2879 ex1->maskbits = 0;
2880 ex1->prt_min = ex1->prt_max = 80;
2881 ex2->policy_type = ADDR_POLICY_REJECT;
2882 tor_addr_from_ipv4h(&ex2->addr, 18<<24);
2883 ex2->maskbits = 8;
2884 ex2->prt_min = ex2->prt_max = 24;
2885 r2 = tor_malloc_zero(sizeof(routerinfo_t));
2886 r2->address = tor_strdup("1.1.1.1");
2887 r2->addr = 0x0a030201u; /* 10.3.2.1 */
2888 r2->platform = tor_strdup(platform);
2889 r2->cache_info.published_on = 5;
2890 r2->or_port = 9005;
2891 r2->dir_port = 0;
2892 r2->onion_pkey = crypto_pk_dup_key(pk2);
2893 r2->identity_pkey = crypto_pk_dup_key(pk1);
2894 r2->bandwidthrate = r2->bandwidthburst = r2->bandwidthcapacity = 3000;
2895 r2->exit_policy = smartlist_create();
2896 smartlist_add(r2->exit_policy, ex2);
2897 smartlist_add(r2->exit_policy, ex1);
2898 r2->nickname = tor_strdup("Fred");
2900 test_assert(!crypto_pk_write_public_key_to_string(pk1, &pk1_str,
2901 &pk1_str_len));
2902 test_assert(!crypto_pk_write_public_key_to_string(pk2 , &pk2_str,
2903 &pk2_str_len));
2904 test_assert(!crypto_pk_write_public_key_to_string(pk3 , &pk3_str,
2905 &pk3_str_len));
2907 memset(buf, 0, 2048);
2908 test_assert(router_dump_router_to_string(buf, 2048, r1, pk2)>0);
2910 strlcpy(buf2, "router Magri 18.244.0.1 9000 0 9003\n"
2911 "platform Tor "VERSION" on ", sizeof(buf2));
2912 strlcat(buf2, get_uname(), sizeof(buf2));
2913 strlcat(buf2, "\n"
2914 "opt protocols Link 1 2 Circuit 1\n"
2915 "published 1970-01-01 00:00:00\n"
2916 "opt fingerprint ", sizeof(buf2));
2917 test_assert(!crypto_pk_get_fingerprint(pk2, fingerprint, 1));
2918 strlcat(buf2, fingerprint, sizeof(buf2));
2919 strlcat(buf2, "\nuptime 0\n"
2920 /* XXX the "0" above is hardcoded, but even if we made it reflect
2921 * uptime, that still wouldn't make it right, because the two
2922 * descriptors might be made on different seconds... hm. */
2923 "bandwidth 1000 5000 10000\n"
2924 "opt extra-info-digest 0000000000000000000000000000000000000000\n"
2925 "onion-key\n", sizeof(buf2));
2926 strlcat(buf2, pk1_str, sizeof(buf2));
2927 strlcat(buf2, "signing-key\n", sizeof(buf2));
2928 strlcat(buf2, pk2_str, sizeof(buf2));
2929 strlcat(buf2, "opt hidden-service-dir\n", sizeof(buf2));
2930 strlcat(buf2, "reject *:*\nrouter-signature\n", sizeof(buf2));
2931 buf[strlen(buf2)] = '\0'; /* Don't compare the sig; it's never the same
2932 * twice */
2934 test_streq(buf, buf2);
2936 test_assert(router_dump_router_to_string(buf, 2048, r1, pk2)>0);
2937 cp = buf;
2938 rp1 = router_parse_entry_from_string((const char*)cp,NULL,1,0,NULL);
2939 test_assert(rp1);
2940 test_streq(rp1->address, r1->address);
2941 test_eq(rp1->or_port, r1->or_port);
2942 //test_eq(rp1->dir_port, r1->dir_port);
2943 test_eq(rp1->bandwidthrate, r1->bandwidthrate);
2944 test_eq(rp1->bandwidthburst, r1->bandwidthburst);
2945 test_eq(rp1->bandwidthcapacity, r1->bandwidthcapacity);
2946 test_assert(crypto_pk_cmp_keys(rp1->onion_pkey, pk1) == 0);
2947 test_assert(crypto_pk_cmp_keys(rp1->identity_pkey, pk2) == 0);
2948 //test_assert(rp1->exit_policy == NULL);
2950 #if 0
2951 /* XXX Once we have exit policies, test this again. XXX */
2952 strlcpy(buf2, "router tor.tor.tor 9005 0 0 3000\n", sizeof(buf2));
2953 strlcat(buf2, pk2_str, sizeof(buf2));
2954 strlcat(buf2, "signing-key\n", sizeof(buf2));
2955 strlcat(buf2, pk1_str, sizeof(buf2));
2956 strlcat(buf2, "accept *:80\nreject 18.*:24\n\n", sizeof(buf2));
2957 test_assert(router_dump_router_to_string(buf, 2048, &r2, pk2)>0);
2958 test_streq(buf, buf2);
2960 cp = buf;
2961 rp2 = router_parse_entry_from_string(&cp,1);
2962 test_assert(rp2);
2963 test_streq(rp2->address, r2.address);
2964 test_eq(rp2->or_port, r2.or_port);
2965 test_eq(rp2->dir_port, r2.dir_port);
2966 test_eq(rp2->bandwidth, r2.bandwidth);
2967 test_assert(crypto_pk_cmp_keys(rp2->onion_pkey, pk2) == 0);
2968 test_assert(crypto_pk_cmp_keys(rp2->identity_pkey, pk1) == 0);
2969 test_eq(rp2->exit_policy->policy_type, EXIT_POLICY_ACCEPT);
2970 test_streq(rp2->exit_policy->string, "accept *:80");
2971 test_streq(rp2->exit_policy->address, "*");
2972 test_streq(rp2->exit_policy->port, "80");
2973 test_eq(rp2->exit_policy->next->policy_type, EXIT_POLICY_REJECT);
2974 test_streq(rp2->exit_policy->next->string, "reject 18.*:24");
2975 test_streq(rp2->exit_policy->next->address, "18.*");
2976 test_streq(rp2->exit_policy->next->port, "24");
2977 test_assert(rp2->exit_policy->next->next == NULL);
2979 /* Okay, now for the directories. */
2981 fingerprint_list = smartlist_create();
2982 crypto_pk_get_fingerprint(pk2, buf, 1);
2983 add_fingerprint_to_dir("Magri", buf, fingerprint_list);
2984 crypto_pk_get_fingerprint(pk1, buf, 1);
2985 add_fingerprint_to_dir("Fred", buf, fingerprint_list);
2989 char d[DIGEST_LEN];
2990 const char *m;
2991 /* XXXX NM re-enable. */
2992 /* Make sure routers aren't too far in the past any more. */
2993 r1->cache_info.published_on = time(NULL);
2994 r2->cache_info.published_on = time(NULL)-3*60*60;
2995 test_assert(router_dump_router_to_string(buf, 2048, r1, pk2)>0);
2996 test_eq(dirserv_add_descriptor(buf,&m), ROUTER_ADDED_NOTIFY_GENERATOR);
2997 test_assert(router_dump_router_to_string(buf, 2048, r2, pk1)>0);
2998 test_eq(dirserv_add_descriptor(buf,&m), ROUTER_ADDED_NOTIFY_GENERATOR);
2999 get_options()->Nickname = tor_strdup("DirServer");
3000 test_assert(!dirserv_dump_directory_to_string(&cp,pk3, 0));
3001 crypto_pk_get_digest(pk3, d);
3002 test_assert(!router_parse_directory(cp));
3003 test_eq(2, smartlist_len(dir1->routers));
3004 tor_free(cp);
3006 #endif
3007 dirserv_free_fingerprint_list();
3009 /* Try out version parsing functionality */
3010 test_eq(0, tor_version_parse("0.3.4pre2-cvs", &ver1));
3011 test_eq(0, ver1.major);
3012 test_eq(3, ver1.minor);
3013 test_eq(4, ver1.micro);
3014 test_eq(VER_PRE, ver1.status);
3015 test_eq(2, ver1.patchlevel);
3016 test_eq(0, tor_version_parse("0.3.4rc1", &ver1));
3017 test_eq(0, ver1.major);
3018 test_eq(3, ver1.minor);
3019 test_eq(4, ver1.micro);
3020 test_eq(VER_RC, ver1.status);
3021 test_eq(1, ver1.patchlevel);
3022 test_eq(0, tor_version_parse("1.3.4", &ver1));
3023 test_eq(1, ver1.major);
3024 test_eq(3, ver1.minor);
3025 test_eq(4, ver1.micro);
3026 test_eq(VER_RELEASE, ver1.status);
3027 test_eq(0, ver1.patchlevel);
3028 test_eq(0, tor_version_parse("1.3.4.999", &ver1));
3029 test_eq(1, ver1.major);
3030 test_eq(3, ver1.minor);
3031 test_eq(4, ver1.micro);
3032 test_eq(VER_RELEASE, ver1.status);
3033 test_eq(999, ver1.patchlevel);
3034 test_eq(0, tor_version_parse("0.1.2.4-alpha", &ver1));
3035 test_eq(0, ver1.major);
3036 test_eq(1, ver1.minor);
3037 test_eq(2, ver1.micro);
3038 test_eq(4, ver1.patchlevel);
3039 test_eq(VER_RELEASE, ver1.status);
3040 test_streq("alpha", ver1.status_tag);
3041 test_eq(0, tor_version_parse("0.1.2.4", &ver1));
3042 test_eq(0, ver1.major);
3043 test_eq(1, ver1.minor);
3044 test_eq(2, ver1.micro);
3045 test_eq(4, ver1.patchlevel);
3046 test_eq(VER_RELEASE, ver1.status);
3047 test_streq("", ver1.status_tag);
3049 #define test_eq_vs(vs1, vs2) test_eq_type(version_status_t, "%d", (vs1), (vs2))
3050 #define test_v_i_o(val, ver, lst) \
3051 test_eq_vs(val, tor_version_is_obsolete(ver, lst))
3053 /* make sure tor_version_is_obsolete() works */
3054 test_v_i_o(VS_OLD, "0.0.1", "Tor 0.0.2");
3055 test_v_i_o(VS_OLD, "0.0.1", "0.0.2, Tor 0.0.3");
3056 test_v_i_o(VS_OLD, "0.0.1", "0.0.2,Tor 0.0.3");
3057 test_v_i_o(VS_OLD, "0.0.1","0.0.3,BetterTor 0.0.1");
3058 test_v_i_o(VS_RECOMMENDED, "0.0.2", "Tor 0.0.2,Tor 0.0.3");
3059 test_v_i_o(VS_NEW_IN_SERIES, "0.0.2", "Tor 0.0.2pre1,Tor 0.0.3");
3060 test_v_i_o(VS_OLD, "0.0.2", "Tor 0.0.2.1,Tor 0.0.3");
3061 test_v_i_o(VS_NEW, "0.1.0", "Tor 0.0.2,Tor 0.0.3");
3062 test_v_i_o(VS_RECOMMENDED, "0.0.7rc2", "0.0.7,Tor 0.0.7rc2,Tor 0.0.8");
3063 test_v_i_o(VS_OLD, "0.0.5.0", "0.0.5.1-cvs");
3064 test_v_i_o(VS_NEW_IN_SERIES, "0.0.5.1-cvs", "0.0.5, 0.0.6");
3065 /* Not on list, but newer than any in same series. */
3066 test_v_i_o(VS_NEW_IN_SERIES, "0.1.0.3",
3067 "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
3068 /* Series newer than any on list. */
3069 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");
3070 /* Series older than any on list. */
3071 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");
3072 /* Not on list, not newer than any on same series. */
3073 test_v_i_o(VS_UNRECOMMENDED, "0.1.0.1",
3074 "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
3075 /* On list, not newer than any on same series. */
3076 test_v_i_o(VS_UNRECOMMENDED,
3077 "0.1.0.1", "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
3078 test_eq(0, tor_version_as_new_as("Tor 0.0.5", "0.0.9pre1-cvs"));
3079 test_eq(1, tor_version_as_new_as(
3080 "Tor 0.0.8 on Darwin 64-121-192-100.c3-0."
3081 "sfpo-ubr1.sfrn-sfpo.ca.cable.rcn.com Power Macintosh",
3082 "0.0.8rc2"));
3083 test_eq(0, tor_version_as_new_as(
3084 "Tor 0.0.8 on Darwin 64-121-192-100.c3-0."
3085 "sfpo-ubr1.sfrn-sfpo.ca.cable.rcn.com Power Macintosh", "0.0.8.2"));
3087 /* Now try svn revisions. */
3088 test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100)",
3089 "Tor 0.2.1.0-dev (r99)"));
3090 test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100) on Banana Jr",
3091 "Tor 0.2.1.0-dev (r99) on Hal 9000"));
3092 test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100)",
3093 "Tor 0.2.1.0-dev on Colossus"));
3094 test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev (r99)",
3095 "Tor 0.2.1.0-dev (r100)"));
3096 test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev (r99) on MCP",
3097 "Tor 0.2.1.0-dev (r100) on AM"));
3098 test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev",
3099 "Tor 0.2.1.0-dev (r99)"));
3100 test_eq(1, tor_version_as_new_as("Tor 0.2.1.1",
3101 "Tor 0.2.1.0-dev (r99)"));
3102 done:
3103 if (r1)
3104 routerinfo_free(r1);
3105 if (r2)
3106 routerinfo_free(r2);
3108 tor_free(pk1_str);
3109 tor_free(pk2_str);
3110 tor_free(pk3_str);
3111 if (pk1) crypto_free_pk_env(pk1);
3112 if (pk2) crypto_free_pk_env(pk2);
3113 if (pk3) crypto_free_pk_env(pk3);
3114 if (rp1) routerinfo_free(rp1);
3115 tor_free(dir1); /* XXXX And more !*/
3116 tor_free(dir2); /* And more !*/
3119 /** Run unit tests for misc directory functions. */
3120 static void
3121 test_dirutil(void)
3123 smartlist_t *sl = smartlist_create();
3124 fp_pair_t *pair;
3126 dir_split_resource_into_fingerprint_pairs(
3127 /* Two pairs, out of order, with one duplicate. */
3128 "73656372657420646174612E0000000000FFFFFF-"
3129 "557365204145532d32353620696e73746561642e+"
3130 "73656372657420646174612E0000000000FFFFFF-"
3131 "557365204145532d32353620696e73746561642e+"
3132 "48657861646563696d616c2069736e277420736f-"
3133 "676f6f6420666f7220686964696e6720796f7572.z", sl);
3135 test_eq(smartlist_len(sl), 2);
3136 pair = smartlist_get(sl, 0);
3137 test_memeq(pair->first, "Hexadecimal isn't so", DIGEST_LEN);
3138 test_memeq(pair->second, "good for hiding your", DIGEST_LEN);
3139 pair = smartlist_get(sl, 1);
3140 test_memeq(pair->first, "secret data.\0\0\0\0\0\xff\xff\xff", DIGEST_LEN);
3141 test_memeq(pair->second, "Use AES-256 instead.", DIGEST_LEN);
3143 done:
3144 SMARTLIST_FOREACH(sl, fp_pair_t *, pair, tor_free(pair));
3145 smartlist_free(sl);
3148 extern const char AUTHORITY_CERT_1[];
3149 extern const char AUTHORITY_SIGNKEY_1[];
3150 extern const char AUTHORITY_CERT_2[];
3151 extern const char AUTHORITY_SIGNKEY_2[];
3152 extern const char AUTHORITY_CERT_3[];
3153 extern const char AUTHORITY_SIGNKEY_3[];
3155 /** Helper: Test that two networkstatus_voter_info_t do in fact represent the
3156 * same voting authority, and that they do in fact have all the same
3157 * information. */
3158 static void
3159 test_same_voter(networkstatus_voter_info_t *v1,
3160 networkstatus_voter_info_t *v2)
3162 test_streq(v1->nickname, v2->nickname);
3163 test_memeq(v1->identity_digest, v2->identity_digest, DIGEST_LEN);
3164 test_streq(v1->address, v2->address);
3165 test_eq(v1->addr, v2->addr);
3166 test_eq(v1->dir_port, v2->dir_port);
3167 test_eq(v1->or_port, v2->or_port);
3168 test_streq(v1->contact, v2->contact);
3169 test_memeq(v1->vote_digest, v2->vote_digest, DIGEST_LEN);
3170 done:
3174 /** Run unit tests for getting the median of a list. */
3175 static void
3176 test_util_order_functions(void)
3178 int lst[25], n = 0;
3179 // int a=12,b=24,c=25,d=60,e=77;
3181 #define median() median_int(lst, n)
3183 lst[n++] = 12;
3184 test_eq(12, median()); /* 12 */
3185 lst[n++] = 77;
3186 //smartlist_shuffle(sl);
3187 test_eq(12, median()); /* 12, 77 */
3188 lst[n++] = 77;
3189 //smartlist_shuffle(sl);
3190 test_eq(77, median()); /* 12, 77, 77 */
3191 lst[n++] = 24;
3192 test_eq(24, median()); /* 12,24,77,77 */
3193 lst[n++] = 60;
3194 lst[n++] = 12;
3195 lst[n++] = 25;
3196 //smartlist_shuffle(sl);
3197 test_eq(25, median()); /* 12,12,24,25,60,77,77 */
3198 #undef median
3200 done:
3204 /** Helper: Make a new routerinfo containing the right information for a
3205 * given vote_routerstatus_t. */
3206 static routerinfo_t *
3207 generate_ri_from_rs(const vote_routerstatus_t *vrs)
3209 routerinfo_t *r;
3210 const routerstatus_t *rs = &vrs->status;
3211 static time_t published = 0;
3213 r = tor_malloc_zero(sizeof(routerinfo_t));
3214 memcpy(r->cache_info.identity_digest, rs->identity_digest, DIGEST_LEN);
3215 memcpy(r->cache_info.signed_descriptor_digest, rs->descriptor_digest,
3216 DIGEST_LEN);
3217 r->cache_info.do_not_cache = 1;
3218 r->cache_info.routerlist_index = -1;
3219 r->cache_info.signed_descriptor_body =
3220 tor_strdup("123456789012345678901234567890123");
3221 r->cache_info.signed_descriptor_len =
3222 strlen(r->cache_info.signed_descriptor_body);
3223 r->exit_policy = smartlist_create();
3224 r->cache_info.published_on = ++published + time(NULL);
3225 return r;
3228 /** Run unit tests for generating and parsing V3 consensus networkstatus
3229 * documents. */
3230 static void
3231 test_v3_networkstatus(void)
3233 authority_cert_t *cert1=NULL, *cert2=NULL, *cert3=NULL;
3234 crypto_pk_env_t *sign_skey_1=NULL, *sign_skey_2=NULL, *sign_skey_3=NULL;
3235 crypto_pk_env_t *sign_skey_leg1=NULL;
3236 const char *msg=NULL;
3238 time_t now = time(NULL);
3239 networkstatus_voter_info_t *voter;
3240 networkstatus_t *vote=NULL, *v1=NULL, *v2=NULL, *v3=NULL, *con=NULL;
3241 vote_routerstatus_t *vrs;
3242 routerstatus_t *rs;
3243 char *v1_text=NULL, *v2_text=NULL, *v3_text=NULL, *consensus_text=NULL, *cp;
3244 smartlist_t *votes = smartlist_create();
3246 /* For generating the two other consensuses. */
3247 char *detached_text1=NULL, *detached_text2=NULL;
3248 char *consensus_text2=NULL, *consensus_text3=NULL;
3249 networkstatus_t *con2=NULL, *con3=NULL;
3250 ns_detached_signatures_t *dsig1=NULL, *dsig2=NULL;
3252 /* Parse certificates and keys. */
3253 cert1 = authority_cert_parse_from_string(AUTHORITY_CERT_1, NULL);
3254 test_assert(cert1);
3255 test_assert(cert1->is_cross_certified);
3256 cert2 = authority_cert_parse_from_string(AUTHORITY_CERT_2, NULL);
3257 test_assert(cert2);
3258 cert3 = authority_cert_parse_from_string(AUTHORITY_CERT_3, NULL);
3259 test_assert(cert3);
3260 sign_skey_1 = crypto_new_pk_env();
3261 sign_skey_2 = crypto_new_pk_env();
3262 sign_skey_3 = crypto_new_pk_env();
3263 sign_skey_leg1 = pk_generate(4);
3265 test_assert(!crypto_pk_read_private_key_from_string(sign_skey_1,
3266 AUTHORITY_SIGNKEY_1));
3267 test_assert(!crypto_pk_read_private_key_from_string(sign_skey_2,
3268 AUTHORITY_SIGNKEY_2));
3269 test_assert(!crypto_pk_read_private_key_from_string(sign_skey_3,
3270 AUTHORITY_SIGNKEY_3));
3272 test_assert(!crypto_pk_cmp_keys(sign_skey_1, cert1->signing_key));
3273 test_assert(!crypto_pk_cmp_keys(sign_skey_2, cert2->signing_key));
3276 * Set up a vote; generate it; try to parse it.
3278 vote = tor_malloc_zero(sizeof(networkstatus_t));
3279 vote->type = NS_TYPE_VOTE;
3280 vote->published = now;
3281 vote->valid_after = now+1000;
3282 vote->fresh_until = now+2000;
3283 vote->valid_until = now+3000;
3284 vote->vote_seconds = 100;
3285 vote->dist_seconds = 200;
3286 vote->supported_methods = smartlist_create();
3287 smartlist_split_string(vote->supported_methods, "1 2 3", NULL, 0, -1);
3288 vote->client_versions = tor_strdup("0.1.2.14,0.1.2.15");
3289 vote->server_versions = tor_strdup("0.1.2.14,0.1.2.15,0.1.2.16");
3290 vote->known_flags = smartlist_create();
3291 smartlist_split_string(vote->known_flags,
3292 "Authority Exit Fast Guard Running Stable V2Dir Valid",
3293 0, SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
3294 vote->voters = smartlist_create();
3295 voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
3296 voter->nickname = tor_strdup("Voter1");
3297 voter->address = tor_strdup("1.2.3.4");
3298 voter->addr = 0x01020304;
3299 voter->dir_port = 80;
3300 voter->or_port = 9000;
3301 voter->contact = tor_strdup("voter@example.com");
3302 crypto_pk_get_digest(cert1->identity_key, voter->identity_digest);
3303 smartlist_add(vote->voters, voter);
3304 vote->cert = authority_cert_dup(cert1);
3305 vote->routerstatus_list = smartlist_create();
3306 /* add the first routerstatus. */
3307 vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
3308 rs = &vrs->status;
3309 vrs->version = tor_strdup("0.1.2.14");
3310 rs->published_on = now-1500;
3311 strlcpy(rs->nickname, "router2", sizeof(rs->nickname));
3312 memset(rs->identity_digest, 3, DIGEST_LEN);
3313 memset(rs->descriptor_digest, 78, DIGEST_LEN);
3314 rs->addr = 0x99008801;
3315 rs->or_port = 443;
3316 rs->dir_port = 8000;
3317 /* all flags but running cleared */
3318 rs->is_running = 1;
3319 smartlist_add(vote->routerstatus_list, vrs);
3320 test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs), &msg,0,0)>=0);
3322 /* add the second routerstatus. */
3323 vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
3324 rs = &vrs->status;
3325 vrs->version = tor_strdup("0.2.0.5");
3326 rs->published_on = now-1000;
3327 strlcpy(rs->nickname, "router1", sizeof(rs->nickname));
3328 memset(rs->identity_digest, 5, DIGEST_LEN);
3329 memset(rs->descriptor_digest, 77, DIGEST_LEN);
3330 rs->addr = 0x99009901;
3331 rs->or_port = 443;
3332 rs->dir_port = 0;
3333 rs->is_exit = rs->is_stable = rs->is_fast = rs->is_running =
3334 rs->is_valid = rs->is_v2_dir = rs->is_possible_guard = 1;
3335 smartlist_add(vote->routerstatus_list, vrs);
3336 test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs), &msg,0,0)>=0);
3338 /* add the third routerstatus. */
3339 vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
3340 rs = &vrs->status;
3341 vrs->version = tor_strdup("0.1.0.3");
3342 rs->published_on = now-1000;
3343 strlcpy(rs->nickname, "router3", sizeof(rs->nickname));
3344 memset(rs->identity_digest, 33, DIGEST_LEN);
3345 memset(rs->descriptor_digest, 79, DIGEST_LEN);
3346 rs->addr = 0xAA009901;
3347 rs->or_port = 400;
3348 rs->dir_port = 9999;
3349 rs->is_authority = rs->is_exit = rs->is_stable = rs->is_fast =
3350 rs->is_running = rs->is_valid = rs->is_v2_dir = rs->is_possible_guard = 1;
3351 smartlist_add(vote->routerstatus_list, vrs);
3352 test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs), &msg,0,0)>=0);
3354 /* add a fourth routerstatus that is not running. */
3355 vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
3356 rs = &vrs->status;
3357 vrs->version = tor_strdup("0.1.6.3");
3358 rs->published_on = now-1000;
3359 strlcpy(rs->nickname, "router4", sizeof(rs->nickname));
3360 memset(rs->identity_digest, 34, DIGEST_LEN);
3361 memset(rs->descriptor_digest, 48, DIGEST_LEN);
3362 rs->addr = 0xC0000203;
3363 rs->or_port = 500;
3364 rs->dir_port = 1999;
3365 /* Running flag (and others) cleared */
3366 smartlist_add(vote->routerstatus_list, vrs);
3367 test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs), &msg,0,0)>=0);
3369 /* dump the vote and try to parse it. */
3370 v1_text = format_networkstatus_vote(sign_skey_1, vote);
3371 test_assert(v1_text);
3372 v1 = networkstatus_parse_vote_from_string(v1_text, NULL, NS_TYPE_VOTE);
3373 test_assert(v1);
3375 /* Make sure the parsed thing was right. */
3376 test_eq(v1->type, NS_TYPE_VOTE);
3377 test_eq(v1->published, vote->published);
3378 test_eq(v1->valid_after, vote->valid_after);
3379 test_eq(v1->fresh_until, vote->fresh_until);
3380 test_eq(v1->valid_until, vote->valid_until);
3381 test_eq(v1->vote_seconds, vote->vote_seconds);
3382 test_eq(v1->dist_seconds, vote->dist_seconds);
3383 test_streq(v1->client_versions, vote->client_versions);
3384 test_streq(v1->server_versions, vote->server_versions);
3385 test_assert(v1->voters && smartlist_len(v1->voters));
3386 voter = smartlist_get(v1->voters, 0);
3387 test_streq(voter->nickname, "Voter1");
3388 test_streq(voter->address, "1.2.3.4");
3389 test_eq(voter->addr, 0x01020304);
3390 test_eq(voter->dir_port, 80);
3391 test_eq(voter->or_port, 9000);
3392 test_streq(voter->contact, "voter@example.com");
3393 test_assert(v1->cert);
3394 test_assert(!crypto_pk_cmp_keys(sign_skey_1, v1->cert->signing_key));
3395 cp = smartlist_join_strings(v1->known_flags, ":", 0, NULL);
3396 test_streq(cp, "Authority:Exit:Fast:Guard:Running:Stable:V2Dir:Valid");
3397 tor_free(cp);
3398 test_eq(smartlist_len(v1->routerstatus_list), 4);
3399 /* Check the first routerstatus. */
3400 vrs = smartlist_get(v1->routerstatus_list, 0);
3401 rs = &vrs->status;
3402 test_streq(vrs->version, "0.1.2.14");
3403 test_eq(rs->published_on, now-1500);
3404 test_streq(rs->nickname, "router2");
3405 test_memeq(rs->identity_digest,
3406 "\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3",
3407 DIGEST_LEN);
3408 test_memeq(rs->descriptor_digest, "NNNNNNNNNNNNNNNNNNNN", DIGEST_LEN);
3409 test_eq(rs->addr, 0x99008801);
3410 test_eq(rs->or_port, 443);
3411 test_eq(rs->dir_port, 8000);
3412 test_eq(vrs->flags, U64_LITERAL(16)); // no flags except "running"
3413 /* Check the second routerstatus. */
3414 vrs = smartlist_get(v1->routerstatus_list, 1);
3415 rs = &vrs->status;
3416 test_streq(vrs->version, "0.2.0.5");
3417 test_eq(rs->published_on, now-1000);
3418 test_streq(rs->nickname, "router1");
3419 test_memeq(rs->identity_digest,
3420 "\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5",
3421 DIGEST_LEN);
3422 test_memeq(rs->descriptor_digest, "MMMMMMMMMMMMMMMMMMMM", DIGEST_LEN);
3423 test_eq(rs->addr, 0x99009901);
3424 test_eq(rs->or_port, 443);
3425 test_eq(rs->dir_port, 0);
3426 test_eq(vrs->flags, U64_LITERAL(254)); // all flags except "authority."
3428 /* Generate second vote. It disagrees on some of the times,
3429 * and doesn't list versions, and knows some crazy flags */
3430 vote->published = now+1;
3431 vote->fresh_until = now+3005;
3432 vote->dist_seconds = 300;
3433 authority_cert_free(vote->cert);
3434 vote->cert = authority_cert_dup(cert2);
3435 tor_free(vote->client_versions);
3436 tor_free(vote->server_versions);
3437 voter = smartlist_get(vote->voters, 0);
3438 tor_free(voter->nickname);
3439 tor_free(voter->address);
3440 voter->nickname = tor_strdup("Voter2");
3441 voter->address = tor_strdup("2.3.4.5");
3442 voter->addr = 0x02030405;
3443 crypto_pk_get_digest(cert2->identity_key, voter->identity_digest);
3444 smartlist_add(vote->known_flags, tor_strdup("MadeOfCheese"));
3445 smartlist_add(vote->known_flags, tor_strdup("MadeOfTin"));
3446 smartlist_sort_strings(vote->known_flags);
3447 vrs = smartlist_get(vote->routerstatus_list, 2);
3448 smartlist_del_keeporder(vote->routerstatus_list, 2);
3449 tor_free(vrs->version);
3450 tor_free(vrs);
3451 vrs = smartlist_get(vote->routerstatus_list, 0);
3452 vrs->status.is_fast = 1;
3453 /* generate and parse. */
3454 v2_text = format_networkstatus_vote(sign_skey_2, vote);
3455 test_assert(v2_text);
3456 v2 = networkstatus_parse_vote_from_string(v2_text, NULL, NS_TYPE_VOTE);
3457 test_assert(v2);
3458 /* Check that flags come out right.*/
3459 cp = smartlist_join_strings(v2->known_flags, ":", 0, NULL);
3460 test_streq(cp, "Authority:Exit:Fast:Guard:MadeOfCheese:MadeOfTin:"
3461 "Running:Stable:V2Dir:Valid");
3462 tor_free(cp);
3463 vrs = smartlist_get(v2->routerstatus_list, 1);
3464 /* 1023 - authority(1) - madeofcheese(16) - madeoftin(32) */
3465 test_eq(vrs->flags, U64_LITERAL(974));
3467 /* Generate the third vote. */
3468 vote->published = now;
3469 vote->fresh_until = now+2003;
3470 vote->dist_seconds = 250;
3471 authority_cert_free(vote->cert);
3472 vote->cert = authority_cert_dup(cert3);
3473 smartlist_add(vote->supported_methods, tor_strdup("4"));
3474 vote->client_versions = tor_strdup("0.1.2.14,0.1.2.17");
3475 vote->server_versions = tor_strdup("0.1.2.10,0.1.2.15,0.1.2.16");
3476 voter = smartlist_get(vote->voters, 0);
3477 tor_free(voter->nickname);
3478 tor_free(voter->address);
3479 voter->nickname = tor_strdup("Voter3");
3480 voter->address = tor_strdup("3.4.5.6");
3481 voter->addr = 0x03040506;
3482 crypto_pk_get_digest(cert3->identity_key, voter->identity_digest);
3483 /* This one has a legacy id. */
3484 memset(voter->legacy_id_digest, (int)'A', DIGEST_LEN);
3485 vrs = smartlist_get(vote->routerstatus_list, 0);
3486 smartlist_del_keeporder(vote->routerstatus_list, 0);
3487 tor_free(vrs->version);
3488 tor_free(vrs);
3489 vrs = smartlist_get(vote->routerstatus_list, 0);
3490 memset(vrs->status.descriptor_digest, (int)'Z', DIGEST_LEN);
3491 test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs), &msg,0,0)>=0);
3493 v3_text = format_networkstatus_vote(sign_skey_3, vote);
3494 test_assert(v3_text);
3496 v3 = networkstatus_parse_vote_from_string(v3_text, NULL, NS_TYPE_VOTE);
3497 test_assert(v3);
3499 /* Compute a consensus as voter 3. */
3500 smartlist_add(votes, v3);
3501 smartlist_add(votes, v1);
3502 smartlist_add(votes, v2);
3503 consensus_text = networkstatus_compute_consensus(votes, 3,
3504 cert3->identity_key,
3505 sign_skey_3,
3506 "AAAAAAAAAAAAAAAAAAAA",
3507 sign_skey_leg1);
3508 test_assert(consensus_text);
3509 con = networkstatus_parse_vote_from_string(consensus_text, NULL,
3510 NS_TYPE_CONSENSUS);
3511 test_assert(con);
3512 //log_notice(LD_GENERAL, "<<%s>>\n<<%s>>\n<<%s>>\n",
3513 // v1_text, v2_text, v3_text);
3515 /* Check consensus contents. */
3516 test_assert(con->type == NS_TYPE_CONSENSUS);
3517 test_eq(con->published, 0); /* this field only appears in votes. */
3518 test_eq(con->valid_after, now+1000);
3519 test_eq(con->fresh_until, now+2003); /* median */
3520 test_eq(con->valid_until, now+3000);
3521 test_eq(con->vote_seconds, 100);
3522 test_eq(con->dist_seconds, 250); /* median */
3523 test_streq(con->client_versions, "0.1.2.14");
3524 test_streq(con->server_versions, "0.1.2.15,0.1.2.16");
3525 cp = smartlist_join_strings(v2->known_flags, ":", 0, NULL);
3526 test_streq(cp, "Authority:Exit:Fast:Guard:MadeOfCheese:MadeOfTin:"
3527 "Running:Stable:V2Dir:Valid");
3528 tor_free(cp);
3529 test_eq(4, smartlist_len(con->voters)); /*3 voters, 1 legacy key.*/
3530 /* The voter id digests should be in this order. */
3531 test_assert(memcmp(cert2->cache_info.identity_digest,
3532 cert1->cache_info.identity_digest,DIGEST_LEN)<0);
3533 test_assert(memcmp(cert1->cache_info.identity_digest,
3534 cert3->cache_info.identity_digest,DIGEST_LEN)<0);
3535 test_same_voter(smartlist_get(con->voters, 1),
3536 smartlist_get(v2->voters, 0));
3537 test_same_voter(smartlist_get(con->voters, 2),
3538 smartlist_get(v1->voters, 0));
3539 test_same_voter(smartlist_get(con->voters, 3),
3540 smartlist_get(v3->voters, 0));
3542 test_assert(!con->cert);
3543 test_eq(2, smartlist_len(con->routerstatus_list));
3544 /* There should be two listed routers: one with identity 3, one with
3545 * identity 5. */
3546 /* This one showed up in 2 digests. */
3547 rs = smartlist_get(con->routerstatus_list, 0);
3548 test_memeq(rs->identity_digest,
3549 "\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3",
3550 DIGEST_LEN);
3551 test_memeq(rs->descriptor_digest, "NNNNNNNNNNNNNNNNNNNN", DIGEST_LEN);
3552 test_assert(!rs->is_authority);
3553 test_assert(!rs->is_exit);
3554 test_assert(!rs->is_fast);
3555 test_assert(!rs->is_possible_guard);
3556 test_assert(!rs->is_stable);
3557 test_assert(rs->is_running); /* If it wasn't running it wouldn't be here */
3558 test_assert(!rs->is_v2_dir);
3559 test_assert(!rs->is_valid);
3560 test_assert(!rs->is_named);
3561 /* XXXX check version */
3563 rs = smartlist_get(con->routerstatus_list, 1);
3564 /* This one showed up in 3 digests. Twice with ID 'M', once with 'Z'. */
3565 test_memeq(rs->identity_digest,
3566 "\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5",
3567 DIGEST_LEN);
3568 test_streq(rs->nickname, "router1");
3569 test_memeq(rs->descriptor_digest, "MMMMMMMMMMMMMMMMMMMM", DIGEST_LEN);
3570 test_eq(rs->published_on, now-1000);
3571 test_eq(rs->addr, 0x99009901);
3572 test_eq(rs->or_port, 443);
3573 test_eq(rs->dir_port, 0);
3574 test_assert(!rs->is_authority);
3575 test_assert(rs->is_exit);
3576 test_assert(rs->is_fast);
3577 test_assert(rs->is_possible_guard);
3578 test_assert(rs->is_stable);
3579 test_assert(rs->is_running);
3580 test_assert(rs->is_v2_dir);
3581 test_assert(rs->is_valid);
3582 test_assert(!rs->is_named);
3583 /* XXXX check version */
3584 // x231
3585 // x213
3587 /* Check signatures. the first voter is a pseudo-entry with a legacy key.
3588 * The second one hasn't signed. The fourth one has signed: validate it. */
3589 voter = smartlist_get(con->voters, 1);
3590 test_assert(!voter->signature);
3591 test_assert(!voter->good_signature);
3592 test_assert(!voter->bad_signature);
3594 voter = smartlist_get(con->voters, 3);
3595 test_assert(voter->signature);
3596 test_assert(!voter->good_signature);
3597 test_assert(!voter->bad_signature);
3598 test_assert(!networkstatus_check_voter_signature(con,
3599 smartlist_get(con->voters, 3),
3600 cert3));
3601 test_assert(voter->signature);
3602 test_assert(voter->good_signature);
3603 test_assert(!voter->bad_signature);
3606 const char *msg=NULL;
3607 /* Compute the other two signed consensuses. */
3608 smartlist_shuffle(votes);
3609 consensus_text2 = networkstatus_compute_consensus(votes, 3,
3610 cert2->identity_key,
3611 sign_skey_2, NULL,NULL);
3612 smartlist_shuffle(votes);
3613 consensus_text3 = networkstatus_compute_consensus(votes, 3,
3614 cert1->identity_key,
3615 sign_skey_1, NULL,NULL);
3616 test_assert(consensus_text2);
3617 test_assert(consensus_text3);
3618 con2 = networkstatus_parse_vote_from_string(consensus_text2, NULL,
3619 NS_TYPE_CONSENSUS);
3620 con3 = networkstatus_parse_vote_from_string(consensus_text3, NULL,
3621 NS_TYPE_CONSENSUS);
3622 test_assert(con2);
3623 test_assert(con3);
3625 /* All three should have the same digest. */
3626 test_memeq(con->networkstatus_digest, con2->networkstatus_digest,
3627 DIGEST_LEN);
3628 test_memeq(con->networkstatus_digest, con3->networkstatus_digest,
3629 DIGEST_LEN);
3631 /* Extract a detached signature from con3. */
3632 detached_text1 = networkstatus_get_detached_signatures(con3);
3633 tor_assert(detached_text1);
3634 /* Try to parse it. */
3635 dsig1 = networkstatus_parse_detached_signatures(detached_text1, NULL);
3636 tor_assert(dsig1);
3638 /* Are parsed values as expected? */
3639 test_eq(dsig1->valid_after, con3->valid_after);
3640 test_eq(dsig1->fresh_until, con3->fresh_until);
3641 test_eq(dsig1->valid_until, con3->valid_until);
3642 test_memeq(dsig1->networkstatus_digest, con3->networkstatus_digest,
3643 DIGEST_LEN);
3644 test_eq(1, smartlist_len(dsig1->signatures));
3645 voter = smartlist_get(dsig1->signatures, 0);
3646 test_memeq(voter->identity_digest, cert1->cache_info.identity_digest,
3647 DIGEST_LEN);
3649 /* Try adding it to con2. */
3650 detached_text2 = networkstatus_get_detached_signatures(con2);
3651 test_eq(1, networkstatus_add_detached_signatures(con2, dsig1, &msg));
3652 tor_free(detached_text2);
3653 detached_text2 = networkstatus_get_detached_signatures(con2);
3654 //printf("\n<%s>\n", detached_text2);
3655 dsig2 = networkstatus_parse_detached_signatures(detached_text2, NULL);
3656 test_assert(dsig2);
3658 printf("\n");
3659 SMARTLIST_FOREACH(dsig2->signatures, networkstatus_voter_info_t *, vi, {
3660 char hd[64];
3661 base16_encode(hd, sizeof(hd), vi->identity_digest, DIGEST_LEN);
3662 printf("%s\n", hd);
3665 test_eq(2, smartlist_len(dsig2->signatures));
3667 /* Try adding to con2 twice; verify that nothing changes. */
3668 test_eq(0, networkstatus_add_detached_signatures(con2, dsig1, &msg));
3670 /* Add to con. */
3671 test_eq(2, networkstatus_add_detached_signatures(con, dsig2, &msg));
3672 /* Check signatures */
3673 test_assert(!networkstatus_check_voter_signature(con,
3674 smartlist_get(con->voters, 1),
3675 cert2));
3676 test_assert(!networkstatus_check_voter_signature(con,
3677 smartlist_get(con->voters, 2),
3678 cert1));
3682 done:
3683 smartlist_free(votes);
3684 tor_free(v1_text);
3685 tor_free(v2_text);
3686 tor_free(v3_text);
3687 tor_free(consensus_text);
3689 if (vote)
3690 networkstatus_vote_free(vote);
3691 if (v1)
3692 networkstatus_vote_free(v1);
3693 if (v2)
3694 networkstatus_vote_free(v2);
3695 if (v3)
3696 networkstatus_vote_free(v3);
3697 if (con)
3698 networkstatus_vote_free(con);
3699 if (sign_skey_1)
3700 crypto_free_pk_env(sign_skey_1);
3701 if (sign_skey_2)
3702 crypto_free_pk_env(sign_skey_2);
3703 if (sign_skey_3)
3704 crypto_free_pk_env(sign_skey_3);
3705 if (sign_skey_leg1)
3706 crypto_free_pk_env(sign_skey_leg1);
3707 if (cert1)
3708 authority_cert_free(cert1);
3709 if (cert2)
3710 authority_cert_free(cert2);
3711 if (cert3)
3712 authority_cert_free(cert3);
3714 tor_free(consensus_text2);
3715 tor_free(consensus_text3);
3716 tor_free(detached_text1);
3717 tor_free(detached_text2);
3718 if (con2)
3719 networkstatus_vote_free(con2);
3720 if (con3)
3721 networkstatus_vote_free(con3);
3722 if (dsig1)
3723 ns_detached_signatures_free(dsig1);
3724 if (dsig2)
3725 ns_detached_signatures_free(dsig2);
3728 /** Helper: Parse the exit policy string in <b>policy_str</b>, and make sure
3729 * that policies_summarize() produces the string <b>expected_summary</b> from
3730 * it. */
3731 static void
3732 test_policy_summary_helper(const char *policy_str,
3733 const char *expected_summary)
3735 config_line_t line;
3736 smartlist_t *policy = smartlist_create();
3737 char *summary = NULL;
3738 int r;
3740 line.key = (char*)"foo";
3741 line.value = (char *)policy_str;
3742 line.next = NULL;
3744 r = policies_parse_exit_policy(&line, &policy, 0, NULL);
3745 test_eq(r, 0);
3746 summary = policy_summarize(policy);
3748 test_assert(summary != NULL);
3749 test_streq(summary, expected_summary);
3751 done:
3752 tor_free(summary);
3753 if (policy)
3754 addr_policy_list_free(policy);
3757 /** Run unit tests for generating summary lines of exit policies */
3758 static void
3759 test_policies(void)
3761 int i;
3762 smartlist_t *policy = NULL, *policy2 = NULL;
3763 addr_policy_t *p;
3764 tor_addr_t tar;
3765 config_line_t line;
3766 smartlist_t *sm = NULL;
3767 char *policy_str = NULL;
3769 policy = smartlist_create();
3771 p = router_parse_addr_policy_item_from_string("reject 192.168.0.0/16:*",-1);
3772 test_assert(p != NULL);
3773 test_eq(ADDR_POLICY_REJECT, p->policy_type);
3774 tor_addr_from_ipv4h(&tar, 0xc0a80000u);
3775 test_eq(0, tor_addr_compare(&p->addr, &tar, CMP_EXACT));
3776 test_eq(16, p->maskbits);
3777 test_eq(1, p->prt_min);
3778 test_eq(65535, p->prt_max);
3780 smartlist_add(policy, p);
3782 test_assert(ADDR_POLICY_ACCEPTED ==
3783 compare_addr_to_addr_policy(0x01020304u, 2, policy));
3784 test_assert(ADDR_POLICY_PROBABLY_ACCEPTED ==
3785 compare_addr_to_addr_policy(0, 2, policy));
3786 test_assert(ADDR_POLICY_REJECTED ==
3787 compare_addr_to_addr_policy(0xc0a80102, 2, policy));
3789 policy2 = NULL;
3790 test_assert(0 == policies_parse_exit_policy(NULL, &policy2, 1, NULL));
3791 test_assert(policy2);
3793 test_assert(!exit_policy_is_general_exit(policy));
3794 test_assert(exit_policy_is_general_exit(policy2));
3795 test_assert(!exit_policy_is_general_exit(NULL));
3797 test_assert(cmp_addr_policies(policy, policy2));
3798 test_assert(cmp_addr_policies(policy, NULL));
3799 test_assert(!cmp_addr_policies(policy2, policy2));
3800 test_assert(!cmp_addr_policies(NULL, NULL));
3802 test_assert(!policy_is_reject_star(policy2));
3803 test_assert(policy_is_reject_star(policy));
3804 test_assert(policy_is_reject_star(NULL));
3806 addr_policy_list_free(policy);
3807 policy = NULL;
3809 /* make sure compacting logic works. */
3810 policy = NULL;
3811 line.key = (char*)"foo";
3812 line.value = (char*)"accept *:80,reject private:*,reject *:*";
3813 line.next = NULL;
3814 test_assert(0 == policies_parse_exit_policy(&line, &policy, 0, NULL));
3815 test_assert(policy);
3816 //test_streq(policy->string, "accept *:80");
3817 //test_streq(policy->next->string, "reject *:*");
3818 test_eq(smartlist_len(policy), 2);
3820 /* test policy summaries */
3821 /* check if we properly ignore private IP addresses */
3822 test_policy_summary_helper("reject 192.168.0.0/16:*,"
3823 "reject 0.0.0.0/8:*,"
3824 "reject 10.0.0.0/8:*,"
3825 "accept *:10-30,"
3826 "accept *:90,"
3827 "reject *:*",
3828 "accept 10-30,90");
3829 /* check all accept policies, and proper counting of rejects */
3830 test_policy_summary_helper("reject 11.0.0.0/9:80,"
3831 "reject 12.0.0.0/9:80,"
3832 "reject 13.0.0.0/9:80,"
3833 "reject 14.0.0.0/9:80,"
3834 "accept *:*", "accept 1-65535");
3835 test_policy_summary_helper("reject 11.0.0.0/9:80,"
3836 "reject 12.0.0.0/9:80,"
3837 "reject 13.0.0.0/9:80,"
3838 "reject 14.0.0.0/9:80,"
3839 "reject 15.0.0.0:81,"
3840 "accept *:*", "accept 1-65535");
3841 test_policy_summary_helper("reject 11.0.0.0/9:80,"
3842 "reject 12.0.0.0/9:80,"
3843 "reject 13.0.0.0/9:80,"
3844 "reject 14.0.0.0/9:80,"
3845 "reject 15.0.0.0:80,"
3846 "accept *:*",
3847 "reject 80");
3848 /* no exits */
3849 test_policy_summary_helper("accept 11.0.0.0/9:80,"
3850 "reject *:*",
3851 "reject 1-65535");
3852 /* port merging */
3853 test_policy_summary_helper("accept *:80,"
3854 "accept *:81,"
3855 "accept *:100-110,"
3856 "accept *:111,"
3857 "reject *:*",
3858 "accept 80-81,100-111");
3859 /* border ports */
3860 test_policy_summary_helper("accept *:1,"
3861 "accept *:3,"
3862 "accept *:65535,"
3863 "reject *:*",
3864 "accept 1,3,65535");
3865 /* holes */
3866 test_policy_summary_helper("accept *:1,"
3867 "accept *:3,"
3868 "accept *:5,"
3869 "accept *:7,"
3870 "reject *:*",
3871 "accept 1,3,5,7");
3872 test_policy_summary_helper("reject *:1,"
3873 "reject *:3,"
3874 "reject *:5,"
3875 "reject *:7,"
3876 "accept *:*",
3877 "reject 1,3,5,7");
3879 /* truncation ports */
3880 sm = smartlist_create();
3881 for (i=1; i<2000; i+=2) {
3882 char buf[POLICY_BUF_LEN];
3883 tor_snprintf(buf, sizeof(buf), "reject *:%d", i);
3884 smartlist_add(sm, tor_strdup(buf));
3886 smartlist_add(sm, tor_strdup("accept *:*"));
3887 policy_str = smartlist_join_strings(sm, ",", 0, NULL);
3888 test_policy_summary_helper( policy_str,
3889 "accept 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,"
3890 "46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,"
3891 "92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,"
3892 "130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,"
3893 "166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198,200,"
3894 "202,204,206,208,210,212,214,216,218,220,222,224,226,228,230,232,234,236,"
3895 "238,240,242,244,246,248,250,252,254,256,258,260,262,264,266,268,270,272,"
3896 "274,276,278,280,282,284,286,288,290,292,294,296,298,300,302,304,306,308,"
3897 "310,312,314,316,318,320,322,324,326,328,330,332,334,336,338,340,342,344,"
3898 "346,348,350,352,354,356,358,360,362,364,366,368,370,372,374,376,378,380,"
3899 "382,384,386,388,390,392,394,396,398,400,402,404,406,408,410,412,414,416,"
3900 "418,420,422,424,426,428,430,432,434,436,438,440,442,444,446,448,450,452,"
3901 "454,456,458,460,462,464,466,468,470,472,474,476,478,480,482,484,486,488,"
3902 "490,492,494,496,498,500,502,504,506,508,510,512,514,516,518,520,522");
3904 done:
3905 if (policy)
3906 addr_policy_list_free(policy);
3907 if (policy2)
3908 addr_policy_list_free(policy2);
3909 tor_free(policy_str);
3910 if (sm) {
3911 SMARTLIST_FOREACH(sm, char *, s, tor_free(s));
3912 smartlist_free(sm);
3916 /** Run unit tests for basic rendezvous functions. */
3917 static void
3918 test_rend_fns(void)
3920 char address1[] = "fooaddress.onion";
3921 char address2[] = "aaaaaaaaaaaaaaaa.onion";
3922 char address3[] = "fooaddress.exit";
3923 char address4[] = "www.torproject.org";
3924 rend_service_descriptor_t *d1 = NULL, *d2 = NULL;
3925 char *encoded = NULL;
3926 size_t len;
3927 crypto_pk_env_t *pk1 = NULL, *pk2 = NULL;
3928 time_t now;
3929 int i;
3930 pk1 = pk_generate(0);
3931 pk2 = pk_generate(1);
3933 /* Test unversioned (v0) descriptor */
3934 d1 = tor_malloc_zero(sizeof(rend_service_descriptor_t));
3935 d1->pk = crypto_pk_dup_key(pk1);
3936 now = time(NULL);
3937 d1->timestamp = now;
3938 d1->version = 0;
3939 d1->intro_nodes = smartlist_create();
3940 for (i = 0; i < 3; i++) {
3941 rend_intro_point_t *intro = tor_malloc_zero(sizeof(rend_intro_point_t));
3942 intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
3943 crypto_rand(intro->extend_info->identity_digest, DIGEST_LEN);
3944 intro->extend_info->nickname[0] = '$';
3945 base16_encode(intro->extend_info->nickname+1, HEX_DIGEST_LEN+1,
3946 intro->extend_info->identity_digest, DIGEST_LEN);
3947 smartlist_add(d1->intro_nodes, intro);
3949 test_assert(! rend_encode_service_descriptor(d1, pk1, &encoded, &len));
3950 d2 = rend_parse_service_descriptor(encoded, len);
3951 test_assert(d2);
3953 test_assert(!crypto_pk_cmp_keys(d1->pk, d2->pk));
3954 test_eq(d2->timestamp, now);
3955 test_eq(d2->version, 0);
3956 test_eq(d2->protocols, 1<<2);
3957 test_eq(smartlist_len(d2->intro_nodes), 3);
3958 for (i = 0; i < 3; i++) {
3959 rend_intro_point_t *intro1 = smartlist_get(d1->intro_nodes, i);
3960 rend_intro_point_t *intro2 = smartlist_get(d2->intro_nodes, i);
3961 test_streq(intro1->extend_info->nickname,
3962 intro2->extend_info->nickname);
3965 test_assert(BAD_HOSTNAME == parse_extended_hostname(address1));
3966 test_assert(ONION_HOSTNAME == parse_extended_hostname(address2));
3967 test_assert(EXIT_HOSTNAME == parse_extended_hostname(address3));
3968 test_assert(NORMAL_HOSTNAME == parse_extended_hostname(address4));
3970 done:
3971 if (pk1)
3972 crypto_free_pk_env(pk1);
3973 if (pk2)
3974 crypto_free_pk_env(pk2);
3975 if (d1)
3976 rend_service_descriptor_free(d1);
3977 if (d2)
3978 rend_service_descriptor_free(d2);
3979 tor_free(encoded);
3982 /** Run AES performance benchmarks. */
3983 static void
3984 bench_aes(void)
3986 int len, i;
3987 char *b1, *b2;
3988 crypto_cipher_env_t *c;
3989 struct timeval start, end;
3990 const int iters = 100000;
3991 uint64_t nsec;
3992 c = crypto_new_cipher_env();
3993 crypto_cipher_generate_key(c);
3994 crypto_cipher_encrypt_init_cipher(c);
3995 for (len = 1; len <= 8192; len *= 2) {
3996 b1 = tor_malloc_zero(len);
3997 b2 = tor_malloc_zero(len);
3998 tor_gettimeofday(&start);
3999 for (i = 0; i < iters; ++i) {
4000 crypto_cipher_encrypt(c, b1, b2, len);
4002 tor_gettimeofday(&end);
4003 tor_free(b1);
4004 tor_free(b2);
4005 nsec = (uint64_t) tv_udiff(&start,&end);
4006 nsec *= 1000;
4007 nsec /= (iters*len);
4008 printf("%d bytes: "U64_FORMAT" nsec per byte\n", len,
4009 U64_PRINTF_ARG(nsec));
4011 crypto_free_cipher_env(c);
4014 /** Run digestmap_t performance benchmarks. */
4015 static void
4016 bench_dmap(void)
4018 smartlist_t *sl = smartlist_create();
4019 smartlist_t *sl2 = smartlist_create();
4020 struct timeval start, end, pt2, pt3, pt4;
4021 const int iters = 10000;
4022 const int elts = 4000;
4023 const int fpostests = 1000000;
4024 char d[20];
4025 int i,n=0, fp = 0;
4026 digestmap_t *dm = digestmap_new();
4027 digestset_t *ds = digestset_new(elts);
4029 for (i = 0; i < elts; ++i) {
4030 crypto_rand(d, 20);
4031 smartlist_add(sl, tor_memdup(d, 20));
4033 for (i = 0; i < elts; ++i) {
4034 crypto_rand(d, 20);
4035 smartlist_add(sl2, tor_memdup(d, 20));
4037 printf("nbits=%d\n", ds->mask+1);
4039 tor_gettimeofday(&start);
4040 for (i = 0; i < iters; ++i) {
4041 SMARTLIST_FOREACH(sl, const char *, cp, digestmap_set(dm, cp, (void*)1));
4043 tor_gettimeofday(&pt2);
4044 for (i = 0; i < iters; ++i) {
4045 SMARTLIST_FOREACH(sl, const char *, cp, digestmap_get(dm, cp));
4046 SMARTLIST_FOREACH(sl2, const char *, cp, digestmap_get(dm, cp));
4048 tor_gettimeofday(&pt3);
4049 for (i = 0; i < iters; ++i) {
4050 SMARTLIST_FOREACH(sl, const char *, cp, digestset_add(ds, cp));
4052 tor_gettimeofday(&pt4);
4053 for (i = 0; i < iters; ++i) {
4054 SMARTLIST_FOREACH(sl, const char *, cp, n += digestset_isin(ds, cp));
4055 SMARTLIST_FOREACH(sl2, const char *, cp, n += digestset_isin(ds, cp));
4057 tor_gettimeofday(&end);
4059 for (i = 0; i < fpostests; ++i) {
4060 crypto_rand(d, 20);
4061 if (digestset_isin(ds, d)) ++fp;
4064 printf("%ld\n",(unsigned long)tv_udiff(&start, &pt2));
4065 printf("%ld\n",(unsigned long)tv_udiff(&pt2, &pt3));
4066 printf("%ld\n",(unsigned long)tv_udiff(&pt3, &pt4));
4067 printf("%ld\n",(unsigned long)tv_udiff(&pt4, &end));
4068 printf("-- %d\n", n);
4069 printf("++ %f\n", fp/(double)fpostests);
4070 digestmap_free(dm, NULL);
4071 digestset_free(ds);
4072 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
4073 SMARTLIST_FOREACH(sl2, char *, cp, tor_free(cp));
4074 smartlist_free(sl);
4075 smartlist_free(sl2);
4078 /** Run unittests for memory pool allocator */
4079 static void
4080 test_util_mempool(void)
4082 mp_pool_t *pool = NULL;
4083 smartlist_t *allocated = NULL;
4084 int i;
4086 pool = mp_pool_new(1, 100);
4087 test_assert(pool);
4088 test_assert(pool->new_chunk_capacity >= 100);
4089 test_assert(pool->item_alloc_size >= sizeof(void*)+1);
4090 mp_pool_destroy(pool);
4091 pool = NULL;
4093 pool = mp_pool_new(241, 2500);
4094 test_assert(pool);
4095 test_assert(pool->new_chunk_capacity >= 10);
4096 test_assert(pool->item_alloc_size >= sizeof(void*)+241);
4097 test_eq(pool->item_alloc_size & 0x03, 0);
4098 test_assert(pool->new_chunk_capacity < 60);
4100 allocated = smartlist_create();
4101 for (i = 0; i < 20000; ++i) {
4102 if (smartlist_len(allocated) < 20 || crypto_rand_int(2)) {
4103 void *m = mp_pool_get(pool);
4104 memset(m, 0x09, 241);
4105 smartlist_add(allocated, m);
4106 //printf("%d: %p\n", i, m);
4107 //mp_pool_assert_ok(pool);
4108 } else {
4109 int idx = crypto_rand_int(smartlist_len(allocated));
4110 void *m = smartlist_get(allocated, idx);
4111 //printf("%d: free %p\n", i, m);
4112 smartlist_del(allocated, idx);
4113 mp_pool_release(m);
4114 //mp_pool_assert_ok(pool);
4116 if (crypto_rand_int(777)==0)
4117 mp_pool_clean(pool, 1, 1);
4119 if (i % 777)
4120 mp_pool_assert_ok(pool);
4123 done:
4124 if (allocated) {
4125 SMARTLIST_FOREACH(allocated, void *, m, mp_pool_release(m));
4126 mp_pool_assert_ok(pool);
4127 mp_pool_clean(pool, 0, 0);
4128 mp_pool_assert_ok(pool);
4129 smartlist_free(allocated);
4132 if (pool)
4133 mp_pool_destroy(pool);
4136 /** Run unittests for memory area allocator */
4137 static void
4138 test_util_memarea(void)
4140 memarea_t *area = memarea_new();
4141 char *p1, *p2, *p3, *p1_orig;
4142 void *malloced_ptr = NULL;
4143 int i;
4145 test_assert(area);
4147 p1_orig = p1 = memarea_alloc(area,64);
4148 p2 = memarea_alloc_zero(area,52);
4149 p3 = memarea_alloc(area,11);
4151 test_assert(memarea_owns_ptr(area, p1));
4152 test_assert(memarea_owns_ptr(area, p2));
4153 test_assert(memarea_owns_ptr(area, p3));
4154 /* Make sure we left enough space. */
4155 test_assert(p1+64 <= p2);
4156 test_assert(p2+52 <= p3);
4157 /* Make sure we aligned. */
4158 test_eq(((uintptr_t)p1) % sizeof(void*), 0);
4159 test_eq(((uintptr_t)p2) % sizeof(void*), 0);
4160 test_eq(((uintptr_t)p3) % sizeof(void*), 0);
4161 test_assert(!memarea_owns_ptr(area, p3+8192));
4162 test_assert(!memarea_owns_ptr(area, p3+30));
4163 test_assert(tor_mem_is_zero(p2, 52));
4164 /* Make sure we don't overalign. */
4165 p1 = memarea_alloc(area, 1);
4166 p2 = memarea_alloc(area, 1);
4167 test_eq(p1+sizeof(void*), p2);
4169 malloced_ptr = tor_malloc(64);
4170 test_assert(!memarea_owns_ptr(area, malloced_ptr));
4171 tor_free(malloced_ptr);
4174 /* memarea_memdup */
4176 malloced_ptr = tor_malloc(64);
4177 crypto_rand((char*)malloced_ptr, 64);
4178 p1 = memarea_memdup(area, malloced_ptr, 64);
4179 test_assert(p1 != malloced_ptr);
4180 test_memeq(p1, malloced_ptr, 64);
4181 tor_free(malloced_ptr);
4184 /* memarea_strdup. */
4185 p1 = memarea_strdup(area,"");
4186 p2 = memarea_strdup(area, "abcd");
4187 test_assert(p1);
4188 test_assert(p2);
4189 test_streq(p1, "");
4190 test_streq(p2, "abcd");
4192 /* memarea_strndup. */
4194 const char *s = "Ad ogni porta batte la morte e grida: il nome!";
4195 /* (From Turandot, act 3.) */
4196 size_t len = strlen(s);
4197 p1 = memarea_strndup(area, s, 1000);
4198 p2 = memarea_strndup(area, s, 10);
4199 test_streq(p1, s);
4200 test_assert(p2 >= p1 + len + 1);
4201 test_memeq(s, p2, 10);
4202 test_eq(p2[10], '\0');
4203 p3 = memarea_strndup(area, s, len);
4204 test_streq(p3, s);
4205 p3 = memarea_strndup(area, s, len-1);
4206 test_memeq(s, p3, len-1);
4207 test_eq(p3[len-1], '\0');
4210 memarea_clear(area);
4211 p1 = memarea_alloc(area, 1);
4212 test_eq(p1, p1_orig);
4213 memarea_clear(area);
4215 /* Check for running over an area's size. */
4216 for (i = 0; i < 512; ++i) {
4217 p1 = memarea_alloc(area, crypto_rand_int(5)+1);
4218 test_assert(memarea_owns_ptr(area, p1));
4220 memarea_assert_ok(area);
4221 /* Make sure we can allocate a too-big object. */
4222 p1 = memarea_alloc_zero(area, 9000);
4223 p2 = memarea_alloc_zero(area, 16);
4224 test_assert(memarea_owns_ptr(area, p1));
4225 test_assert(memarea_owns_ptr(area, p2));
4227 done:
4228 memarea_drop_all(area);
4229 tor_free(malloced_ptr);
4232 /** Run unit tests for utility functions to get file names relative to
4233 * the data directory. */
4234 static void
4235 test_util_datadir(void)
4237 char buf[1024];
4238 char *f = NULL;
4240 f = get_datadir_fname(NULL);
4241 test_streq(f, temp_dir);
4242 tor_free(f);
4243 f = get_datadir_fname("state");
4244 tor_snprintf(buf, sizeof(buf), "%s"PATH_SEPARATOR"state", temp_dir);
4245 test_streq(f, buf);
4246 tor_free(f);
4247 f = get_datadir_fname2("cache", "thingy");
4248 tor_snprintf(buf, sizeof(buf),
4249 "%s"PATH_SEPARATOR"cache"PATH_SEPARATOR"thingy", temp_dir);
4250 test_streq(f, buf);
4251 tor_free(f);
4252 f = get_datadir_fname2_suffix("cache", "thingy", ".foo");
4253 tor_snprintf(buf, sizeof(buf),
4254 "%s"PATH_SEPARATOR"cache"PATH_SEPARATOR"thingy.foo", temp_dir);
4255 test_streq(f, buf);
4256 tor_free(f);
4257 f = get_datadir_fname_suffix("cache", ".foo");
4258 tor_snprintf(buf, sizeof(buf), "%s"PATH_SEPARATOR"cache.foo",
4259 temp_dir);
4260 test_streq(f, buf);
4262 done:
4263 tor_free(f);
4266 /** Test AES-CTR encryption and decryption with IV. */
4267 static void
4268 test_crypto_aes_iv(void)
4270 crypto_cipher_env_t *cipher;
4271 char *plain, *encrypted1, *encrypted2, *decrypted1, *decrypted2;
4272 char plain_1[1], plain_15[15], plain_16[16], plain_17[17];
4273 char key1[16], key2[16];
4274 ssize_t encrypted_size, decrypted_size;
4276 plain = tor_malloc(4095);
4277 encrypted1 = tor_malloc(4095 + 1 + 16);
4278 encrypted2 = tor_malloc(4095 + 1 + 16);
4279 decrypted1 = tor_malloc(4095 + 1);
4280 decrypted2 = tor_malloc(4095 + 1);
4282 crypto_rand(plain, 4095);
4283 crypto_rand(key1, 16);
4284 crypto_rand(key2, 16);
4285 crypto_rand(plain_1, 1);
4286 crypto_rand(plain_15, 15);
4287 crypto_rand(plain_16, 16);
4288 crypto_rand(plain_17, 17);
4289 key1[0] = key2[0] + 128; /* Make sure that contents are different. */
4290 /* Encrypt and decrypt with the same key. */
4291 cipher = crypto_create_init_cipher(key1, 1);
4292 encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 4095,
4293 plain, 4095);
4294 crypto_free_cipher_env(cipher);
4295 cipher = NULL;
4296 test_eq(encrypted_size, 16 + 4095);
4297 cipher = crypto_create_init_cipher(key1, 0);
4298 decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 4095,
4299 encrypted1, encrypted_size);
4300 crypto_free_cipher_env(cipher);
4301 cipher = NULL;
4302 test_eq(decrypted_size, 4095);
4303 test_memeq(plain, decrypted1, 4095);
4304 /* Encrypt a second time (with a new random initialization vector). */
4305 cipher = crypto_create_init_cipher(key1, 1);
4306 encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted2, 16 + 4095,
4307 plain, 4095);
4308 crypto_free_cipher_env(cipher);
4309 cipher = NULL;
4310 test_eq(encrypted_size, 16 + 4095);
4311 cipher = crypto_create_init_cipher(key1, 0);
4312 decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted2, 4095,
4313 encrypted2, encrypted_size);
4314 crypto_free_cipher_env(cipher);
4315 cipher = NULL;
4316 test_eq(decrypted_size, 4095);
4317 test_memeq(plain, decrypted2, 4095);
4318 test_memneq(encrypted1, encrypted2, encrypted_size);
4319 /* Decrypt with the wrong key. */
4320 cipher = crypto_create_init_cipher(key2, 0);
4321 decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted2, 4095,
4322 encrypted1, encrypted_size);
4323 crypto_free_cipher_env(cipher);
4324 cipher = NULL;
4325 test_memneq(plain, decrypted2, encrypted_size);
4326 /* Alter the initialization vector. */
4327 encrypted1[0] += 42;
4328 cipher = crypto_create_init_cipher(key1, 0);
4329 decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 4095,
4330 encrypted1, encrypted_size);
4331 crypto_free_cipher_env(cipher);
4332 cipher = NULL;
4333 test_memneq(plain, decrypted2, 4095);
4334 /* Special length case: 1. */
4335 cipher = crypto_create_init_cipher(key1, 1);
4336 encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 1,
4337 plain_1, 1);
4338 crypto_free_cipher_env(cipher);
4339 cipher = NULL;
4340 test_eq(encrypted_size, 16 + 1);
4341 tor_assert(encrypted_size > 0); /* This is obviously true, since 17 is
4342 * greater than 0, but its truth is not
4343 * obvious to all analysis tools. */
4344 cipher = crypto_create_init_cipher(key1, 0);
4345 decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 1,
4346 encrypted1, encrypted_size);
4347 crypto_free_cipher_env(cipher);
4348 cipher = NULL;
4349 test_eq(decrypted_size, 1);
4350 test_memeq(plain_1, decrypted1, 1);
4351 /* Special length case: 15. */
4352 cipher = crypto_create_init_cipher(key1, 1);
4353 encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 15,
4354 plain_15, 15);
4355 crypto_free_cipher_env(cipher);
4356 cipher = NULL;
4357 test_eq(encrypted_size, 16 + 15);
4358 cipher = crypto_create_init_cipher(key1, 0);
4359 decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 15,
4360 encrypted1, encrypted_size);
4361 crypto_free_cipher_env(cipher);
4362 cipher = NULL;
4363 test_eq(decrypted_size, 15);
4364 test_memeq(plain_15, decrypted1, 15);
4365 /* Special length case: 16. */
4366 cipher = crypto_create_init_cipher(key1, 1);
4367 encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 16,
4368 plain_16, 16);
4369 crypto_free_cipher_env(cipher);
4370 cipher = NULL;
4371 test_eq(encrypted_size, 16 + 16);
4372 cipher = crypto_create_init_cipher(key1, 0);
4373 decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 16,
4374 encrypted1, encrypted_size);
4375 crypto_free_cipher_env(cipher);
4376 cipher = NULL;
4377 test_eq(decrypted_size, 16);
4378 test_memeq(plain_16, decrypted1, 16);
4379 /* Special length case: 17. */
4380 cipher = crypto_create_init_cipher(key1, 1);
4381 encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 17,
4382 plain_17, 17);
4383 crypto_free_cipher_env(cipher);
4384 cipher = NULL;
4385 test_eq(encrypted_size, 16 + 17);
4386 cipher = crypto_create_init_cipher(key1, 0);
4387 decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 17,
4388 encrypted1, encrypted_size);
4389 test_eq(decrypted_size, 17);
4390 test_memeq(plain_17, decrypted1, 17);
4392 done:
4393 /* Free memory. */
4394 tor_free(plain);
4395 tor_free(encrypted1);
4396 tor_free(encrypted2);
4397 tor_free(decrypted1);
4398 tor_free(decrypted2);
4399 if (cipher)
4400 crypto_free_cipher_env(cipher);
4403 /** Test base32 decoding. */
4404 static void
4405 test_crypto_base32_decode(void)
4407 char plain[60], encoded[96 + 1], decoded[60];
4408 int res;
4409 crypto_rand(plain, 60);
4410 /* Encode and decode a random string. */
4411 base32_encode(encoded, 96 + 1, plain, 60);
4412 res = base32_decode(decoded, 60, encoded, 96);
4413 test_eq(res, 0);
4414 test_memeq(plain, decoded, 60);
4415 /* Encode, uppercase, and decode a random string. */
4416 base32_encode(encoded, 96 + 1, plain, 60);
4417 tor_strupper(encoded);
4418 res = base32_decode(decoded, 60, encoded, 96);
4419 test_eq(res, 0);
4420 test_memeq(plain, decoded, 60);
4421 /* Change encoded string and decode. */
4422 if (encoded[0] == 'A' || encoded[0] == 'a')
4423 encoded[0] = 'B';
4424 else
4425 encoded[0] = 'A';
4426 res = base32_decode(decoded, 60, encoded, 96);
4427 test_eq(res, 0);
4428 test_memneq(plain, decoded, 60);
4429 /* Bad encodings. */
4430 encoded[0] = '!';
4431 res = base32_decode(decoded, 60, encoded, 96);
4432 test_assert(res < 0);
4434 done:
4438 /** Test encoding and parsing of v2 rendezvous service descriptors. */
4439 static void
4440 test_rend_fns_v2(void)
4442 rend_service_descriptor_t *generated = NULL, *parsed = NULL;
4443 char service_id[DIGEST_LEN];
4444 char service_id_base32[REND_SERVICE_ID_LEN_BASE32+1];
4445 const char *next_desc;
4446 smartlist_t *descs = smartlist_create();
4447 char computed_desc_id[DIGEST_LEN];
4448 char parsed_desc_id[DIGEST_LEN];
4449 crypto_pk_env_t *pk1 = NULL, *pk2 = NULL;
4450 time_t now;
4451 char *intro_points_encrypted = NULL;
4452 size_t intro_points_size;
4453 size_t encoded_size;
4454 int i;
4455 pk1 = pk_generate(0);
4456 pk2 = pk_generate(1);
4457 generated = tor_malloc_zero(sizeof(rend_service_descriptor_t));
4458 generated->pk = crypto_pk_dup_key(pk1);
4459 crypto_pk_get_digest(generated->pk, service_id);
4460 base32_encode(service_id_base32, REND_SERVICE_ID_LEN_BASE32+1,
4461 service_id, REND_SERVICE_ID_LEN);
4462 now = time(NULL);
4463 generated->timestamp = now;
4464 generated->version = 2;
4465 generated->protocols = 42;
4466 generated->intro_nodes = smartlist_create();
4468 for (i = 0; i < 3; i++) {
4469 rend_intro_point_t *intro = tor_malloc_zero(sizeof(rend_intro_point_t));
4470 crypto_pk_env_t *okey = pk_generate(2 + i);
4471 intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
4472 intro->extend_info->onion_key = okey;
4473 crypto_pk_get_digest(intro->extend_info->onion_key,
4474 intro->extend_info->identity_digest);
4475 //crypto_rand(info->identity_digest, DIGEST_LEN); /* Would this work? */
4476 intro->extend_info->nickname[0] = '$';
4477 base16_encode(intro->extend_info->nickname + 1,
4478 sizeof(intro->extend_info->nickname) - 1,
4479 intro->extend_info->identity_digest, DIGEST_LEN);
4480 /* Does not cover all IP addresses. */
4481 tor_addr_from_ipv4h(&intro->extend_info->addr, crypto_rand_int(65536));
4482 intro->extend_info->port = crypto_rand_int(65536);
4483 intro->intro_key = crypto_pk_dup_key(pk2);
4484 smartlist_add(generated->intro_nodes, intro);
4486 test_assert(rend_encode_v2_descriptors(descs, generated, now, 0,
4487 REND_NO_AUTH, NULL, NULL) > 0);
4488 test_assert(rend_compute_v2_desc_id(computed_desc_id, service_id_base32,
4489 NULL, now, 0) == 0);
4490 test_memeq(((rend_encoded_v2_service_descriptor_t *)
4491 smartlist_get(descs, 0))->desc_id, computed_desc_id, DIGEST_LEN);
4492 test_assert(rend_parse_v2_service_descriptor(&parsed, parsed_desc_id,
4493 &intro_points_encrypted,
4494 &intro_points_size,
4495 &encoded_size,
4496 &next_desc,
4497 ((rend_encoded_v2_service_descriptor_t *)
4498 smartlist_get(descs, 0))->desc_str) == 0);
4499 test_assert(parsed);
4500 test_memeq(((rend_encoded_v2_service_descriptor_t *)
4501 smartlist_get(descs, 0))->desc_id, parsed_desc_id, DIGEST_LEN);
4502 test_eq(rend_parse_introduction_points(parsed, intro_points_encrypted,
4503 intro_points_size), 3);
4504 test_assert(!crypto_pk_cmp_keys(generated->pk, parsed->pk));
4505 test_eq(parsed->timestamp, now);
4506 test_eq(parsed->version, 2);
4507 test_eq(parsed->protocols, 42);
4508 test_eq(smartlist_len(parsed->intro_nodes), 3);
4509 for (i = 0; i < smartlist_len(parsed->intro_nodes); i++) {
4510 rend_intro_point_t *par_intro = smartlist_get(parsed->intro_nodes, i),
4511 *gen_intro = smartlist_get(generated->intro_nodes, i);
4512 extend_info_t *par_info = par_intro->extend_info;
4513 extend_info_t *gen_info = gen_intro->extend_info;
4514 test_assert(!crypto_pk_cmp_keys(gen_info->onion_key, par_info->onion_key));
4515 test_memeq(gen_info->identity_digest, par_info->identity_digest,
4516 DIGEST_LEN);
4517 test_streq(gen_info->nickname, par_info->nickname);
4518 test_assert(tor_addr_eq(&gen_info->addr, &par_info->addr));
4519 test_eq(gen_info->port, par_info->port);
4522 done:
4523 if (descs) {
4524 for (i = 0; i < smartlist_len(descs); i++)
4525 rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
4526 smartlist_free(descs);
4528 if (parsed)
4529 rend_service_descriptor_free(parsed);
4530 if (generated)
4531 rend_service_descriptor_free(generated);
4532 if (pk1)
4533 crypto_free_pk_env(pk1);
4534 if (pk2)
4535 crypto_free_pk_env(pk2);
4536 tor_free(intro_points_encrypted);
4539 /** Run unit tests for GeoIP code. */
4540 static void
4541 test_geoip(void)
4543 int i, j;
4544 time_t now = time(NULL);
4545 char *s = NULL;
4547 /* Populate the DB a bit. Add these in order, since we can't do the final
4548 * 'sort' step. These aren't very good IP addresses, but they're perfectly
4549 * fine uint32_t values. */
4550 test_eq(0, geoip_parse_entry("10,50,AB"));
4551 test_eq(0, geoip_parse_entry("52,90,XY"));
4552 test_eq(0, geoip_parse_entry("95,100,AB"));
4553 test_eq(0, geoip_parse_entry("\"105\",\"140\",\"ZZ\""));
4554 test_eq(0, geoip_parse_entry("\"150\",\"190\",\"XY\""));
4555 test_eq(0, geoip_parse_entry("\"200\",\"250\",\"AB\""));
4557 /* We should have 3 countries: ab, xy, zz. */
4558 test_eq(3, geoip_get_n_countries());
4559 /* Make sure that country ID actually works. */
4560 #define NAMEFOR(x) geoip_get_country_name(geoip_get_country_by_ip(x))
4561 test_streq("ab", NAMEFOR(32));
4562 test_streq("??", NAMEFOR(5));
4563 test_streq("??", NAMEFOR(51));
4564 test_streq("xy", NAMEFOR(150));
4565 test_streq("xy", NAMEFOR(190));
4566 test_streq("??", NAMEFOR(2000));
4567 #undef NAMEFOR
4569 get_options()->BridgeRelay = 1;
4570 get_options()->BridgeRecordUsageByCountry = 1;
4571 /* Put 9 observations in AB... */
4572 for (i=32; i < 40; ++i)
4573 geoip_note_client_seen(GEOIP_CLIENT_CONNECT, i, now);
4574 geoip_note_client_seen(GEOIP_CLIENT_CONNECT, 225, now);
4575 /* and 3 observations in XY, several times. */
4576 for (j=0; j < 10; ++j)
4577 for (i=52; i < 55; ++i)
4578 geoip_note_client_seen(GEOIP_CLIENT_CONNECT, i, now-3600);
4579 /* and 17 observations in ZZ... */
4580 for (i=110; i < 127; ++i)
4581 geoip_note_client_seen(GEOIP_CLIENT_CONNECT, i, now-7200);
4582 s = geoip_get_client_history(now+5*24*60*60, GEOIP_CLIENT_CONNECT);
4583 test_assert(s);
4584 test_streq("zz=24,ab=16,xy=8", s);
4585 tor_free(s);
4587 /* Now clear out all the zz observations. */
4588 geoip_remove_old_clients(now-6000);
4589 s = geoip_get_client_history(now+5*24*60*60, GEOIP_CLIENT_CONNECT);
4590 test_assert(s);
4591 test_streq("ab=16,xy=8", s);
4593 done:
4594 tor_free(s);
4597 /** For test_array. Declare an CLI-invocable off-by-default function in the
4598 * unit tests, with function name and user-visible name <b>x</b>*/
4599 #define DISABLED(x) { #x, x, 0, 0, 0 }
4600 /** For test_array. Declare an CLI-invocable unit test function, with function
4601 * name test_<b>x</b>(), and user-visible name <b>x</b> */
4602 #define ENT(x) { #x, test_ ## x, 0, 0, 1 }
4603 /** For test_array. Declare an CLI-invocable unit test function, with function
4604 * name test_<b>x</b>_<b>y</b>(), and user-visible name
4605 * <b>x</b>/<b>y</b>. This function will be treated as a subentry of <b>x</b>,
4606 * so that invoking <b>x</b> from the CLI invokes this test too. */
4607 #define SUBENT(x,y) { #x "/" #y, test_ ## x ## _ ## y, 1, 0, 1 }
4609 /** An array of functions and information for all the unit tests we can run. */
4610 static struct {
4611 const char *test_name; /**< How does the user refer to this test from the
4612 * command line? */
4613 void (*test_fn)(void); /**< What function is called to run this test? */
4614 int is_subent; /**< Is this a subentry of a bigger set of related tests? */
4615 int selected; /**< Are we planning to run this one? */
4616 int is_default; /**< If the user doesn't say what tests they want, do they
4617 * get this function by default? */
4618 } test_array[] = {
4619 ENT(buffers),
4620 ENT(crypto),
4621 SUBENT(crypto, rng),
4622 SUBENT(crypto, aes),
4623 SUBENT(crypto, sha),
4624 SUBENT(crypto, pk),
4625 SUBENT(crypto, dh),
4626 SUBENT(crypto, s2k),
4627 SUBENT(crypto, aes_iv),
4628 SUBENT(crypto, base32_decode),
4629 ENT(util),
4630 SUBENT(util, ip6_helpers),
4631 SUBENT(util, gzip),
4632 SUBENT(util, datadir),
4633 SUBENT(util, smartlist_basic),
4634 SUBENT(util, smartlist_strings),
4635 SUBENT(util, smartlist_overlap),
4636 SUBENT(util, smartlist_digests),
4637 SUBENT(util, smartlist_join),
4638 SUBENT(util, bitarray),
4639 SUBENT(util, digestset),
4640 SUBENT(util, mempool),
4641 SUBENT(util, memarea),
4642 SUBENT(util, strmap),
4643 SUBENT(util, control_formats),
4644 SUBENT(util, pqueue),
4645 SUBENT(util, mmap),
4646 SUBENT(util, threads),
4647 SUBENT(util, order_functions),
4648 ENT(onion_handshake),
4649 ENT(dir_format),
4650 ENT(dirutil),
4651 ENT(v3_networkstatus),
4652 ENT(policies),
4653 ENT(rend_fns),
4654 SUBENT(rend_fns, v2),
4655 ENT(geoip),
4657 DISABLED(bench_aes),
4658 DISABLED(bench_dmap),
4659 { NULL, NULL, 0, 0, 0 },
4662 static void syntax(void) ATTR_NORETURN;
4664 /** Print a syntax usage message, and exit.*/
4665 static void
4666 syntax(void)
4668 int i;
4669 printf("Syntax:\n"
4670 " test [-v|--verbose] [--warn|--notice|--info|--debug]\n"
4671 " [testname...]\n"
4672 "Recognized tests are:\n");
4673 for (i = 0; test_array[i].test_name; ++i) {
4674 printf(" %s\n", test_array[i].test_name);
4677 exit(0);
4680 /** Main entry point for unit test code: parse the command line, and run
4681 * some unit tests. */
4683 main(int c, char**v)
4685 or_options_t *options;
4686 char *errmsg = NULL;
4687 int i;
4688 int verbose = 0, any_selected = 0;
4689 int loglevel = LOG_ERR;
4691 #ifdef USE_DMALLOC
4693 int r = CRYPTO_set_mem_ex_functions(_tor_malloc, _tor_realloc, _tor_free);
4694 tor_assert(r);
4696 #endif
4698 update_approx_time(time(NULL));
4699 options = options_new();
4700 tor_threads_init();
4701 init_logging();
4703 for (i = 1; i < c; ++i) {
4704 if (!strcmp(v[i], "-v") || !strcmp(v[i], "--verbose"))
4705 verbose++;
4706 else if (!strcmp(v[i], "--warn"))
4707 loglevel = LOG_WARN;
4708 else if (!strcmp(v[i], "--notice"))
4709 loglevel = LOG_NOTICE;
4710 else if (!strcmp(v[i], "--info"))
4711 loglevel = LOG_INFO;
4712 else if (!strcmp(v[i], "--debug"))
4713 loglevel = LOG_DEBUG;
4714 else if (!strcmp(v[i], "--help") || !strcmp(v[i], "-h") || v[i][0] == '-')
4715 syntax();
4716 else {
4717 int j, found=0;
4718 for (j = 0; test_array[j].test_name; ++j) {
4719 if (!strcmp(v[i], test_array[j].test_name) ||
4720 (test_array[j].is_subent &&
4721 !strcmpstart(test_array[j].test_name, v[i]) &&
4722 test_array[j].test_name[strlen(v[i])] == '/') ||
4723 (v[i][0] == '=' && !strcmp(v[i]+1, test_array[j].test_name))) {
4724 test_array[j].selected = 1;
4725 any_selected = 1;
4726 found = 1;
4729 if (!found) {
4730 printf("Unknown test: %s\n", v[i]);
4731 syntax();
4736 if (!any_selected) {
4737 for (i = 0; test_array[i].test_name; ++i) {
4738 test_array[i].selected = test_array[i].is_default;
4743 log_severity_list_t s;
4744 memset(&s, 0, sizeof(s));
4745 set_log_severity_config(loglevel, LOG_ERR, &s);
4746 add_stream_log(&s, "", fileno(stdout));
4749 options->command = CMD_RUN_UNITTESTS;
4750 crypto_global_init(0);
4751 rep_hist_init();
4752 network_init();
4753 setup_directory();
4754 options_init(options);
4755 options->DataDirectory = tor_strdup(temp_dir);
4756 if (set_options(options, &errmsg) < 0) {
4757 printf("Failed to set initial options: %s\n", errmsg);
4758 tor_free(errmsg);
4759 return 1;
4762 crypto_seed_rng(1);
4764 atexit(remove_directory);
4766 printf("Running Tor unit tests on %s\n", get_uname());
4768 for (i = 0; test_array[i].test_name; ++i) {
4769 if (!test_array[i].selected)
4770 continue;
4771 if (!test_array[i].is_subent) {
4772 printf("\n============================== %s\n",test_array[i].test_name);
4773 } else if (test_array[i].is_subent && verbose) {
4774 printf("\n%s", test_array[i].test_name);
4776 test_array[i].test_fn();
4778 puts("");
4780 free_pregenerated_keys();
4781 #ifdef USE_DMALLOC
4782 tor_free_all(0);
4783 dmalloc_log_unfreed();
4784 #endif
4786 if (have_failed)
4787 return 1;
4788 else
4789 return 0;