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