make it build, too
[tor.git] / src / or / test.c
blobbb4ba09f26d6248041cc1e8449782cc6081b4e5e
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"
17 #include <stdio.h>
18 #ifdef HAVE_FCNTL_H
19 #include <fcntl.h>
20 #endif
22 #ifdef MS_WINDOWS
23 /* For mkdir() */
24 #include <direct.h>
25 #else
26 #include <dirent.h>
27 #endif
29 /* These macros pull in declarations for some functions and structures that
30 * are typically file-private. */
31 #define BUFFERS_PRIVATE
32 #define CONFIG_PRIVATE
33 #define CONTROL_PRIVATE
34 #define CRYPTO_PRIVATE
35 #define DIRSERV_PRIVATE
36 #define DIRVOTE_PRIVATE
37 #define GEOIP_PRIVATE
38 #define MEMPOOL_PRIVATE
39 #define ROUTER_PRIVATE
41 #include "or.h"
42 #include "test.h"
43 #include "torgzip.h"
44 #include "mempool.h"
46 int have_failed = 0;
48 static char temp_dir[256];
50 static void
51 setup_directory(void)
53 static int is_setup = 0;
54 int r;
55 if (is_setup) return;
57 #ifdef MS_WINDOWS
58 // XXXX
59 tor_snprintf(temp_dir, sizeof(temp_dir),
60 "c:\\windows\\temp\\tor_test_%d", (int)getpid());
61 r = mkdir(temp_dir);
62 #else
63 tor_snprintf(temp_dir, sizeof(temp_dir), "/tmp/tor_test_%d", (int) getpid());
64 r = mkdir(temp_dir, 0700);
65 #endif
66 if (r) {
67 fprintf(stderr, "Can't create directory %s:", temp_dir);
68 perror("");
69 exit(1);
71 is_setup = 1;
74 static const char *
75 get_fname(const char *name)
77 static char buf[1024];
78 setup_directory();
79 tor_snprintf(buf,sizeof(buf),"%s/%s",temp_dir,name);
80 return buf;
83 static void
84 remove_directory(void)
86 smartlist_t *elements = tor_listdir(temp_dir);
87 if (elements) {
88 SMARTLIST_FOREACH(elements, const char *, cp,
90 size_t len = strlen(cp)+strlen(temp_dir)+16;
91 char *tmp = tor_malloc(len);
92 tor_snprintf(tmp, len, "%s"PATH_SEPARATOR"%s", temp_dir, cp);
93 unlink(tmp);
94 tor_free(tmp);
95 });
96 SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
97 smartlist_free(elements);
99 rmdir(temp_dir);
102 static crypto_pk_env_t *
103 pk_generate(int idx)
105 static crypto_pk_env_t *pregen[5] = {NULL, NULL, NULL, NULL, NULL};
106 tor_assert(idx < (int)(sizeof(pregen)/sizeof(pregen[0])));
107 if (! pregen[idx]) {
108 pregen[idx] = crypto_new_pk_env();
109 tor_assert(!crypto_pk_generate_key(pregen[idx]));
111 return crypto_pk_dup_key(pregen[idx]);
114 static void
115 test_buffers(void)
117 char str[256];
118 char str2[256];
120 buf_t *buf, *buf2;
121 const char *cp;
123 int j;
124 size_t r;
126 /****
127 * buf_new
128 ****/
129 if (!(buf = buf_new()))
130 test_fail();
132 //test_eq(buf_capacity(buf), 4096);
133 test_eq(buf_datalen(buf), 0);
135 /****
136 * General pointer frobbing
138 for (j=0;j<256;++j) {
139 str[j] = (char)j;
141 write_to_buf(str, 256, buf);
142 write_to_buf(str, 256, buf);
143 test_eq(buf_datalen(buf), 512);
144 fetch_from_buf(str2, 200, buf);
145 test_memeq(str, str2, 200);
146 test_eq(buf_datalen(buf), 312);
147 memset(str2, 0, sizeof(str2));
149 fetch_from_buf(str2, 256, buf);
150 test_memeq(str+200, str2, 56);
151 test_memeq(str, str2+56, 200);
152 test_eq(buf_datalen(buf), 56);
153 memset(str2, 0, sizeof(str2));
154 /* Okay, now we should be 512 bytes into the 4096-byte buffer. If we add
155 * another 3584 bytes, we hit the end. */
156 for (j=0;j<15;++j) {
157 write_to_buf(str, 256, buf);
159 assert_buf_ok(buf);
160 test_eq(buf_datalen(buf), 3896);
161 fetch_from_buf(str2, 56, buf);
162 test_eq(buf_datalen(buf), 3840);
163 test_memeq(str+200, str2, 56);
164 for (j=0;j<15;++j) {
165 memset(str2, 0, sizeof(str2));
166 fetch_from_buf(str2, 256, buf);
167 test_memeq(str, str2, 256);
169 test_eq(buf_datalen(buf), 0);
170 buf_free(buf);
172 /* Okay, now make sure growing can work. */
173 buf = buf_new_with_capacity(16);
174 //test_eq(buf_capacity(buf), 16);
175 write_to_buf(str+1, 255, buf);
176 //test_eq(buf_capacity(buf), 256);
177 fetch_from_buf(str2, 254, buf);
178 test_memeq(str+1, str2, 254);
179 //test_eq(buf_capacity(buf), 256);
180 assert_buf_ok(buf);
181 write_to_buf(str, 32, buf);
182 //test_eq(buf_capacity(buf), 256);
183 assert_buf_ok(buf);
184 write_to_buf(str, 256, buf);
185 assert_buf_ok(buf);
186 //test_eq(buf_capacity(buf), 512);
187 test_eq(buf_datalen(buf), 33+256);
188 fetch_from_buf(str2, 33, buf);
189 test_eq(*str2, str[255]);
191 test_memeq(str2+1, str, 32);
192 //test_eq(buf_capacity(buf), 512);
193 test_eq(buf_datalen(buf), 256);
194 fetch_from_buf(str2, 256, buf);
195 test_memeq(str, str2, 256);
197 /* now try shrinking: case 1. */
198 buf_free(buf);
199 buf = buf_new_with_capacity(33668);
200 for (j=0;j<67;++j) {
201 write_to_buf(str,255, buf);
203 //test_eq(buf_capacity(buf), 33668);
204 test_eq(buf_datalen(buf), 17085);
205 for (j=0; j < 40; ++j) {
206 fetch_from_buf(str2, 255,buf);
207 test_memeq(str2, str, 255);
210 /* now try shrinking: case 2. */
211 buf_free(buf);
212 buf = buf_new_with_capacity(33668);
213 for (j=0;j<67;++j) {
214 write_to_buf(str,255, buf);
216 for (j=0; j < 20; ++j) {
217 fetch_from_buf(str2, 255,buf);
218 test_memeq(str2, str, 255);
220 for (j=0;j<80;++j) {
221 write_to_buf(str,255, buf);
223 //test_eq(buf_capacity(buf),33668);
224 for (j=0; j < 120; ++j) {
225 fetch_from_buf(str2, 255,buf);
226 test_memeq(str2, str, 255);
229 /* Move from buf to buf. */
230 buf_free(buf);
231 buf = buf_new_with_capacity(4096);
232 buf2 = buf_new_with_capacity(4096);
233 for (j=0;j<100;++j)
234 write_to_buf(str, 255, buf);
235 test_eq(buf_datalen(buf), 25500);
236 for (j=0;j<100;++j) {
237 r = 10;
238 move_buf_to_buf(buf2, buf, &r);
239 test_eq(r, 0);
241 test_eq(buf_datalen(buf), 24500);
242 test_eq(buf_datalen(buf2), 1000);
243 for (j=0;j<3;++j) {
244 fetch_from_buf(str2, 255, buf2);
245 test_memeq(str2, str, 255);
247 r = 8192; /*big move*/
248 move_buf_to_buf(buf2, buf, &r);
249 test_eq(r, 0);
250 r = 30000; /* incomplete move */
251 move_buf_to_buf(buf2, buf, &r);
252 test_eq(r, 13692);
253 for (j=0;j<97;++j) {
254 fetch_from_buf(str2, 255, buf2);
255 test_memeq(str2, str, 255);
257 buf_free(buf);
258 buf_free(buf2);
260 buf = buf_new_with_capacity(5);
261 cp = "Testing. This is a moderately long Testing string.";
262 for (j = 0; cp[j]; j++)
263 write_to_buf(cp+j, 1, buf);
264 test_eq(0, buf_find_string_offset(buf, "Testing", 7));
265 test_eq(1, buf_find_string_offset(buf, "esting", 6));
266 test_eq(1, buf_find_string_offset(buf, "est", 3));
267 test_eq(39, buf_find_string_offset(buf, "ing str", 7));
268 test_eq(35, buf_find_string_offset(buf, "Testing str", 11));
269 test_eq(32, buf_find_string_offset(buf, "ng ", 3));
270 test_eq(43, buf_find_string_offset(buf, "string.", 7));
271 test_eq(-1, buf_find_string_offset(buf, "shrdlu", 6));
272 test_eq(-1, buf_find_string_offset(buf, "Testing thing", 13));
273 test_eq(-1, buf_find_string_offset(buf, "ngx", 3));
274 buf_free(buf);
276 #if 0
278 int s;
279 int eof;
280 int i;
281 buf_t *buf2;
282 /****
283 * read_to_buf
284 ****/
285 s = open(get_fname("data"), O_WRONLY|O_CREAT|O_TRUNC, 0600);
286 write(s, str, 256);
287 close(s);
289 s = open(get_fname("data"), O_RDONLY, 0);
290 eof = 0;
291 errno = 0; /* XXXX */
292 i = read_to_buf(s, 10, buf, &eof);
293 printf("%s\n", strerror(errno));
294 test_eq(i, 10);
295 test_eq(eof, 0);
296 //test_eq(buf_capacity(buf), 4096);
297 test_eq(buf_datalen(buf), 10);
299 test_memeq(str, (char*)_buf_peek_raw_buffer(buf), 10);
301 /* Test reading 0 bytes. */
302 i = read_to_buf(s, 0, buf, &eof);
303 //test_eq(buf_capacity(buf), 512*1024);
304 test_eq(buf_datalen(buf), 10);
305 test_eq(eof, 0);
306 test_eq(i, 0);
308 /* Now test when buffer is filled exactly. */
309 buf2 = buf_new_with_capacity(6);
310 i = read_to_buf(s, 6, buf2, &eof);
311 //test_eq(buf_capacity(buf2), 6);
312 test_eq(buf_datalen(buf2), 6);
313 test_eq(eof, 0);
314 test_eq(i, 6);
315 test_memeq(str+10, (char*)_buf_peek_raw_buffer(buf2), 6);
316 buf_free(buf2);
318 /* Now test when buffer is filled with more data to read. */
319 buf2 = buf_new_with_capacity(32);
320 i = read_to_buf(s, 128, buf2, &eof);
321 //test_eq(buf_capacity(buf2), 128);
322 test_eq(buf_datalen(buf2), 32);
323 test_eq(eof, 0);
324 test_eq(i, 32);
325 buf_free(buf2);
327 /* Now read to eof. */
328 test_assert(buf_capacity(buf) > 256);
329 i = read_to_buf(s, 1024, buf, &eof);
330 test_eq(i, (256-32-10-6));
331 test_eq(buf_capacity(buf), MAX_BUF_SIZE);
332 test_eq(buf_datalen(buf), 256-6-32);
333 test_memeq(str, (char*)_buf_peek_raw_buffer(buf), 10); /* XXX Check rest. */
334 test_eq(eof, 0);
336 i = read_to_buf(s, 1024, buf, &eof);
337 test_eq(i, 0);
338 test_eq(buf_capacity(buf), MAX_BUF_SIZE);
339 test_eq(buf_datalen(buf), 256-6-32);
340 test_eq(eof, 1);
342 #endif
345 static void
346 test_crypto_dh(void)
348 crypto_dh_env_t *dh1, *dh2;
349 char p1[DH_BYTES];
350 char p2[DH_BYTES];
351 char s1[DH_BYTES];
352 char s2[DH_BYTES];
353 int s1len, s2len;
355 dh1 = crypto_dh_new();
356 dh2 = crypto_dh_new();
357 test_eq(crypto_dh_get_bytes(dh1), DH_BYTES);
358 test_eq(crypto_dh_get_bytes(dh2), DH_BYTES);
360 memset(p1, 0, DH_BYTES);
361 memset(p2, 0, DH_BYTES);
362 test_memeq(p1, p2, DH_BYTES);
363 test_assert(! crypto_dh_get_public(dh1, p1, DH_BYTES));
364 test_memneq(p1, p2, DH_BYTES);
365 test_assert(! crypto_dh_get_public(dh2, p2, DH_BYTES));
366 test_memneq(p1, p2, DH_BYTES);
368 memset(s1, 0, DH_BYTES);
369 memset(s2, 0xFF, DH_BYTES);
370 s1len = crypto_dh_compute_secret(dh1, p2, DH_BYTES, s1, 50);
371 s2len = crypto_dh_compute_secret(dh2, p1, DH_BYTES, s2, 50);
372 test_assert(s1len > 0);
373 test_eq(s1len, s2len);
374 test_memeq(s1, s2, s1len);
376 crypto_dh_free(dh1);
377 crypto_dh_free(dh2);
380 static void
381 test_crypto(void)
383 crypto_cipher_env_t *env1, *env2;
384 crypto_pk_env_t *pk1, *pk2;
385 char *data1, *data2, *data3, *cp;
386 int i, j, p, len, idx;
387 size_t size;
389 data1 = tor_malloc(1024);
390 data2 = tor_malloc(1024);
391 data3 = tor_malloc(1024);
392 test_assert(data1 && data2 && data3);
394 /* Try out RNG. */
395 test_assert(! crypto_seed_rng(0));
396 crypto_rand(data1, 100);
397 crypto_rand(data2, 100);
398 test_memneq(data1,data2,100);
400 /* Now, test encryption and decryption with stream cipher. */
401 data1[0]='\0';
402 for (i = 1023; i>0; i -= 35)
403 strncat(data1, "Now is the time for all good onions", i);
405 memset(data2, 0, 1024);
406 memset(data3, 0, 1024);
407 env1 = crypto_new_cipher_env();
408 test_neq(env1, 0);
409 env2 = crypto_new_cipher_env();
410 test_neq(env2, 0);
411 j = crypto_cipher_generate_key(env1);
412 crypto_cipher_set_key(env2, crypto_cipher_get_key(env1));
413 crypto_cipher_encrypt_init_cipher(env1);
414 crypto_cipher_decrypt_init_cipher(env2);
416 /* Try encrypting 512 chars. */
417 crypto_cipher_encrypt(env1, data2, data1, 512);
418 crypto_cipher_decrypt(env2, data3, data2, 512);
419 test_memeq(data1, data3, 512);
420 test_memneq(data1, data2, 512);
422 /* Now encrypt 1 at a time, and get 1 at a time. */
423 for (j = 512; j < 560; ++j) {
424 crypto_cipher_encrypt(env1, data2+j, data1+j, 1);
426 for (j = 512; j < 560; ++j) {
427 crypto_cipher_decrypt(env2, data3+j, data2+j, 1);
429 test_memeq(data1, data3, 560);
430 /* Now encrypt 3 at a time, and get 5 at a time. */
431 for (j = 560; j < 1024-5; j += 3) {
432 crypto_cipher_encrypt(env1, data2+j, data1+j, 3);
434 for (j = 560; j < 1024-5; j += 5) {
435 crypto_cipher_decrypt(env2, data3+j, data2+j, 5);
437 test_memeq(data1, data3, 1024-5);
438 /* Now make sure that when we encrypt with different chunk sizes, we get
439 the same results. */
440 crypto_free_cipher_env(env2);
442 memset(data3, 0, 1024);
443 env2 = crypto_new_cipher_env();
444 test_neq(env2, 0);
445 crypto_cipher_set_key(env2, crypto_cipher_get_key(env1));
446 crypto_cipher_encrypt_init_cipher(env2);
447 for (j = 0; j < 1024-16; j += 17) {
448 crypto_cipher_encrypt(env2, data3+j, data1+j, 17);
450 for (j= 0; j < 1024-16; ++j) {
451 if (data2[j] != data3[j]) {
452 printf("%d: %d\t%d\n", j, (int) data2[j], (int) data3[j]);
455 test_memeq(data2, data3, 1024-16);
456 crypto_free_cipher_env(env1);
457 crypto_free_cipher_env(env2);
459 /* Test vectors for stream ciphers. */
460 /* XXXX Look up some test vectors for the ciphers and make sure we match. */
462 /* Test SHA-1 with a test vector from the specification. */
463 i = crypto_digest(data1, "abc", 3);
464 test_memeq(data1,
465 "\xA9\x99\x3E\x36\x47\x06\x81\x6A\xBA\x3E\x25\x71\x78"
466 "\x50\xC2\x6C\x9C\xD0\xD8\x9D", 20);
468 /* Test HMAC-SHA-1 with test cases from RFC2202. */
470 char key[80];
471 char digest[20];
472 char data[50];
474 /* Case 1. */
475 memset(key, 0x0b, 20);
476 crypto_hmac_sha1(digest, key, 20, "Hi There", 8);
477 test_streq(hex_str(digest, 20),
478 "B617318655057264E28BC0B6FB378C8EF146BE00");
480 /* Case 2. */
481 crypto_hmac_sha1(digest, "Jefe", 4, "what do ya want for nothing?", 28);
482 test_streq(hex_str(digest, 20),
483 "EFFCDF6AE5EB2FA2D27416D5F184DF9C259A7C79");
485 /* Case 4. */
486 base16_decode(key, 25,
487 "0102030405060708090a0b0c0d0e0f10111213141516171819", 50);
488 memset(data, 0xcd, 50);
489 crypto_hmac_sha1(digest, key, 25, data, 50);
490 test_streq(hex_str(digest, 20),
491 "4C9007F4026250C6BC8414F9BF50C86C2D7235DA");
493 /* Case . */
494 memset(key, 0xaa, 80);
495 crypto_hmac_sha1(digest, key, 80,
496 "Test Using Larger Than Block-Size Key - Hash Key First",
497 54);
498 test_streq(hex_str(digest, 20),
499 "AA4AE5E15272D00E95705637CE8A3B55ED402112");
503 /* Public-key ciphers */
504 pk1 = pk_generate(0);
505 pk2 = crypto_new_pk_env();
506 test_assert(pk1 && pk2);
507 test_assert(! crypto_pk_write_public_key_to_string(pk1, &cp, &size));
508 test_assert(! crypto_pk_read_public_key_from_string(pk2, cp, size));
509 test_eq(0, crypto_pk_cmp_keys(pk1, pk2));
510 tor_free(cp);
512 test_eq(128, crypto_pk_keysize(pk1));
513 test_eq(128, crypto_pk_keysize(pk2));
515 test_eq(128, crypto_pk_public_encrypt(pk2, data1, "Hello whirled.", 15,
516 PK_PKCS1_OAEP_PADDING));
517 test_eq(128, crypto_pk_public_encrypt(pk1, data2, "Hello whirled.", 15,
518 PK_PKCS1_OAEP_PADDING));
519 /* oaep padding should make encryption not match */
520 test_memneq(data1, data2, 128);
521 test_eq(15, crypto_pk_private_decrypt(pk1, data3, data1, 128,
522 PK_PKCS1_OAEP_PADDING,1));
523 test_streq(data3, "Hello whirled.");
524 memset(data3, 0, 1024);
525 test_eq(15, crypto_pk_private_decrypt(pk1, data3, data2, 128,
526 PK_PKCS1_OAEP_PADDING,1));
527 test_streq(data3, "Hello whirled.");
528 /* Can't decrypt with public key. */
529 test_eq(-1, crypto_pk_private_decrypt(pk2, data3, data2, 128,
530 PK_PKCS1_OAEP_PADDING,1));
531 /* Try again with bad padding */
532 memcpy(data2+1, "XYZZY", 5); /* This has fails ~ once-in-2^40 */
533 test_eq(-1, crypto_pk_private_decrypt(pk1, data3, data2, 128,
534 PK_PKCS1_OAEP_PADDING,1));
536 /* File operations: save and load private key */
537 test_assert(! crypto_pk_write_private_key_to_filename(pk1,
538 get_fname("pkey1")));
540 test_assert(! crypto_pk_read_private_key_from_filename(pk2,
541 get_fname("pkey1")));
542 test_eq(15, crypto_pk_private_decrypt(pk2, data3, data1, 128,
543 PK_PKCS1_OAEP_PADDING,1));
545 /* Now try signing. */
546 strlcpy(data1, "Ossifrage", 1024);
547 test_eq(128, crypto_pk_private_sign(pk1, data2, data1, 10));
548 test_eq(10, crypto_pk_public_checksig(pk1, data3, data2, 128));
549 test_streq(data3, "Ossifrage");
550 /* Try signing digests. */
551 test_eq(128, crypto_pk_private_sign_digest(pk1, data2, data1, 10));
552 test_eq(20, crypto_pk_public_checksig(pk1, data3, data2, 128));
553 test_eq(0, crypto_pk_public_checksig_digest(pk1, data1, 10, data2, 128));
554 test_eq(-1, crypto_pk_public_checksig_digest(pk1, data1, 11, data2, 128));
555 /*XXXX test failed signing*/
557 /* Try encoding */
558 crypto_free_pk_env(pk2);
559 pk2 = NULL;
560 i = crypto_pk_asn1_encode(pk1, data1, 1024);
561 test_assert(i>0);
562 pk2 = crypto_pk_asn1_decode(data1, i);
563 test_assert(crypto_pk_cmp_keys(pk1,pk2) == 0);
565 /* Try with hybrid encryption wrappers. */
566 crypto_rand(data1, 1024);
567 for (i = 0; i < 3; ++i) {
568 for (j = 85; j < 140; ++j) {
569 memset(data2,0,1024);
570 memset(data3,0,1024);
571 if (i == 0 && j < 129)
572 continue;
573 p = (i==0)?PK_NO_PADDING:
574 (i==1)?PK_PKCS1_PADDING:PK_PKCS1_OAEP_PADDING;
575 len = crypto_pk_public_hybrid_encrypt(pk1,data2,data1,j,p,0);
576 test_assert(len>=0);
577 len = crypto_pk_private_hybrid_decrypt(pk1,data3,data2,len,p,1);
578 test_eq(len,j);
579 test_memeq(data1,data3,j);
582 crypto_free_pk_env(pk1);
583 crypto_free_pk_env(pk2);
585 /* Base64 tests */
586 memset(data1, 6, 1024);
587 for (idx = 0; idx < 10; ++idx) {
588 i = base64_encode(data2, 1024, data1, idx);
589 j = base64_decode(data3, 1024, data2, i);
590 test_eq(j,idx);
591 test_memeq(data3, data1, idx);
594 strlcpy(data1, "Test string that contains 35 chars.", 1024);
595 strlcat(data1, " 2nd string that contains 35 chars.", 1024);
597 i = base64_encode(data2, 1024, data1, 71);
598 j = base64_decode(data3, 1024, data2, i);
599 test_eq(j, 71);
600 test_streq(data3, data1);
601 test_assert(data2[i] == '\0');
603 crypto_rand(data1, DIGEST_LEN);
604 memset(data2, 100, 1024);
605 digest_to_base64(data2, data1);
606 test_eq(BASE64_DIGEST_LEN, strlen(data2));
607 test_eq(100, data2[BASE64_DIGEST_LEN+2]);
608 memset(data3, 99, 1024);
609 test_eq(digest_from_base64(data3, data2), 0);
610 test_memeq(data1, data3, DIGEST_LEN);
611 test_eq(99, data3[DIGEST_LEN+1]);
613 /* Base32 tests */
614 strlcpy(data1, "5chrs", 1024);
615 /* bit pattern is: [35 63 68 72 73] ->
616 * [00110101 01100011 01101000 01110010 01110011]
617 * By 5s: [00110 10101 10001 10110 10000 11100 10011 10011]
619 base32_encode(data2, 9, data1, 5);
620 test_streq(data2, "gvrwq4tt");
622 strlcpy(data1, "\xFF\xF5\x6D\x44\xAE\x0D\x5C\xC9\x62\xC4", 1024);
623 base32_encode(data2, 30, data1, 10);
624 test_streq(data2, "772w2rfobvomsywe");
626 /* Base16 tests */
627 strlcpy(data1, "6chrs\xff", 1024);
628 base16_encode(data2, 13, data1, 6);
629 test_streq(data2, "3663687273FF");
631 strlcpy(data1, "f0d678affc000100", 1024);
632 i = base16_decode(data2, 8, data1, 16);
633 test_eq(i,0);
634 test_memeq(data2, "\xf0\xd6\x78\xaf\xfc\x00\x01\x00",8);
636 /* now try some failing base16 decodes */
637 test_eq(-1, base16_decode(data2, 8, data1, 15)); /* odd input len */
638 test_eq(-1, base16_decode(data2, 7, data1, 16)); /* dest too short */
639 strlcpy(data1, "f0dz!8affc000100", 1024);
640 test_eq(-1, base16_decode(data2, 8, data1, 16));
642 tor_free(data1);
643 tor_free(data2);
644 tor_free(data3);
646 /* Add spaces to fingerprint */
648 data1 = tor_strdup("ABCD1234ABCD56780000ABCD1234ABCD56780000");
649 test_eq(strlen(data1), 40);
650 data2 = tor_malloc(FINGERPRINT_LEN+1);
651 add_spaces_to_fp(data2, FINGERPRINT_LEN+1, data1);
652 test_streq(data2, "ABCD 1234 ABCD 5678 0000 ABCD 1234 ABCD 5678 0000");
653 tor_free(data1);
654 tor_free(data2);
658 static void
659 test_crypto_s2k(void)
661 char buf[29];
662 char buf2[29];
663 char *buf3;
664 int i;
666 memset(buf, 0, sizeof(buf));
667 memset(buf2, 0, sizeof(buf2));
668 buf3 = tor_malloc(65536);
669 memset(buf3, 0, 65536);
671 secret_to_key(buf+9, 20, "", 0, buf);
672 crypto_digest(buf2+9, buf3, 1024);
673 test_memeq(buf, buf2, 29);
675 memcpy(buf,"vrbacrda",8);
676 memcpy(buf2,"vrbacrda",8);
677 buf[8] = 96;
678 buf2[8] = 96;
679 secret_to_key(buf+9, 20, "12345678", 8, buf);
680 for (i = 0; i < 65536; i += 16) {
681 memcpy(buf3+i, "vrbacrda12345678", 16);
683 crypto_digest(buf2+9, buf3, 65536);
684 test_memeq(buf, buf2, 29);
685 tor_free(buf3);
688 static int
689 _compare_strs(const void **a, const void **b)
691 const char *s1 = *a, *s2 = *b;
692 return strcmp(s1, s2);
695 static int
696 _compare_without_first_ch(const void *a, const void **b)
698 const char *s1 = a, *s2 = *b;
699 return strcasecmp(s1+1, s2);
702 static void
703 test_util(void)
705 struct timeval start, end;
706 struct tm a_time;
707 char timestr[RFC1123_TIME_LEN+1];
708 char buf[1024];
709 time_t t_res;
710 int i;
711 uint32_t u32;
712 uint16_t u16;
713 char *cp, *k, *v;
714 const char *str;
716 start.tv_sec = 5;
717 start.tv_usec = 5000;
719 end.tv_sec = 5;
720 end.tv_usec = 5000;
722 test_eq(0L, tv_udiff(&start, &end));
724 end.tv_usec = 7000;
726 test_eq(2000L, tv_udiff(&start, &end));
728 end.tv_sec = 6;
730 test_eq(1002000L, tv_udiff(&start, &end));
732 end.tv_usec = 0;
734 test_eq(995000L, tv_udiff(&start, &end));
736 end.tv_sec = 4;
738 test_eq(-1005000L, tv_udiff(&start, &end));
740 end.tv_usec = 999990;
741 start.tv_sec = 1;
742 start.tv_usec = 500;
744 /* The test values here are confirmed to be correct on a platform
745 * with a working timegm. */
746 a_time.tm_year = 2003-1900;
747 a_time.tm_mon = 7;
748 a_time.tm_mday = 30;
749 a_time.tm_hour = 6;
750 a_time.tm_min = 14;
751 a_time.tm_sec = 55;
752 test_eq((time_t) 1062224095UL, tor_timegm(&a_time));
753 a_time.tm_year = 2004-1900; /* Try a leap year, after feb. */
754 test_eq((time_t) 1093846495UL, tor_timegm(&a_time));
755 a_time.tm_mon = 1; /* Try a leap year, in feb. */
756 a_time.tm_mday = 10;
757 test_eq((time_t) 1076393695UL, tor_timegm(&a_time));
759 format_rfc1123_time(timestr, 0);
760 test_streq("Thu, 01 Jan 1970 00:00:00 GMT", timestr);
761 format_rfc1123_time(timestr, (time_t)1091580502UL);
762 test_streq("Wed, 04 Aug 2004 00:48:22 GMT", timestr);
764 t_res = 0;
765 i = parse_rfc1123_time(timestr, &t_res);
766 test_eq(i,0);
767 test_eq(t_res, (time_t)1091580502UL);
768 test_eq(-1, parse_rfc1123_time("Wed, zz Aug 2004 99-99x99 GMT", &t_res));
769 tor_gettimeofday(&start);
771 /* Test tor_strstrip() */
772 strlcpy(buf, "Testing 1 2 3", sizeof(buf));
773 tor_strstrip(buf, ",!");
774 test_streq(buf, "Testing 1 2 3");
775 strlcpy(buf, "!Testing 1 2 3?", sizeof(buf));
776 tor_strstrip(buf, "!? ");
777 test_streq(buf, "Testing123");
779 /* Test parse_addr_port */
780 cp = NULL; u32 = 3; u16 = 3;
781 test_assert(!parse_addr_port(LOG_WARN, "1.2.3.4", &cp, &u32, &u16));
782 test_streq(cp, "1.2.3.4");
783 test_eq(u32, 0x01020304u);
784 test_eq(u16, 0);
785 tor_free(cp);
786 test_assert(!parse_addr_port(LOG_WARN, "4.3.2.1:99", &cp, &u32, &u16));
787 test_streq(cp, "4.3.2.1");
788 test_eq(u32, 0x04030201u);
789 test_eq(u16, 99);
790 tor_free(cp);
791 test_assert(!parse_addr_port(LOG_WARN, "nonexistent.address:4040",
792 &cp, NULL, &u16));
793 test_streq(cp, "nonexistent.address");
794 test_eq(u16, 4040);
795 tor_free(cp);
796 test_assert(!parse_addr_port(LOG_WARN, "localhost:9999", &cp, &u32, &u16));
797 test_streq(cp, "localhost");
798 test_eq(u32, 0x7f000001u);
799 test_eq(u16, 9999);
800 tor_free(cp);
801 u32 = 3;
802 test_assert(!parse_addr_port(LOG_WARN, "localhost", NULL, &u32, &u16));
803 test_eq(cp, NULL);
804 test_eq(u32, 0x7f000001u);
805 test_eq(u16, 0);
806 tor_free(cp);
807 test_eq(0, addr_mask_get_bits(0x0u));
808 test_eq(32, addr_mask_get_bits(0xFFFFFFFFu));
809 test_eq(16, addr_mask_get_bits(0xFFFF0000u));
810 test_eq(31, addr_mask_get_bits(0xFFFFFFFEu));
811 test_eq(1, addr_mask_get_bits(0x80000000u));
813 /* Test tor_parse_long. */
814 test_eq(10L, tor_parse_long("10",10,0,100,NULL,NULL));
815 test_eq(0L, tor_parse_long("10",10,50,100,NULL,NULL));
816 test_eq(-50L, tor_parse_long("-50",10,-100,100,NULL,NULL));
818 /* Test tor_parse_ulong */
819 test_eq(10UL, tor_parse_ulong("10",10,0,100,NULL,NULL));
820 test_eq(0UL, tor_parse_ulong("10",10,50,100,NULL,NULL));
822 /* Test tor_parse_uint64. */
823 test_assert(U64_LITERAL(10) == tor_parse_uint64("10 x",10,0,100, &i, &cp));
824 test_assert(i == 1);
825 test_streq(cp, " x");
826 test_assert(U64_LITERAL(12345678901) ==
827 tor_parse_uint64("12345678901",10,0,UINT64_MAX, &i, &cp));
828 test_assert(i == 1);
829 test_streq(cp, "");
830 test_assert(U64_LITERAL(0) ==
831 tor_parse_uint64("12345678901",10,500,INT32_MAX, &i, &cp));
832 test_assert(i == 0);
834 /* Test printf with uint64 */
835 tor_snprintf(buf, sizeof(buf), "x!"U64_FORMAT"!x",
836 U64_PRINTF_ARG(U64_LITERAL(12345678901)));
837 test_streq(buf, "x!12345678901!x");
839 /* Test parse_config_line_from_str */
840 strlcpy(buf, "k v\n" " key value with spaces \n" "keykey val\n"
841 "k2\n"
842 "k3 \n" "\n" " \n" "#comment\n"
843 "k4#a\n" "k5#abc\n" "k6 val #with comment\n"
844 "kseven \"a quoted 'string\"\n"
845 "k8 \"a \\x71uoted\\n\\\"str\\\\ing\\t\\001\\01\\1\\\"\"\n"
846 , sizeof(buf));
847 str = buf;
849 str = parse_config_line_from_str(str, &k, &v);
850 test_streq(k, "k");
851 test_streq(v, "v");
852 tor_free(k); tor_free(v);
853 test_assert(!strcmpstart(str, "key value with"));
855 str = parse_config_line_from_str(str, &k, &v);
856 test_streq(k, "key");
857 test_streq(v, "value with spaces");
858 tor_free(k); tor_free(v);
859 test_assert(!strcmpstart(str, "keykey"));
861 str = parse_config_line_from_str(str, &k, &v);
862 test_streq(k, "keykey");
863 test_streq(v, "val");
864 tor_free(k); tor_free(v);
865 test_assert(!strcmpstart(str, "k2\n"));
867 str = parse_config_line_from_str(str, &k, &v);
868 test_streq(k, "k2");
869 test_streq(v, "");
870 tor_free(k); tor_free(v);
871 test_assert(!strcmpstart(str, "k3 \n"));
873 str = parse_config_line_from_str(str, &k, &v);
874 test_streq(k, "k3");
875 test_streq(v, "");
876 tor_free(k); tor_free(v);
877 test_assert(!strcmpstart(str, "#comment"));
879 str = parse_config_line_from_str(str, &k, &v);
880 test_streq(k, "k4");
881 test_streq(v, "");
882 tor_free(k); tor_free(v);
883 test_assert(!strcmpstart(str, "k5#abc"));
885 str = parse_config_line_from_str(str, &k, &v);
886 test_streq(k, "k5");
887 test_streq(v, "");
888 tor_free(k); tor_free(v);
889 test_assert(!strcmpstart(str, "k6"));
891 str = parse_config_line_from_str(str, &k, &v);
892 test_streq(k, "k6");
893 test_streq(v, "val");
894 tor_free(k); tor_free(v);
895 test_assert(!strcmpstart(str, "kseven"));
897 str = parse_config_line_from_str(str, &k, &v);
898 test_streq(k, "kseven");
899 test_streq(v, "a quoted 'string");
900 tor_free(k); tor_free(v);
901 test_assert(!strcmpstart(str, "k8 "));
903 str = parse_config_line_from_str(str, &k, &v);
904 test_streq(k, "k8");
905 test_streq(v, "a quoted\n\"str\\ing\t\x01\x01\x01\"");
906 tor_free(k); tor_free(v);
907 test_streq(str, "");
909 /* Test for strcmpstart and strcmpend. */
910 test_assert(strcmpstart("abcdef", "abcdef")==0);
911 test_assert(strcmpstart("abcdef", "abc")==0);
912 test_assert(strcmpstart("abcdef", "abd")<0);
913 test_assert(strcmpstart("abcdef", "abb")>0);
914 test_assert(strcmpstart("ab", "abb")<0);
916 test_assert(strcmpend("abcdef", "abcdef")==0);
917 test_assert(strcmpend("abcdef", "def")==0);
918 test_assert(strcmpend("abcdef", "deg")<0);
919 test_assert(strcmpend("abcdef", "dee")>0);
920 test_assert(strcmpend("ab", "abb")<0);
922 test_assert(strcasecmpend("AbcDEF", "abcdef")==0);
923 test_assert(strcasecmpend("abcdef", "dEF")==0);
924 test_assert(strcasecmpend("abcDEf", "deg")<0);
925 test_assert(strcasecmpend("abcdef", "DEE")>0);
926 test_assert(strcasecmpend("ab", "abB")<0);
928 /* Test mem_is_zero */
929 memset(buf,0,128);
930 buf[128] = 'x';
931 test_assert(tor_digest_is_zero(buf));
932 test_assert(tor_mem_is_zero(buf, 10));
933 test_assert(tor_mem_is_zero(buf, 20));
934 test_assert(tor_mem_is_zero(buf, 128));
935 test_assert(!tor_mem_is_zero(buf, 129));
936 buf[60] = (char)255;
937 test_assert(!tor_mem_is_zero(buf, 128));
938 buf[0] = (char)1;
939 test_assert(!tor_mem_is_zero(buf, 10));
941 /* Test inet_ntop */
943 char tmpbuf[TOR_ADDR_BUF_LEN];
944 const char *ip = "176.192.208.224";
945 struct in_addr in;
946 tor_inet_pton(AF_INET, ip, &in);
947 tor_inet_ntop(AF_INET, &in, tmpbuf, sizeof(tmpbuf));
948 test_streq(tmpbuf, ip);
951 /* Test 'escaped' */
952 test_streq("\"\"", escaped(""));
953 test_streq("\"abcd\"", escaped("abcd"));
954 test_streq("\"\\\\\\n\\r\\t\\\"\\'\"", escaped("\\\n\r\t\"\'"));
955 test_streq("\"z\\001abc\\277d\"", escaped("z\001abc\277d"));
956 test_assert(NULL == escaped(NULL));
958 /* Test strndup and memdup */
960 const char *s = "abcdefghijklmnopqrstuvwxyz";
961 cp = tor_strndup(s, 30);
962 test_streq(cp, s); /* same string, */
963 test_neq(cp, s); /* but different pointers. */
964 tor_free(cp);
966 cp = tor_strndup(s, 5);
967 test_streq(cp, "abcde");
968 tor_free(cp);
970 s = "a\0b\0c\0d\0e\0";
971 cp = tor_memdup(s,10);
972 test_memeq(cp, s, 10); /* same ram, */
973 test_neq(cp, s); /* but different pointers. */
974 tor_free(cp);
977 /* Test str-foo functions */
978 cp = tor_strdup("abcdef");
979 test_assert(tor_strisnonupper(cp));
980 cp[3] = 'D';
981 test_assert(!tor_strisnonupper(cp));
982 tor_strupper(cp);
983 test_streq(cp, "ABCDEF");
984 test_assert(tor_strisprint(cp));
985 cp[3] = 3;
986 test_assert(!tor_strisprint(cp));
987 tor_free(cp);
989 /* Test eat_whitespace. */
991 const char *s = " \n a";
992 test_eq_ptr(eat_whitespace(s), s+4);
993 s = "abcd";
994 test_eq_ptr(eat_whitespace(s), s);
995 s = "#xyz\nab";
996 test_eq_ptr(eat_whitespace(s), s+5);
999 /* Test memmem */
1001 const char *haystack = "abcde";
1002 tor_assert(!tor_memmem(haystack, 5, "ef", 2));
1003 test_eq_ptr(tor_memmem(haystack, 5, "cd", 2), haystack + 2);
1004 test_eq_ptr(tor_memmem(haystack, 5, "cde", 3), haystack + 2);
1005 haystack = "ababcad";
1006 test_eq_ptr(tor_memmem(haystack, 7, "abc", 3), haystack + 2);
1009 /* Test wrap_string */
1011 smartlist_t *sl = smartlist_create();
1012 wrap_string(sl, "This is a test of string wrapping functionality: woot.",
1013 10, "", "");
1014 cp = smartlist_join_strings(sl, "", 0, NULL);
1015 test_streq(cp,
1016 "This is a\ntest of\nstring\nwrapping\nfunctional\nity: woot.\n");
1017 tor_free(cp);
1018 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1019 smartlist_clear(sl);
1021 wrap_string(sl, "This is a test of string wrapping functionality: woot.",
1022 16, "### ", "# ");
1023 cp = smartlist_join_strings(sl, "", 0, NULL);
1024 test_streq(cp,
1025 "### This is a\n# test of string\n# wrapping\n# functionality:\n"
1026 "# woot.\n");
1028 tor_free(cp);
1029 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1030 smartlist_free(sl);
1033 /* now make sure time works. */
1034 tor_gettimeofday(&end);
1035 /* We might've timewarped a little. */
1036 test_assert(tv_udiff(&start, &end) >= -5000);
1038 /* Test tor_log2(). */
1039 test_eq(tor_log2(64), 6);
1040 test_eq(tor_log2(65), 6);
1041 test_eq(tor_log2(63), 5);
1042 test_eq(tor_log2(1), 0);
1043 test_eq(tor_log2(2), 1);
1044 test_eq(tor_log2(3), 1);
1045 test_eq(tor_log2(4), 2);
1046 test_eq(tor_log2(5), 2);
1047 test_eq(tor_log2(U64_LITERAL(40000000000000000)), 55);
1048 test_eq(tor_log2(UINT64_MAX), 63);
1050 /* Test round_to_power_of_2 */
1051 test_eq(round_to_power_of_2(120), 128);
1052 test_eq(round_to_power_of_2(128), 128);
1053 test_eq(round_to_power_of_2(130), 128);
1054 test_eq(round_to_power_of_2(U64_LITERAL(40000000000000000)),
1055 U64_LITERAL(1)<<55);
1056 test_eq(round_to_power_of_2(0), 2);
1059 /** Helper: assert that IPv6 addresses <b>a</b> and <b>b</b> are the same. On
1060 * failure, reports an error, describing the addresses as <b>e1</b> and
1061 * <b>e2</b>, and reporting the line number as <b>line</b>. */
1062 static void
1063 _test_eq_ip6(struct in6_addr *a, struct in6_addr *b, const char *e1,
1064 const char *e2, int line)
1066 int i;
1067 int ok = 1;
1068 for (i = 0; i < 16; ++i) {
1069 if (a->s6_addr[i] != b->s6_addr[i]) {
1070 ok = 0;
1071 break;
1074 if (ok) {
1075 printf("."); fflush(stdout);
1076 } else {
1077 char buf1[128], *cp1;
1078 char buf2[128], *cp2;
1079 have_failed = 1;
1080 cp1 = buf1; cp2 = buf2;
1081 for (i=0; i<16; ++i) {
1082 tor_snprintf(cp1, sizeof(buf1)-(cp1-buf1), "%02x", a->s6_addr[i]);
1083 tor_snprintf(cp2, sizeof(buf2)-(cp2-buf2), "%02x", b->s6_addr[i]);
1084 cp1 += 2; cp2 += 2;
1085 if ((i%2)==1 && i != 15) {
1086 *cp1++ = ':';
1087 *cp2++ = ':';
1090 *cp1 = *cp2 = '\0';
1091 printf("Line %d: assertion failed: (%s == %s)\n"
1092 " %s != %s\n", line, e1, e2, buf1, buf2);
1093 fflush(stdout);
1097 /** Helper: Assert that two strings both decode as IPv6 addresses with
1098 * tor_inet_pton(), and both decode to the same address. */
1099 #define test_pton6_same(a,b) STMT_BEGIN \
1100 test_eq(tor_inet_pton(AF_INET6, a, &a1), 1); \
1101 test_eq(tor_inet_pton(AF_INET6, b, &a2), 1); \
1102 _test_eq_ip6(&a1,&a2,#a,#b,__LINE__); \
1103 STMT_END
1105 /** Helper: Assert that <b>a</b> is recognized as a bad IPv6 address by
1106 * tor_inet_pton(). */
1107 #define test_pton6_bad(a) \
1108 test_eq(0, tor_inet_pton(AF_INET6, a, &a1))
1110 /** Helper: assert that <b>a</b>, when parsed by tor_inet_pton() and displayed
1111 * with tor_inet_ntop(), yields <b>b</b>. Also assert that <b>b</b> parses to
1112 * the same value as <b>a</b>. */
1113 #define test_ntop6_reduces(a,b) STMT_BEGIN \
1114 test_eq(tor_inet_pton(AF_INET6, a, &a1), 1); \
1115 test_streq(tor_inet_ntop(AF_INET6, &a1, buf, sizeof(buf)), b); \
1116 test_eq(tor_inet_pton(AF_INET6, b, &a2), 1); \
1117 _test_eq_ip6(&a1, &a2, a, b, __LINE__); \
1118 STMT_END
1120 /** Helper: assert that <b>a</a> parses by tor_inet_pton() into a address that
1121 * passes tor_addr_is_internal() with <b>for_listening</b> */
1122 #define test_internal_ip(a,for_listening) STMT_BEGIN \
1123 test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
1124 t1.family = AF_INET6; \
1125 if (!tor_addr_is_internal(&t1, for_listening)) \
1126 test_fail_msg( a "was not internal."); \
1127 STMT_END
1129 /** Helper: assert that <b>a</a> parses by tor_inet_pton() into a address that
1130 * does not pass tor_addr_is_internal() with <b>for_listening</b>. */
1131 #define test_external_ip(a,for_listening) STMT_BEGIN \
1132 test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
1133 t1.family = AF_INET6; \
1134 if (tor_addr_is_internal(&t1, for_listening)) \
1135 test_fail_msg(a "was not external."); \
1136 STMT_END
1138 /** Helper: Assert that <b>a</b> and <b>b</b>, when parsed by
1139 * tor_inet_pton(), give addresses that compare in the order defined by
1140 * <b>op</b> with tor_addr_compare(). */
1141 #define test_addr_compare(a, op, b) STMT_BEGIN \
1142 test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
1143 test_eq(tor_inet_pton(AF_INET6, b, &t2.addr.in6_addr), 1); \
1144 t1.family = t2.family = AF_INET6; \
1145 r = tor_addr_compare(&t1,&t2); \
1146 if (!(r op 0)) \
1147 test_fail_msg("failed: tor_addr_compare("a","b") "#op" 0"); \
1148 STMT_END
1150 /** Helper: Assert that <b>a</b> and <b>b</b>, when parsed by
1151 * tor_inet_pton(), give addresses that compare in the order defined by
1152 * <b>op</b> with tor_addr_compare_masked() with <b>m</b> masked. */
1153 #define test_addr_compare_masked(a, op, b, m) STMT_BEGIN \
1154 test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
1155 test_eq(tor_inet_pton(AF_INET6, b, &t2.addr.in6_addr), 1); \
1156 t1.family = t2.family = AF_INET6; \
1157 r = tor_addr_compare_masked(&t1,&t2,m); \
1158 if (!(r op 0)) \
1159 test_fail_msg("failed: tor_addr_compare_masked("a","b","#m") "#op" 0"); \
1160 STMT_END
1162 /** Helper: assert that <b>xx</b> is parseable as a masked IPv6 address with
1163 * ports by <b>tor_parse_mask_addr_ports(), with family <b>f</b>, IP address
1164 * as 4 32-bit words <b>ip1...ip4</b>, mask bits as <b>mm</b>, and port range
1165 * as <b>pt1..pt2</b>. */
1166 #define test_addr_mask_ports_parse(xx, f, ip1, ip2, ip3, ip4, mm, pt1, pt2) \
1167 STMT_BEGIN \
1168 test_eq(tor_addr_parse_mask_ports(xx, &t1, &mask, &port1, &port2), f); \
1169 p1=tor_inet_ntop(AF_INET6, &t1.addr.in6_addr, bug, sizeof(bug)); \
1170 test_eq(htonl(ip1), IN6_ADDRESS32(&t1)[0]); \
1171 test_eq(htonl(ip2), IN6_ADDRESS32(&t1)[1]); \
1172 test_eq(htonl(ip3), IN6_ADDRESS32(&t1)[2]); \
1173 test_eq(htonl(ip4), IN6_ADDRESS32(&t1)[3]); \
1174 test_eq(mask, mm); \
1175 test_eq(port1, pt1); \
1176 test_eq(port2, pt2); \
1177 STMT_END
1179 static void
1180 test_util_ip6_helpers(void)
1182 char buf[TOR_ADDR_BUF_LEN], bug[TOR_ADDR_BUF_LEN];
1183 struct in6_addr a1, a2;
1184 tor_addr_t t1, t2;
1185 int r, i;
1186 uint16_t port1, port2;
1187 maskbits_t mask;
1188 const char *p1;
1190 // struct in_addr b1, b2;
1191 /* Test tor_inet_ntop and tor_inet_pton: IPv6 */
1193 /* === Test pton: valid af_inet6 */
1194 /* Simple, valid parsing. */
1195 r = tor_inet_pton(AF_INET6,
1196 "0102:0304:0506:0708:090A:0B0C:0D0E:0F10", &a1);
1197 test_assert(r==1);
1198 for (i=0;i<16;++i) { test_eq(i+1, (int)a1.s6_addr[i]); }
1199 /* ipv4 ending. */
1200 test_pton6_same("0102:0304:0506:0708:090A:0B0C:0D0E:0F10",
1201 "0102:0304:0506:0708:090A:0B0C:13.14.15.16");
1202 /* shortened words. */
1203 test_pton6_same("0001:0099:BEEF:0000:0123:FFFF:0001:0001",
1204 "1:99:BEEF:0:0123:FFFF:1:1");
1205 /* zeros at the beginning */
1206 test_pton6_same("0000:0000:0000:0000:0009:C0A8:0001:0001",
1207 "::9:c0a8:1:1");
1208 test_pton6_same("0000:0000:0000:0000:0009:C0A8:0001:0001",
1209 "::9:c0a8:0.1.0.1");
1210 /* zeros in the middle. */
1211 test_pton6_same("fe80:0000:0000:0000:0202:1111:0001:0001",
1212 "fe80::202:1111:1:1");
1213 /* zeros at the end. */
1214 test_pton6_same("1000:0001:0000:0007:0000:0000:0000:0000",
1215 "1000:1:0:7::");
1217 /* === Test ntop: af_inet6 */
1218 test_ntop6_reduces("0:0:0:0:0:0:0:0", "::");
1220 test_ntop6_reduces("0001:0099:BEEF:0006:0123:FFFF:0001:0001",
1221 "1:99:beef:6:123:ffff:1:1");
1223 //test_ntop6_reduces("0:0:0:0:0:0:c0a8:0101", "::192.168.1.1");
1224 test_ntop6_reduces("0:0:0:0:0:ffff:c0a8:0101", "::ffff:192.168.1.1");
1225 test_ntop6_reduces("002:0:0000:0:3::4", "2::3:0:0:4");
1226 test_ntop6_reduces("0:0::1:0:3", "::1:0:3");
1227 test_ntop6_reduces("008:0::0", "8::");
1228 test_ntop6_reduces("0:0:0:0:0:ffff::1", "::ffff:0.0.0.1");
1229 test_ntop6_reduces("abcd:0:0:0:0:0:7f00::", "abcd::7f00:0");
1230 test_ntop6_reduces("0000:0000:0000:0000:0009:C0A8:0001:0001",
1231 "::9:c0a8:1:1");
1232 test_ntop6_reduces("fe80:0000:0000:0000:0202:1111:0001:0001",
1233 "fe80::202:1111:1:1");
1234 test_ntop6_reduces("1000:0001:0000:0007:0000:0000:0000:0000",
1235 "1000:1:0:7::");
1237 /* === Test pton: invalid in6. */
1238 test_pton6_bad("foobar.");
1239 test_pton6_bad("55555::");
1240 test_pton6_bad("9:-60::");
1241 test_pton6_bad("1:2:33333:4:0002:3::");
1242 //test_pton6_bad("1:2:3333:4:00002:3::");// BAD, but glibc doesn't say so.
1243 test_pton6_bad("1:2:3333:4:fish:3::");
1244 test_pton6_bad("1:2:3:4:5:6:7:8:9");
1245 test_pton6_bad("1:2:3:4:5:6:7");
1246 test_pton6_bad("1:2:3:4:5:6:1.2.3.4.5");
1247 test_pton6_bad("1:2:3:4:5:6:1.2.3");
1248 test_pton6_bad("::1.2.3");
1249 test_pton6_bad("::1.2.3.4.5");
1250 test_pton6_bad("99");
1251 test_pton6_bad("");
1252 test_pton6_bad("1::2::3:4");
1253 test_pton6_bad("a:::b:c");
1254 test_pton6_bad(":::a:b:c");
1255 test_pton6_bad("a:b:c:::");
1257 /* test internal checking */
1258 test_external_ip("fbff:ffff::2:7", 0);
1259 test_internal_ip("fc01::2:7", 0);
1260 test_internal_ip("fdff:ffff::f:f", 0);
1261 test_external_ip("fe00::3:f", 0);
1263 test_external_ip("fe7f:ffff::2:7", 0);
1264 test_internal_ip("fe80::2:7", 0);
1265 test_internal_ip("febf:ffff::f:f", 0);
1267 test_internal_ip("fec0::2:7:7", 0);
1268 test_internal_ip("feff:ffff::e:7:7", 0);
1269 test_external_ip("ff00::e:7:7", 0);
1271 test_internal_ip("::", 0);
1272 test_internal_ip("::1", 0);
1273 test_internal_ip("::1", 1);
1274 test_internal_ip("::", 0);
1275 test_external_ip("::", 1);
1276 test_external_ip("::2", 0);
1277 test_external_ip("2001::", 0);
1278 test_external_ip("ffff::", 0);
1280 test_external_ip("::ffff:0.0.0.0", 1);
1281 test_internal_ip("::ffff:0.0.0.0", 0);
1282 test_internal_ip("::ffff:0.255.255.255", 0);
1283 test_external_ip("::ffff:1.0.0.0", 0);
1285 test_external_ip("::ffff:9.255.255.255", 0);
1286 test_internal_ip("::ffff:10.0.0.0", 0);
1287 test_internal_ip("::ffff:10.255.255.255", 0);
1288 test_external_ip("::ffff:11.0.0.0", 0);
1290 test_external_ip("::ffff:126.255.255.255", 0);
1291 test_internal_ip("::ffff:127.0.0.0", 0);
1292 test_internal_ip("::ffff:127.255.255.255", 0);
1293 test_external_ip("::ffff:128.0.0.0", 0);
1295 test_external_ip("::ffff:172.15.255.255", 0);
1296 test_internal_ip("::ffff:172.16.0.0", 0);
1297 test_internal_ip("::ffff:172.31.255.255", 0);
1298 test_external_ip("::ffff:172.32.0.0", 0);
1300 test_external_ip("::ffff:192.167.255.255", 0);
1301 test_internal_ip("::ffff:192.168.0.0", 0);
1302 test_internal_ip("::ffff:192.168.255.255", 0);
1303 test_external_ip("::ffff:192.169.0.0", 0);
1305 test_external_ip("::ffff:169.253.255.255", 0);
1306 test_internal_ip("::ffff:169.254.0.0", 0);
1307 test_internal_ip("::ffff:169.254.255.255", 0);
1308 test_external_ip("::ffff:169.255.0.0", 0);
1310 /* tor_addr_compare(tor_addr_t x2) */
1311 test_addr_compare("ffff::", ==, "ffff::0");
1312 test_addr_compare("0::3:2:1", >, "0::ffff:0.3.2.1");
1313 test_addr_compare("0::2:2:1", >, "0::ffff:0.3.2.1");
1314 test_addr_compare("0::ffff:0.3.2.1", <, "0::0:0:0");
1315 test_addr_compare("0::ffff:5.2.2.1", <, "::ffff:6.0.0.0"); /* XXXX wrong. */
1316 tor_addr_parse_mask_ports("[::ffff:2.3.4.5]", &t1, NULL, NULL, NULL);
1317 tor_addr_parse_mask_ports("2.3.4.5", &t2, NULL, NULL, NULL);
1318 test_assert(tor_addr_compare(&t1, &t2) == 0);
1319 tor_addr_parse_mask_ports("[::ffff:2.3.4.4]", &t1, NULL, NULL, NULL);
1320 tor_addr_parse_mask_ports("2.3.4.5", &t2, NULL, NULL, NULL);
1321 test_assert(tor_addr_compare(&t1, &t2) < 0);
1323 /* test compare_masked */
1324 test_addr_compare_masked("ffff::", ==, "ffff::0", 128);
1325 test_addr_compare_masked("ffff::", ==, "ffff::0", 64);
1326 test_addr_compare_masked("0::2:2:1", <, "0::8000:2:1", 81);
1327 test_addr_compare_masked("0::2:2:1", ==, "0::8000:2:1", 80);
1329 /* test tor_addr_parse_mask_ports */
1330 test_addr_mask_ports_parse("[::f]/17:47-95", AF_INET6,
1331 0, 0, 0, 0x0000000f, 17, 47, 95);
1332 //test_addr_parse("[::fefe:4.1.1.7/120]:999-1000");
1333 //test_addr_parse_check("::fefe:401:107", 120, 999, 1000);
1334 test_addr_mask_ports_parse("[::ffff:4.1.1.7]/120:443", AF_INET6,
1335 0, 0, 0x0000ffff, 0x04010107, 120, 443, 443);
1336 test_addr_mask_ports_parse("[abcd:2::44a:0]:2-65000", AF_INET6,
1337 0xabcd0002, 0, 0, 0x044a0000, 128, 2, 65000);
1339 r=tor_addr_parse_mask_ports("[fefef::]/112", &t1, NULL, NULL, NULL);
1340 test_assert(r == -1);
1341 r=tor_addr_parse_mask_ports("efef::/112", &t1, NULL, NULL, NULL);
1342 test_assert(r == -1);
1343 r=tor_addr_parse_mask_ports("[f:f:f:f:f:f:f:f::]", &t1, NULL, NULL, NULL);
1344 test_assert(r == -1);
1345 r=tor_addr_parse_mask_ports("[::f:f:f:f:f:f:f:f]", &t1, NULL, NULL, NULL);
1346 test_assert(r == -1);
1347 r=tor_addr_parse_mask_ports("[f:f:f:f:f:f:f:f:f]", &t1, NULL, NULL, NULL);
1348 test_assert(r == -1);
1349 /* Test for V4-mapped address with mask < 96. (arguably not valid) */
1350 r=tor_addr_parse_mask_ports("[::ffff:1.1.2.2/33]", &t1, &mask, NULL, NULL);
1351 test_assert(r == -1);
1352 r=tor_addr_parse_mask_ports("1.1.2.2/33", &t1, &mask, NULL, NULL);
1353 test_assert(r == -1);
1354 r=tor_addr_parse_mask_ports("1.1.2.2/31", &t1, &mask, NULL, NULL);
1355 test_assert(r == AF_INET);
1356 r=tor_addr_parse_mask_ports("[efef::]/112", &t1, &mask, &port1, &port2);
1357 test_assert(r == AF_INET6);
1358 test_assert(port1 == 1);
1359 test_assert(port2 == 65535);
1361 /* make sure inet address lengths >= max */
1362 test_assert(INET_NTOA_BUF_LEN >= sizeof("255.255.255.255"));
1363 test_assert(TOR_ADDR_BUF_LEN >=
1364 sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"));
1366 test_assert(sizeof(tor_addr_t) >= sizeof(struct in6_addr));
1368 /* get interface addresses */
1369 r = get_interface_address6(LOG_DEBUG, AF_INET, &t1);
1370 i = get_interface_address6(LOG_DEBUG, AF_INET6, &t2);
1371 #if 0
1372 tor_inet_ntop(AF_INET, &t1.sa.sin_addr, buf, sizeof(buf));
1373 printf("\nv4 address: %s (family=%i)", buf, IN_FAMILY(&t1));
1374 tor_inet_ntop(AF_INET6, &t2.sa6.sin6_addr, buf, sizeof(buf));
1375 printf("\nv6 address: %s (family=%i)", buf, IN_FAMILY(&t2));
1376 #endif
1379 static void
1380 test_util_smartlist(void)
1382 smartlist_t *sl;
1383 char *cp;
1384 size_t sz;
1386 /* XXXX test sort_digests, uniq_strings, uniq_digests */
1388 /* Test smartlist add, del_keeporder, insert, get. */
1389 sl = smartlist_create();
1390 smartlist_add(sl, (void*)1);
1391 smartlist_add(sl, (void*)2);
1392 smartlist_add(sl, (void*)3);
1393 smartlist_add(sl, (void*)4);
1394 smartlist_del_keeporder(sl, 1);
1395 smartlist_insert(sl, 1, (void*)22);
1396 smartlist_insert(sl, 0, (void*)0);
1397 smartlist_insert(sl, 5, (void*)555);
1398 test_eq_ptr((void*)0, smartlist_get(sl,0));
1399 test_eq_ptr((void*)1, smartlist_get(sl,1));
1400 test_eq_ptr((void*)22, smartlist_get(sl,2));
1401 test_eq_ptr((void*)3, smartlist_get(sl,3));
1402 test_eq_ptr((void*)4, smartlist_get(sl,4));
1403 test_eq_ptr((void*)555, smartlist_get(sl,5));
1404 /* Try deleting in the middle. */
1405 smartlist_del(sl, 1);
1406 test_eq_ptr((void*)555, smartlist_get(sl, 1));
1407 /* Try deleting at the end. */
1408 smartlist_del(sl, 4);
1409 test_eq(4, smartlist_len(sl));
1411 /* test isin. */
1412 test_assert(smartlist_isin(sl, (void*)3));
1413 test_assert(!smartlist_isin(sl, (void*)99));
1415 /* Test split and join */
1416 smartlist_clear(sl);
1417 test_eq(0, smartlist_len(sl));
1418 smartlist_split_string(sl, "abc", ":", 0, 0);
1419 test_eq(1, smartlist_len(sl));
1420 test_streq("abc", smartlist_get(sl, 0));
1421 smartlist_split_string(sl, "a::bc::", "::", 0, 0);
1422 test_eq(4, smartlist_len(sl));
1423 test_streq("a", smartlist_get(sl, 1));
1424 test_streq("bc", smartlist_get(sl, 2));
1425 test_streq("", smartlist_get(sl, 3));
1426 cp = smartlist_join_strings(sl, "", 0, NULL);
1427 test_streq(cp, "abcabc");
1428 tor_free(cp);
1429 cp = smartlist_join_strings(sl, "!", 0, NULL);
1430 test_streq(cp, "abc!a!bc!");
1431 tor_free(cp);
1432 cp = smartlist_join_strings(sl, "XY", 0, NULL);
1433 test_streq(cp, "abcXYaXYbcXY");
1434 tor_free(cp);
1435 cp = smartlist_join_strings(sl, "XY", 1, NULL);
1436 test_streq(cp, "abcXYaXYbcXYXY");
1437 tor_free(cp);
1438 cp = smartlist_join_strings(sl, "", 1, NULL);
1439 test_streq(cp, "abcabc");
1440 tor_free(cp);
1442 smartlist_split_string(sl, "/def/ /ghijk", "/", 0, 0);
1443 test_eq(8, smartlist_len(sl));
1444 test_streq("", smartlist_get(sl, 4));
1445 test_streq("def", smartlist_get(sl, 5));
1446 test_streq(" ", smartlist_get(sl, 6));
1447 test_streq("ghijk", smartlist_get(sl, 7));
1448 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1449 smartlist_clear(sl);
1451 smartlist_split_string(sl, "a,bbd,cdef", ",", SPLIT_SKIP_SPACE, 0);
1452 test_eq(3, smartlist_len(sl));
1453 test_streq("a", smartlist_get(sl,0));
1454 test_streq("bbd", smartlist_get(sl,1));
1455 test_streq("cdef", smartlist_get(sl,2));
1456 smartlist_split_string(sl, " z <> zhasd <> <> bnud<> ", "<>",
1457 SPLIT_SKIP_SPACE, 0);
1458 test_eq(8, smartlist_len(sl));
1459 test_streq("z", smartlist_get(sl,3));
1460 test_streq("zhasd", smartlist_get(sl,4));
1461 test_streq("", smartlist_get(sl,5));
1462 test_streq("bnud", smartlist_get(sl,6));
1463 test_streq("", smartlist_get(sl,7));
1465 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1466 smartlist_clear(sl);
1468 smartlist_split_string(sl, " ab\tc \td ef ", NULL,
1469 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1470 test_eq(4, smartlist_len(sl));
1471 test_streq("ab", smartlist_get(sl,0));
1472 test_streq("c", smartlist_get(sl,1));
1473 test_streq("d", smartlist_get(sl,2));
1474 test_streq("ef", smartlist_get(sl,3));
1475 smartlist_split_string(sl, "ghi\tj", NULL,
1476 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1477 test_eq(6, smartlist_len(sl));
1478 test_streq("ghi", smartlist_get(sl,4));
1479 test_streq("j", smartlist_get(sl,5));
1481 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1482 smartlist_clear(sl);
1484 cp = smartlist_join_strings(sl, "XY", 0, NULL);
1485 test_streq(cp, "");
1486 tor_free(cp);
1487 cp = smartlist_join_strings(sl, "XY", 1, NULL);
1488 test_streq(cp, "XY");
1489 tor_free(cp);
1491 smartlist_split_string(sl, " z <> zhasd <> <> bnud<> ", "<>",
1492 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1493 test_eq(3, smartlist_len(sl));
1494 test_streq("z", smartlist_get(sl, 0));
1495 test_streq("zhasd", smartlist_get(sl, 1));
1496 test_streq("bnud", smartlist_get(sl, 2));
1497 smartlist_split_string(sl, " z <> zhasd <> <> bnud<> ", "<>",
1498 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
1499 test_eq(5, smartlist_len(sl));
1500 test_streq("z", smartlist_get(sl, 3));
1501 test_streq("zhasd <> <> bnud<>", smartlist_get(sl, 4));
1502 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1503 smartlist_clear(sl);
1505 smartlist_split_string(sl, "abcd\n", "\n",
1506 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1507 test_eq(1, smartlist_len(sl));
1508 test_streq("abcd", smartlist_get(sl, 0));
1509 smartlist_split_string(sl, "efgh", "\n",
1510 SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
1511 test_eq(2, smartlist_len(sl));
1512 test_streq("efgh", smartlist_get(sl, 1));
1514 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1515 smartlist_clear(sl);
1517 /* Test swapping, shuffling, and sorting. */
1518 smartlist_split_string(sl, "the,onion,router,by,arma,and,nickm", ",", 0, 0);
1519 test_eq(7, smartlist_len(sl));
1520 smartlist_sort(sl, _compare_strs);
1521 cp = smartlist_join_strings(sl, ",", 0, NULL);
1522 test_streq(cp,"and,arma,by,nickm,onion,router,the");
1523 tor_free(cp);
1524 smartlist_swap(sl, 1, 5);
1525 cp = smartlist_join_strings(sl, ",", 0, NULL);
1526 test_streq(cp,"and,router,by,nickm,onion,arma,the");
1527 tor_free(cp);
1528 smartlist_shuffle(sl);
1529 test_eq(7, smartlist_len(sl));
1530 test_assert(smartlist_string_isin(sl, "and"));
1531 test_assert(smartlist_string_isin(sl, "router"));
1532 test_assert(smartlist_string_isin(sl, "by"));
1533 test_assert(smartlist_string_isin(sl, "nickm"));
1534 test_assert(smartlist_string_isin(sl, "onion"));
1535 test_assert(smartlist_string_isin(sl, "arma"));
1536 test_assert(smartlist_string_isin(sl, "the"));
1538 /* Test bsearch. */
1539 smartlist_sort(sl, _compare_strs);
1540 test_streq("nickm", smartlist_bsearch(sl, "zNicKM",
1541 _compare_without_first_ch));
1542 test_streq("and", smartlist_bsearch(sl, " AND", _compare_without_first_ch));
1543 test_eq_ptr(NULL, smartlist_bsearch(sl, " ANz", _compare_without_first_ch));
1545 /* Test bsearch_idx */
1547 int f;
1548 test_eq(0, smartlist_bsearch_idx(sl," aaa",_compare_without_first_ch,&f));
1549 test_eq(f, 0);
1550 test_eq(0, smartlist_bsearch_idx(sl," and",_compare_without_first_ch,&f));
1551 test_eq(f, 1);
1552 test_eq(1, smartlist_bsearch_idx(sl," arm",_compare_without_first_ch,&f));
1553 test_eq(f, 0);
1554 test_eq(1, smartlist_bsearch_idx(sl," arma",_compare_without_first_ch,&f));
1555 test_eq(f, 1);
1556 test_eq(2, smartlist_bsearch_idx(sl," armb",_compare_without_first_ch,&f));
1557 test_eq(f, 0);
1558 test_eq(7, smartlist_bsearch_idx(sl," zzzz",_compare_without_first_ch,&f));
1559 test_eq(f, 0);
1562 /* Test reverse() and pop_last() */
1563 smartlist_reverse(sl);
1564 cp = smartlist_join_strings(sl, ",", 0, NULL);
1565 test_streq(cp,"the,router,onion,nickm,by,arma,and");
1566 tor_free(cp);
1567 cp = smartlist_pop_last(sl);
1568 test_streq(cp, "and");
1569 tor_free(cp);
1570 test_eq(smartlist_len(sl), 6);
1571 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1572 smartlist_clear(sl);
1573 cp = smartlist_pop_last(sl);
1574 test_eq(cp, NULL);
1576 /* Test uniq() */
1577 smartlist_split_string(sl,
1578 "50,noon,radar,a,man,a,plan,a,canal,panama,radar,noon,50",
1579 ",", 0, 0);
1580 smartlist_sort(sl, _compare_strs);
1581 smartlist_uniq(sl, _compare_strs, _tor_free);
1582 cp = smartlist_join_strings(sl, ",", 0, NULL);
1583 test_streq(cp, "50,a,canal,man,noon,panama,plan,radar");
1584 tor_free(cp);
1586 /* Test string_isin and isin_case and num_isin */
1587 test_assert(smartlist_string_isin(sl, "noon"));
1588 test_assert(!smartlist_string_isin(sl, "noonoon"));
1589 test_assert(smartlist_string_isin_case(sl, "nOOn"));
1590 test_assert(!smartlist_string_isin_case(sl, "nooNooN"));
1591 test_assert(smartlist_string_num_isin(sl, 50));
1592 test_assert(!smartlist_string_num_isin(sl, 60));
1593 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1594 smartlist_clear(sl);
1596 /* Test string_remove and remove and join_strings2 */
1597 smartlist_split_string(sl,
1598 "Some say the Earth will end in ice and some in fire",
1599 " ", 0, 0);
1600 cp = smartlist_get(sl, 4);
1601 test_streq(cp, "will");
1602 smartlist_add(sl, cp);
1603 smartlist_remove(sl, cp);
1604 tor_free(cp);
1605 cp = smartlist_join_strings(sl, ",", 0, NULL);
1606 test_streq(cp, "Some,say,the,Earth,fire,end,in,ice,and,some,in");
1607 tor_free(cp);
1608 smartlist_string_remove(sl, "in");
1609 cp = smartlist_join_strings2(sl, "+XX", 1, 0, &sz);
1610 test_streq(cp, "Some+say+the+Earth+fire+end+some+ice+and");
1611 test_eq((int)sz, 40);
1612 tor_free(cp);
1614 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1615 smartlist_clear(sl);
1618 smartlist_t *ints = smartlist_create();
1619 smartlist_t *odds = smartlist_create();
1620 smartlist_t *evens = smartlist_create();
1621 smartlist_t *primes = smartlist_create();
1622 int i;
1623 for (i=1; i < 10; i += 2)
1624 smartlist_add(odds, (void*)(uintptr_t)i);
1625 for (i=0; i < 10; i += 2)
1626 smartlist_add(evens, (void*)(uintptr_t)i);
1628 /* add_all */
1629 smartlist_add_all(ints, odds);
1630 smartlist_add_all(ints, evens);
1631 test_eq(smartlist_len(ints), 10);
1633 smartlist_add(primes, (void*)2);
1634 smartlist_add(primes, (void*)3);
1635 smartlist_add(primes, (void*)5);
1636 smartlist_add(primes, (void*)7);
1638 /* overlap */
1639 test_assert(smartlist_overlap(ints, odds));
1640 test_assert(smartlist_overlap(odds, primes));
1641 test_assert(smartlist_overlap(evens, primes));
1642 test_assert(!smartlist_overlap(odds, evens));
1644 /* intersect */
1645 smartlist_add_all(sl, odds);
1646 smartlist_intersect(sl, primes);
1647 test_eq(smartlist_len(sl), 3);
1648 test_assert(smartlist_isin(sl, (void*)3));
1649 test_assert(smartlist_isin(sl, (void*)5));
1650 test_assert(smartlist_isin(sl, (void*)7));
1652 /* subtract */
1653 smartlist_add_all(sl, primes);
1654 smartlist_subtract(sl, odds);
1655 test_eq(smartlist_len(sl), 1);
1656 test_assert(smartlist_isin(sl, (void*)2));
1658 smartlist_free(odds);
1659 smartlist_free(evens);
1660 smartlist_free(ints);
1661 smartlist_free(primes);
1662 smartlist_clear(sl);
1666 /* digest_isin. */
1667 smartlist_add(sl, tor_memdup("AAAAAAAAAAAAAAAAAAAA", DIGEST_LEN));
1668 smartlist_add(sl, tor_memdup("\00090AAB2AAAAaasdAAAAA", DIGEST_LEN));
1669 smartlist_add(sl, tor_memdup("\00090AAB2AAAAaasdAAAAA", DIGEST_LEN));
1670 test_eq(0, smartlist_digest_isin(NULL, "AAAAAAAAAAAAAAAAAAAA"));
1671 test_assert(smartlist_digest_isin(sl, "AAAAAAAAAAAAAAAAAAAA"));
1672 test_assert(smartlist_digest_isin(sl, "\00090AAB2AAAAaasdAAAAA"));
1673 test_eq(0, smartlist_digest_isin(sl, "\00090AAB2AAABaasdAAAAA"));
1675 /* sort digests */
1676 smartlist_sort_digests(sl);
1677 test_memeq(smartlist_get(sl, 0), "\00090AAB2AAAAaasdAAAAA", DIGEST_LEN);
1678 test_memeq(smartlist_get(sl, 1), "\00090AAB2AAAAaasdAAAAA", DIGEST_LEN);
1679 test_memeq(smartlist_get(sl, 2), "AAAAAAAAAAAAAAAAAAAA", DIGEST_LEN);
1680 test_eq(3, smartlist_len(sl));
1682 /* uniq_digests */
1683 smartlist_uniq_digests(sl);
1684 test_eq(2, smartlist_len(sl));
1685 test_memeq(smartlist_get(sl, 0), "\00090AAB2AAAAaasdAAAAA", DIGEST_LEN);
1686 test_memeq(smartlist_get(sl, 1), "AAAAAAAAAAAAAAAAAAAA", DIGEST_LEN);
1688 SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
1689 smartlist_clear(sl);
1692 smartlist_free(sl);
1695 static void
1696 test_util_bitarray(void)
1698 bitarray_t *ba;
1699 int i, j, ok=1;
1701 ba = bitarray_init_zero(1);
1702 test_assert(! bitarray_is_set(ba, 0));
1703 bitarray_set(ba, 0);
1704 test_assert(bitarray_is_set(ba, 0));
1705 bitarray_clear(ba, 0);
1706 test_assert(! bitarray_is_set(ba, 0));
1707 bitarray_free(ba);
1709 ba = bitarray_init_zero(1023);
1710 for (i = 1; i < 64; ) {
1711 for (j = 0; j < 1023; ++j) {
1712 if (j % i)
1713 bitarray_set(ba, j);
1714 else
1715 bitarray_clear(ba, j);
1717 for (j = 0; j < 1023; ++j) {
1718 if (!bool_eq(bitarray_is_set(ba, j), j%i))
1719 ok = 0;
1721 test_assert(ok);
1722 if (i < 7)
1723 ++i;
1724 else if (i == 28)
1725 i = 32;
1726 else
1727 i += 7;
1729 bitarray_free(ba);
1732 /* stop threads running at once. */
1733 static tor_mutex_t *_thread_test_mutex = NULL;
1734 /* make sure that threads have to run at the same time. */
1735 static tor_mutex_t *_thread_test_start1 = NULL;
1736 static tor_mutex_t *_thread_test_start2 = NULL;
1737 static strmap_t *_thread_test_strmap = NULL;
1739 static void _thread_test_func(void* _s) ATTR_NORETURN;
1741 static int t1_count = 0;
1742 static int t2_count = 0;
1744 static void
1745 _thread_test_func(void* _s)
1747 char *s = _s;
1748 int i, *count;
1749 tor_mutex_t *m;
1750 char buf[64];
1751 char *cp;
1752 if (!strcmp(s, "thread 1")) {
1753 m = _thread_test_start1;
1754 count = &t1_count;
1755 } else {
1756 m = _thread_test_start2;
1757 count = &t2_count;
1759 tor_mutex_acquire(m);
1761 tor_snprintf(buf, sizeof(buf), "%lu", tor_get_thread_id());
1762 cp = tor_strdup(buf);
1764 for (i=0; i<10000; ++i) {
1765 tor_mutex_acquire(_thread_test_mutex);
1766 strmap_set(_thread_test_strmap, "last to run", cp);
1767 ++*count;
1768 tor_mutex_release(_thread_test_mutex);
1770 tor_mutex_acquire(_thread_test_mutex);
1771 strmap_set(_thread_test_strmap, s, tor_strdup(buf));
1772 tor_mutex_release(_thread_test_mutex);
1774 tor_mutex_release(m);
1776 spawn_exit();
1779 static void
1780 test_util_threads(void)
1782 char *s1, *s2;
1783 int done = 0, timedout = 0;
1784 time_t started;
1785 #ifndef TOR_IS_MULTITHREADED
1786 /* Skip this test if we aren't threading. We should be threading most
1787 * everywhere by now. */
1788 if (1)
1789 return;
1790 #endif
1791 _thread_test_mutex = tor_mutex_new();
1792 _thread_test_start1 = tor_mutex_new();
1793 _thread_test_start2 = tor_mutex_new();
1794 _thread_test_strmap = strmap_new();
1795 s1 = tor_strdup("thread 1");
1796 s2 = tor_strdup("thread 2");
1797 tor_mutex_acquire(_thread_test_start1);
1798 tor_mutex_acquire(_thread_test_start2);
1799 spawn_func(_thread_test_func, s1);
1800 spawn_func(_thread_test_func, s2);
1801 tor_mutex_release(_thread_test_start2);
1802 tor_mutex_release(_thread_test_start1);
1803 started = time(NULL);
1804 while (!done) {
1805 tor_mutex_acquire(_thread_test_mutex);
1806 strmap_assert_ok(_thread_test_strmap);
1807 if (strmap_get(_thread_test_strmap, "thread 1") &&
1808 strmap_get(_thread_test_strmap, "thread 2")) {
1809 done = 1;
1810 } else if (time(NULL) > started + 25) {
1811 timedout = done = 1;
1813 tor_mutex_release(_thread_test_mutex);
1815 tor_mutex_free(_thread_test_mutex);
1817 if (timedout) {
1818 printf("\nTimed out: %d %d", t1_count, t2_count);
1819 test_assert(strmap_get(_thread_test_strmap, "thread 1"));
1820 test_assert(strmap_get(_thread_test_strmap, "thread 2"));
1821 test_assert(!timedout);
1824 /* different thread IDs. */
1825 test_assert(strcmp(strmap_get(_thread_test_strmap, "thread 1"),
1826 strmap_get(_thread_test_strmap, "thread 2")));
1827 test_assert(!strcmp(strmap_get(_thread_test_strmap, "thread 1"),
1828 strmap_get(_thread_test_strmap, "last to run")) ||
1829 !strcmp(strmap_get(_thread_test_strmap, "thread 2"),
1830 strmap_get(_thread_test_strmap, "last to run")));
1832 strmap_free(_thread_test_strmap, _tor_free);
1834 tor_free(s1);
1835 tor_free(s2);
1838 static int
1839 _compare_strings_for_pqueue(const void *s1, const void *s2)
1841 return strcmp((const char*)s1, (const char*)s2);
1844 static void
1845 test_util_pqueue(void)
1847 smartlist_t *sl;
1848 int (*cmp)(const void *, const void*);
1849 #define OK() smartlist_pqueue_assert_ok(sl, cmp)
1851 cmp = _compare_strings_for_pqueue;
1853 sl = smartlist_create();
1854 smartlist_pqueue_add(sl, cmp, (char*)"cows");
1855 smartlist_pqueue_add(sl, cmp, (char*)"zebras");
1856 smartlist_pqueue_add(sl, cmp, (char*)"fish");
1857 smartlist_pqueue_add(sl, cmp, (char*)"frogs");
1858 smartlist_pqueue_add(sl, cmp, (char*)"apples");
1859 smartlist_pqueue_add(sl, cmp, (char*)"squid");
1860 smartlist_pqueue_add(sl, cmp, (char*)"daschunds");
1861 smartlist_pqueue_add(sl, cmp, (char*)"eggplants");
1862 smartlist_pqueue_add(sl, cmp, (char*)"weissbier");
1863 smartlist_pqueue_add(sl, cmp, (char*)"lobsters");
1864 smartlist_pqueue_add(sl, cmp, (char*)"roquefort");
1866 OK();
1868 test_eq(smartlist_len(sl), 11);
1869 test_streq(smartlist_get(sl, 0), "apples");
1870 test_streq(smartlist_pqueue_pop(sl, cmp), "apples");
1871 test_eq(smartlist_len(sl), 10);
1872 OK();
1873 test_streq(smartlist_pqueue_pop(sl, cmp), "cows");
1874 test_streq(smartlist_pqueue_pop(sl, cmp), "daschunds");
1875 smartlist_pqueue_add(sl, cmp, (char*)"chinchillas");
1876 OK();
1877 smartlist_pqueue_add(sl, cmp, (char*)"fireflies");
1878 OK();
1879 test_streq(smartlist_pqueue_pop(sl, cmp), "chinchillas");
1880 test_streq(smartlist_pqueue_pop(sl, cmp), "eggplants");
1881 test_streq(smartlist_pqueue_pop(sl, cmp), "fireflies");
1882 OK();
1883 test_streq(smartlist_pqueue_pop(sl, cmp), "fish");
1884 test_streq(smartlist_pqueue_pop(sl, cmp), "frogs");
1885 test_streq(smartlist_pqueue_pop(sl, cmp), "lobsters");
1886 test_streq(smartlist_pqueue_pop(sl, cmp), "roquefort");
1887 OK();
1888 test_eq(smartlist_len(sl), 3);
1889 test_streq(smartlist_pqueue_pop(sl, cmp), "squid");
1890 test_streq(smartlist_pqueue_pop(sl, cmp), "weissbier");
1891 test_streq(smartlist_pqueue_pop(sl, cmp), "zebras");
1892 test_eq(smartlist_len(sl), 0);
1893 OK();
1894 #undef OK
1895 smartlist_free(sl);
1898 static void
1899 test_util_gzip(void)
1901 char *buf1, *buf2=NULL, *buf3=NULL, *cp1, *cp2;
1902 const char *ccp2;
1903 size_t len1, len2;
1904 tor_zlib_state_t *state;
1906 buf1 = tor_strdup("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ");
1907 test_assert(detect_compression_method(buf1, strlen(buf1)) == UNKNOWN_METHOD);
1908 if (is_gzip_supported()) {
1909 test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
1910 GZIP_METHOD));
1911 test_assert(buf2);
1912 test_assert(!memcmp(buf2, "\037\213", 2)); /* Gzip magic. */
1913 test_assert(detect_compression_method(buf2, len1) == GZIP_METHOD);
1915 test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1,
1916 GZIP_METHOD, 1, LOG_INFO));
1917 test_assert(buf3);
1918 test_streq(buf1,buf3);
1920 tor_free(buf2);
1921 tor_free(buf3);
1924 test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
1925 ZLIB_METHOD));
1926 test_assert(buf2);
1927 test_assert(!memcmp(buf2, "\x78\xDA", 2)); /* deflate magic. */
1928 test_assert(detect_compression_method(buf2, len1) == ZLIB_METHOD);
1930 test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1,
1931 ZLIB_METHOD, 1, LOG_INFO));
1932 test_assert(buf3);
1933 test_streq(buf1,buf3);
1935 /* Check whether we can uncompress concatenated, compresed strings. */
1936 tor_free(buf3);
1937 buf2 = tor_realloc(buf2, len1*2);
1938 memcpy(buf2+len1, buf2, len1);
1939 test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1*2,
1940 ZLIB_METHOD, 1, LOG_INFO));
1941 test_eq(len2, (strlen(buf1)+1)*2);
1942 test_memeq(buf3,
1943 "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ\0"
1944 "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ\0",
1945 (strlen(buf1)+1)*2);
1947 tor_free(buf1);
1948 tor_free(buf2);
1949 tor_free(buf3);
1951 /* Check whether we can uncompress partial strings. */
1952 buf1 =
1953 tor_strdup("String with low redundancy that won't be compressed much.");
1954 test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
1955 ZLIB_METHOD));
1956 tor_assert(len1>16);
1957 /* when we allow an uncomplete string, we should succeed.*/
1958 tor_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1-16,
1959 ZLIB_METHOD, 0, LOG_INFO));
1960 buf3[len2]='\0';
1961 tor_assert(len2 > 5);
1962 tor_assert(!strcmpstart(buf1, buf3));
1964 /* when we demand a complete string, this must fail. */
1965 tor_free(buf3);
1966 tor_assert(tor_gzip_uncompress(&buf3, &len2, buf2, len1-16,
1967 ZLIB_METHOD, 1, LOG_INFO));
1968 tor_assert(!buf3);
1970 /* Now, try streaming compression. */
1971 tor_free(buf1);
1972 tor_free(buf2);
1973 tor_free(buf3);
1974 state = tor_zlib_new(1, ZLIB_METHOD);
1975 tor_assert(state);
1976 cp1 = buf1 = tor_malloc(1024);
1977 len1 = 1024;
1978 ccp2 = "ABCDEFGHIJABCDEFGHIJ";
1979 len2 = 21;
1980 test_assert(tor_zlib_process(state, &cp1, &len1, &ccp2, &len2, 0)
1981 == TOR_ZLIB_OK);
1982 test_eq(len2, 0); /* Make sure we compressed it all. */
1983 test_assert(cp1 > buf1);
1985 len2 = 0;
1986 cp2 = cp1;
1987 test_assert(tor_zlib_process(state, &cp1, &len1, &ccp2, &len2, 1)
1988 == TOR_ZLIB_DONE);
1989 test_eq(len2, 0);
1990 test_assert(cp1 > cp2); /* Make sure we really added something. */
1992 tor_assert(!tor_gzip_uncompress(&buf3, &len2, buf1, 1024-len1,
1993 ZLIB_METHOD, 1, LOG_WARN));
1994 test_streq(buf3, "ABCDEFGHIJABCDEFGHIJ"); /*Make sure it compressed right.*/
1995 tor_free(buf3);
1997 tor_zlib_free(state);
1999 tor_free(buf2);
2000 tor_free(buf3);
2001 tor_free(buf1);
2004 static void
2005 test_util_strmap(void)
2007 strmap_t *map;
2008 strmap_iter_t *iter;
2009 const char *k;
2010 void *v;
2011 char *visited;
2012 smartlist_t *found_keys;
2014 map = strmap_new();
2015 v = strmap_set(map, "K1", (void*)99);
2016 test_eq(v, NULL);
2017 v = strmap_set(map, "K2", (void*)101);
2018 test_eq(v, NULL);
2019 v = strmap_set(map, "K1", (void*)100);
2020 test_eq(v, (void*)99);
2021 test_eq_ptr(strmap_get(map,"K1"), (void*)100);
2022 test_eq_ptr(strmap_get(map,"K2"), (void*)101);
2023 test_eq_ptr(strmap_get(map,"K-not-there"), NULL);
2024 strmap_assert_ok(map);
2026 v = strmap_remove(map,"K2");
2027 strmap_assert_ok(map);
2028 test_eq_ptr(v, (void*)101);
2029 test_eq_ptr(strmap_get(map,"K2"), NULL);
2030 test_eq_ptr(strmap_remove(map,"K2"), NULL);
2032 strmap_set(map, "K2", (void*)101);
2033 strmap_set(map, "K3", (void*)102);
2034 strmap_set(map, "K4", (void*)103);
2035 strmap_assert_ok(map);
2036 strmap_set(map, "K5", (void*)104);
2037 strmap_set(map, "K6", (void*)105);
2038 strmap_assert_ok(map);
2040 /* Test iterator. */
2041 iter = strmap_iter_init(map);
2042 found_keys = smartlist_create();
2043 while (!strmap_iter_done(iter)) {
2044 strmap_iter_get(iter,&k,&v);
2045 smartlist_add(found_keys, tor_strdup(k));
2046 test_eq_ptr(v, strmap_get(map, k));
2048 if (!strcmp(k, "K2")) {
2049 iter = strmap_iter_next_rmv(map,iter);
2050 } else {
2051 iter = strmap_iter_next(map,iter);
2055 /* Make sure we removed K2, but not the others. */
2056 test_eq_ptr(strmap_get(map, "K2"), NULL);
2057 test_eq_ptr(strmap_get(map, "K5"), (void*)104);
2058 /* Make sure we visited everyone once */
2059 smartlist_sort_strings(found_keys);
2060 visited = smartlist_join_strings(found_keys, ":", 0, NULL);
2061 test_streq(visited, "K1:K2:K3:K4:K5:K6");
2062 tor_free(visited);
2063 SMARTLIST_FOREACH(found_keys, char *, cp, tor_free(cp));
2064 smartlist_free(found_keys);
2066 strmap_assert_ok(map);
2067 /* Clean up after ourselves. */
2068 strmap_free(map, NULL);
2070 /* Now try some lc functions. */
2071 map = strmap_new();
2072 strmap_set_lc(map,"Ab.C", (void*)1);
2073 test_eq_ptr(strmap_get(map,"ab.c"), (void*)1);
2074 strmap_assert_ok(map);
2075 test_eq_ptr(strmap_get_lc(map,"AB.C"), (void*)1);
2076 test_eq_ptr(strmap_get(map,"AB.C"), NULL);
2077 test_eq_ptr(strmap_remove_lc(map,"aB.C"), (void*)1);
2078 strmap_assert_ok(map);
2079 test_eq_ptr(strmap_get_lc(map,"AB.C"), NULL);
2080 strmap_free(map,NULL);
2083 static void
2084 test_util_mmap(void)
2086 char *fname1 = tor_strdup(get_fname("mapped_1"));
2087 char *fname2 = tor_strdup(get_fname("mapped_2"));
2088 char *fname3 = tor_strdup(get_fname("mapped_3"));
2089 const size_t buflen = 17000;
2090 char *buf = tor_malloc(17000);
2091 tor_mmap_t *mapping;
2093 crypto_rand(buf, buflen);
2095 write_str_to_file(fname1, "Short file.", 1);
2096 write_bytes_to_file(fname2, buf, buflen, 1);
2097 write_bytes_to_file(fname3, buf, 16384, 1);
2099 mapping = tor_mmap_file(fname1);
2100 test_assert(mapping);
2101 test_eq(mapping->size, strlen("Short file."));
2102 test_streq(mapping->data, "Short file.");
2103 #ifdef MS_WINDOWS
2104 tor_munmap_file(mapping);
2105 test_assert(unlink(fname1) == 0);
2106 #else
2107 /* make sure we can unlink. */
2108 test_assert(unlink(fname1) == 0);
2109 test_streq(mapping->data, "Short file.");
2110 tor_munmap_file(mapping);
2111 #endif
2113 /* Now a zero-length file. */
2114 write_str_to_file(fname1, "", 1);
2115 mapping = tor_mmap_file(fname1);
2116 test_eq(mapping, NULL);
2117 test_eq(ERANGE, errno);
2118 unlink(fname1);
2120 /* Make sure that we fail to map a no-longer-existent file. */
2121 mapping = tor_mmap_file(fname1);
2122 test_assert(mapping == NULL);
2124 /* Now try a big file that stretches across a few pages and isn't aligned */
2125 mapping = tor_mmap_file(fname2);
2126 test_assert(mapping);
2127 test_eq(mapping->size, buflen);
2128 test_memeq(mapping->data, buf, buflen);
2129 tor_munmap_file(mapping);
2131 /* Now try a big aligned file. */
2132 mapping = tor_mmap_file(fname3);
2133 test_assert(mapping);
2134 test_eq(mapping->size, 16384);
2135 test_memeq(mapping->data, buf, 16384);
2136 tor_munmap_file(mapping);
2138 /* fname1 got unlinked above */
2139 unlink(fname2);
2140 unlink(fname3);
2142 tor_free(fname1);
2143 tor_free(fname2);
2144 tor_free(fname3);
2145 tor_free(buf);
2148 static void
2149 test_util_control_formats(void)
2151 char *out;
2152 const char *inp =
2153 "..This is a test\r\nof the emergency \nbroadcast\r\n..system.\r\nZ.\r\n";
2154 size_t sz;
2156 sz = read_escaped_data(inp, strlen(inp), &out);
2157 test_streq(out,
2158 ".This is a test\nof the emergency \nbroadcast\n.system.\nZ.\n");
2159 test_eq(sz, strlen(out));
2161 tor_free(out);
2164 static void
2165 test_onion_handshake(void)
2167 /* client-side */
2168 crypto_dh_env_t *c_dh = NULL;
2169 char c_buf[ONIONSKIN_CHALLENGE_LEN];
2170 char c_keys[40];
2172 /* server-side */
2173 char s_buf[ONIONSKIN_REPLY_LEN];
2174 char s_keys[40];
2176 /* shared */
2177 crypto_pk_env_t *pk = NULL;
2179 pk = pk_generate(0);
2181 /* client handshake 1. */
2182 memset(c_buf, 0, ONIONSKIN_CHALLENGE_LEN);
2183 test_assert(! onion_skin_create(pk, &c_dh, c_buf));
2185 /* server handshake */
2186 memset(s_buf, 0, ONIONSKIN_REPLY_LEN);
2187 memset(s_keys, 0, 40);
2188 test_assert(! onion_skin_server_handshake(c_buf, pk, NULL,
2189 s_buf, s_keys, 40));
2191 /* client handshake 2 */
2192 memset(c_keys, 0, 40);
2193 test_assert(! onion_skin_client_handshake(c_dh, s_buf, c_keys, 40));
2195 crypto_dh_free(c_dh);
2197 if (memcmp(c_keys, s_keys, 40)) {
2198 puts("Aiiiie");
2199 exit(1);
2201 test_memeq(c_keys, s_keys, 40);
2202 memset(s_buf, 0, 40);
2203 test_memneq(c_keys, s_buf, 40);
2204 crypto_free_pk_env(pk);
2207 extern smartlist_t *fingerprint_list;
2209 static void
2210 test_dir_format(void)
2212 char buf[8192], buf2[8192];
2213 char platform[256];
2214 char fingerprint[FINGERPRINT_LEN+1];
2215 char *pk1_str = NULL, *pk2_str = NULL, *pk3_str = NULL, *cp;
2216 size_t pk1_str_len, pk2_str_len, pk3_str_len;
2217 routerinfo_t *r1, *r2;
2218 crypto_pk_env_t *pk1 = NULL, *pk2 = NULL, *pk3 = NULL;
2219 routerinfo_t *rp1 = NULL, *rp2 = NULL;
2220 addr_policy_t *ex1, *ex2;
2221 routerlist_t *dir1 = NULL, *dir2 = NULL;
2222 tor_version_t ver1;
2224 pk1 = pk_generate(0);
2225 pk2 = pk_generate(1);
2226 pk3 = pk_generate(2);
2228 test_assert( is_legal_nickname("a"));
2229 test_assert(!is_legal_nickname(""));
2230 test_assert(!is_legal_nickname("abcdefghijklmnopqrst")); /* 20 chars */
2231 test_assert(!is_legal_nickname("hyphen-")); /* bad char */
2232 test_assert( is_legal_nickname("abcdefghijklmnopqrs")); /* 19 chars */
2233 test_assert(!is_legal_nickname("$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2234 /* valid */
2235 test_assert( is_legal_nickname_or_hexdigest(
2236 "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2237 test_assert( is_legal_nickname_or_hexdigest(
2238 "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA=fred"));
2239 test_assert( is_legal_nickname_or_hexdigest(
2240 "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA~fred"));
2241 /* too short */
2242 test_assert(!is_legal_nickname_or_hexdigest(
2243 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2244 /* illegal char */
2245 test_assert(!is_legal_nickname_or_hexdigest(
2246 "$AAAAAAzAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2247 /* hex part too long */
2248 test_assert(!is_legal_nickname_or_hexdigest(
2249 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
2250 test_assert(!is_legal_nickname_or_hexdigest(
2251 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=fred"));
2252 /* Bad nickname */
2253 test_assert(!is_legal_nickname_or_hexdigest(
2254 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="));
2255 test_assert(!is_legal_nickname_or_hexdigest(
2256 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~"));
2257 test_assert(!is_legal_nickname_or_hexdigest(
2258 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~hyphen-"));
2259 test_assert(!is_legal_nickname_or_hexdigest(
2260 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~"
2261 "abcdefghijklmnoppqrst"));
2262 /* Bad extra char. */
2263 test_assert(!is_legal_nickname_or_hexdigest(
2264 "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA!"));
2265 test_assert(is_legal_nickname_or_hexdigest("xyzzy"));
2266 test_assert(is_legal_nickname_or_hexdigest("abcdefghijklmnopqrs"));
2267 test_assert(!is_legal_nickname_or_hexdigest("abcdefghijklmnopqrst"));
2269 get_platform_str(platform, sizeof(platform));
2270 r1 = tor_malloc_zero(sizeof(routerinfo_t));
2271 r1->address = tor_strdup("18.244.0.1");
2272 r1->addr = 0xc0a80001u; /* 192.168.0.1 */
2273 r1->cache_info.published_on = 0;
2274 r1->or_port = 9000;
2275 r1->dir_port = 9003;
2276 r1->onion_pkey = crypto_pk_dup_key(pk1);
2277 r1->identity_pkey = crypto_pk_dup_key(pk2);
2278 r1->bandwidthrate = 1000;
2279 r1->bandwidthburst = 5000;
2280 r1->bandwidthcapacity = 10000;
2281 r1->exit_policy = NULL;
2282 r1->nickname = tor_strdup("Magri");
2283 r1->platform = tor_strdup(platform);
2285 ex1 = tor_malloc_zero(sizeof(addr_policy_t));
2286 ex2 = tor_malloc_zero(sizeof(addr_policy_t));
2287 ex1->policy_type = ADDR_POLICY_ACCEPT;
2288 ex1->addr = 0;
2289 ex1->maskbits = 0;
2290 ex1->prt_min = ex1->prt_max = 80;
2291 ex2->policy_type = ADDR_POLICY_REJECT;
2292 ex2->addr = 18 << 24;
2293 ex2->maskbits = 8;
2294 ex2->prt_min = ex2->prt_max = 24;
2295 r2 = tor_malloc_zero(sizeof(routerinfo_t));
2296 r2->address = tor_strdup("1.1.1.1");
2297 r2->addr = 0x0a030201u; /* 10.3.2.1 */
2298 r2->platform = tor_strdup(platform);
2299 r2->cache_info.published_on = 5;
2300 r2->or_port = 9005;
2301 r2->dir_port = 0;
2302 r2->onion_pkey = crypto_pk_dup_key(pk2);
2303 r2->identity_pkey = crypto_pk_dup_key(pk1);
2304 r2->bandwidthrate = r2->bandwidthburst = r2->bandwidthcapacity = 3000;
2305 r2->exit_policy = smartlist_create();
2306 smartlist_add(r2->exit_policy, ex2);
2307 smartlist_add(r2->exit_policy, ex1);
2308 r2->nickname = tor_strdup("Fred");
2310 test_assert(!crypto_pk_write_public_key_to_string(pk1, &pk1_str,
2311 &pk1_str_len));
2312 test_assert(!crypto_pk_write_public_key_to_string(pk2 , &pk2_str,
2313 &pk2_str_len));
2314 test_assert(!crypto_pk_write_public_key_to_string(pk3 , &pk3_str,
2315 &pk3_str_len));
2317 memset(buf, 0, 2048);
2318 test_assert(router_dump_router_to_string(buf, 2048, r1, pk2)>0);
2320 strlcpy(buf2, "router Magri 18.244.0.1 9000 0 9003\n"
2321 "platform Tor "VERSION" on ", sizeof(buf2));
2322 strlcat(buf2, get_uname(), sizeof(buf2));
2323 strlcat(buf2, "\n"
2324 "opt protocols Link 1 Circuit 1\n"
2325 "published 1970-01-01 00:00:00\n"
2326 "opt fingerprint ", sizeof(buf2));
2327 test_assert(!crypto_pk_get_fingerprint(pk2, fingerprint, 1));
2328 strlcat(buf2, fingerprint, sizeof(buf2));
2329 strlcat(buf2, "\nuptime 0\n"
2330 /* XXX the "0" above is hardcoded, but even if we made it reflect
2331 * uptime, that still wouldn't make it right, because the two
2332 * descriptors might be made on different seconds... hm. */
2333 "bandwidth 1000 5000 10000\n"
2334 "opt extra-info-digest 0000000000000000000000000000000000000000\n"
2335 "onion-key\n", sizeof(buf2));
2336 strlcat(buf2, pk1_str, sizeof(buf2));
2337 strlcat(buf2, "signing-key\n", sizeof(buf2));
2338 strlcat(buf2, pk2_str, sizeof(buf2));
2339 strlcat(buf2, "reject *:*\nrouter-signature\n", sizeof(buf2));
2340 buf[strlen(buf2)] = '\0'; /* Don't compare the sig; it's never the same
2341 * twice */
2343 test_streq(buf, buf2);
2345 test_assert(router_dump_router_to_string(buf, 2048, r1, pk2)>0);
2346 cp = buf;
2347 rp1 = router_parse_entry_from_string((const char*)cp,NULL,1,0,NULL);
2348 test_assert(rp1);
2349 test_streq(rp1->address, r1->address);
2350 test_eq(rp1->or_port, r1->or_port);
2351 //test_eq(rp1->dir_port, r1->dir_port);
2352 test_eq(rp1->bandwidthrate, r1->bandwidthrate);
2353 test_eq(rp1->bandwidthburst, r1->bandwidthburst);
2354 test_eq(rp1->bandwidthcapacity, r1->bandwidthcapacity);
2355 test_assert(crypto_pk_cmp_keys(rp1->onion_pkey, pk1) == 0);
2356 test_assert(crypto_pk_cmp_keys(rp1->identity_pkey, pk2) == 0);
2357 //test_assert(rp1->exit_policy == NULL);
2359 #if 0
2360 /* XXX Once we have exit policies, test this again. XXX */
2361 strlcpy(buf2, "router tor.tor.tor 9005 0 0 3000\n", sizeof(buf2));
2362 strlcat(buf2, pk2_str, sizeof(buf2));
2363 strlcat(buf2, "signing-key\n", sizeof(buf2));
2364 strlcat(buf2, pk1_str, sizeof(buf2));
2365 strlcat(buf2, "accept *:80\nreject 18.*:24\n\n", sizeof(buf2));
2366 test_assert(router_dump_router_to_string(buf, 2048, &r2, pk2)>0);
2367 test_streq(buf, buf2);
2369 cp = buf;
2370 rp2 = router_parse_entry_from_string(&cp,1);
2371 test_assert(rp2);
2372 test_streq(rp2->address, r2.address);
2373 test_eq(rp2->or_port, r2.or_port);
2374 test_eq(rp2->dir_port, r2.dir_port);
2375 test_eq(rp2->bandwidth, r2.bandwidth);
2376 test_assert(crypto_pk_cmp_keys(rp2->onion_pkey, pk2) == 0);
2377 test_assert(crypto_pk_cmp_keys(rp2->identity_pkey, pk1) == 0);
2378 test_eq(rp2->exit_policy->policy_type, EXIT_POLICY_ACCEPT);
2379 test_streq(rp2->exit_policy->string, "accept *:80");
2380 test_streq(rp2->exit_policy->address, "*");
2381 test_streq(rp2->exit_policy->port, "80");
2382 test_eq(rp2->exit_policy->next->policy_type, EXIT_POLICY_REJECT);
2383 test_streq(rp2->exit_policy->next->string, "reject 18.*:24");
2384 test_streq(rp2->exit_policy->next->address, "18.*");
2385 test_streq(rp2->exit_policy->next->port, "24");
2386 test_assert(rp2->exit_policy->next->next == NULL);
2388 /* Okay, now for the directories. */
2390 fingerprint_list = smartlist_create();
2391 crypto_pk_get_fingerprint(pk2, buf, 1);
2392 add_fingerprint_to_dir("Magri", buf, fingerprint_list);
2393 crypto_pk_get_fingerprint(pk1, buf, 1);
2394 add_fingerprint_to_dir("Fred", buf, fingerprint_list);
2398 char d[DIGEST_LEN];
2399 const char *m;
2400 /* XXXX NM re-enable. */
2401 /* Make sure routers aren't too far in the past any more. */
2402 r1->cache_info.published_on = time(NULL);
2403 r2->cache_info.published_on = time(NULL)-3*60*60;
2404 test_assert(router_dump_router_to_string(buf, 2048, r1, pk2)>0);
2405 test_eq(dirserv_add_descriptor(buf,&m), 2);
2406 test_assert(router_dump_router_to_string(buf, 2048, r2, pk1)>0);
2407 test_eq(dirserv_add_descriptor(buf,&m), 2);
2408 get_options()->Nickname = tor_strdup("DirServer");
2409 test_assert(!dirserv_dump_directory_to_string(&cp,pk3, 0));
2410 crypto_pk_get_digest(pk3, d);
2411 test_assert(!router_parse_directory(cp));
2412 test_eq(2, smartlist_len(dir1->routers));
2413 tor_free(cp);
2415 #endif
2416 dirserv_free_fingerprint_list();
2418 tor_free(pk1_str);
2419 tor_free(pk2_str);
2420 tor_free(pk3_str);
2421 if (pk1) crypto_free_pk_env(pk1);
2422 if (pk2) crypto_free_pk_env(pk2);
2423 if (pk3) crypto_free_pk_env(pk3);
2424 if (rp1) routerinfo_free(rp1);
2425 if (rp2) routerinfo_free(rp2);
2426 tor_free(dir1); /* XXXX And more !*/
2427 tor_free(dir2); /* And more !*/
2428 routerinfo_free(r1);
2429 routerinfo_free(r2);
2431 /* Try out version parsing functionality */
2432 test_eq(0, tor_version_parse("0.3.4pre2-cvs", &ver1));
2433 test_eq(0, ver1.major);
2434 test_eq(3, ver1.minor);
2435 test_eq(4, ver1.micro);
2436 test_eq(VER_PRE, ver1.status);
2437 test_eq(2, ver1.patchlevel);
2438 test_eq(0, tor_version_parse("0.3.4rc1", &ver1));
2439 test_eq(0, ver1.major);
2440 test_eq(3, ver1.minor);
2441 test_eq(4, ver1.micro);
2442 test_eq(VER_RC, ver1.status);
2443 test_eq(1, ver1.patchlevel);
2444 test_eq(0, tor_version_parse("1.3.4", &ver1));
2445 test_eq(1, ver1.major);
2446 test_eq(3, ver1.minor);
2447 test_eq(4, ver1.micro);
2448 test_eq(VER_RELEASE, ver1.status);
2449 test_eq(0, ver1.patchlevel);
2450 test_eq(0, tor_version_parse("1.3.4.999", &ver1));
2451 test_eq(1, ver1.major);
2452 test_eq(3, ver1.minor);
2453 test_eq(4, ver1.micro);
2454 test_eq(VER_RELEASE, ver1.status);
2455 test_eq(999, ver1.patchlevel);
2456 test_eq(0, tor_version_parse("0.1.2.4-alpha", &ver1));
2457 test_eq(0, ver1.major);
2458 test_eq(1, ver1.minor);
2459 test_eq(2, ver1.micro);
2460 test_eq(4, ver1.patchlevel);
2461 test_eq(VER_RELEASE, ver1.status);
2462 test_streq("alpha", ver1.status_tag);
2463 test_eq(0, tor_version_parse("0.1.2.4", &ver1));
2464 test_eq(0, ver1.major);
2465 test_eq(1, ver1.minor);
2466 test_eq(2, ver1.micro);
2467 test_eq(4, ver1.patchlevel);
2468 test_eq(VER_RELEASE, ver1.status);
2469 test_streq("", ver1.status_tag);
2471 #define test_eq_vs(vs1, vs2) test_eq_type(version_status_t, "%d", (vs1), (vs2))
2472 #define test_v_i_o(val, ver, lst) \
2473 test_eq_vs(val, tor_version_is_obsolete(ver, lst))
2475 /* make sure tor_version_is_obsolete() works */
2476 test_v_i_o(VS_OLD, "0.0.1", "Tor 0.0.2");
2477 test_v_i_o(VS_OLD, "0.0.1", "0.0.2, Tor 0.0.3");
2478 test_v_i_o(VS_OLD, "0.0.1", "0.0.2,Tor 0.0.3");
2479 test_v_i_o(VS_OLD, "0.0.1","0.0.3,BetterTor 0.0.1");
2480 test_v_i_o(VS_RECOMMENDED, "0.0.2", "Tor 0.0.2,Tor 0.0.3");
2481 test_v_i_o(VS_NEW_IN_SERIES, "0.0.2", "Tor 0.0.2pre1,Tor 0.0.3");
2482 test_v_i_o(VS_OLD, "0.0.2", "Tor 0.0.2.1,Tor 0.0.3");
2483 test_v_i_o(VS_NEW, "0.1.0", "Tor 0.0.2,Tor 0.0.3");
2484 test_v_i_o(VS_RECOMMENDED, "0.0.7rc2", "0.0.7,Tor 0.0.7rc2,Tor 0.0.8");
2485 test_v_i_o(VS_OLD, "0.0.5.0", "0.0.5.1-cvs");
2486 test_v_i_o(VS_NEW_IN_SERIES, "0.0.5.1-cvs", "0.0.5, 0.0.6");
2487 /* Not on list, but newer than any in same series. */
2488 test_v_i_o(VS_NEW_IN_SERIES, "0.1.0.3",
2489 "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
2490 /* Series newer than any on list. */
2491 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");
2492 /* Series older than any on list. */
2493 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");
2494 /* Not on list, not newer than any on same series. */
2495 test_v_i_o(VS_UNRECOMMENDED, "0.1.0.1",
2496 "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
2497 /* On list, not newer than any on same series. */
2498 test_v_i_o(VS_UNRECOMMENDED,
2499 "0.1.0.1", "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
2500 test_eq(0, tor_version_as_new_as("Tor 0.0.5", "0.0.9pre1-cvs"));
2501 test_eq(1, tor_version_as_new_as(
2502 "Tor 0.0.8 on Darwin 64-121-192-100.c3-0."
2503 "sfpo-ubr1.sfrn-sfpo.ca.cable.rcn.com Power Macintosh",
2504 "0.0.8rc2"));
2505 test_eq(0, tor_version_as_new_as(
2506 "Tor 0.0.8 on Darwin 64-121-192-100.c3-0."
2507 "sfpo-ubr1.sfrn-sfpo.ca.cable.rcn.com Power Macintosh", "0.0.8.2"));
2509 /* Now try svn revisions. */
2510 test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100)",
2511 "Tor 0.2.1.0-dev (r99)"));
2512 test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100) on Banana Jr",
2513 "Tor 0.2.1.0-dev (r99) on Hal 9000"));
2514 test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100)",
2515 "Tor 0.2.1.0-dev on Colossus"));
2516 test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev (r99)",
2517 "Tor 0.2.1.0-dev (r100)"));
2518 test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev (r99) on MCP",
2519 "Tor 0.2.1.0-dev (r100) on AM"));
2520 test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev",
2521 "Tor 0.2.1.0-dev (r99)"));
2522 test_eq(1, tor_version_as_new_as("Tor 0.2.1.1",
2523 "Tor 0.2.1.0-dev (r99)"));
2526 extern const char AUTHORITY_CERT_1[];
2527 extern const char AUTHORITY_SIGNKEY_1[];
2528 extern const char AUTHORITY_CERT_2[];
2529 extern const char AUTHORITY_SIGNKEY_2[];
2530 extern const char AUTHORITY_CERT_3[];
2531 extern const char AUTHORITY_SIGNKEY_3[];
2533 static void
2534 test_same_voter(networkstatus_voter_info_t *v1,
2535 networkstatus_voter_info_t *v2)
2537 test_streq(v1->nickname, v2->nickname);
2538 test_memeq(v1->identity_digest, v2->identity_digest, DIGEST_LEN);
2539 test_streq(v1->address, v2->address);
2540 test_eq(v1->addr, v2->addr);
2541 test_eq(v1->dir_port, v2->dir_port);
2542 test_eq(v1->or_port, v2->or_port);
2543 test_streq(v1->contact, v2->contact);
2544 test_memeq(v1->vote_digest, v2->vote_digest, DIGEST_LEN);
2547 static void
2548 test_util_order_functions(void)
2550 int lst[25], n = 0;
2551 // int a=12,b=24,c=25,d=60,e=77;
2553 #define median() median_int(lst, n)
2555 lst[n++] = 12;
2556 test_eq(12, median()); /* 12 */
2557 lst[n++] = 77;
2558 //smartlist_shuffle(sl);
2559 test_eq(12, median()); /* 12, 77 */
2560 lst[n++] = 77;
2561 //smartlist_shuffle(sl);
2562 test_eq(77, median()); /* 12, 77, 77 */
2563 lst[n++] = 24;
2564 test_eq(24, median()); /* 12,24,77,77 */
2565 lst[n++] = 60;
2566 lst[n++] = 12;
2567 lst[n++] = 25;
2568 //smartlist_shuffle(sl);
2569 test_eq(25, median()); /* 12,12,24,25,60,77,77 */
2570 #undef median
2573 static void
2574 test_v3_networkstatus(void)
2576 authority_cert_t *cert1, *cert2, *cert3;
2577 crypto_pk_env_t *sign_skey_1, *sign_skey_2, *sign_skey_3;
2579 time_t now = time(NULL);
2580 networkstatus_voter_info_t *voter;
2581 networkstatus_t *vote, *v1, *v2, *v3, *con;
2582 vote_routerstatus_t *vrs;
2583 routerstatus_t *rs;
2584 char *v1_text, *v2_text, *v3_text, *consensus_text, *cp;
2585 smartlist_t *votes = smartlist_create();
2587 /* Parse certificates and keys. */
2588 cert1 = authority_cert_parse_from_string(AUTHORITY_CERT_1, NULL);
2589 test_assert(cert1);
2590 cert2 = authority_cert_parse_from_string(AUTHORITY_CERT_2, NULL);
2591 test_assert(cert2);
2592 cert3 = authority_cert_parse_from_string(AUTHORITY_CERT_3, NULL);
2593 test_assert(cert3);
2594 sign_skey_1 = crypto_new_pk_env();
2595 sign_skey_2 = crypto_new_pk_env();
2596 sign_skey_3 = crypto_new_pk_env();
2598 test_assert(!crypto_pk_read_private_key_from_string(sign_skey_1,
2599 AUTHORITY_SIGNKEY_1));
2600 test_assert(!crypto_pk_read_private_key_from_string(sign_skey_2,
2601 AUTHORITY_SIGNKEY_2));
2602 test_assert(!crypto_pk_read_private_key_from_string(sign_skey_3,
2603 AUTHORITY_SIGNKEY_3));
2605 test_assert(!crypto_pk_cmp_keys(sign_skey_1, cert1->signing_key));
2606 test_assert(!crypto_pk_cmp_keys(sign_skey_2, cert2->signing_key));
2609 * Set up a vote; generate it; try to parse it.
2611 vote = tor_malloc_zero(sizeof(networkstatus_t));
2612 vote->is_vote = 1;
2613 vote->published = now;
2614 vote->valid_after = now+1000;
2615 vote->fresh_until = now+2000;
2616 vote->valid_until = now+3000;
2617 vote->vote_seconds = 100;
2618 vote->dist_seconds = 200;
2619 vote->client_versions = tor_strdup("0.1.2.14,0.1.2.15");
2620 vote->server_versions = tor_strdup("0.1.2.14,0.1.2.15,0.1.2.16");
2621 vote->known_flags = smartlist_create();
2622 smartlist_split_string(vote->known_flags,
2623 "Authority Exit Fast Guard Running Stable V2Dir Valid",
2624 0, SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
2625 vote->voters = smartlist_create();
2626 voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
2627 voter->nickname = tor_strdup("Voter1");
2628 voter->address = tor_strdup("1.2.3.4");
2629 voter->addr = 0x01020304;
2630 voter->dir_port = 80;
2631 voter->or_port = 9000;
2632 voter->contact = tor_strdup("voter@example.com");
2633 crypto_pk_get_digest(cert1->identity_key, voter->identity_digest);
2634 smartlist_add(vote->voters, voter);
2635 vote->cert = authority_cert_dup(cert1);
2636 vote->routerstatus_list = smartlist_create();
2637 /* add the first routerstatus. */
2638 vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
2639 rs = &vrs->status;
2640 vrs->version = tor_strdup("0.1.2.14");
2641 rs->published_on = now-1500;
2642 strlcpy(rs->nickname, "router2", sizeof(rs->nickname));
2643 memset(rs->identity_digest, 3, DIGEST_LEN);
2644 memset(rs->descriptor_digest, 78, DIGEST_LEN);
2645 rs->addr = 0x99008801;
2646 rs->or_port = 443;
2647 rs->dir_port = 8000;
2648 /* all flags cleared */
2649 smartlist_add(vote->routerstatus_list, vrs);
2650 /* add the second routerstatus. */
2651 vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
2652 rs = &vrs->status;
2653 vrs->version = tor_strdup("0.2.0.5");
2654 rs->published_on = now-1000;
2655 strlcpy(rs->nickname, "router1", sizeof(rs->nickname));
2656 memset(rs->identity_digest, 5, DIGEST_LEN);
2657 memset(rs->descriptor_digest, 77, DIGEST_LEN);
2658 rs->addr = 0x99009901;
2659 rs->or_port = 443;
2660 rs->dir_port = 0;
2661 rs->is_exit = rs->is_stable = rs->is_fast = rs->is_running =
2662 rs->is_valid = rs->is_v2_dir = rs->is_possible_guard = 1;
2663 smartlist_add(vote->routerstatus_list, vrs);
2664 /* add the third routerstatus. */
2665 vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
2666 rs = &vrs->status;
2667 vrs->version = tor_strdup("0.1.0.3");
2668 rs->published_on = now-1000;
2669 strlcpy(rs->nickname, "router3", sizeof(rs->nickname));
2670 memset(rs->identity_digest, 33, DIGEST_LEN);
2671 memset(rs->descriptor_digest, 78, DIGEST_LEN);
2672 rs->addr = 0xAA009901;
2673 rs->or_port = 400;
2674 rs->dir_port = 9999;
2675 rs->is_authority = rs->is_exit = rs->is_stable = rs->is_fast =
2676 rs->is_running = rs->is_valid = rs->is_v2_dir = rs->is_possible_guard = 1;
2677 smartlist_add(vote->routerstatus_list, vrs);
2679 /* dump the vote and try to parse it. */
2680 v1_text = format_networkstatus_vote(sign_skey_1, vote);
2681 test_assert(v1_text);
2682 v1 = networkstatus_parse_vote_from_string(v1_text, NULL, 1);
2683 test_assert(v1);
2685 /* Make sure the parsed thing was right. */
2686 test_eq(v1->is_vote, 1);
2687 test_eq(v1->published, vote->published);
2688 test_eq(v1->valid_after, vote->valid_after);
2689 test_eq(v1->fresh_until, vote->fresh_until);
2690 test_eq(v1->valid_until, vote->valid_until);
2691 test_eq(v1->vote_seconds, vote->vote_seconds);
2692 test_eq(v1->dist_seconds, vote->dist_seconds);
2693 test_streq(v1->client_versions, vote->client_versions);
2694 test_streq(v1->server_versions, vote->server_versions);
2695 test_assert(v1->voters && smartlist_len(v1->voters));
2696 voter = smartlist_get(v1->voters, 0);
2697 test_streq(voter->nickname, "Voter1");
2698 test_streq(voter->address, "1.2.3.4");
2699 test_eq(voter->addr, 0x01020304);
2700 test_eq(voter->dir_port, 80);
2701 test_eq(voter->or_port, 9000);
2702 test_streq(voter->contact, "voter@example.com");
2703 test_assert(v1->cert);
2704 test_assert(!crypto_pk_cmp_keys(sign_skey_1, v1->cert->signing_key));
2705 cp = smartlist_join_strings(v1->known_flags, ":", 0, NULL);
2706 test_streq(cp, "Authority:Exit:Fast:Guard:Running:Stable:V2Dir:Valid");
2707 tor_free(cp);
2708 test_eq(smartlist_len(v1->routerstatus_list), 3);
2709 /* Check the first routerstatus. */
2710 vrs = smartlist_get(v1->routerstatus_list, 0);
2711 rs = &vrs->status;
2712 test_streq(vrs->version, "0.1.2.14");
2713 test_eq(rs->published_on, now-1500);
2714 test_streq(rs->nickname, "router2");
2715 test_memeq(rs->identity_digest,
2716 "\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3",
2717 DIGEST_LEN);
2718 test_memeq(rs->descriptor_digest, "NNNNNNNNNNNNNNNNNNNN", DIGEST_LEN);
2719 test_eq(rs->addr, 0x99008801);
2720 test_eq(rs->or_port, 443);
2721 test_eq(rs->dir_port, 8000);
2722 test_eq(vrs->flags, U64_LITERAL(0));
2723 /* Check the second routerstatus. */
2724 vrs = smartlist_get(v1->routerstatus_list, 1);
2725 rs = &vrs->status;
2726 test_streq(vrs->version, "0.2.0.5");
2727 test_eq(rs->published_on, now-1000);
2728 test_streq(rs->nickname, "router1");
2729 test_memeq(rs->identity_digest,
2730 "\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5",
2731 DIGEST_LEN);
2732 test_memeq(rs->descriptor_digest, "MMMMMMMMMMMMMMMMMMMM", DIGEST_LEN);
2733 test_eq(rs->addr, 0x99009901);
2734 test_eq(rs->or_port, 443);
2735 test_eq(rs->dir_port, 0);
2736 test_eq(vrs->flags, U64_LITERAL(254)); // all flags except "authority."
2738 /* Generate second vote. It disagrees on some of the times,
2739 * and doesn't list versions, and knows some crazy flags */
2740 vote->published = now+1;
2741 vote->fresh_until = now+3005;
2742 vote->dist_seconds = 300;
2743 authority_cert_free(vote->cert);
2744 vote->cert = authority_cert_dup(cert2);
2745 tor_free(vote->client_versions);
2746 tor_free(vote->server_versions);
2747 voter = smartlist_get(vote->voters, 0);
2748 tor_free(voter->nickname);
2749 tor_free(voter->address);
2750 voter->nickname = tor_strdup("Voter2");
2751 voter->address = tor_strdup("2.3.4.5");
2752 voter->addr = 0x02030405;
2753 crypto_pk_get_digest(cert2->identity_key, voter->identity_digest);
2754 smartlist_add(vote->known_flags, tor_strdup("MadeOfCheese"));
2755 smartlist_add(vote->known_flags, tor_strdup("MadeOfTin"));
2756 smartlist_sort_strings(vote->known_flags);
2757 vrs = smartlist_get(vote->routerstatus_list, 2);
2758 smartlist_del_keeporder(vote->routerstatus_list, 2);
2759 tor_free(vrs->version);
2760 tor_free(vrs);
2761 vrs = smartlist_get(vote->routerstatus_list, 0);
2762 vrs->status.is_fast = 1;
2763 /* generate and parse. */
2764 v2_text = format_networkstatus_vote(sign_skey_2, vote);
2765 test_assert(v2_text);
2766 v2 = networkstatus_parse_vote_from_string(v2_text, NULL, 1);
2767 test_assert(v2);
2768 /* Check that flags come out right.*/
2769 cp = smartlist_join_strings(v2->known_flags, ":", 0, NULL);
2770 test_streq(cp, "Authority:Exit:Fast:Guard:MadeOfCheese:MadeOfTin:"
2771 "Running:Stable:V2Dir:Valid");
2772 tor_free(cp);
2773 vrs = smartlist_get(v2->routerstatus_list, 1);
2774 /* 1023 - authority(1) - madeofcheese(16) - madeoftin(32) */
2775 test_eq(vrs->flags, U64_LITERAL(974));
2777 /* Generate the third vote. */
2778 vote->published = now;
2779 vote->fresh_until = now+2003;
2780 vote->dist_seconds = 250;
2781 authority_cert_free(vote->cert);
2782 vote->cert = authority_cert_dup(cert3);
2783 vote->client_versions = tor_strdup("0.1.2.14,0.1.2.17");
2784 vote->server_versions = tor_strdup("0.1.2.10,0.1.2.15,0.1.2.16");
2785 voter = smartlist_get(vote->voters, 0);
2786 tor_free(voter->nickname);
2787 tor_free(voter->address);
2788 voter->nickname = tor_strdup("Voter3");
2789 voter->address = tor_strdup("3.4.5.6");
2790 voter->addr = 0x03040506;
2791 crypto_pk_get_digest(cert3->identity_key, voter->identity_digest);
2792 vrs = smartlist_get(vote->routerstatus_list, 0);
2793 smartlist_del_keeporder(vote->routerstatus_list, 0);
2794 tor_free(vrs->version);
2795 tor_free(vrs);
2796 vrs = smartlist_get(vote->routerstatus_list, 0);
2797 memset(vrs->status.descriptor_digest, (int)'Z', DIGEST_LEN);
2799 v3_text = format_networkstatus_vote(sign_skey_3, vote);
2800 test_assert(v3_text);
2802 v3 = networkstatus_parse_vote_from_string(v3_text, NULL, 1);
2803 test_assert(v3);
2805 /* Compute a consensus as voter 3. */
2806 smartlist_add(votes, v3);
2807 smartlist_add(votes, v1);
2808 smartlist_add(votes, v2);
2809 consensus_text = networkstatus_compute_consensus(votes, 3,
2810 cert3->identity_key,
2811 sign_skey_3);
2812 test_assert(consensus_text);
2813 con = networkstatus_parse_vote_from_string(consensus_text, NULL, 0);
2814 test_assert(con);
2815 //log_notice(LD_GENERAL, "<<%s>>\n<<%s>>\n<<%s>>\n",
2816 // v1_text, v2_text, v3_text);
2818 /* Check consensus contents. */
2819 test_assert(!con->is_vote);
2820 test_eq(con->published, 0); /* this field only appears in votes. */
2821 test_eq(con->valid_after, now+1000);
2822 test_eq(con->fresh_until, now+2003); /* median */
2823 test_eq(con->valid_until, now+3000);
2824 test_eq(con->vote_seconds, 100);
2825 test_eq(con->dist_seconds, 250); /* median */
2826 test_streq(con->client_versions, "0.1.2.14");
2827 test_streq(con->server_versions, "0.1.2.15,0.1.2.16");
2828 cp = smartlist_join_strings(v2->known_flags, ":", 0, NULL);
2829 test_streq(cp, "Authority:Exit:Fast:Guard:MadeOfCheese:MadeOfTin:"
2830 "Running:Stable:V2Dir:Valid");
2831 tor_free(cp);
2832 test_eq(3, smartlist_len(con->voters));
2833 /* The voter id digests should be in this order. */
2834 test_assert(memcmp(cert2->cache_info.identity_digest,
2835 cert3->cache_info.identity_digest,DIGEST_LEN)<0);
2836 test_assert(memcmp(cert3->cache_info.identity_digest,
2837 cert1->cache_info.identity_digest,DIGEST_LEN)<0);
2838 test_same_voter(smartlist_get(con->voters, 0),
2839 smartlist_get(v2->voters, 0));
2840 test_same_voter(smartlist_get(con->voters, 1),
2841 smartlist_get(v3->voters, 0));
2842 test_same_voter(smartlist_get(con->voters, 2),
2843 smartlist_get(v1->voters, 0));
2845 test_assert(!con->cert);
2846 test_eq(2, smartlist_len(con->routerstatus_list));
2847 /* There should be two listed routers: one with identity 3, one with
2848 * identity 5. */
2849 /* This one showed up in 2 digests. */
2850 rs = smartlist_get(con->routerstatus_list, 0);
2851 test_memeq(rs->identity_digest,
2852 "\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3",
2853 DIGEST_LEN);
2854 test_memeq(rs->descriptor_digest, "NNNNNNNNNNNNNNNNNNNN", DIGEST_LEN);
2855 test_assert(!rs->is_authority);
2856 test_assert(!rs->is_exit);
2857 test_assert(!rs->is_fast);
2858 test_assert(!rs->is_possible_guard);
2859 test_assert(!rs->is_stable);
2860 test_assert(!rs->is_running);
2861 test_assert(!rs->is_v2_dir);
2862 test_assert(!rs->is_valid);
2863 test_assert(!rs->is_named);
2864 /* XXXX check version */
2866 rs = smartlist_get(con->routerstatus_list, 1);
2867 /* This one showed up in 3 digests. Twice with ID 'M', once with 'Z'. */
2868 test_memeq(rs->identity_digest,
2869 "\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5",
2870 DIGEST_LEN);
2871 test_streq(rs->nickname, "router1");
2872 test_memeq(rs->descriptor_digest, "MMMMMMMMMMMMMMMMMMMM", DIGEST_LEN);
2873 test_eq(rs->published_on, now-1000);
2874 test_eq(rs->addr, 0x99009901);
2875 test_eq(rs->or_port, 443);
2876 test_eq(rs->dir_port, 0);
2877 test_assert(!rs->is_authority);
2878 test_assert(rs->is_exit);
2879 test_assert(rs->is_fast);
2880 test_assert(rs->is_possible_guard);
2881 test_assert(rs->is_stable);
2882 test_assert(rs->is_running);
2883 test_assert(rs->is_v2_dir);
2884 test_assert(rs->is_valid);
2885 test_assert(!rs->is_named);
2886 /* XXXX check version */
2888 /* Check signatures. the first voter hasn't got one. The second one
2889 * does: validate it. */
2890 voter = smartlist_get(con->voters, 0);
2891 test_assert(!voter->signature);
2892 test_assert(!voter->good_signature);
2893 test_assert(!voter->bad_signature);
2895 voter = smartlist_get(con->voters, 1);
2896 test_assert(voter->signature);
2897 test_assert(!voter->good_signature);
2898 test_assert(!voter->bad_signature);
2899 test_assert(!networkstatus_check_voter_signature(con,
2900 smartlist_get(con->voters, 1),
2901 cert3));
2902 test_assert(voter->signature);
2903 test_assert(voter->good_signature);
2904 test_assert(!voter->bad_signature);
2907 char *consensus_text2, *consensus_text3;
2908 networkstatus_t *con2, *con3;
2909 char *detached_text1, *detached_text2;
2910 ns_detached_signatures_t *dsig1, *dsig2;
2911 const char *msg=NULL;
2912 /* Compute the other two signed consensuses. */
2913 smartlist_shuffle(votes);
2914 consensus_text2 = networkstatus_compute_consensus(votes, 3,
2915 cert2->identity_key,
2916 sign_skey_2);
2917 smartlist_shuffle(votes);
2918 consensus_text3 = networkstatus_compute_consensus(votes, 3,
2919 cert1->identity_key,
2920 sign_skey_1);
2921 test_assert(consensus_text2);
2922 test_assert(consensus_text3);
2923 con2 = networkstatus_parse_vote_from_string(consensus_text2, NULL, 0);
2924 con3 = networkstatus_parse_vote_from_string(consensus_text3, NULL, 0);
2925 test_assert(con2);
2926 test_assert(con3);
2928 /* All three should have the same digest. */
2929 test_memeq(con->networkstatus_digest, con2->networkstatus_digest,
2930 DIGEST_LEN);
2931 test_memeq(con->networkstatus_digest, con3->networkstatus_digest,
2932 DIGEST_LEN);
2934 /* Extract a detached signature from con3. */
2935 detached_text1 = networkstatus_get_detached_signatures(con3);
2936 tor_assert(detached_text1);
2937 /* Try to parse it. */
2938 dsig1 = networkstatus_parse_detached_signatures(detached_text1, NULL);
2939 tor_assert(dsig1);
2941 /* Are parsed values as expected? */
2942 test_eq(dsig1->valid_after, con3->valid_after);
2943 test_eq(dsig1->fresh_until, con3->fresh_until);
2944 test_eq(dsig1->valid_until, con3->valid_until);
2945 test_memeq(dsig1->networkstatus_digest, con3->networkstatus_digest,
2946 DIGEST_LEN);
2947 test_eq(1, smartlist_len(dsig1->signatures));
2948 voter = smartlist_get(dsig1->signatures, 0);
2949 test_memeq(voter->identity_digest, cert1->cache_info.identity_digest,
2950 DIGEST_LEN);
2952 /* Try adding it to con2. */
2953 detached_text2 = networkstatus_get_detached_signatures(con2);
2954 test_eq(1, networkstatus_add_detached_signatures(con2, dsig1, &msg));
2955 tor_free(detached_text2);
2956 detached_text2 = networkstatus_get_detached_signatures(con2);
2957 //printf("\n<%s>\n", detached_text2);
2958 dsig2 = networkstatus_parse_detached_signatures(detached_text2, NULL);
2959 test_assert(dsig2);
2961 printf("\n");
2962 SMARTLIST_FOREACH(dsig2->signatures, networkstatus_voter_info_t *, vi, {
2963 char hd[64];
2964 base16_encode(hd, sizeof(hd), vi->identity_digest, DIGEST_LEN);
2965 printf("%s\n", hd);
2968 test_eq(2, smartlist_len(dsig2->signatures));
2970 /* Try adding to con2 twice; verify that nothing changes. */
2971 test_eq(0, networkstatus_add_detached_signatures(con2, dsig1, &msg));
2973 /* Add to con. */
2974 test_eq(2, networkstatus_add_detached_signatures(con, dsig2, &msg));
2975 /* Check signatures */
2976 test_assert(!networkstatus_check_voter_signature(con,
2977 smartlist_get(con->voters, 0),
2978 cert2));
2979 test_assert(!networkstatus_check_voter_signature(con,
2980 smartlist_get(con->voters, 2),
2981 cert1));
2983 networkstatus_vote_free(con2);
2984 networkstatus_vote_free(con3);
2985 tor_free(consensus_text2);
2986 tor_free(consensus_text3);
2987 tor_free(detached_text1);
2988 tor_free(detached_text2);
2989 ns_detached_signatures_free(dsig1);
2990 ns_detached_signatures_free(dsig2);
2993 smartlist_free(votes);
2994 tor_free(v1_text);
2995 tor_free(v2_text);
2996 tor_free(v3_text);
2997 tor_free(consensus_text);
2998 networkstatus_vote_free(vote);
2999 networkstatus_vote_free(v1);
3000 networkstatus_vote_free(v2);
3001 networkstatus_vote_free(v3);
3002 networkstatus_vote_free(con);
3003 crypto_free_pk_env(sign_skey_1);
3004 crypto_free_pk_env(sign_skey_2);
3005 crypto_free_pk_env(sign_skey_3);
3006 authority_cert_free(cert1);
3007 authority_cert_free(cert2);
3008 authority_cert_free(cert3);
3011 static void
3012 test_policies(void)
3014 smartlist_t *policy, *policy2;
3015 addr_policy_t *p;
3016 tor_addr_t tar;
3017 config_line_t line;
3019 policy = smartlist_create();
3021 p = router_parse_addr_policy_item_from_string("reject 192.168.0.0/16:*",-1);
3022 test_eq(ADDR_POLICY_REJECT, p->policy_type);
3023 tor_addr_from_ipv4(&tar, 0xc0a80000u);
3024 test_assert(p->addr == 0xc0a80000u);
3025 test_eq(16, p->maskbits);
3026 test_eq(1, p->prt_min);
3027 test_eq(65535, p->prt_max);
3029 smartlist_add(policy, p);
3031 test_assert(ADDR_POLICY_ACCEPTED ==
3032 compare_addr_to_addr_policy(0x01020304u, 2, policy));
3033 test_assert(ADDR_POLICY_PROBABLY_ACCEPTED ==
3034 compare_addr_to_addr_policy(0, 2, policy));
3035 test_assert(ADDR_POLICY_REJECTED ==
3036 compare_addr_to_addr_policy(0xc0a80102, 2, policy));
3038 policy2 = NULL;
3039 test_assert(0 == policies_parse_exit_policy(NULL, &policy2, 1, NULL));
3040 test_assert(policy2);
3042 test_assert(!exit_policy_is_general_exit(policy));
3043 test_assert(exit_policy_is_general_exit(policy2));
3044 test_assert(!exit_policy_is_general_exit(NULL));
3046 test_assert(cmp_addr_policies(policy, policy2));
3047 test_assert(cmp_addr_policies(policy, NULL));
3048 test_assert(!cmp_addr_policies(policy2, policy2));
3049 test_assert(!cmp_addr_policies(NULL, NULL));
3051 test_assert(!policy_is_reject_star(policy2));
3052 test_assert(policy_is_reject_star(policy));
3053 test_assert(policy_is_reject_star(NULL));
3055 addr_policy_list_free(policy);
3056 addr_policy_list_free(policy2);
3058 /* make sure compacting logic works. */
3059 policy = NULL;
3060 line.key = (char*)"foo";
3061 line.value = (char*)"accept *:80,reject private:*,reject *:*";
3062 line.next = NULL;
3063 test_assert(0 == policies_parse_exit_policy(&line, &policy, 0, NULL));
3064 test_assert(policy);
3065 //test_streq(policy->string, "accept *:80");
3066 //test_streq(policy->next->string, "reject *:*");
3067 test_eq(smartlist_len(policy), 2);
3069 addr_policy_list_free(policy);
3072 static void
3073 test_rend_fns(void)
3075 char address1[] = "fooaddress.onion";
3076 char address2[] = "aaaaaaaaaaaaaaaa.onion";
3077 char address3[] = "fooaddress.exit";
3078 char address4[] = "www.torproject.org";
3079 rend_service_descriptor_t *d1, *d2;
3080 char *encoded;
3081 size_t len;
3082 crypto_pk_env_t *pk1, *pk2;
3083 time_t now;
3084 int i;
3085 pk1 = pk_generate(0);
3086 pk2 = pk_generate(1);
3088 /* Test unversioned (v0) descriptor */
3089 d1 = tor_malloc_zero(sizeof(rend_service_descriptor_t));
3090 d1->pk = crypto_pk_dup_key(pk1);
3091 now = time(NULL);
3092 d1->timestamp = now;
3093 d1->version = 0;
3094 d1->intro_nodes = smartlist_create();
3095 for (i = 0; i < 3; i++) {
3096 rend_intro_point_t *intro = tor_malloc_zero(sizeof(rend_intro_point_t));
3097 intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
3098 crypto_rand(intro->extend_info->identity_digest, DIGEST_LEN);
3099 intro->extend_info->nickname[0] = '$';
3100 base16_encode(intro->extend_info->nickname+1, HEX_DIGEST_LEN+1,
3101 intro->extend_info->identity_digest, DIGEST_LEN);
3102 smartlist_add(d1->intro_nodes, intro);
3104 test_assert(! rend_encode_service_descriptor(d1, pk1, &encoded, &len));
3105 d2 = rend_parse_service_descriptor(encoded, len);
3106 test_assert(d2);
3108 test_assert(!crypto_pk_cmp_keys(d1->pk, d2->pk));
3109 test_eq(d2->timestamp, now);
3110 test_eq(d2->version, 0);
3111 test_eq(d2->protocols, 1<<2);
3112 test_eq(smartlist_len(d2->intro_nodes), 3);
3113 for (i = 0; i < 3; i++) {
3114 rend_intro_point_t *intro1 = smartlist_get(d1->intro_nodes, i);
3115 rend_intro_point_t *intro2 = smartlist_get(d2->intro_nodes, i);
3116 test_streq(intro1->extend_info->nickname,
3117 intro2->extend_info->nickname);
3120 rend_service_descriptor_free(d1);
3121 rend_service_descriptor_free(d2);
3122 tor_free(encoded);
3124 test_assert(BAD_HOSTNAME == parse_extended_hostname(address1));
3125 test_assert(ONION_HOSTNAME == parse_extended_hostname(address2));
3126 test_assert(EXIT_HOSTNAME == parse_extended_hostname(address3));
3127 test_assert(NORMAL_HOSTNAME == parse_extended_hostname(address4));
3129 crypto_free_pk_env(pk1);
3130 crypto_free_pk_env(pk2);
3133 static void
3134 bench_aes(void)
3136 int len, i;
3137 char *b1, *b2;
3138 crypto_cipher_env_t *c;
3139 struct timeval start, end;
3140 const int iters = 100000;
3141 uint64_t nsec;
3142 c = crypto_new_cipher_env();
3143 crypto_cipher_generate_key(c);
3144 crypto_cipher_encrypt_init_cipher(c);
3145 for (len = 1; len <= 8192; len *= 2) {
3146 b1 = tor_malloc_zero(len);
3147 b2 = tor_malloc_zero(len);
3148 tor_gettimeofday(&start);
3149 for (i = 0; i < iters; ++i) {
3150 crypto_cipher_encrypt(c, b1, b2, len);
3152 tor_gettimeofday(&end);
3153 tor_free(b1);
3154 tor_free(b2);
3155 nsec = (uint64_t) tv_udiff(&start,&end);
3156 nsec *= 1000;
3157 nsec /= (iters*len);
3158 printf("%d bytes: "U64_FORMAT" nsec per byte\n", len,
3159 U64_PRINTF_ARG(nsec));
3161 crypto_free_cipher_env(c);
3164 static void
3165 test_util_mempool(void)
3167 mp_pool_t *pool;
3168 smartlist_t *allocated;
3169 int i;
3171 pool = mp_pool_new(1, 100);
3172 test_assert(pool->new_chunk_capacity >= 100);
3173 test_assert(pool->item_alloc_size >= sizeof(void*)+1);
3174 mp_pool_destroy(pool);
3176 pool = mp_pool_new(241, 2500);
3177 test_assert(pool->new_chunk_capacity >= 10);
3178 test_assert(pool->item_alloc_size >= sizeof(void*)+241);
3179 test_eq(pool->item_alloc_size & 0x03, 0);
3180 test_assert(pool->new_chunk_capacity < 60);
3182 allocated = smartlist_create();
3183 for (i = 0; i < 100000; ++i) {
3184 if (smartlist_len(allocated) < 20 || crypto_rand_int(2)) {
3185 void *m = mp_pool_get(pool);
3186 memset(m, 0x09, 241);
3187 smartlist_add(allocated, m);
3188 //printf("%d: %p\n", i, m);
3189 //mp_pool_assert_ok(pool);
3190 } else {
3191 int idx = crypto_rand_int(smartlist_len(allocated));
3192 void *m = smartlist_get(allocated, idx);
3193 //printf("%d: free %p\n", i, m);
3194 smartlist_del(allocated, idx);
3195 mp_pool_release(m);
3196 //mp_pool_assert_ok(pool);
3198 if (crypto_rand_int(777)==0)
3199 mp_pool_clean(pool, 1, 1);
3201 if (i % 777)
3202 mp_pool_assert_ok(pool);
3204 SMARTLIST_FOREACH(allocated, void *, m, mp_pool_release(m));
3205 mp_pool_assert_ok(pool);
3206 mp_pool_clean(pool, 0, 0);
3207 mp_pool_assert_ok(pool);
3208 mp_pool_destroy(pool);
3209 smartlist_free(allocated);
3212 static void
3213 test_util_datadir(void)
3215 char buf[1024];
3216 char *f;
3218 f = get_datadir_fname(NULL);
3219 test_streq(f, temp_dir);
3220 tor_free(f);
3221 f = get_datadir_fname("state");
3222 tor_snprintf(buf, sizeof(buf), "%s"PATH_SEPARATOR"state", temp_dir);
3223 test_streq(f, buf);
3224 tor_free(f);
3225 f = get_datadir_fname2("cache", "thingy");
3226 tor_snprintf(buf, sizeof(buf),
3227 "%s"PATH_SEPARATOR"cache"PATH_SEPARATOR"thingy", temp_dir);
3228 test_streq(f, buf);
3229 tor_free(f);
3230 f = get_datadir_fname2_suffix("cache", "thingy", ".foo");
3231 tor_snprintf(buf, sizeof(buf),
3232 "%s"PATH_SEPARATOR"cache"PATH_SEPARATOR"thingy.foo", temp_dir);
3233 test_streq(f, buf);
3234 tor_free(f);
3235 f = get_datadir_fname_suffix("cache", ".foo");
3236 tor_snprintf(buf, sizeof(buf), "%s"PATH_SEPARATOR"cache.foo",
3237 temp_dir);
3238 test_streq(f, buf);
3239 tor_free(f);
3242 /* Test AES-CTR encryption and decryption with IV. */
3243 static void
3244 test_crypto_aes_iv(void)
3246 crypto_cipher_env_t *cipher;
3247 char *plain, *encrypted1, *encrypted2, *decrypted1, *decrypted2;
3248 char plain_1[1], plain_15[15], plain_16[16], plain_17[17];
3249 char key1[16], key2[16];
3250 size_t encrypted_size, decrypted_size;
3251 plain = tor_malloc(4095);
3252 encrypted1 = tor_malloc(4095 + 1 + 16);
3253 encrypted2 = tor_malloc(4095 + 1 + 16);
3254 decrypted1 = tor_malloc(4095 + 1);
3255 decrypted2 = tor_malloc(4095 + 1);
3256 crypto_rand(plain, 4095);
3257 crypto_rand(key1, 16);
3258 crypto_rand(key2, 16);
3259 crypto_rand(plain_1, 1);
3260 crypto_rand(plain_15, 15);
3261 crypto_rand(plain_16, 16);
3262 crypto_rand(plain_17, 17);
3263 key1[0] = key2[0] + 128; /* Make sure that contents are different. */
3264 /* Encrypt and decrypt with the same key. */
3265 cipher = crypto_create_init_cipher(key1, 1);
3266 encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 4095,
3267 plain, 4095);
3268 crypto_free_cipher_env(cipher);
3269 test_eq(encrypted_size, 16 + 4095);
3270 cipher = crypto_create_init_cipher(key1, 0);
3271 decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 4095,
3272 encrypted1, encrypted_size);
3273 crypto_free_cipher_env(cipher);
3274 test_eq(decrypted_size, 4095);
3275 test_memeq(plain, decrypted1, 4095);
3276 /* Encrypt a second time (with a new random initialization vector). */
3277 cipher = crypto_create_init_cipher(key1, 1);
3278 encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted2, 16 + 4095,
3279 plain, 4095);
3280 crypto_free_cipher_env(cipher);
3281 test_eq(encrypted_size, 16 + 4095);
3282 cipher = crypto_create_init_cipher(key1, 0);
3283 decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted2, 4095,
3284 encrypted2, encrypted_size);
3285 crypto_free_cipher_env(cipher);
3286 test_eq(decrypted_size, 4095);
3287 test_memeq(plain, decrypted2, 4095);
3288 test_memneq(encrypted1, encrypted2, encrypted_size);
3289 /* Decrypt with the wrong key. */
3290 cipher = crypto_create_init_cipher(key2, 0);
3291 decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted2, 4095,
3292 encrypted1, encrypted_size);
3293 crypto_free_cipher_env(cipher);
3294 test_memneq(plain, decrypted2, encrypted_size);
3295 /* Alter the initialization vector. */
3296 encrypted1[0] += 42;
3297 cipher = crypto_create_init_cipher(key1, 0);
3298 decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 4095,
3299 encrypted1, encrypted_size);
3300 crypto_free_cipher_env(cipher);
3301 test_memneq(plain, decrypted2, 4095);
3302 /* Special length case: 1. */
3303 cipher = crypto_create_init_cipher(key1, 1);
3304 encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 1,
3305 plain_1, 1);
3306 crypto_free_cipher_env(cipher);
3307 test_eq(encrypted_size, 16 + 1);
3308 cipher = crypto_create_init_cipher(key1, 0);
3309 decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 1,
3310 encrypted1, encrypted_size);
3311 crypto_free_cipher_env(cipher);
3312 test_eq(decrypted_size, 1);
3313 test_memeq(plain_1, decrypted1, 1);
3314 /* Special length case: 15. */
3315 cipher = crypto_create_init_cipher(key1, 1);
3316 encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 15,
3317 plain_15, 15);
3318 crypto_free_cipher_env(cipher);
3319 test_eq(encrypted_size, 16 + 15);
3320 cipher = crypto_create_init_cipher(key1, 0);
3321 decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 15,
3322 encrypted1, encrypted_size);
3323 crypto_free_cipher_env(cipher);
3324 test_eq(decrypted_size, 15);
3325 test_memeq(plain_15, decrypted1, 15);
3326 /* Special length case: 16. */
3327 cipher = crypto_create_init_cipher(key1, 1);
3328 encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 16,
3329 plain_16, 16);
3330 crypto_free_cipher_env(cipher);
3331 test_eq(encrypted_size, 16 + 16);
3332 cipher = crypto_create_init_cipher(key1, 0);
3333 decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 16,
3334 encrypted1, encrypted_size);
3335 crypto_free_cipher_env(cipher);
3336 test_eq(decrypted_size, 16);
3337 test_memeq(plain_16, decrypted1, 16);
3338 /* Special length case: 17. */
3339 cipher = crypto_create_init_cipher(key1, 1);
3340 encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 17,
3341 plain_17, 17);
3342 crypto_free_cipher_env(cipher);
3343 test_eq(encrypted_size, 16 + 17);
3344 cipher = crypto_create_init_cipher(key1, 0);
3345 decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 17,
3346 encrypted1, encrypted_size);
3347 crypto_free_cipher_env(cipher);
3348 test_eq(decrypted_size, 17);
3349 test_memeq(plain_17, decrypted1, 17);
3350 /* Free memory. */
3351 tor_free(plain);
3352 tor_free(encrypted1);
3353 tor_free(encrypted2);
3354 tor_free(decrypted1);
3355 tor_free(decrypted2);
3358 /* Test base32 decoding. */
3359 static void
3360 test_crypto_base32_decode(void)
3362 char plain[60], encoded[96 + 1], decoded[60];
3363 int res;
3364 crypto_rand(plain, 60);
3365 /* Encode and decode a random string. */
3366 base32_encode(encoded, 96 + 1, plain, 60);
3367 res = base32_decode(decoded, 60, encoded, 96);
3368 test_eq(res, 0);
3369 test_memeq(plain, decoded, 60);
3370 /* Encode, uppercase, and decode a random string. */
3371 base32_encode(encoded, 96 + 1, plain, 60);
3372 tor_strupper(encoded);
3373 res = base32_decode(decoded, 60, encoded, 96);
3374 test_eq(res, 0);
3375 test_memeq(plain, decoded, 60);
3376 /* Change encoded string and decode. */
3377 if (encoded[0] == 'A' || encoded[0] == 'a')
3378 encoded[0] = 'B';
3379 else
3380 encoded[0] = 'A';
3381 res = base32_decode(decoded, 60, encoded, 96);
3382 test_eq(res, 0);
3383 test_memneq(plain, decoded, 60);
3386 /* Test encoding and parsing of v2 rendezvous service descriptors. */
3387 static void
3388 test_rend_fns_v2(void)
3390 rend_service_descriptor_t *generated, *parsed;
3391 char service_id[DIGEST_LEN];
3392 char service_id_base32[REND_SERVICE_ID_LEN_BASE32+1];
3393 const char *next_desc;
3394 smartlist_t *descs = smartlist_create();
3395 char computed_desc_id[DIGEST_LEN];
3396 char parsed_desc_id[DIGEST_LEN];
3397 crypto_pk_env_t *pk1, *pk2;
3398 time_t now;
3399 char *intro_points_encrypted;
3400 size_t intro_points_size;
3401 size_t encoded_size;
3402 int i;
3403 pk1 = pk_generate(0);
3404 pk2 = pk_generate(1);
3405 generated = tor_malloc_zero(sizeof(rend_service_descriptor_t));
3406 generated->pk = crypto_pk_dup_key(pk1);
3407 crypto_pk_get_digest(generated->pk, service_id);
3408 base32_encode(service_id_base32, REND_SERVICE_ID_LEN_BASE32+1,
3409 service_id, REND_SERVICE_ID_LEN);
3410 now = time(NULL);
3411 generated->timestamp = now;
3412 generated->version = 2;
3413 generated->protocols = 42;
3414 generated->intro_nodes = smartlist_create();
3415 for (i = 0; i < 3; i++) {
3416 rend_intro_point_t *intro = tor_malloc_zero(sizeof(rend_intro_point_t));
3417 crypto_pk_env_t *okey = pk_generate(2 + i);
3418 intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
3419 intro->extend_info->onion_key = crypto_pk_dup_key(okey);
3420 crypto_pk_get_digest(intro->extend_info->onion_key,
3421 intro->extend_info->identity_digest);
3422 //crypto_rand(info->identity_digest, DIGEST_LEN); /* Would this work? */
3423 intro->extend_info->nickname[0] = '$';
3424 base16_encode(intro->extend_info->nickname + 1,
3425 sizeof(intro->extend_info->nickname) - 1,
3426 intro->extend_info->identity_digest, DIGEST_LEN);
3427 intro->extend_info->addr = crypto_rand_int(65536); /* Does not cover all
3428 * IP addresses. */
3429 intro->extend_info->port = crypto_rand_int(65536);
3430 intro->intro_key = crypto_pk_dup_key(pk2);
3431 smartlist_add(generated->intro_nodes, intro);
3433 test_assert(rend_encode_v2_descriptors(descs, generated, now,
3434 NULL, 0) > 0);
3435 test_assert(rend_compute_v2_desc_id(computed_desc_id, service_id_base32,
3436 NULL, now, 0) == 0);
3437 test_memeq(((rend_encoded_v2_service_descriptor_t *)
3438 smartlist_get(descs, 0))->desc_id, computed_desc_id, DIGEST_LEN);
3439 test_assert(rend_parse_v2_service_descriptor(&parsed, parsed_desc_id,
3440 &intro_points_encrypted,
3441 &intro_points_size,
3442 &encoded_size,
3443 &next_desc,
3444 ((rend_encoded_v2_service_descriptor_t *)
3445 smartlist_get(descs, 0))->desc_str) == 0);
3446 test_assert(parsed);
3447 test_memeq(((rend_encoded_v2_service_descriptor_t *)
3448 smartlist_get(descs, 0))->desc_id, parsed_desc_id, DIGEST_LEN);
3449 test_assert(rend_decrypt_introduction_points(parsed, NULL,
3450 intro_points_encrypted,
3451 intro_points_size) == 3);
3452 test_assert(!crypto_pk_cmp_keys(generated->pk, parsed->pk));
3453 test_eq(parsed->timestamp, now);
3454 test_eq(parsed->version, 2);
3455 test_eq(parsed->protocols, 42);
3456 test_eq(smartlist_len(parsed->intro_nodes), 3);
3457 for (i = 0; i < smartlist_len(parsed->intro_nodes); i++) {
3458 rend_intro_point_t *par_intro = smartlist_get(parsed->intro_nodes, i),
3459 *gen_intro = smartlist_get(generated->intro_nodes, i);
3460 extend_info_t *par_info = par_intro->extend_info;
3461 extend_info_t *gen_info = gen_intro->extend_info;
3462 test_assert(!crypto_pk_cmp_keys(gen_info->onion_key, par_info->onion_key));
3463 test_memeq(gen_info->identity_digest, par_info->identity_digest,
3464 DIGEST_LEN);
3465 test_streq(gen_info->nickname, par_info->nickname);
3466 test_eq(gen_info->addr, par_info->addr);
3467 test_eq(gen_info->port, par_info->port);
3469 tor_free(intro_points_encrypted);
3470 for (i = 0; i < smartlist_len(descs); i++)
3471 rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
3472 smartlist_free(descs);
3473 rend_service_descriptor_free(parsed);
3474 rend_service_descriptor_free(generated);
3477 static void
3478 test_geoip(void)
3480 int i, j;
3481 time_t now = time(NULL);
3482 char *s;
3484 /* Populate the DB a bit. Add these in order, since we can't do the final
3485 * 'sort' step. These aren't very good IP addresses, but they're perfectly
3486 * fine uint32_t values. */
3487 test_eq(0, geoip_parse_entry("10,50,AB"));
3488 test_eq(0, geoip_parse_entry("52,90,XY"));
3489 test_eq(0, geoip_parse_entry("95,100,AB"));
3490 test_eq(0, geoip_parse_entry("\"105\",\"140\",\"ZZ\""));
3491 test_eq(0, geoip_parse_entry("\"150\",\"190\",\"XY\""));
3492 test_eq(0, geoip_parse_entry("\"200\",\"250\",\"AB\""));
3494 /* We should have 3 countries: ab, xy, zz. */
3495 test_eq(3, geoip_get_n_countries());
3496 /* Make sure that country ID actually works. */
3497 #define NAMEFOR(x) geoip_get_country_name(geoip_get_country_by_ip(x))
3498 test_streq("ab", NAMEFOR(32));
3499 test_streq("??", NAMEFOR(5));
3500 test_streq("??", NAMEFOR(51));
3501 test_streq("xy", NAMEFOR(150));
3502 test_streq("xy", NAMEFOR(190));
3503 test_streq("??", NAMEFOR(2000));
3504 #undef NAMEFOR
3506 get_options()->BridgeRelay = 1;
3507 get_options()->BridgeRecordUsageByCountry = 1;
3508 /* Put 9 observations in AB... */
3509 for (i=32; i < 40; ++i)
3510 geoip_note_client_seen(i, now);
3511 geoip_note_client_seen(225, now);
3512 /* and 3 observations in XY, several times. */
3513 for (j=0; j < 10; ++j)
3514 for (i=52; i < 55; ++i)
3515 geoip_note_client_seen(i, now-3600);
3516 /* and 17 observations in ZZ... */
3517 for (i=110; i < 127; ++i)
3518 geoip_note_client_seen(i, now-7200);
3519 s = geoip_get_client_history(now+5*24*60*60);
3520 test_assert(s);
3521 test_streq("zz=24,ab=16", s);
3522 tor_free(s);
3524 /* Now clear out all the zz observations. */
3525 geoip_remove_old_clients(now-6000);
3526 s = geoip_get_client_history(now+5*24*60*60);
3527 test_assert(! s); /* There are only 12 observations left. Not enough to
3528 build an answer. Add 4 more in XY... */
3529 for (i=55; i < 59; ++i)
3530 geoip_note_client_seen(i, now-3600);
3531 s = geoip_get_client_history(now+5*24*60*60);
3532 test_assert(s);
3533 test_streq("ab=16", s);
3534 tor_free(s);
3537 #define ENT(x) { #x, test_ ## x, 0, 0 }
3538 #define SUBENT(x,y) { #x "/" #y, test_ ## x ## _ ## y, 1, 0 }
3540 static struct {
3541 const char *test_name;
3542 void (*test_fn)(void);
3543 int is_subent;
3544 int selected;
3545 } test_array[] = {
3546 ENT(buffers),
3547 ENT(crypto),
3548 SUBENT(crypto, dh),
3549 SUBENT(crypto, s2k),
3550 SUBENT(crypto, aes_iv),
3551 SUBENT(crypto, base32_decode),
3552 ENT(util),
3553 SUBENT(util, ip6_helpers),
3554 SUBENT(util, gzip),
3555 SUBENT(util, datadir),
3556 SUBENT(util, smartlist),
3557 SUBENT(util, bitarray),
3558 SUBENT(util, mempool),
3559 SUBENT(util, strmap),
3560 SUBENT(util, control_formats),
3561 SUBENT(util, pqueue),
3562 SUBENT(util, mmap),
3563 SUBENT(util, threads),
3564 SUBENT(util, order_functions),
3565 ENT(onion_handshake),
3566 ENT(dir_format),
3567 ENT(v3_networkstatus),
3568 ENT(policies),
3569 ENT(rend_fns),
3570 SUBENT(rend_fns, v2),
3571 ENT(geoip),
3572 { NULL, NULL, 0, 0 },
3575 static void syntax(void) ATTR_NORETURN;
3576 static void
3577 syntax(void)
3579 int i;
3580 printf("Syntax:\n"
3581 " test [-v|--verbose] [--warn|--notice|--info|--debug]\n"
3582 " [testname...]\n"
3583 "Recognized tests are:\n");
3584 for (i = 0; test_array[i].test_name; ++i) {
3585 printf(" %s\n", test_array[i].test_name);
3588 exit(0);
3592 main(int c, char**v)
3594 or_options_t *options = options_new();
3595 char *errmsg = NULL;
3596 int i;
3597 int verbose = 0, any_selected = 0;
3598 int loglevel = LOG_ERR;
3600 init_logging();
3602 for (i = 1; i < c; ++i) {
3603 if (!strcmp(v[i], "-v") || !strcmp(v[i], "--verbose"))
3604 verbose++;
3605 else if (!strcmp(v[i], "--warn"))
3606 loglevel = LOG_WARN;
3607 else if (!strcmp(v[i], "--notice"))
3608 loglevel = LOG_NOTICE;
3609 else if (!strcmp(v[i], "--info"))
3610 loglevel = LOG_INFO;
3611 else if (!strcmp(v[i], "--debug"))
3612 loglevel = LOG_DEBUG;
3613 else if (!strcmp(v[i], "--help") || !strcmp(v[i], "-h") || v[i][0] == '-')
3614 syntax();
3615 else {
3616 int j, found=0;
3617 for (j = 0; test_array[j].test_name; ++j) {
3618 if (!strcmp(v[i], test_array[j].test_name) ||
3619 (test_array[j].is_subent &&
3620 !strcmpstart(test_array[j].test_name, v[i]) &&
3621 test_array[j].test_name[strlen(v[i])] == '/') ||
3622 (v[i][0] == '=' && !strcmp(v[i]+1, test_array[j].test_name))) {
3623 test_array[j].selected = 1;
3624 any_selected = 1;
3625 found = 1;
3628 if (!found) {
3629 printf("Unknown test: %s\n", v[i]);
3630 syntax();
3635 if (!any_selected) {
3636 for (i = 0; test_array[i].test_name; ++i) {
3637 test_array[i].selected = 1;
3642 log_severity_list_t *s = tor_malloc_zero(sizeof(log_severity_list_t));
3643 set_log_severity_config(loglevel, LOG_ERR, s);
3644 add_stream_log(s, "", stdout);
3647 options->command = CMD_RUN_UNITTESTS;
3648 rep_hist_init();
3649 network_init();
3650 setup_directory();
3651 options_init(options);
3652 options->DataDirectory = tor_strdup(temp_dir);
3653 if (set_options(options, &errmsg) < 0) {
3654 printf("Failed to set initial options: %s\n", errmsg);
3655 tor_free(errmsg);
3656 return 1;
3659 crypto_seed_rng(1);
3661 if (0) {
3662 bench_aes();
3663 return 0;
3666 atexit(remove_directory);
3668 printf("Running Tor unit tests on %s\n", get_uname());
3670 for (i = 0; test_array[i].test_name; ++i) {
3671 if (!test_array[i].selected)
3672 continue;
3673 if (!test_array[i].is_subent) {
3674 printf("\n============================== %s\n",test_array[i].test_name);
3675 } else if (test_array[i].is_subent && verbose) {
3676 printf("\n%s", test_array[i].test_name);
3678 test_array[i].test_fn();
3680 puts("");
3682 if (have_failed)
3683 return 1;
3684 else
3685 return 0;