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