test.c 40 KB

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