test.c 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282
  1. /* Copyright (c) 2001-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2010, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /* Ordinarily defined in tor_main.c; this bit is just here to provide one
  6. * since we're not linking to tor_main.c */
  7. const char tor_git_revision[] = "";
  8. /**
  9. * \file test.c
  10. * \brief Unit tests for many pieces of the lower level Tor modules.
  11. **/
  12. #include "orconfig.h"
  13. #include <stdio.h>
  14. #ifdef HAVE_FCNTL_H
  15. #include <fcntl.h>
  16. #endif
  17. #ifdef MS_WINDOWS
  18. /* For mkdir() */
  19. #include <direct.h>
  20. #else
  21. #include <dirent.h>
  22. #endif
  23. /* These macros pull in declarations for some functions and structures that
  24. * are typically file-private. */
  25. #define BUFFERS_PRIVATE
  26. #define CONFIG_PRIVATE
  27. #define GEOIP_PRIVATE
  28. #define ROUTER_PRIVATE
  29. #define CIRCUIT_PRIVATE
  30. /*
  31. * Linux doesn't provide lround in math.h by default, but mac os does...
  32. * It's best just to leave math.h out of the picture entirely.
  33. */
  34. //#include <math.h>
  35. long int lround(double x);
  36. double fabs(double x);
  37. #include "or.h"
  38. #include "geoip.h"
  39. #include "rendcommon.h"
  40. #include "test.h"
  41. #include "torgzip.h"
  42. #include "mempool.h"
  43. #include "memarea.h"
  44. #ifdef USE_DMALLOC
  45. #include <dmalloc.h>
  46. #include <openssl/crypto.h>
  47. #endif
  48. /** Set to true if any unit test has failed. Mostly, this is set by the macros
  49. * in test.h */
  50. int have_failed = 0;
  51. /** Temporary directory (set up by setup_directory) under which we store all
  52. * our files during testing. */
  53. static char temp_dir[256];
  54. /** Select and create the temporary directory we'll use to run our unit tests.
  55. * Store it in <b>temp_dir</b>. Exit immediately if we can't create it.
  56. * idempotent. */
  57. static void
  58. setup_directory(void)
  59. {
  60. static int is_setup = 0;
  61. int r;
  62. if (is_setup) return;
  63. #ifdef MS_WINDOWS
  64. // XXXX
  65. tor_snprintf(temp_dir, sizeof(temp_dir),
  66. "c:\\windows\\temp\\tor_test_%d", (int)getpid());
  67. r = mkdir(temp_dir);
  68. #else
  69. tor_snprintf(temp_dir, sizeof(temp_dir), "/tmp/tor_test_%d", (int) getpid());
  70. r = mkdir(temp_dir, 0700);
  71. #endif
  72. if (r) {
  73. fprintf(stderr, "Can't create directory %s:", temp_dir);
  74. perror("");
  75. exit(1);
  76. }
  77. is_setup = 1;
  78. }
  79. /** Return a filename relative to our testing temporary directory */
  80. const char *
  81. get_fname(const char *name)
  82. {
  83. static char buf[1024];
  84. setup_directory();
  85. tor_snprintf(buf,sizeof(buf),"%s/%s",temp_dir,name);
  86. return buf;
  87. }
  88. /** Remove all files stored under the temporary directory, and the directory
  89. * itself. */
  90. static void
  91. remove_directory(void)
  92. {
  93. smartlist_t *elements = tor_listdir(temp_dir);
  94. if (elements) {
  95. SMARTLIST_FOREACH(elements, const char *, cp,
  96. {
  97. size_t len = strlen(cp)+strlen(temp_dir)+16;
  98. char *tmp = tor_malloc(len);
  99. tor_snprintf(tmp, len, "%s"PATH_SEPARATOR"%s", temp_dir, cp);
  100. unlink(tmp);
  101. tor_free(tmp);
  102. });
  103. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  104. smartlist_free(elements);
  105. }
  106. rmdir(temp_dir);
  107. }
  108. /** Define this if unit tests spend too much time generating public keys*/
  109. #undef CACHE_GENERATED_KEYS
  110. static crypto_pk_env_t *pregen_keys[5] = {NULL, NULL, NULL, NULL, NULL};
  111. #define N_PREGEN_KEYS ((int)(sizeof(pregen_keys)/sizeof(pregen_keys[0])))
  112. /** Generate and return a new keypair for use in unit tests. If we're using
  113. * the key cache optimization, we might reuse keys: we only guarantee that
  114. * keys made with distinct values for <b>idx</b> are different. The value of
  115. * <b>idx</b> must be at least 0, and less than N_PREGEN_KEYS. */
  116. crypto_pk_env_t *
  117. pk_generate(int idx)
  118. {
  119. #ifdef CACHE_GENERATED_KEYS
  120. tor_assert(idx < N_PREGEN_KEYS);
  121. if (! pregen_keys[idx]) {
  122. pregen_keys[idx] = crypto_new_pk_env();
  123. tor_assert(!crypto_pk_generate_key(pregen_keys[idx]));
  124. }
  125. return crypto_pk_dup_key(pregen_keys[idx]);
  126. #else
  127. crypto_pk_env_t *result;
  128. (void) idx;
  129. result = crypto_new_pk_env();
  130. tor_assert(!crypto_pk_generate_key(result));
  131. return result;
  132. #endif
  133. }
  134. /** Free all storage used for the cached key optimization. */
  135. static void
  136. free_pregenerated_keys(void)
  137. {
  138. unsigned idx;
  139. for (idx = 0; idx < N_PREGEN_KEYS; ++idx) {
  140. if (pregen_keys[idx]) {
  141. crypto_free_pk_env(pregen_keys[idx]);
  142. pregen_keys[idx] = NULL;
  143. }
  144. }
  145. }
  146. /** Run unit tests for buffers.c */
  147. static void
  148. test_buffers(void)
  149. {
  150. char str[256];
  151. char str2[256];
  152. buf_t *buf = NULL, *buf2 = NULL;
  153. const char *cp;
  154. int j;
  155. size_t r;
  156. /****
  157. * buf_new
  158. ****/
  159. if (!(buf = buf_new()))
  160. test_fail();
  161. //test_eq(buf_capacity(buf), 4096);
  162. test_eq(buf_datalen(buf), 0);
  163. /****
  164. * General pointer frobbing
  165. */
  166. for (j=0;j<256;++j) {
  167. str[j] = (char)j;
  168. }
  169. write_to_buf(str, 256, buf);
  170. write_to_buf(str, 256, buf);
  171. test_eq(buf_datalen(buf), 512);
  172. fetch_from_buf(str2, 200, buf);
  173. test_memeq(str, str2, 200);
  174. test_eq(buf_datalen(buf), 312);
  175. memset(str2, 0, sizeof(str2));
  176. fetch_from_buf(str2, 256, buf);
  177. test_memeq(str+200, str2, 56);
  178. test_memeq(str, str2+56, 200);
  179. test_eq(buf_datalen(buf), 56);
  180. memset(str2, 0, sizeof(str2));
  181. /* Okay, now we should be 512 bytes into the 4096-byte buffer. If we add
  182. * another 3584 bytes, we hit the end. */
  183. for (j=0;j<15;++j) {
  184. write_to_buf(str, 256, buf);
  185. }
  186. assert_buf_ok(buf);
  187. test_eq(buf_datalen(buf), 3896);
  188. fetch_from_buf(str2, 56, buf);
  189. test_eq(buf_datalen(buf), 3840);
  190. test_memeq(str+200, str2, 56);
  191. for (j=0;j<15;++j) {
  192. memset(str2, 0, sizeof(str2));
  193. fetch_from_buf(str2, 256, buf);
  194. test_memeq(str, str2, 256);
  195. }
  196. test_eq(buf_datalen(buf), 0);
  197. buf_free(buf);
  198. buf = NULL;
  199. /* Okay, now make sure growing can work. */
  200. buf = buf_new_with_capacity(16);
  201. //test_eq(buf_capacity(buf), 16);
  202. write_to_buf(str+1, 255, buf);
  203. //test_eq(buf_capacity(buf), 256);
  204. fetch_from_buf(str2, 254, buf);
  205. test_memeq(str+1, str2, 254);
  206. //test_eq(buf_capacity(buf), 256);
  207. assert_buf_ok(buf);
  208. write_to_buf(str, 32, buf);
  209. //test_eq(buf_capacity(buf), 256);
  210. assert_buf_ok(buf);
  211. write_to_buf(str, 256, buf);
  212. assert_buf_ok(buf);
  213. //test_eq(buf_capacity(buf), 512);
  214. test_eq(buf_datalen(buf), 33+256);
  215. fetch_from_buf(str2, 33, buf);
  216. test_eq(*str2, str[255]);
  217. test_memeq(str2+1, str, 32);
  218. //test_eq(buf_capacity(buf), 512);
  219. test_eq(buf_datalen(buf), 256);
  220. fetch_from_buf(str2, 256, buf);
  221. test_memeq(str, str2, 256);
  222. /* now try shrinking: case 1. */
  223. buf_free(buf);
  224. buf = buf_new_with_capacity(33668);
  225. for (j=0;j<67;++j) {
  226. write_to_buf(str,255, buf);
  227. }
  228. //test_eq(buf_capacity(buf), 33668);
  229. test_eq(buf_datalen(buf), 17085);
  230. for (j=0; j < 40; ++j) {
  231. fetch_from_buf(str2, 255,buf);
  232. test_memeq(str2, str, 255);
  233. }
  234. /* now try shrinking: case 2. */
  235. buf_free(buf);
  236. buf = buf_new_with_capacity(33668);
  237. for (j=0;j<67;++j) {
  238. write_to_buf(str,255, buf);
  239. }
  240. for (j=0; j < 20; ++j) {
  241. fetch_from_buf(str2, 255,buf);
  242. test_memeq(str2, str, 255);
  243. }
  244. for (j=0;j<80;++j) {
  245. write_to_buf(str,255, buf);
  246. }
  247. //test_eq(buf_capacity(buf),33668);
  248. for (j=0; j < 120; ++j) {
  249. fetch_from_buf(str2, 255,buf);
  250. test_memeq(str2, str, 255);
  251. }
  252. /* Move from buf to buf. */
  253. buf_free(buf);
  254. buf = buf_new_with_capacity(4096);
  255. buf2 = buf_new_with_capacity(4096);
  256. for (j=0;j<100;++j)
  257. write_to_buf(str, 255, buf);
  258. test_eq(buf_datalen(buf), 25500);
  259. for (j=0;j<100;++j) {
  260. r = 10;
  261. move_buf_to_buf(buf2, buf, &r);
  262. test_eq(r, 0);
  263. }
  264. test_eq(buf_datalen(buf), 24500);
  265. test_eq(buf_datalen(buf2), 1000);
  266. for (j=0;j<3;++j) {
  267. fetch_from_buf(str2, 255, buf2);
  268. test_memeq(str2, str, 255);
  269. }
  270. r = 8192; /*big move*/
  271. move_buf_to_buf(buf2, buf, &r);
  272. test_eq(r, 0);
  273. r = 30000; /* incomplete move */
  274. move_buf_to_buf(buf2, buf, &r);
  275. test_eq(r, 13692);
  276. for (j=0;j<97;++j) {
  277. fetch_from_buf(str2, 255, buf2);
  278. test_memeq(str2, str, 255);
  279. }
  280. buf_free(buf);
  281. buf_free(buf2);
  282. buf = buf2 = NULL;
  283. buf = buf_new_with_capacity(5);
  284. cp = "Testing. This is a moderately long Testing string.";
  285. for (j = 0; cp[j]; j++)
  286. write_to_buf(cp+j, 1, buf);
  287. test_eq(0, buf_find_string_offset(buf, "Testing", 7));
  288. test_eq(1, buf_find_string_offset(buf, "esting", 6));
  289. test_eq(1, buf_find_string_offset(buf, "est", 3));
  290. test_eq(39, buf_find_string_offset(buf, "ing str", 7));
  291. test_eq(35, buf_find_string_offset(buf, "Testing str", 11));
  292. test_eq(32, buf_find_string_offset(buf, "ng ", 3));
  293. test_eq(43, buf_find_string_offset(buf, "string.", 7));
  294. test_eq(-1, buf_find_string_offset(buf, "shrdlu", 6));
  295. test_eq(-1, buf_find_string_offset(buf, "Testing thing", 13));
  296. test_eq(-1, buf_find_string_offset(buf, "ngx", 3));
  297. buf_free(buf);
  298. buf = NULL;
  299. #if 0
  300. {
  301. int s;
  302. int eof;
  303. int i;
  304. buf_t *buf2;
  305. /****
  306. * read_to_buf
  307. ****/
  308. s = open(get_fname("data"), O_WRONLY|O_CREAT|O_TRUNC, 0600);
  309. write(s, str, 256);
  310. close(s);
  311. s = open(get_fname("data"), O_RDONLY, 0);
  312. eof = 0;
  313. errno = 0; /* XXXX */
  314. i = read_to_buf(s, 10, buf, &eof);
  315. printf("%s\n", strerror(errno));
  316. test_eq(i, 10);
  317. test_eq(eof, 0);
  318. //test_eq(buf_capacity(buf), 4096);
  319. test_eq(buf_datalen(buf), 10);
  320. test_memeq(str, (char*)_buf_peek_raw_buffer(buf), 10);
  321. /* Test reading 0 bytes. */
  322. i = read_to_buf(s, 0, buf, &eof);
  323. //test_eq(buf_capacity(buf), 512*1024);
  324. test_eq(buf_datalen(buf), 10);
  325. test_eq(eof, 0);
  326. test_eq(i, 0);
  327. /* Now test when buffer is filled exactly. */
  328. buf2 = buf_new_with_capacity(6);
  329. i = read_to_buf(s, 6, buf2, &eof);
  330. //test_eq(buf_capacity(buf2), 6);
  331. test_eq(buf_datalen(buf2), 6);
  332. test_eq(eof, 0);
  333. test_eq(i, 6);
  334. test_memeq(str+10, (char*)_buf_peek_raw_buffer(buf2), 6);
  335. buf_free(buf2);
  336. buf2 = NULL;
  337. /* Now test when buffer is filled with more data to read. */
  338. buf2 = buf_new_with_capacity(32);
  339. i = read_to_buf(s, 128, buf2, &eof);
  340. //test_eq(buf_capacity(buf2), 128);
  341. test_eq(buf_datalen(buf2), 32);
  342. test_eq(eof, 0);
  343. test_eq(i, 32);
  344. buf_free(buf2);
  345. buf2 = NULL;
  346. /* Now read to eof. */
  347. test_assert(buf_capacity(buf) > 256);
  348. i = read_to_buf(s, 1024, buf, &eof);
  349. test_eq(i, (256-32-10-6));
  350. test_eq(buf_capacity(buf), MAX_BUF_SIZE);
  351. test_eq(buf_datalen(buf), 256-6-32);
  352. test_memeq(str, (char*)_buf_peek_raw_buffer(buf), 10); /* XXX Check rest. */
  353. test_eq(eof, 0);
  354. i = read_to_buf(s, 1024, buf, &eof);
  355. test_eq(i, 0);
  356. test_eq(buf_capacity(buf), MAX_BUF_SIZE);
  357. test_eq(buf_datalen(buf), 256-6-32);
  358. test_eq(eof, 1);
  359. }
  360. #endif
  361. done:
  362. if (buf)
  363. buf_free(buf);
  364. if (buf2)
  365. buf_free(buf2);
  366. }
  367. /** Run unit tests for the onion handshake code. */
  368. static void
  369. test_onion_handshake(void)
  370. {
  371. /* client-side */
  372. crypto_dh_env_t *c_dh = NULL;
  373. char c_buf[ONIONSKIN_CHALLENGE_LEN];
  374. char c_keys[40];
  375. /* server-side */
  376. char s_buf[ONIONSKIN_REPLY_LEN];
  377. char s_keys[40];
  378. /* shared */
  379. crypto_pk_env_t *pk = NULL;
  380. pk = pk_generate(0);
  381. /* client handshake 1. */
  382. memset(c_buf, 0, ONIONSKIN_CHALLENGE_LEN);
  383. test_assert(! onion_skin_create(pk, &c_dh, c_buf));
  384. /* server handshake */
  385. memset(s_buf, 0, ONIONSKIN_REPLY_LEN);
  386. memset(s_keys, 0, 40);
  387. test_assert(! onion_skin_server_handshake(c_buf, pk, NULL,
  388. s_buf, s_keys, 40));
  389. /* client handshake 2 */
  390. memset(c_keys, 0, 40);
  391. test_assert(! onion_skin_client_handshake(c_dh, s_buf, c_keys, 40));
  392. if (memcmp(c_keys, s_keys, 40)) {
  393. puts("Aiiiie");
  394. exit(1);
  395. }
  396. test_memeq(c_keys, s_keys, 40);
  397. memset(s_buf, 0, 40);
  398. test_memneq(c_keys, s_buf, 40);
  399. done:
  400. if (c_dh)
  401. crypto_dh_free(c_dh);
  402. if (pk)
  403. crypto_free_pk_env(pk);
  404. }
  405. static void
  406. test_circuit_timeout(void)
  407. {
  408. /* Plan:
  409. * 1. Generate 1000 samples
  410. * 2. Estimate parameters
  411. * 3. If difference, repeat
  412. * 4. Save state
  413. * 5. load state
  414. * 6. Estimate parameters
  415. * 7. compare differences
  416. */
  417. circuit_build_times_t initial;
  418. circuit_build_times_t estimate;
  419. circuit_build_times_t final;
  420. double timeout1, timeout2;
  421. or_state_t state;
  422. char *msg;
  423. int i, runs;
  424. double close_ms;
  425. circuit_build_times_init(&initial);
  426. circuit_build_times_init(&estimate);
  427. circuit_build_times_init(&final);
  428. memset(&state, 0, sizeof(or_state_t));
  429. circuitbuild_running_unit_tests();
  430. #define timeout0 (build_time_t)(30*1000.0)
  431. initial.Xm = 3000;
  432. circuit_build_times_initial_alpha(&initial,
  433. CBT_DEFAULT_QUANTILE_CUTOFF/100.0,
  434. timeout0);
  435. close_ms = MAX(circuit_build_times_calculate_timeout(&initial,
  436. CBT_DEFAULT_CLOSE_QUANTILE/100.0),
  437. CBT_DEFAULT_TIMEOUT_INITIAL_VALUE);
  438. do {
  439. for (i=0; i < CBT_DEFAULT_MIN_CIRCUITS_TO_OBSERVE; i++) {
  440. build_time_t sample = circuit_build_times_generate_sample(&initial,0,1);
  441. if (sample > close_ms) {
  442. circuit_build_times_add_time(&estimate, CBT_BUILD_ABANDONED);
  443. } else {
  444. circuit_build_times_add_time(&estimate, sample);
  445. }
  446. }
  447. circuit_build_times_update_alpha(&estimate);
  448. timeout1 = circuit_build_times_calculate_timeout(&estimate,
  449. CBT_DEFAULT_QUANTILE_CUTOFF/100.0);
  450. circuit_build_times_set_timeout(&estimate);
  451. log_notice(LD_CIRC, "Timeout1 is %lf, Xm is %d", timeout1, estimate.Xm);
  452. /* 2% error */
  453. } while (fabs(circuit_build_times_cdf(&initial, timeout0) -
  454. circuit_build_times_cdf(&initial, timeout1)) > 0.02);
  455. test_assert(estimate.total_build_times <= CBT_NCIRCUITS_TO_OBSERVE);
  456. circuit_build_times_update_state(&estimate, &state);
  457. test_assert(circuit_build_times_parse_state(&final, &state, &msg) == 0);
  458. circuit_build_times_update_alpha(&final);
  459. timeout2 = circuit_build_times_calculate_timeout(&final,
  460. CBT_DEFAULT_QUANTILE_CUTOFF/100.0);
  461. circuit_build_times_set_timeout(&final);
  462. log_notice(LD_CIRC, "Timeout2 is %lf, Xm is %d", timeout2, final.Xm);
  463. /* 5% here because some accuracy is lost due to histogram conversion */
  464. test_assert(fabs(circuit_build_times_cdf(&initial, timeout0) -
  465. circuit_build_times_cdf(&initial, timeout2)) < 0.05);
  466. for (runs = 0; runs < 50; runs++) {
  467. int build_times_idx = 0;
  468. int total_build_times = 0;
  469. final.close_ms = final.timeout_ms = CBT_DEFAULT_TIMEOUT_INITIAL_VALUE;
  470. estimate.close_ms = estimate.timeout_ms
  471. = CBT_DEFAULT_TIMEOUT_INITIAL_VALUE;
  472. for (i = 0; i < CBT_DEFAULT_RECENT_CIRCUITS*2; i++) {
  473. circuit_build_times_network_circ_success(&estimate);
  474. circuit_build_times_add_time(&estimate,
  475. circuit_build_times_generate_sample(&estimate, 0,
  476. CBT_DEFAULT_QUANTILE_CUTOFF/100.0));
  477. circuit_build_times_network_circ_success(&estimate);
  478. circuit_build_times_add_time(&final,
  479. circuit_build_times_generate_sample(&final, 0,
  480. CBT_DEFAULT_QUANTILE_CUTOFF/100.0));
  481. }
  482. test_assert(!circuit_build_times_network_check_changed(&estimate));
  483. test_assert(!circuit_build_times_network_check_changed(&final));
  484. /* Reset liveness to be non-live */
  485. final.liveness.network_last_live = 0;
  486. estimate.liveness.network_last_live = 0;
  487. build_times_idx = estimate.build_times_idx;
  488. total_build_times = estimate.total_build_times;
  489. for (i = 0; i < CBT_NETWORK_NONLIVE_TIMEOUT_COUNT; i++) {
  490. test_assert(circuit_build_times_network_check_live(&estimate));
  491. test_assert(circuit_build_times_network_check_live(&final));
  492. circuit_build_times_count_close(&estimate, 0,
  493. (time_t)(approx_time()-estimate.close_ms/1000.0-1));
  494. circuit_build_times_count_close(&final, 0,
  495. (time_t)(approx_time()-final.close_ms/1000.0-1));
  496. }
  497. test_assert(!circuit_build_times_network_check_live(&estimate));
  498. test_assert(!circuit_build_times_network_check_live(&final));
  499. for ( ; i < CBT_NETWORK_NONLIVE_DISCARD_COUNT; i++) {
  500. circuit_build_times_count_close(&estimate, 0,
  501. (time_t)(approx_time()-estimate.close_ms/1000.0-1));
  502. if (i < CBT_NETWORK_NONLIVE_DISCARD_COUNT-1) {
  503. circuit_build_times_count_close(&final, 0,
  504. (time_t)(approx_time()-final.close_ms/1000.0-1));
  505. }
  506. }
  507. test_assert(!circuit_build_times_network_check_live(&estimate));
  508. test_assert(!circuit_build_times_network_check_live(&final));
  509. log_info(LD_CIRC, "idx: %d %d, tot: %d %d",
  510. build_times_idx, estimate.build_times_idx,
  511. total_build_times, estimate.total_build_times);
  512. /* Check rollback index. Should match top of loop. */
  513. test_assert(build_times_idx == estimate.build_times_idx);
  514. // This can fail if estimate.total_build_times == 1000, because
  515. // in that case, rewind actually causes us to lose timeouts
  516. if (total_build_times != CBT_NCIRCUITS_TO_OBSERVE)
  517. test_assert(total_build_times == estimate.total_build_times);
  518. /* Now simulate that the network has become live and we need
  519. * a change */
  520. circuit_build_times_network_is_live(&estimate);
  521. circuit_build_times_network_is_live(&final);
  522. for (i = 0; i < CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT; i++) {
  523. circuit_build_times_count_timeout(&estimate, 1);
  524. if (i < CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT-1) {
  525. circuit_build_times_count_timeout(&final, 1);
  526. }
  527. }
  528. test_assert(estimate.liveness.after_firsthop_idx == 0);
  529. test_assert(final.liveness.after_firsthop_idx ==
  530. CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT-1);
  531. test_assert(circuit_build_times_network_check_live(&estimate));
  532. test_assert(circuit_build_times_network_check_live(&final));
  533. circuit_build_times_count_timeout(&final, 1);
  534. }
  535. done:
  536. return;
  537. }
  538. /** Helper: Parse the exit policy string in <b>policy_str</b>, and make sure
  539. * that policies_summarize() produces the string <b>expected_summary</b> from
  540. * it. */
  541. static void
  542. test_policy_summary_helper(const char *policy_str,
  543. const char *expected_summary)
  544. {
  545. config_line_t line;
  546. smartlist_t *policy = smartlist_create();
  547. char *summary = NULL;
  548. int r;
  549. line.key = (char*)"foo";
  550. line.value = (char *)policy_str;
  551. line.next = NULL;
  552. r = policies_parse_exit_policy(&line, &policy, 0, NULL, 1);
  553. test_eq(r, 0);
  554. summary = policy_summarize(policy);
  555. test_assert(summary != NULL);
  556. test_streq(summary, expected_summary);
  557. done:
  558. tor_free(summary);
  559. if (policy)
  560. addr_policy_list_free(policy);
  561. }
  562. /** Run unit tests for generating summary lines of exit policies */
  563. static void
  564. test_policies(void)
  565. {
  566. int i;
  567. smartlist_t *policy = NULL, *policy2 = NULL, *policy3 = NULL,
  568. *policy4 = NULL, *policy5 = NULL, *policy6 = NULL,
  569. *policy7 = NULL;
  570. addr_policy_t *p;
  571. tor_addr_t tar;
  572. config_line_t line;
  573. smartlist_t *sm = NULL;
  574. char *policy_str = NULL;
  575. policy = smartlist_create();
  576. p = router_parse_addr_policy_item_from_string("reject 192.168.0.0/16:*",-1);
  577. test_assert(p != NULL);
  578. test_eq(ADDR_POLICY_REJECT, p->policy_type);
  579. tor_addr_from_ipv4h(&tar, 0xc0a80000u);
  580. test_eq(0, tor_addr_compare(&p->addr, &tar, CMP_EXACT));
  581. test_eq(16, p->maskbits);
  582. test_eq(1, p->prt_min);
  583. test_eq(65535, p->prt_max);
  584. smartlist_add(policy, p);
  585. test_assert(ADDR_POLICY_ACCEPTED ==
  586. compare_addr_to_addr_policy(0x01020304u, 2, policy));
  587. test_assert(ADDR_POLICY_PROBABLY_ACCEPTED ==
  588. compare_addr_to_addr_policy(0, 2, policy));
  589. test_assert(ADDR_POLICY_REJECTED ==
  590. compare_addr_to_addr_policy(0xc0a80102, 2, policy));
  591. test_assert(0 == policies_parse_exit_policy(NULL, &policy2, 1, NULL, 1));
  592. test_assert(policy2);
  593. policy3 = smartlist_create();
  594. p = router_parse_addr_policy_item_from_string("reject *:*",-1);
  595. test_assert(p != NULL);
  596. smartlist_add(policy3, p);
  597. p = router_parse_addr_policy_item_from_string("accept *:*",-1);
  598. test_assert(p != NULL);
  599. smartlist_add(policy3, p);
  600. policy4 = smartlist_create();
  601. p = router_parse_addr_policy_item_from_string("accept *:443",-1);
  602. test_assert(p != NULL);
  603. smartlist_add(policy4, p);
  604. p = router_parse_addr_policy_item_from_string("accept *:443",-1);
  605. test_assert(p != NULL);
  606. smartlist_add(policy4, p);
  607. policy5 = smartlist_create();
  608. p = router_parse_addr_policy_item_from_string("reject 0.0.0.0/8:*",-1);
  609. test_assert(p != NULL);
  610. smartlist_add(policy5, p);
  611. p = router_parse_addr_policy_item_from_string("reject 169.254.0.0/16:*",-1);
  612. test_assert(p != NULL);
  613. smartlist_add(policy5, p);
  614. p = router_parse_addr_policy_item_from_string("reject 127.0.0.0/8:*",-1);
  615. test_assert(p != NULL);
  616. smartlist_add(policy5, p);
  617. p = router_parse_addr_policy_item_from_string("reject 192.168.0.0/16:*",-1);
  618. test_assert(p != NULL);
  619. smartlist_add(policy5, p);
  620. p = router_parse_addr_policy_item_from_string("reject 10.0.0.0/8:*",-1);
  621. test_assert(p != NULL);
  622. smartlist_add(policy5, p);
  623. p = router_parse_addr_policy_item_from_string("reject 172.16.0.0/12:*",-1);
  624. test_assert(p != NULL);
  625. smartlist_add(policy5, p);
  626. p = router_parse_addr_policy_item_from_string("reject 80.190.250.90:*",-1);
  627. test_assert(p != NULL);
  628. smartlist_add(policy5, p);
  629. p = router_parse_addr_policy_item_from_string("reject *:1-65534",-1);
  630. test_assert(p != NULL);
  631. smartlist_add(policy5, p);
  632. p = router_parse_addr_policy_item_from_string("reject *:65535",-1);
  633. test_assert(p != NULL);
  634. smartlist_add(policy5, p);
  635. p = router_parse_addr_policy_item_from_string("accept *:1-65535",-1);
  636. test_assert(p != NULL);
  637. smartlist_add(policy5, p);
  638. policy6 = smartlist_create();
  639. p = router_parse_addr_policy_item_from_string("accept 43.3.0.0/9:*",-1);
  640. test_assert(p != NULL);
  641. smartlist_add(policy6, p);
  642. policy7 = smartlist_create();
  643. p = router_parse_addr_policy_item_from_string("accept 0.0.0.0/8:*",-1);
  644. test_assert(p != NULL);
  645. smartlist_add(policy7, p);
  646. test_assert(!exit_policy_is_general_exit(policy));
  647. test_assert(exit_policy_is_general_exit(policy2));
  648. test_assert(!exit_policy_is_general_exit(NULL));
  649. test_assert(!exit_policy_is_general_exit(policy3));
  650. test_assert(!exit_policy_is_general_exit(policy4));
  651. test_assert(!exit_policy_is_general_exit(policy5));
  652. test_assert(!exit_policy_is_general_exit(policy6));
  653. test_assert(!exit_policy_is_general_exit(policy7));
  654. test_assert(cmp_addr_policies(policy, policy2));
  655. test_assert(cmp_addr_policies(policy, NULL));
  656. test_assert(!cmp_addr_policies(policy2, policy2));
  657. test_assert(!cmp_addr_policies(NULL, NULL));
  658. test_assert(!policy_is_reject_star(policy2));
  659. test_assert(policy_is_reject_star(policy));
  660. test_assert(policy_is_reject_star(NULL));
  661. addr_policy_list_free(policy);
  662. policy = NULL;
  663. /* make sure compacting logic works. */
  664. policy = NULL;
  665. line.key = (char*)"foo";
  666. line.value = (char*)"accept *:80,reject private:*,reject *:*";
  667. line.next = NULL;
  668. test_assert(0 == policies_parse_exit_policy(&line, &policy, 0, NULL, 1));
  669. test_assert(policy);
  670. //test_streq(policy->string, "accept *:80");
  671. //test_streq(policy->next->string, "reject *:*");
  672. test_eq(smartlist_len(policy), 2);
  673. /* test policy summaries */
  674. /* check if we properly ignore private IP addresses */
  675. test_policy_summary_helper("reject 192.168.0.0/16:*,"
  676. "reject 0.0.0.0/8:*,"
  677. "reject 10.0.0.0/8:*,"
  678. "accept *:10-30,"
  679. "accept *:90,"
  680. "reject *:*",
  681. "accept 10-30,90");
  682. /* check all accept policies, and proper counting of rejects */
  683. test_policy_summary_helper("reject 11.0.0.0/9:80,"
  684. "reject 12.0.0.0/9:80,"
  685. "reject 13.0.0.0/9:80,"
  686. "reject 14.0.0.0/9:80,"
  687. "accept *:*", "accept 1-65535");
  688. test_policy_summary_helper("reject 11.0.0.0/9:80,"
  689. "reject 12.0.0.0/9:80,"
  690. "reject 13.0.0.0/9:80,"
  691. "reject 14.0.0.0/9:80,"
  692. "reject 15.0.0.0:81,"
  693. "accept *:*", "accept 1-65535");
  694. test_policy_summary_helper("reject 11.0.0.0/9:80,"
  695. "reject 12.0.0.0/9:80,"
  696. "reject 13.0.0.0/9:80,"
  697. "reject 14.0.0.0/9:80,"
  698. "reject 15.0.0.0:80,"
  699. "accept *:*",
  700. "reject 80");
  701. /* no exits */
  702. test_policy_summary_helper("accept 11.0.0.0/9:80,"
  703. "reject *:*",
  704. "reject 1-65535");
  705. /* port merging */
  706. test_policy_summary_helper("accept *:80,"
  707. "accept *:81,"
  708. "accept *:100-110,"
  709. "accept *:111,"
  710. "reject *:*",
  711. "accept 80-81,100-111");
  712. /* border ports */
  713. test_policy_summary_helper("accept *:1,"
  714. "accept *:3,"
  715. "accept *:65535,"
  716. "reject *:*",
  717. "accept 1,3,65535");
  718. /* holes */
  719. test_policy_summary_helper("accept *:1,"
  720. "accept *:3,"
  721. "accept *:5,"
  722. "accept *:7,"
  723. "reject *:*",
  724. "accept 1,3,5,7");
  725. test_policy_summary_helper("reject *:1,"
  726. "reject *:3,"
  727. "reject *:5,"
  728. "reject *:7,"
  729. "accept *:*",
  730. "reject 1,3,5,7");
  731. /* truncation ports */
  732. sm = smartlist_create();
  733. for (i=1; i<2000; i+=2) {
  734. char buf[POLICY_BUF_LEN];
  735. tor_snprintf(buf, sizeof(buf), "reject *:%d", i);
  736. smartlist_add(sm, tor_strdup(buf));
  737. }
  738. smartlist_add(sm, tor_strdup("accept *:*"));
  739. policy_str = smartlist_join_strings(sm, ",", 0, NULL);
  740. test_policy_summary_helper( policy_str,
  741. "accept 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,"
  742. "46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,"
  743. "92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,"
  744. "130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,"
  745. "166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198,200,"
  746. "202,204,206,208,210,212,214,216,218,220,222,224,226,228,230,232,234,236,"
  747. "238,240,242,244,246,248,250,252,254,256,258,260,262,264,266,268,270,272,"
  748. "274,276,278,280,282,284,286,288,290,292,294,296,298,300,302,304,306,308,"
  749. "310,312,314,316,318,320,322,324,326,328,330,332,334,336,338,340,342,344,"
  750. "346,348,350,352,354,356,358,360,362,364,366,368,370,372,374,376,378,380,"
  751. "382,384,386,388,390,392,394,396,398,400,402,404,406,408,410,412,414,416,"
  752. "418,420,422,424,426,428,430,432,434,436,438,440,442,444,446,448,450,452,"
  753. "454,456,458,460,462,464,466,468,470,472,474,476,478,480,482,484,486,488,"
  754. "490,492,494,496,498,500,502,504,506,508,510,512,514,516,518,520,522");
  755. done:
  756. addr_policy_list_free(policy);
  757. addr_policy_list_free(policy2);
  758. addr_policy_list_free(policy3);
  759. addr_policy_list_free(policy4);
  760. addr_policy_list_free(policy5);
  761. addr_policy_list_free(policy6);
  762. addr_policy_list_free(policy7);
  763. tor_free(policy_str);
  764. if (sm) {
  765. SMARTLIST_FOREACH(sm, char *, s, tor_free(s));
  766. smartlist_free(sm);
  767. }
  768. }
  769. /** Run AES performance benchmarks. */
  770. static void
  771. bench_aes(void)
  772. {
  773. int len, i;
  774. char *b1, *b2;
  775. crypto_cipher_env_t *c;
  776. struct timeval start, end;
  777. const int iters = 100000;
  778. uint64_t nsec;
  779. c = crypto_new_cipher_env();
  780. crypto_cipher_generate_key(c);
  781. crypto_cipher_encrypt_init_cipher(c);
  782. for (len = 1; len <= 8192; len *= 2) {
  783. b1 = tor_malloc_zero(len);
  784. b2 = tor_malloc_zero(len);
  785. tor_gettimeofday(&start);
  786. for (i = 0; i < iters; ++i) {
  787. crypto_cipher_encrypt(c, b1, b2, len);
  788. }
  789. tor_gettimeofday(&end);
  790. tor_free(b1);
  791. tor_free(b2);
  792. nsec = (uint64_t) tv_udiff(&start,&end);
  793. nsec *= 1000;
  794. nsec /= (iters*len);
  795. printf("%d bytes: "U64_FORMAT" nsec per byte\n", len,
  796. U64_PRINTF_ARG(nsec));
  797. }
  798. crypto_free_cipher_env(c);
  799. }
  800. /** Run digestmap_t performance benchmarks. */
  801. static void
  802. bench_dmap(void)
  803. {
  804. smartlist_t *sl = smartlist_create();
  805. smartlist_t *sl2 = smartlist_create();
  806. struct timeval start, end, pt2, pt3, pt4;
  807. const int iters = 10000;
  808. const int elts = 4000;
  809. const int fpostests = 1000000;
  810. char d[20];
  811. int i,n=0, fp = 0;
  812. digestmap_t *dm = digestmap_new();
  813. digestset_t *ds = digestset_new(elts);
  814. for (i = 0; i < elts; ++i) {
  815. crypto_rand(d, 20);
  816. smartlist_add(sl, tor_memdup(d, 20));
  817. }
  818. for (i = 0; i < elts; ++i) {
  819. crypto_rand(d, 20);
  820. smartlist_add(sl2, tor_memdup(d, 20));
  821. }
  822. printf("nbits=%d\n", ds->mask+1);
  823. tor_gettimeofday(&start);
  824. for (i = 0; i < iters; ++i) {
  825. SMARTLIST_FOREACH(sl, const char *, cp, digestmap_set(dm, cp, (void*)1));
  826. }
  827. tor_gettimeofday(&pt2);
  828. for (i = 0; i < iters; ++i) {
  829. SMARTLIST_FOREACH(sl, const char *, cp, digestmap_get(dm, cp));
  830. SMARTLIST_FOREACH(sl2, const char *, cp, digestmap_get(dm, cp));
  831. }
  832. tor_gettimeofday(&pt3);
  833. for (i = 0; i < iters; ++i) {
  834. SMARTLIST_FOREACH(sl, const char *, cp, digestset_add(ds, cp));
  835. }
  836. tor_gettimeofday(&pt4);
  837. for (i = 0; i < iters; ++i) {
  838. SMARTLIST_FOREACH(sl, const char *, cp, n += digestset_isin(ds, cp));
  839. SMARTLIST_FOREACH(sl2, const char *, cp, n += digestset_isin(ds, cp));
  840. }
  841. tor_gettimeofday(&end);
  842. for (i = 0; i < fpostests; ++i) {
  843. crypto_rand(d, 20);
  844. if (digestset_isin(ds, d)) ++fp;
  845. }
  846. printf("%ld\n",(unsigned long)tv_udiff(&start, &pt2));
  847. printf("%ld\n",(unsigned long)tv_udiff(&pt2, &pt3));
  848. printf("%ld\n",(unsigned long)tv_udiff(&pt3, &pt4));
  849. printf("%ld\n",(unsigned long)tv_udiff(&pt4, &end));
  850. printf("-- %d\n", n);
  851. printf("++ %f\n", fp/(double)fpostests);
  852. digestmap_free(dm, NULL);
  853. digestset_free(ds);
  854. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  855. SMARTLIST_FOREACH(sl2, char *, cp, tor_free(cp));
  856. smartlist_free(sl);
  857. smartlist_free(sl2);
  858. }
  859. /** Test encoding and parsing of rendezvous service descriptors. */
  860. static void
  861. test_rend_fns(void)
  862. {
  863. rend_service_descriptor_t *generated = NULL, *parsed = NULL;
  864. char service_id[DIGEST_LEN];
  865. char service_id_base32[REND_SERVICE_ID_LEN_BASE32+1];
  866. const char *next_desc;
  867. smartlist_t *descs = smartlist_create();
  868. char computed_desc_id[DIGEST_LEN];
  869. char parsed_desc_id[DIGEST_LEN];
  870. crypto_pk_env_t *pk1 = NULL, *pk2 = NULL;
  871. time_t now;
  872. char *intro_points_encrypted = NULL;
  873. size_t intro_points_size;
  874. size_t encoded_size;
  875. int i;
  876. char address1[] = "fooaddress.onion";
  877. char address2[] = "aaaaaaaaaaaaaaaa.onion";
  878. char address3[] = "fooaddress.exit";
  879. char address4[] = "www.torproject.org";
  880. test_assert(BAD_HOSTNAME == parse_extended_hostname(address1, 1));
  881. test_assert(ONION_HOSTNAME == parse_extended_hostname(address2, 1));
  882. test_assert(EXIT_HOSTNAME == parse_extended_hostname(address3, 1));
  883. test_assert(NORMAL_HOSTNAME == parse_extended_hostname(address4, 1));
  884. pk1 = pk_generate(0);
  885. pk2 = pk_generate(1);
  886. generated = tor_malloc_zero(sizeof(rend_service_descriptor_t));
  887. generated->pk = crypto_pk_dup_key(pk1);
  888. crypto_pk_get_digest(generated->pk, service_id);
  889. base32_encode(service_id_base32, REND_SERVICE_ID_LEN_BASE32+1,
  890. service_id, REND_SERVICE_ID_LEN);
  891. now = time(NULL);
  892. generated->timestamp = now;
  893. generated->version = 2;
  894. generated->protocols = 42;
  895. generated->intro_nodes = smartlist_create();
  896. for (i = 0; i < 3; i++) {
  897. rend_intro_point_t *intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  898. crypto_pk_env_t *okey = pk_generate(2 + i);
  899. intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
  900. intro->extend_info->onion_key = okey;
  901. crypto_pk_get_digest(intro->extend_info->onion_key,
  902. intro->extend_info->identity_digest);
  903. //crypto_rand(info->identity_digest, DIGEST_LEN); /* Would this work? */
  904. intro->extend_info->nickname[0] = '$';
  905. base16_encode(intro->extend_info->nickname + 1,
  906. sizeof(intro->extend_info->nickname) - 1,
  907. intro->extend_info->identity_digest, DIGEST_LEN);
  908. /* Does not cover all IP addresses. */
  909. tor_addr_from_ipv4h(&intro->extend_info->addr, crypto_rand_int(65536));
  910. intro->extend_info->port = crypto_rand_int(65536);
  911. intro->intro_key = crypto_pk_dup_key(pk2);
  912. smartlist_add(generated->intro_nodes, intro);
  913. }
  914. test_assert(rend_encode_v2_descriptors(descs, generated, now, 0,
  915. REND_NO_AUTH, NULL, NULL) > 0);
  916. test_assert(rend_compute_v2_desc_id(computed_desc_id, service_id_base32,
  917. NULL, now, 0) == 0);
  918. test_memeq(((rend_encoded_v2_service_descriptor_t *)
  919. smartlist_get(descs, 0))->desc_id, computed_desc_id, DIGEST_LEN);
  920. test_assert(rend_parse_v2_service_descriptor(&parsed, parsed_desc_id,
  921. &intro_points_encrypted,
  922. &intro_points_size,
  923. &encoded_size,
  924. &next_desc,
  925. ((rend_encoded_v2_service_descriptor_t *)
  926. smartlist_get(descs, 0))->desc_str) == 0);
  927. test_assert(parsed);
  928. test_memeq(((rend_encoded_v2_service_descriptor_t *)
  929. smartlist_get(descs, 0))->desc_id, parsed_desc_id, DIGEST_LEN);
  930. test_eq(rend_parse_introduction_points(parsed, intro_points_encrypted,
  931. intro_points_size), 3);
  932. test_assert(!crypto_pk_cmp_keys(generated->pk, parsed->pk));
  933. test_eq(parsed->timestamp, now);
  934. test_eq(parsed->version, 2);
  935. test_eq(parsed->protocols, 42);
  936. test_eq(smartlist_len(parsed->intro_nodes), 3);
  937. for (i = 0; i < smartlist_len(parsed->intro_nodes); i++) {
  938. rend_intro_point_t *par_intro = smartlist_get(parsed->intro_nodes, i),
  939. *gen_intro = smartlist_get(generated->intro_nodes, i);
  940. extend_info_t *par_info = par_intro->extend_info;
  941. extend_info_t *gen_info = gen_intro->extend_info;
  942. test_assert(!crypto_pk_cmp_keys(gen_info->onion_key, par_info->onion_key));
  943. test_memeq(gen_info->identity_digest, par_info->identity_digest,
  944. DIGEST_LEN);
  945. test_streq(gen_info->nickname, par_info->nickname);
  946. test_assert(tor_addr_eq(&gen_info->addr, &par_info->addr));
  947. test_eq(gen_info->port, par_info->port);
  948. }
  949. rend_service_descriptor_free(parsed);
  950. rend_service_descriptor_free(generated);
  951. parsed = generated = NULL;
  952. done:
  953. if (descs) {
  954. for (i = 0; i < smartlist_len(descs); i++)
  955. rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
  956. smartlist_free(descs);
  957. }
  958. if (parsed)
  959. rend_service_descriptor_free(parsed);
  960. if (generated)
  961. rend_service_descriptor_free(generated);
  962. if (pk1)
  963. crypto_free_pk_env(pk1);
  964. if (pk2)
  965. crypto_free_pk_env(pk2);
  966. tor_free(intro_points_encrypted);
  967. }
  968. /** Run unit tests for GeoIP code. */
  969. static void
  970. test_geoip(void)
  971. {
  972. int i, j;
  973. time_t now = time(NULL);
  974. char *s = NULL;
  975. /* Populate the DB a bit. Add these in order, since we can't do the final
  976. * 'sort' step. These aren't very good IP addresses, but they're perfectly
  977. * fine uint32_t values. */
  978. test_eq(0, geoip_parse_entry("10,50,AB"));
  979. test_eq(0, geoip_parse_entry("52,90,XY"));
  980. test_eq(0, geoip_parse_entry("95,100,AB"));
  981. test_eq(0, geoip_parse_entry("\"105\",\"140\",\"ZZ\""));
  982. test_eq(0, geoip_parse_entry("\"150\",\"190\",\"XY\""));
  983. test_eq(0, geoip_parse_entry("\"200\",\"250\",\"AB\""));
  984. /* We should have 3 countries: ab, xy, zz. */
  985. test_eq(3, geoip_get_n_countries());
  986. /* Make sure that country ID actually works. */
  987. #define NAMEFOR(x) geoip_get_country_name(geoip_get_country_by_ip(x))
  988. test_streq("ab", NAMEFOR(32));
  989. test_streq("??", NAMEFOR(5));
  990. test_streq("??", NAMEFOR(51));
  991. test_streq("xy", NAMEFOR(150));
  992. test_streq("xy", NAMEFOR(190));
  993. test_streq("??", NAMEFOR(2000));
  994. #undef NAMEFOR
  995. get_options()->BridgeRelay = 1;
  996. get_options()->BridgeRecordUsageByCountry = 1;
  997. /* Put 9 observations in AB... */
  998. for (i=32; i < 40; ++i)
  999. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, i, now-7200);
  1000. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, 225, now-7200);
  1001. /* and 3 observations in XY, several times. */
  1002. for (j=0; j < 10; ++j)
  1003. for (i=52; i < 55; ++i)
  1004. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, i, now-3600);
  1005. /* and 17 observations in ZZ... */
  1006. for (i=110; i < 127; ++i)
  1007. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, i, now);
  1008. s = geoip_get_client_history_bridge(now+5*24*60*60,
  1009. GEOIP_CLIENT_CONNECT);
  1010. test_assert(s);
  1011. test_streq("zz=24,ab=16,xy=8", s);
  1012. tor_free(s);
  1013. /* Now clear out all the AB observations. */
  1014. geoip_remove_old_clients(now-6000);
  1015. s = geoip_get_client_history_bridge(now+5*24*60*60,
  1016. GEOIP_CLIENT_CONNECT);
  1017. test_assert(s);
  1018. test_streq("zz=24,xy=8", s);
  1019. done:
  1020. tor_free(s);
  1021. }
  1022. static void *
  1023. legacy_test_setup(const struct testcase_t *testcase)
  1024. {
  1025. return testcase->setup_data;
  1026. }
  1027. void
  1028. legacy_test_helper(void *data)
  1029. {
  1030. void (*fn)(void) = data;
  1031. fn();
  1032. }
  1033. static int
  1034. legacy_test_cleanup(const struct testcase_t *testcase, void *ptr)
  1035. {
  1036. (void)ptr;
  1037. (void)testcase;
  1038. return 1;
  1039. }
  1040. const struct testcase_setup_t legacy_setup = {
  1041. legacy_test_setup, legacy_test_cleanup
  1042. };
  1043. #define ENT(name) \
  1044. { #name, legacy_test_helper, 0, &legacy_setup, test_ ## name }
  1045. #define SUBENT(group, name) \
  1046. { #group "_" #name, legacy_test_helper, 0, &legacy_setup, \
  1047. test_ ## group ## _ ## name }
  1048. #define DISABLED(name) \
  1049. { #name, legacy_test_helper, TT_SKIP, &legacy_setup, name }
  1050. static struct testcase_t test_array[] = {
  1051. ENT(buffers),
  1052. ENT(onion_handshake),
  1053. ENT(circuit_timeout),
  1054. ENT(policies),
  1055. ENT(rend_fns),
  1056. ENT(geoip),
  1057. DISABLED(bench_aes),
  1058. DISABLED(bench_dmap),
  1059. END_OF_TESTCASES
  1060. };
  1061. extern struct testcase_t addr_tests[];
  1062. extern struct testcase_t crypto_tests[];
  1063. extern struct testcase_t container_tests[];
  1064. extern struct testcase_t util_tests[];
  1065. extern struct testcase_t dir_tests[];
  1066. static struct testgroup_t testgroups[] = {
  1067. { "", test_array },
  1068. { "addr/", addr_tests },
  1069. { "crypto/", crypto_tests },
  1070. { "container/", container_tests },
  1071. { "util/", util_tests },
  1072. { "dir/", dir_tests },
  1073. END_OF_GROUPS
  1074. };
  1075. /** Main entry point for unit test code: parse the command line, and run
  1076. * some unit tests. */
  1077. int
  1078. main(int c, const char **v)
  1079. {
  1080. or_options_t *options;
  1081. char *errmsg = NULL;
  1082. int i, i_out;
  1083. int loglevel = LOG_ERR;
  1084. #ifdef USE_DMALLOC
  1085. {
  1086. int r = CRYPTO_set_mem_ex_functions(_tor_malloc, _tor_realloc, _tor_free);
  1087. tor_assert(r);
  1088. }
  1089. #endif
  1090. update_approx_time(time(NULL));
  1091. options = options_new();
  1092. tor_threads_init();
  1093. init_logging();
  1094. for (i_out = i = 1; i < c; ++i) {
  1095. if (!strcmp(v[i], "--warn")) {
  1096. loglevel = LOG_WARN;
  1097. } else if (!strcmp(v[i], "--notice")) {
  1098. loglevel = LOG_NOTICE;
  1099. } else if (!strcmp(v[i], "--info")) {
  1100. loglevel = LOG_INFO;
  1101. } else if (!strcmp(v[i], "--debug")) {
  1102. loglevel = LOG_DEBUG;
  1103. } else {
  1104. v[i_out++] = v[i];
  1105. }
  1106. }
  1107. c = i_out;
  1108. {
  1109. log_severity_list_t s;
  1110. memset(&s, 0, sizeof(s));
  1111. set_log_severity_config(loglevel, LOG_ERR, &s);
  1112. add_stream_log(&s, "", fileno(stdout));
  1113. }
  1114. options->command = CMD_RUN_UNITTESTS;
  1115. crypto_global_init(0, NULL, NULL);
  1116. rep_hist_init();
  1117. network_init();
  1118. setup_directory();
  1119. options_init(options);
  1120. options->DataDirectory = tor_strdup(temp_dir);
  1121. options->EntryStatistics = 1;
  1122. if (set_options(options, &errmsg) < 0) {
  1123. printf("Failed to set initial options: %s\n", errmsg);
  1124. tor_free(errmsg);
  1125. return 1;
  1126. }
  1127. crypto_seed_rng(1);
  1128. atexit(remove_directory);
  1129. have_failed = (tinytest_main(c, v, testgroups) != 0);
  1130. free_pregenerated_keys();
  1131. #ifdef USE_DMALLOC
  1132. tor_free_all(0);
  1133. dmalloc_log_unfreed();
  1134. #endif
  1135. if (have_failed)
  1136. return 1;
  1137. else
  1138. return 0;
  1139. }