test.c 43 KB

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