test.c 40 KB

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