test.c 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261
  1. /* Copyright (c) 2001-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2017, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file test.c
  7. * \brief Unit tests for many pieces of the lower level Tor modules.
  8. **/
  9. #include "orconfig.h"
  10. #include <stdio.h>
  11. #ifdef HAVE_FCNTL_H
  12. #include <fcntl.h>
  13. #endif
  14. #ifdef _WIN32
  15. /* For mkdir() */
  16. #include <direct.h>
  17. #else
  18. #include <dirent.h>
  19. #endif /* defined(_WIN32) */
  20. #include <math.h>
  21. /* These macros pull in declarations for some functions and structures that
  22. * are typically file-private. */
  23. #define GEOIP_PRIVATE
  24. #define ROUTER_PRIVATE
  25. #define CIRCUITSTATS_PRIVATE
  26. #define CIRCUITLIST_PRIVATE
  27. #define MAIN_PRIVATE
  28. #define STATEFILE_PRIVATE
  29. #include "or.h"
  30. #include "backtrace.h"
  31. #include "buffers.h"
  32. #include "circuitlist.h"
  33. #include "circuitstats.h"
  34. #include "compress.h"
  35. #include "config.h"
  36. #include "connection_edge.h"
  37. #include "geoip.h"
  38. #include "rendcommon.h"
  39. #include "rendcache.h"
  40. #include "test.h"
  41. #include "main.h"
  42. #include "memarea.h"
  43. #include "onion.h"
  44. #include "onion_ntor.h"
  45. #include "onion_fast.h"
  46. #include "onion_tap.h"
  47. #include "policies.h"
  48. #include "rephist.h"
  49. #include "routerparse.h"
  50. #include "statefile.h"
  51. #include "crypto_curve25519.h"
  52. /** Run unit tests for the onion handshake code. */
  53. static void
  54. test_onion_handshake(void *arg)
  55. {
  56. /* client-side */
  57. crypto_dh_t *c_dh = NULL;
  58. char c_buf[TAP_ONIONSKIN_CHALLENGE_LEN];
  59. char c_keys[40];
  60. /* server-side */
  61. char s_buf[TAP_ONIONSKIN_REPLY_LEN];
  62. char s_keys[40];
  63. int i;
  64. /* shared */
  65. crypto_pk_t *pk = NULL, *pk2 = NULL;
  66. (void)arg;
  67. pk = pk_generate(0);
  68. pk2 = pk_generate(1);
  69. /* client handshake 1. */
  70. memset(c_buf, 0, TAP_ONIONSKIN_CHALLENGE_LEN);
  71. tt_assert(! onion_skin_TAP_create(pk, &c_dh, c_buf));
  72. for (i = 1; i <= 3; ++i) {
  73. crypto_pk_t *k1, *k2;
  74. if (i==1) {
  75. /* server handshake: only one key known. */
  76. k1 = pk; k2 = NULL;
  77. } else if (i==2) {
  78. /* server handshake: try the right key first. */
  79. k1 = pk; k2 = pk2;
  80. } else {
  81. /* server handshake: try the right key second. */
  82. k1 = pk2; k2 = pk;
  83. }
  84. memset(s_buf, 0, TAP_ONIONSKIN_REPLY_LEN);
  85. memset(s_keys, 0, 40);
  86. tt_assert(! onion_skin_TAP_server_handshake(c_buf, k1, k2,
  87. s_buf, s_keys, 40));
  88. /* client handshake 2 */
  89. memset(c_keys, 0, 40);
  90. tt_assert(! onion_skin_TAP_client_handshake(c_dh, s_buf, c_keys,
  91. 40, NULL));
  92. tt_mem_op(c_keys,OP_EQ, s_keys, 40);
  93. memset(s_buf, 0, 40);
  94. tt_mem_op(c_keys,OP_NE, s_buf, 40);
  95. }
  96. done:
  97. crypto_dh_free(c_dh);
  98. crypto_pk_free(pk);
  99. crypto_pk_free(pk2);
  100. }
  101. static void
  102. test_bad_onion_handshake(void *arg)
  103. {
  104. char junk_buf[TAP_ONIONSKIN_CHALLENGE_LEN];
  105. char junk_buf2[TAP_ONIONSKIN_CHALLENGE_LEN];
  106. /* client-side */
  107. crypto_dh_t *c_dh = NULL;
  108. char c_buf[TAP_ONIONSKIN_CHALLENGE_LEN];
  109. char c_keys[40];
  110. /* server-side */
  111. char s_buf[TAP_ONIONSKIN_REPLY_LEN];
  112. char s_keys[40];
  113. /* shared */
  114. crypto_pk_t *pk = NULL, *pk2 = NULL;
  115. (void)arg;
  116. pk = pk_generate(0);
  117. pk2 = pk_generate(1);
  118. /* Server: Case 1: the encrypted data is degenerate. */
  119. memset(junk_buf, 0, sizeof(junk_buf));
  120. crypto_pk_obsolete_public_hybrid_encrypt(pk,
  121. junk_buf2, TAP_ONIONSKIN_CHALLENGE_LEN,
  122. junk_buf, DH_KEY_LEN, PK_PKCS1_OAEP_PADDING, 1);
  123. tt_int_op(-1, OP_EQ,
  124. onion_skin_TAP_server_handshake(junk_buf2, pk, NULL,
  125. s_buf, s_keys, 40));
  126. /* Server: Case 2: the encrypted data is not long enough. */
  127. memset(junk_buf, 0, sizeof(junk_buf));
  128. memset(junk_buf2, 0, sizeof(junk_buf2));
  129. crypto_pk_public_encrypt(pk, junk_buf2, sizeof(junk_buf2),
  130. junk_buf, 48, PK_PKCS1_OAEP_PADDING);
  131. tt_int_op(-1, OP_EQ,
  132. onion_skin_TAP_server_handshake(junk_buf2, pk, NULL,
  133. s_buf, s_keys, 40));
  134. /* client handshake 1: do it straight. */
  135. memset(c_buf, 0, TAP_ONIONSKIN_CHALLENGE_LEN);
  136. tt_assert(! onion_skin_TAP_create(pk, &c_dh, c_buf));
  137. /* Server: Case 3: we just don't have the right key. */
  138. tt_int_op(-1, OP_EQ,
  139. onion_skin_TAP_server_handshake(c_buf, pk2, NULL,
  140. s_buf, s_keys, 40));
  141. /* Server: Case 4: The RSA-encrypted portion is corrupt. */
  142. c_buf[64] ^= 33;
  143. tt_int_op(-1, OP_EQ,
  144. onion_skin_TAP_server_handshake(c_buf, pk, NULL,
  145. s_buf, s_keys, 40));
  146. c_buf[64] ^= 33;
  147. /* (Let the server proceed) */
  148. tt_int_op(0, OP_EQ,
  149. onion_skin_TAP_server_handshake(c_buf, pk, NULL,
  150. s_buf, s_keys, 40));
  151. /* Client: Case 1: The server sent back junk. */
  152. const char *msg = NULL;
  153. s_buf[64] ^= 33;
  154. tt_int_op(-1, OP_EQ,
  155. onion_skin_TAP_client_handshake(c_dh, s_buf, c_keys, 40, &msg));
  156. s_buf[64] ^= 33;
  157. tt_str_op(msg, OP_EQ, "Digest DOES NOT MATCH on onion handshake. "
  158. "Bug or attack.");
  159. /* Let the client finish; make sure it can. */
  160. msg = NULL;
  161. tt_int_op(0, OP_EQ,
  162. onion_skin_TAP_client_handshake(c_dh, s_buf, c_keys, 40, &msg));
  163. tt_mem_op(s_keys,OP_EQ, c_keys, 40);
  164. tt_ptr_op(msg, OP_EQ, NULL);
  165. /* Client: Case 2: The server sent back a degenerate DH. */
  166. memset(s_buf, 0, sizeof(s_buf));
  167. tt_int_op(-1, OP_EQ,
  168. onion_skin_TAP_client_handshake(c_dh, s_buf, c_keys, 40, &msg));
  169. tt_str_op(msg, OP_EQ, "DH computation failed.");
  170. done:
  171. crypto_dh_free(c_dh);
  172. crypto_pk_free(pk);
  173. crypto_pk_free(pk2);
  174. }
  175. static void
  176. test_ntor_handshake(void *arg)
  177. {
  178. /* client-side */
  179. ntor_handshake_state_t *c_state = NULL;
  180. uint8_t c_buf[NTOR_ONIONSKIN_LEN];
  181. uint8_t c_keys[400];
  182. /* server-side */
  183. di_digest256_map_t *s_keymap=NULL;
  184. curve25519_keypair_t s_keypair;
  185. uint8_t s_buf[NTOR_REPLY_LEN];
  186. uint8_t s_keys[400];
  187. /* shared */
  188. const curve25519_public_key_t *server_pubkey;
  189. uint8_t node_id[20] = "abcdefghijklmnopqrst";
  190. (void) arg;
  191. /* Make the server some keys */
  192. curve25519_secret_key_generate(&s_keypair.seckey, 0);
  193. curve25519_public_key_generate(&s_keypair.pubkey, &s_keypair.seckey);
  194. dimap_add_entry(&s_keymap, s_keypair.pubkey.public_key, &s_keypair);
  195. server_pubkey = &s_keypair.pubkey;
  196. /* client handshake 1. */
  197. memset(c_buf, 0, NTOR_ONIONSKIN_LEN);
  198. tt_int_op(0, OP_EQ, onion_skin_ntor_create(node_id, server_pubkey,
  199. &c_state, c_buf));
  200. /* server handshake */
  201. memset(s_buf, 0, NTOR_REPLY_LEN);
  202. memset(s_keys, 0, 40);
  203. tt_int_op(0, OP_EQ, onion_skin_ntor_server_handshake(c_buf, s_keymap, NULL,
  204. node_id,
  205. s_buf, s_keys, 400));
  206. /* client handshake 2 */
  207. memset(c_keys, 0, 40);
  208. tt_int_op(0, OP_EQ, onion_skin_ntor_client_handshake(c_state, s_buf,
  209. c_keys, 400, NULL));
  210. tt_mem_op(c_keys,OP_EQ, s_keys, 400);
  211. memset(s_buf, 0, 40);
  212. tt_mem_op(c_keys,OP_NE, s_buf, 40);
  213. /* Now try with a bogus server response. Zero input should trigger
  214. * All The Problems. */
  215. memset(c_keys, 0, 400);
  216. memset(s_buf, 0, NTOR_REPLY_LEN);
  217. const char *msg = NULL;
  218. tt_int_op(-1, OP_EQ, onion_skin_ntor_client_handshake(c_state, s_buf,
  219. c_keys, 400, &msg));
  220. tt_str_op(msg, OP_EQ, "Zero output from curve25519 handshake");
  221. done:
  222. ntor_handshake_state_free(c_state);
  223. dimap_free(s_keymap, NULL);
  224. }
  225. static void
  226. test_fast_handshake(void *arg)
  227. {
  228. /* tests for the obsolete "CREATE_FAST" handshake. */
  229. (void) arg;
  230. fast_handshake_state_t *state = NULL;
  231. uint8_t client_handshake[CREATE_FAST_LEN];
  232. uint8_t server_handshake[CREATED_FAST_LEN];
  233. uint8_t s_keys[100], c_keys[100];
  234. /* First, test an entire handshake. */
  235. memset(client_handshake, 0, sizeof(client_handshake));
  236. tt_int_op(0, OP_EQ, fast_onionskin_create(&state, client_handshake));
  237. tt_assert(! tor_mem_is_zero((char*)client_handshake,
  238. sizeof(client_handshake)));
  239. tt_int_op(0, OP_EQ,
  240. fast_server_handshake(client_handshake, server_handshake,
  241. s_keys, 100));
  242. const char *msg = NULL;
  243. tt_int_op(0, OP_EQ,
  244. fast_client_handshake(state, server_handshake, c_keys, 100, &msg));
  245. tt_ptr_op(msg, OP_EQ, NULL);
  246. tt_mem_op(s_keys, OP_EQ, c_keys, 100);
  247. /* Now test a failing handshake. */
  248. server_handshake[0] ^= 3;
  249. tt_int_op(-1, OP_EQ,
  250. fast_client_handshake(state, server_handshake, c_keys, 100, &msg));
  251. tt_str_op(msg, OP_EQ, "Digest DOES NOT MATCH on fast handshake. "
  252. "Bug or attack.");
  253. done:
  254. fast_handshake_state_free(state);
  255. }
  256. /** Run unit tests for the onion queues. */
  257. static void
  258. test_onion_queues(void *arg)
  259. {
  260. uint8_t buf1[TAP_ONIONSKIN_CHALLENGE_LEN] = {0};
  261. uint8_t buf2[NTOR_ONIONSKIN_LEN] = {0};
  262. or_circuit_t *circ1 = or_circuit_new(0, NULL);
  263. or_circuit_t *circ2 = or_circuit_new(0, NULL);
  264. create_cell_t *onionskin = NULL, *create2_ptr;
  265. create_cell_t *create1 = tor_malloc_zero(sizeof(create_cell_t));
  266. create_cell_t *create2 = tor_malloc_zero(sizeof(create_cell_t));
  267. (void)arg;
  268. create2_ptr = create2; /* remember, but do not free */
  269. create_cell_init(create1, CELL_CREATE, ONION_HANDSHAKE_TYPE_TAP,
  270. TAP_ONIONSKIN_CHALLENGE_LEN, buf1);
  271. create_cell_init(create2, CELL_CREATE, ONION_HANDSHAKE_TYPE_NTOR,
  272. NTOR_ONIONSKIN_LEN, buf2);
  273. tt_int_op(0,OP_EQ, onion_num_pending(ONION_HANDSHAKE_TYPE_TAP));
  274. tt_int_op(0,OP_EQ, onion_pending_add(circ1, create1));
  275. create1 = NULL;
  276. tt_int_op(1,OP_EQ, onion_num_pending(ONION_HANDSHAKE_TYPE_TAP));
  277. tt_int_op(0,OP_EQ, onion_num_pending(ONION_HANDSHAKE_TYPE_NTOR));
  278. tt_int_op(0,OP_EQ, onion_pending_add(circ2, create2));
  279. create2 = NULL;
  280. tt_int_op(1,OP_EQ, onion_num_pending(ONION_HANDSHAKE_TYPE_NTOR));
  281. tt_ptr_op(circ2,OP_EQ, onion_next_task(&onionskin));
  282. tt_int_op(1,OP_EQ, onion_num_pending(ONION_HANDSHAKE_TYPE_TAP));
  283. tt_int_op(0,OP_EQ, onion_num_pending(ONION_HANDSHAKE_TYPE_NTOR));
  284. tt_ptr_op(onionskin, OP_EQ, create2_ptr);
  285. clear_pending_onions();
  286. tt_int_op(0,OP_EQ, onion_num_pending(ONION_HANDSHAKE_TYPE_TAP));
  287. tt_int_op(0,OP_EQ, onion_num_pending(ONION_HANDSHAKE_TYPE_NTOR));
  288. done:
  289. circuit_free_(TO_CIRCUIT(circ1));
  290. circuit_free_(TO_CIRCUIT(circ2));
  291. tor_free(create1);
  292. tor_free(create2);
  293. tor_free(onionskin);
  294. }
  295. static void
  296. test_circuit_timeout(void *arg)
  297. {
  298. /* Plan:
  299. * 1. Generate 1000 samples
  300. * 2. Estimate parameters
  301. * 3. If difference, repeat
  302. * 4. Save state
  303. * 5. load state
  304. * 6. Estimate parameters
  305. * 7. compare differences
  306. */
  307. circuit_build_times_t initial;
  308. circuit_build_times_t estimate;
  309. circuit_build_times_t final;
  310. double timeout1, timeout2;
  311. or_state_t *state=NULL;
  312. int i, runs;
  313. double close_ms;
  314. (void)arg;
  315. initialize_periodic_events();
  316. circuit_build_times_init(&initial);
  317. circuit_build_times_init(&estimate);
  318. circuit_build_times_init(&final);
  319. state = or_state_new();
  320. circuitbuild_running_unit_tests();
  321. #define timeout0 (build_time_t)(30*1000.0)
  322. initial.Xm = 3000;
  323. circuit_build_times_initial_alpha(&initial,
  324. CBT_DEFAULT_QUANTILE_CUTOFF/100.0,
  325. timeout0);
  326. close_ms = MAX(circuit_build_times_calculate_timeout(&initial,
  327. CBT_DEFAULT_CLOSE_QUANTILE/100.0),
  328. CBT_DEFAULT_TIMEOUT_INITIAL_VALUE);
  329. do {
  330. for (i=0; i < CBT_DEFAULT_MIN_CIRCUITS_TO_OBSERVE; i++) {
  331. build_time_t sample = circuit_build_times_generate_sample(&initial,0,1);
  332. if (sample > close_ms) {
  333. circuit_build_times_add_time(&estimate, CBT_BUILD_ABANDONED);
  334. } else {
  335. circuit_build_times_add_time(&estimate, sample);
  336. }
  337. }
  338. circuit_build_times_update_alpha(&estimate);
  339. timeout1 = circuit_build_times_calculate_timeout(&estimate,
  340. CBT_DEFAULT_QUANTILE_CUTOFF/100.0);
  341. circuit_build_times_set_timeout(&estimate);
  342. log_notice(LD_CIRC, "Timeout1 is %f, Xm is %d", timeout1, estimate.Xm);
  343. /* 2% error */
  344. } while (fabs(circuit_build_times_cdf(&initial, timeout0) -
  345. circuit_build_times_cdf(&initial, timeout1)) > 0.02);
  346. tt_int_op(estimate.total_build_times, OP_LE, CBT_NCIRCUITS_TO_OBSERVE);
  347. circuit_build_times_update_state(&estimate, state);
  348. circuit_build_times_free_timeouts(&final);
  349. tt_int_op(circuit_build_times_parse_state(&final, state), OP_EQ, 0);
  350. circuit_build_times_update_alpha(&final);
  351. timeout2 = circuit_build_times_calculate_timeout(&final,
  352. CBT_DEFAULT_QUANTILE_CUTOFF/100.0);
  353. circuit_build_times_set_timeout(&final);
  354. log_notice(LD_CIRC, "Timeout2 is %f, Xm is %d", timeout2, final.Xm);
  355. /* 5% here because some accuracy is lost due to histogram conversion */
  356. tt_assert(fabs(circuit_build_times_cdf(&initial, timeout0) -
  357. circuit_build_times_cdf(&initial, timeout2)) < 0.05);
  358. for (runs = 0; runs < 50; runs++) {
  359. int build_times_idx = 0;
  360. int total_build_times = 0;
  361. final.close_ms = final.timeout_ms = CBT_DEFAULT_TIMEOUT_INITIAL_VALUE;
  362. estimate.close_ms = estimate.timeout_ms
  363. = CBT_DEFAULT_TIMEOUT_INITIAL_VALUE;
  364. for (i = 0; i < CBT_DEFAULT_RECENT_CIRCUITS*2; i++) {
  365. circuit_build_times_network_circ_success(&estimate);
  366. circuit_build_times_add_time(&estimate,
  367. circuit_build_times_generate_sample(&estimate, 0,
  368. CBT_DEFAULT_QUANTILE_CUTOFF/100.0));
  369. circuit_build_times_network_circ_success(&estimate);
  370. circuit_build_times_add_time(&final,
  371. circuit_build_times_generate_sample(&final, 0,
  372. CBT_DEFAULT_QUANTILE_CUTOFF/100.0));
  373. }
  374. tt_assert(!circuit_build_times_network_check_changed(&estimate));
  375. tt_assert(!circuit_build_times_network_check_changed(&final));
  376. /* Reset liveness to be non-live */
  377. final.liveness.network_last_live = 0;
  378. estimate.liveness.network_last_live = 0;
  379. build_times_idx = estimate.build_times_idx;
  380. total_build_times = estimate.total_build_times;
  381. tt_assert(circuit_build_times_network_check_live(&estimate));
  382. tt_assert(circuit_build_times_network_check_live(&final));
  383. circuit_build_times_count_close(&estimate, 0,
  384. (time_t)(approx_time()-estimate.close_ms/1000.0-1));
  385. circuit_build_times_count_close(&final, 0,
  386. (time_t)(approx_time()-final.close_ms/1000.0-1));
  387. tt_assert(!circuit_build_times_network_check_live(&estimate));
  388. tt_assert(!circuit_build_times_network_check_live(&final));
  389. log_info(LD_CIRC, "idx: %d %d, tot: %d %d",
  390. build_times_idx, estimate.build_times_idx,
  391. total_build_times, estimate.total_build_times);
  392. /* Check rollback index. Should match top of loop. */
  393. tt_assert(build_times_idx == estimate.build_times_idx);
  394. // This can fail if estimate.total_build_times == 1000, because
  395. // in that case, rewind actually causes us to lose timeouts
  396. if (total_build_times != CBT_NCIRCUITS_TO_OBSERVE)
  397. tt_assert(total_build_times == estimate.total_build_times);
  398. /* Now simulate that the network has become live and we need
  399. * a change */
  400. circuit_build_times_network_is_live(&estimate);
  401. circuit_build_times_network_is_live(&final);
  402. for (i = 0; i < CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT; i++) {
  403. circuit_build_times_count_timeout(&estimate, 1);
  404. if (i < CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT-1) {
  405. circuit_build_times_count_timeout(&final, 1);
  406. }
  407. }
  408. tt_int_op(estimate.liveness.after_firsthop_idx, OP_EQ, 0);
  409. tt_assert(final.liveness.after_firsthop_idx ==
  410. CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT-1);
  411. tt_assert(circuit_build_times_network_check_live(&estimate));
  412. tt_assert(circuit_build_times_network_check_live(&final));
  413. circuit_build_times_count_timeout(&final, 1);
  414. /* Ensure return value for degenerate cases are clamped correctly */
  415. initial.alpha = INT32_MAX;
  416. tt_assert(circuit_build_times_calculate_timeout(&initial, .99999999) <=
  417. INT32_MAX);
  418. initial.alpha = 0;
  419. tt_assert(circuit_build_times_calculate_timeout(&initial, .5) <=
  420. INT32_MAX);
  421. }
  422. done:
  423. circuit_build_times_free_timeouts(&initial);
  424. circuit_build_times_free_timeouts(&estimate);
  425. circuit_build_times_free_timeouts(&final);
  426. or_state_free(state);
  427. teardown_periodic_events();
  428. }
  429. /** Test encoding and parsing of rendezvous service descriptors. */
  430. static void
  431. test_rend_fns(void *arg)
  432. {
  433. rend_service_descriptor_t *generated = NULL, *parsed = NULL;
  434. char service_id[DIGEST_LEN];
  435. char service_id_base32[REND_SERVICE_ID_LEN_BASE32+1];
  436. const char *next_desc;
  437. smartlist_t *descs = smartlist_new();
  438. char computed_desc_id[DIGEST_LEN];
  439. char parsed_desc_id[DIGEST_LEN];
  440. crypto_pk_t *pk1 = NULL, *pk2 = NULL;
  441. time_t now;
  442. char *intro_points_encrypted = NULL;
  443. size_t intro_points_size;
  444. size_t encoded_size;
  445. int i;
  446. (void)arg;
  447. /* Initialize the service cache. */
  448. rend_cache_init();
  449. pk1 = pk_generate(0);
  450. pk2 = pk_generate(1);
  451. generated = tor_malloc_zero(sizeof(rend_service_descriptor_t));
  452. generated->pk = crypto_pk_dup_key(pk1);
  453. crypto_pk_get_digest(generated->pk, service_id);
  454. base32_encode(service_id_base32, REND_SERVICE_ID_LEN_BASE32+1,
  455. service_id, REND_SERVICE_ID_LEN);
  456. now = time(NULL);
  457. generated->timestamp = now;
  458. generated->version = 2;
  459. generated->protocols = 42;
  460. generated->intro_nodes = smartlist_new();
  461. for (i = 0; i < 3; i++) {
  462. rend_intro_point_t *intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  463. crypto_pk_t *okey = pk_generate(2 + i);
  464. intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
  465. intro->extend_info->onion_key = okey;
  466. crypto_pk_get_digest(intro->extend_info->onion_key,
  467. intro->extend_info->identity_digest);
  468. //crypto_rand(info->identity_digest, DIGEST_LEN); /* Would this work? */
  469. intro->extend_info->nickname[0] = '$';
  470. base16_encode(intro->extend_info->nickname + 1,
  471. sizeof(intro->extend_info->nickname) - 1,
  472. intro->extend_info->identity_digest, DIGEST_LEN);
  473. /* Does not cover all IP addresses. */
  474. tor_addr_from_ipv4h(&intro->extend_info->addr, crypto_rand_int(65536));
  475. intro->extend_info->port = 1 + crypto_rand_int(65535);
  476. intro->intro_key = crypto_pk_dup_key(pk2);
  477. smartlist_add(generated->intro_nodes, intro);
  478. }
  479. int rv = rend_encode_v2_descriptors(descs, generated, now, 0,
  480. REND_NO_AUTH, NULL, NULL);
  481. tt_int_op(rv, OP_GT, 0);
  482. rv = rend_compute_v2_desc_id(computed_desc_id, service_id_base32, NULL,
  483. now, 0);
  484. tt_int_op(rv, OP_EQ, 0);
  485. tt_mem_op(((rend_encoded_v2_service_descriptor_t *)
  486. smartlist_get(descs, 0))->desc_id, OP_EQ,
  487. computed_desc_id, DIGEST_LEN);
  488. rv = rend_parse_v2_service_descriptor(&parsed, parsed_desc_id,
  489. &intro_points_encrypted, &intro_points_size, &encoded_size,
  490. &next_desc,
  491. ((rend_encoded_v2_service_descriptor_t *)smartlist_get(descs, 0))
  492. ->desc_str, 1);
  493. tt_int_op(rv, OP_EQ, 0);
  494. tt_assert(parsed);
  495. tt_mem_op(((rend_encoded_v2_service_descriptor_t *)
  496. smartlist_get(descs, 0))->desc_id,OP_EQ, parsed_desc_id, DIGEST_LEN);
  497. tt_int_op(rend_parse_introduction_points(parsed, intro_points_encrypted,
  498. intro_points_size),OP_EQ, 3);
  499. tt_assert(!crypto_pk_cmp_keys(generated->pk, parsed->pk));
  500. tt_int_op(parsed->timestamp,OP_EQ, now);
  501. tt_int_op(parsed->version,OP_EQ, 2);
  502. tt_int_op(parsed->protocols,OP_EQ, 42);
  503. tt_int_op(smartlist_len(parsed->intro_nodes),OP_EQ, 3);
  504. for (i = 0; i < smartlist_len(parsed->intro_nodes); i++) {
  505. rend_intro_point_t *par_intro = smartlist_get(parsed->intro_nodes, i),
  506. *gen_intro = smartlist_get(generated->intro_nodes, i);
  507. extend_info_t *par_info = par_intro->extend_info;
  508. extend_info_t *gen_info = gen_intro->extend_info;
  509. tt_assert(!crypto_pk_cmp_keys(gen_info->onion_key, par_info->onion_key));
  510. tt_mem_op(gen_info->identity_digest,OP_EQ, par_info->identity_digest,
  511. DIGEST_LEN);
  512. tt_str_op(gen_info->nickname,OP_EQ, par_info->nickname);
  513. tt_assert(tor_addr_eq(&gen_info->addr, &par_info->addr));
  514. tt_int_op(gen_info->port,OP_EQ, par_info->port);
  515. }
  516. rend_service_descriptor_free(parsed);
  517. rend_service_descriptor_free(generated);
  518. parsed = generated = NULL;
  519. done:
  520. if (descs) {
  521. for (i = 0; i < smartlist_len(descs); i++)
  522. rend_encoded_v2_service_descriptor_free_(smartlist_get(descs, i));
  523. smartlist_free(descs);
  524. }
  525. if (parsed)
  526. rend_service_descriptor_free(parsed);
  527. if (generated)
  528. rend_service_descriptor_free(generated);
  529. if (pk1)
  530. crypto_pk_free(pk1);
  531. if (pk2)
  532. crypto_pk_free(pk2);
  533. tor_free(intro_points_encrypted);
  534. }
  535. /* Record odd numbered fake-IPs using ipv6, even numbered fake-IPs
  536. * using ipv4. Since our fake geoip database is the same between
  537. * ipv4 and ipv6, we should get the same result no matter which
  538. * address family we pick for each IP. */
  539. #define SET_TEST_ADDRESS(i) do { \
  540. if ((i) & 1) { \
  541. SET_TEST_IPV6(i); \
  542. tor_addr_from_in6(&addr, &in6); \
  543. } else { \
  544. tor_addr_from_ipv4h(&addr, (uint32_t) i); \
  545. } \
  546. } while (0)
  547. /* Make sure that country ID actually works. */
  548. #define SET_TEST_IPV6(i) \
  549. do { \
  550. set_uint32(in6.s6_addr + 12, htonl((uint32_t) (i))); \
  551. } while (0)
  552. #define CHECK_COUNTRY(country, val) do { \
  553. /* test ipv4 country lookup */ \
  554. tt_str_op(country, OP_EQ, \
  555. geoip_get_country_name(geoip_get_country_by_ipv4(val))); \
  556. /* test ipv6 country lookup */ \
  557. SET_TEST_IPV6(val); \
  558. tt_str_op(country, OP_EQ, \
  559. geoip_get_country_name(geoip_get_country_by_ipv6(&in6))); \
  560. } while (0)
  561. /** Run unit tests for GeoIP code. */
  562. static void
  563. test_geoip(void *arg)
  564. {
  565. int i, j;
  566. time_t now = 1281533250; /* 2010-08-11 13:27:30 UTC */
  567. char *s = NULL, *v = NULL;
  568. const char *bridge_stats_1 =
  569. "bridge-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  570. "bridge-ips zz=24,xy=8\n"
  571. "bridge-ip-versions v4=16,v6=16\n"
  572. "bridge-ip-transports <OR>=24\n",
  573. *dirreq_stats_1 =
  574. "dirreq-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  575. "dirreq-v3-ips ab=8\n"
  576. "dirreq-v3-reqs ab=8\n"
  577. "dirreq-v3-resp ok=0,not-enough-sigs=0,unavailable=0,not-found=0,"
  578. "not-modified=0,busy=0\n"
  579. "dirreq-v3-direct-dl complete=0,timeout=0,running=0\n"
  580. "dirreq-v3-tunneled-dl complete=0,timeout=0,running=0\n",
  581. *dirreq_stats_2 =
  582. "dirreq-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  583. "dirreq-v3-ips \n"
  584. "dirreq-v3-reqs \n"
  585. "dirreq-v3-resp ok=0,not-enough-sigs=0,unavailable=0,not-found=0,"
  586. "not-modified=0,busy=0\n"
  587. "dirreq-v3-direct-dl complete=0,timeout=0,running=0\n"
  588. "dirreq-v3-tunneled-dl complete=0,timeout=0,running=0\n",
  589. *dirreq_stats_3 =
  590. "dirreq-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  591. "dirreq-v3-ips \n"
  592. "dirreq-v3-reqs \n"
  593. "dirreq-v3-resp ok=8,not-enough-sigs=0,unavailable=0,not-found=0,"
  594. "not-modified=0,busy=0\n"
  595. "dirreq-v3-direct-dl complete=0,timeout=0,running=0\n"
  596. "dirreq-v3-tunneled-dl complete=0,timeout=0,running=0\n",
  597. *dirreq_stats_4 =
  598. "dirreq-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  599. "dirreq-v3-ips \n"
  600. "dirreq-v3-reqs \n"
  601. "dirreq-v3-resp ok=8,not-enough-sigs=0,unavailable=0,not-found=0,"
  602. "not-modified=0,busy=0\n"
  603. "dirreq-v3-direct-dl complete=0,timeout=0,running=0\n"
  604. "dirreq-v3-tunneled-dl complete=0,timeout=0,running=4\n",
  605. *entry_stats_1 =
  606. "entry-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  607. "entry-ips ab=8\n",
  608. *entry_stats_2 =
  609. "entry-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  610. "entry-ips \n";
  611. tor_addr_t addr;
  612. struct in6_addr in6;
  613. /* Populate the DB a bit. Add these in order, since we can't do the final
  614. * 'sort' step. These aren't very good IP addresses, but they're perfectly
  615. * fine uint32_t values. */
  616. (void)arg;
  617. tt_int_op(0,OP_EQ, geoip_parse_entry("10,50,AB", AF_INET));
  618. tt_int_op(0,OP_EQ, geoip_parse_entry("52,90,XY", AF_INET));
  619. tt_int_op(0,OP_EQ, geoip_parse_entry("95,100,AB", AF_INET));
  620. tt_int_op(0,OP_EQ, geoip_parse_entry("\"105\",\"140\",\"ZZ\"", AF_INET));
  621. tt_int_op(0,OP_EQ, geoip_parse_entry("\"150\",\"190\",\"XY\"", AF_INET));
  622. tt_int_op(0,OP_EQ, geoip_parse_entry("\"200\",\"250\",\"AB\"", AF_INET));
  623. /* Populate the IPv6 DB equivalently with fake IPs in the same range */
  624. tt_int_op(0,OP_EQ, geoip_parse_entry("::a,::32,AB", AF_INET6));
  625. tt_int_op(0,OP_EQ, geoip_parse_entry("::34,::5a,XY", AF_INET6));
  626. tt_int_op(0,OP_EQ, geoip_parse_entry("::5f,::64,AB", AF_INET6));
  627. tt_int_op(0,OP_EQ, geoip_parse_entry("::69,::8c,ZZ", AF_INET6));
  628. tt_int_op(0,OP_EQ, geoip_parse_entry("::96,::be,XY", AF_INET6));
  629. tt_int_op(0,OP_EQ, geoip_parse_entry("::c8,::fa,AB", AF_INET6));
  630. /* We should have 4 countries: ??, ab, xy, zz. */
  631. tt_int_op(4,OP_EQ, geoip_get_n_countries());
  632. memset(&in6, 0, sizeof(in6));
  633. CHECK_COUNTRY("??", 3);
  634. CHECK_COUNTRY("ab", 32);
  635. CHECK_COUNTRY("??", 5);
  636. CHECK_COUNTRY("??", 51);
  637. CHECK_COUNTRY("xy", 150);
  638. CHECK_COUNTRY("xy", 190);
  639. CHECK_COUNTRY("??", 2000);
  640. tt_int_op(0,OP_EQ, geoip_get_country_by_ipv4(3));
  641. SET_TEST_IPV6(3);
  642. tt_int_op(0,OP_EQ, geoip_get_country_by_ipv6(&in6));
  643. get_options_mutable()->BridgeRelay = 1;
  644. get_options_mutable()->BridgeRecordUsageByCountry = 1;
  645. /* Put 9 observations in AB... */
  646. for (i=32; i < 40; ++i) {
  647. SET_TEST_ADDRESS(i);
  648. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL, now-7200);
  649. }
  650. SET_TEST_ADDRESS(225);
  651. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL, now-7200);
  652. /* and 3 observations in XY, several times. */
  653. for (j=0; j < 10; ++j)
  654. for (i=52; i < 55; ++i) {
  655. SET_TEST_ADDRESS(i);
  656. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL, now-3600);
  657. }
  658. /* and 17 observations in ZZ... */
  659. for (i=110; i < 127; ++i) {
  660. SET_TEST_ADDRESS(i);
  661. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL, now);
  662. }
  663. geoip_get_client_history(GEOIP_CLIENT_CONNECT, &s, &v);
  664. tt_assert(s);
  665. tt_assert(v);
  666. tt_str_op("zz=24,ab=16,xy=8",OP_EQ, s);
  667. tt_str_op("v4=16,v6=16",OP_EQ, v);
  668. tor_free(s);
  669. tor_free(v);
  670. /* Now clear out all the AB observations. */
  671. geoip_remove_old_clients(now-6000);
  672. geoip_get_client_history(GEOIP_CLIENT_CONNECT, &s, &v);
  673. tt_assert(s);
  674. tt_assert(v);
  675. tt_str_op("zz=24,xy=8",OP_EQ, s);
  676. tt_str_op("v4=16,v6=16",OP_EQ, v);
  677. tor_free(s);
  678. tor_free(v);
  679. /* Start testing bridge statistics by making sure that we don't output
  680. * bridge stats without initializing them. */
  681. s = geoip_format_bridge_stats(now + 86400);
  682. tt_ptr_op(s, OP_EQ, NULL);
  683. /* Initialize stats and generate the bridge-stats history string out of
  684. * the connecting clients added above. */
  685. geoip_bridge_stats_init(now);
  686. s = geoip_format_bridge_stats(now + 86400);
  687. tt_assert(s);
  688. tt_str_op(bridge_stats_1,OP_EQ, s);
  689. tor_free(s);
  690. /* Stop collecting bridge stats and make sure we don't write a history
  691. * string anymore. */
  692. geoip_bridge_stats_term();
  693. s = geoip_format_bridge_stats(now + 86400);
  694. tt_ptr_op(s, OP_EQ, NULL);
  695. /* Stop being a bridge and start being a directory mirror that gathers
  696. * directory request statistics. */
  697. geoip_bridge_stats_term();
  698. get_options_mutable()->BridgeRelay = 0;
  699. get_options_mutable()->BridgeRecordUsageByCountry = 0;
  700. get_options_mutable()->DirReqStatistics = 1;
  701. /* Start testing dirreq statistics by making sure that we don't collect
  702. * dirreq stats without initializing them. */
  703. SET_TEST_ADDRESS(100);
  704. geoip_note_client_seen(GEOIP_CLIENT_NETWORKSTATUS, &addr, NULL, now);
  705. s = geoip_format_dirreq_stats(now + 86400);
  706. tt_ptr_op(s, OP_EQ, NULL);
  707. /* Initialize stats, note one connecting client, and generate the
  708. * dirreq-stats history string. */
  709. geoip_dirreq_stats_init(now);
  710. SET_TEST_ADDRESS(100);
  711. geoip_note_client_seen(GEOIP_CLIENT_NETWORKSTATUS, &addr, NULL, now);
  712. s = geoip_format_dirreq_stats(now + 86400);
  713. tt_str_op(dirreq_stats_1,OP_EQ, s);
  714. tor_free(s);
  715. /* Stop collecting stats, add another connecting client, and ensure we
  716. * don't generate a history string. */
  717. geoip_dirreq_stats_term();
  718. SET_TEST_ADDRESS(101);
  719. geoip_note_client_seen(GEOIP_CLIENT_NETWORKSTATUS, &addr, NULL, now);
  720. s = geoip_format_dirreq_stats(now + 86400);
  721. tt_ptr_op(s, OP_EQ, NULL);
  722. /* Re-start stats, add a connecting client, reset stats, and make sure
  723. * that we get an all empty history string. */
  724. geoip_dirreq_stats_init(now);
  725. SET_TEST_ADDRESS(100);
  726. geoip_note_client_seen(GEOIP_CLIENT_NETWORKSTATUS, &addr, NULL, now);
  727. geoip_reset_dirreq_stats(now);
  728. s = geoip_format_dirreq_stats(now + 86400);
  729. tt_str_op(dirreq_stats_2,OP_EQ, s);
  730. tor_free(s);
  731. /* Note a successful network status response and make sure that it
  732. * appears in the history string. */
  733. geoip_note_ns_response(GEOIP_SUCCESS);
  734. s = geoip_format_dirreq_stats(now + 86400);
  735. tt_str_op(dirreq_stats_3,OP_EQ, s);
  736. tor_free(s);
  737. /* Start a tunneled directory request. */
  738. geoip_start_dirreq((uint64_t) 1, 1024, DIRREQ_TUNNELED);
  739. s = geoip_format_dirreq_stats(now + 86400);
  740. tt_str_op(dirreq_stats_4,OP_EQ, s);
  741. tor_free(s);
  742. /* Stop collecting directory request statistics and start gathering
  743. * entry stats. */
  744. geoip_dirreq_stats_term();
  745. get_options_mutable()->DirReqStatistics = 0;
  746. get_options_mutable()->EntryStatistics = 1;
  747. /* Start testing entry statistics by making sure that we don't collect
  748. * anything without initializing entry stats. */
  749. SET_TEST_ADDRESS(100);
  750. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL, now);
  751. s = geoip_format_entry_stats(now + 86400);
  752. tt_ptr_op(s, OP_EQ, NULL);
  753. /* Initialize stats, note one connecting client, and generate the
  754. * entry-stats history string. */
  755. geoip_entry_stats_init(now);
  756. SET_TEST_ADDRESS(100);
  757. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL, now);
  758. s = geoip_format_entry_stats(now + 86400);
  759. tt_str_op(entry_stats_1,OP_EQ, s);
  760. tor_free(s);
  761. /* Stop collecting stats, add another connecting client, and ensure we
  762. * don't generate a history string. */
  763. geoip_entry_stats_term();
  764. SET_TEST_ADDRESS(101);
  765. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL, now);
  766. s = geoip_format_entry_stats(now + 86400);
  767. tt_ptr_op(s, OP_EQ, NULL);
  768. /* Re-start stats, add a connecting client, reset stats, and make sure
  769. * that we get an all empty history string. */
  770. geoip_entry_stats_init(now);
  771. SET_TEST_ADDRESS(100);
  772. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL, now);
  773. geoip_reset_entry_stats(now);
  774. s = geoip_format_entry_stats(now + 86400);
  775. tt_str_op(entry_stats_2,OP_EQ, s);
  776. tor_free(s);
  777. /* Test the OOM handler. Add a client, run the OOM. */
  778. geoip_entry_stats_init(now);
  779. SET_TEST_ADDRESS(100);
  780. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL,
  781. now - (12 * 60 * 60));
  782. /* We've seen this 12 hours ago. Run the OOM, it should clean the entry
  783. * because it is above the minimum cutoff of 4 hours. */
  784. size_t bytes_removed = geoip_client_cache_handle_oom(now, 1000);
  785. tt_size_op(bytes_removed, OP_GT, 0);
  786. /* Do it again but this time with an entry with a lower cutoff. */
  787. geoip_entry_stats_init(now);
  788. SET_TEST_ADDRESS(100);
  789. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL,
  790. now - (3 * 60 * 60));
  791. bytes_removed = geoip_client_cache_handle_oom(now, 1000);
  792. tt_size_op(bytes_removed, OP_EQ, 0);
  793. /* Stop collecting entry statistics. */
  794. geoip_entry_stats_term();
  795. get_options_mutable()->EntryStatistics = 0;
  796. done:
  797. tor_free(s);
  798. tor_free(v);
  799. }
  800. static void
  801. test_geoip_with_pt(void *arg)
  802. {
  803. time_t now = 1281533250; /* 2010-08-11 13:27:30 UTC */
  804. char *s = NULL;
  805. int i;
  806. tor_addr_t addr;
  807. struct in6_addr in6;
  808. (void)arg;
  809. get_options_mutable()->BridgeRelay = 1;
  810. get_options_mutable()->BridgeRecordUsageByCountry = 1;
  811. memset(&in6, 0, sizeof(in6));
  812. /* No clients seen yet. */
  813. s = geoip_get_transport_history();
  814. tor_assert(!s);
  815. /* 4 connections without a pluggable transport */
  816. for (i=0; i < 4; ++i) {
  817. SET_TEST_ADDRESS(i);
  818. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL, now-7200);
  819. }
  820. /* 9 connections with "alpha" */
  821. for (i=4; i < 13; ++i) {
  822. SET_TEST_ADDRESS(i);
  823. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, "alpha", now-7200);
  824. }
  825. /* one connection with "beta" */
  826. SET_TEST_ADDRESS(13);
  827. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, "beta", now-7200);
  828. /* 14 connections with "charlie" */
  829. for (i=14; i < 28; ++i) {
  830. SET_TEST_ADDRESS(i);
  831. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, "charlie", now-7200);
  832. }
  833. /* 131 connections with "ddr" */
  834. for (i=28; i < 159; ++i) {
  835. SET_TEST_ADDRESS(i);
  836. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, "ddr", now-7200);
  837. }
  838. /* 8 connections with "entropy" */
  839. for (i=159; i < 167; ++i) {
  840. SET_TEST_ADDRESS(i);
  841. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, "entropy", now-7200);
  842. }
  843. /* 2 connections from the same IP with two different transports. */
  844. SET_TEST_ADDRESS(++i);
  845. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, "fire", now-7200);
  846. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, "google", now-7200);
  847. /* Test the transport history string. */
  848. s = geoip_get_transport_history();
  849. tor_assert(s);
  850. tt_str_op(s,OP_EQ, "<OR>=8,alpha=16,beta=8,charlie=16,ddr=136,"
  851. "entropy=8,fire=8,google=8");
  852. /* Stop collecting entry statistics. */
  853. geoip_entry_stats_term();
  854. get_options_mutable()->EntryStatistics = 0;
  855. done:
  856. tor_free(s);
  857. }
  858. #undef SET_TEST_ADDRESS
  859. #undef SET_TEST_IPV6
  860. #undef CHECK_COUNTRY
  861. /** Run unit tests for stats code. */
  862. static void
  863. test_stats(void *arg)
  864. {
  865. time_t now = 1281533250; /* 2010-08-11 13:27:30 UTC */
  866. char *s = NULL;
  867. int i;
  868. /* Start with testing exit port statistics; we shouldn't collect exit
  869. * stats without initializing them. */
  870. (void)arg;
  871. rep_hist_note_exit_stream_opened(80);
  872. rep_hist_note_exit_bytes(80, 100, 10000);
  873. s = rep_hist_format_exit_stats(now + 86400);
  874. tt_ptr_op(s, OP_EQ, NULL);
  875. /* Initialize stats, note some streams and bytes, and generate history
  876. * string. */
  877. rep_hist_exit_stats_init(now);
  878. rep_hist_note_exit_stream_opened(80);
  879. rep_hist_note_exit_bytes(80, 100, 10000);
  880. rep_hist_note_exit_stream_opened(443);
  881. rep_hist_note_exit_bytes(443, 100, 10000);
  882. rep_hist_note_exit_bytes(443, 100, 10000);
  883. s = rep_hist_format_exit_stats(now + 86400);
  884. tt_str_op("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  885. "exit-kibibytes-written 80=1,443=1,other=0\n"
  886. "exit-kibibytes-read 80=10,443=20,other=0\n"
  887. "exit-streams-opened 80=4,443=4,other=0\n",OP_EQ, s);
  888. tor_free(s);
  889. /* Add a few bytes on 10 more ports and ensure that only the top 10
  890. * ports are contained in the history string. */
  891. for (i = 50; i < 60; i++) {
  892. rep_hist_note_exit_bytes(i, i, i);
  893. rep_hist_note_exit_stream_opened(i);
  894. }
  895. s = rep_hist_format_exit_stats(now + 86400);
  896. tt_str_op("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  897. "exit-kibibytes-written 52=1,53=1,54=1,55=1,56=1,57=1,58=1,"
  898. "59=1,80=1,443=1,other=1\n"
  899. "exit-kibibytes-read 52=1,53=1,54=1,55=1,56=1,57=1,58=1,"
  900. "59=1,80=10,443=20,other=1\n"
  901. "exit-streams-opened 52=4,53=4,54=4,55=4,56=4,57=4,58=4,"
  902. "59=4,80=4,443=4,other=4\n",OP_EQ, s);
  903. tor_free(s);
  904. /* Stop collecting stats, add some bytes, and ensure we don't generate
  905. * a history string. */
  906. rep_hist_exit_stats_term();
  907. rep_hist_note_exit_bytes(80, 100, 10000);
  908. s = rep_hist_format_exit_stats(now + 86400);
  909. tt_ptr_op(s, OP_EQ, NULL);
  910. /* Re-start stats, add some bytes, reset stats, and see what history we
  911. * get when observing no streams or bytes at all. */
  912. rep_hist_exit_stats_init(now);
  913. rep_hist_note_exit_stream_opened(80);
  914. rep_hist_note_exit_bytes(80, 100, 10000);
  915. rep_hist_reset_exit_stats(now);
  916. s = rep_hist_format_exit_stats(now + 86400);
  917. tt_str_op("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  918. "exit-kibibytes-written other=0\n"
  919. "exit-kibibytes-read other=0\n"
  920. "exit-streams-opened other=0\n",OP_EQ, s);
  921. tor_free(s);
  922. /* Continue with testing connection statistics; we shouldn't collect
  923. * conn stats without initializing them. */
  924. rep_hist_note_or_conn_bytes(1, 20, 400, now);
  925. s = rep_hist_format_conn_stats(now + 86400);
  926. tt_ptr_op(s, OP_EQ, NULL);
  927. /* Initialize stats, note bytes, and generate history string. */
  928. rep_hist_conn_stats_init(now);
  929. rep_hist_note_or_conn_bytes(1, 30000, 400000, now);
  930. rep_hist_note_or_conn_bytes(1, 30000, 400000, now + 5);
  931. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 10);
  932. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 15);
  933. s = rep_hist_format_conn_stats(now + 86400);
  934. tt_str_op("conn-bi-direct 2010-08-12 13:27:30 (86400 s) 0,0,1,0\n",OP_EQ, s);
  935. tor_free(s);
  936. /* Stop collecting stats, add some bytes, and ensure we don't generate
  937. * a history string. */
  938. rep_hist_conn_stats_term();
  939. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 15);
  940. s = rep_hist_format_conn_stats(now + 86400);
  941. tt_ptr_op(s, OP_EQ, NULL);
  942. /* Re-start stats, add some bytes, reset stats, and see what history we
  943. * get when observing no bytes at all. */
  944. rep_hist_conn_stats_init(now);
  945. rep_hist_note_or_conn_bytes(1, 30000, 400000, now);
  946. rep_hist_note_or_conn_bytes(1, 30000, 400000, now + 5);
  947. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 10);
  948. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 15);
  949. rep_hist_reset_conn_stats(now);
  950. s = rep_hist_format_conn_stats(now + 86400);
  951. tt_str_op("conn-bi-direct 2010-08-12 13:27:30 (86400 s) 0,0,0,0\n",OP_EQ, s);
  952. tor_free(s);
  953. /* Continue with testing buffer statistics; we shouldn't collect buffer
  954. * stats without initializing them. */
  955. rep_hist_add_buffer_stats(2.0, 2.0, 20);
  956. s = rep_hist_format_buffer_stats(now + 86400);
  957. tt_ptr_op(s, OP_EQ, NULL);
  958. /* Initialize stats, add statistics for a single circuit, and generate
  959. * the history string. */
  960. rep_hist_buffer_stats_init(now);
  961. rep_hist_add_buffer_stats(2.0, 2.0, 20);
  962. s = rep_hist_format_buffer_stats(now + 86400);
  963. tt_str_op("cell-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  964. "cell-processed-cells 20,0,0,0,0,0,0,0,0,0\n"
  965. "cell-queued-cells 2.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,"
  966. "0.00,0.00\n"
  967. "cell-time-in-queue 2,0,0,0,0,0,0,0,0,0\n"
  968. "cell-circuits-per-decile 1\n",OP_EQ, s);
  969. tor_free(s);
  970. /* Add nineteen more circuit statistics to the one that's already in the
  971. * history to see that the math works correctly. */
  972. for (i = 21; i < 30; i++)
  973. rep_hist_add_buffer_stats(2.0, 2.0, i);
  974. for (i = 20; i < 30; i++)
  975. rep_hist_add_buffer_stats(3.5, 3.5, i);
  976. s = rep_hist_format_buffer_stats(now + 86400);
  977. tt_str_op("cell-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  978. "cell-processed-cells 29,28,27,26,25,24,23,22,21,20\n"
  979. "cell-queued-cells 2.75,2.75,2.75,2.75,2.75,2.75,2.75,2.75,"
  980. "2.75,2.75\n"
  981. "cell-time-in-queue 3,3,3,3,3,3,3,3,3,3\n"
  982. "cell-circuits-per-decile 2\n",OP_EQ, s);
  983. tor_free(s);
  984. /* Stop collecting stats, add statistics for one circuit, and ensure we
  985. * don't generate a history string. */
  986. rep_hist_buffer_stats_term();
  987. rep_hist_add_buffer_stats(2.0, 2.0, 20);
  988. s = rep_hist_format_buffer_stats(now + 86400);
  989. tt_ptr_op(s, OP_EQ, NULL);
  990. /* Re-start stats, add statistics for one circuit, reset stats, and make
  991. * sure that the history has all zeros. */
  992. rep_hist_buffer_stats_init(now);
  993. rep_hist_add_buffer_stats(2.0, 2.0, 20);
  994. rep_hist_reset_buffer_stats(now);
  995. s = rep_hist_format_buffer_stats(now + 86400);
  996. tt_str_op("cell-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  997. "cell-processed-cells 0,0,0,0,0,0,0,0,0,0\n"
  998. "cell-queued-cells 0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,"
  999. "0.00,0.00\n"
  1000. "cell-time-in-queue 0,0,0,0,0,0,0,0,0,0\n"
  1001. "cell-circuits-per-decile 0\n",OP_EQ, s);
  1002. done:
  1003. tor_free(s);
  1004. }
  1005. #define ENT(name) \
  1006. { #name, test_ ## name , 0, NULL, NULL }
  1007. #define FORK(name) \
  1008. { #name, test_ ## name , TT_FORK, NULL, NULL }
  1009. static struct testcase_t test_array[] = {
  1010. ENT(onion_handshake),
  1011. { "bad_onion_handshake", test_bad_onion_handshake, 0, NULL, NULL },
  1012. ENT(onion_queues),
  1013. { "ntor_handshake", test_ntor_handshake, 0, NULL, NULL },
  1014. { "fast_handshake", test_fast_handshake, 0, NULL, NULL },
  1015. FORK(circuit_timeout),
  1016. FORK(rend_fns),
  1017. ENT(geoip),
  1018. FORK(geoip_with_pt),
  1019. FORK(stats),
  1020. END_OF_TESTCASES
  1021. };
  1022. struct testgroup_t testgroups[] = {
  1023. { "", test_array },
  1024. { "accounting/", accounting_tests },
  1025. { "addr/", addr_tests },
  1026. { "address/", address_tests },
  1027. { "address_set/", address_set_tests },
  1028. { "buffer/", buffer_tests },
  1029. { "cellfmt/", cell_format_tests },
  1030. { "cellqueue/", cell_queue_tests },
  1031. { "channel/", channel_tests },
  1032. { "channelpadding/", channelpadding_tests },
  1033. { "channeltls/", channeltls_tests },
  1034. { "checkdir/", checkdir_tests },
  1035. { "circuitbuild/", circuitbuild_tests },
  1036. { "circuitlist/", circuitlist_tests },
  1037. { "circuitmux/", circuitmux_tests },
  1038. { "circuituse/", circuituse_tests },
  1039. { "circuitstats/", circuitstats_tests },
  1040. { "compat/libevent/", compat_libevent_tests },
  1041. { "config/", config_tests },
  1042. { "connection/", connection_tests },
  1043. { "conscache/", conscache_tests },
  1044. { "consdiff/", consdiff_tests },
  1045. { "consdiffmgr/", consdiffmgr_tests },
  1046. { "container/", container_tests },
  1047. { "control/", controller_tests },
  1048. { "control/event/", controller_event_tests },
  1049. { "crypto/", crypto_tests },
  1050. { "crypto/openssl/", crypto_openssl_tests },
  1051. { "dir/", dir_tests },
  1052. { "dir_handle_get/", dir_handle_get_tests },
  1053. { "dir/md/", microdesc_tests },
  1054. { "dos/", dos_tests },
  1055. { "entryconn/", entryconn_tests },
  1056. { "entrynodes/", entrynodes_tests },
  1057. { "guardfraction/", guardfraction_tests },
  1058. { "extorport/", extorport_tests },
  1059. { "legacy_hs/", hs_tests },
  1060. { "hs_cache/", hs_cache },
  1061. { "hs_cell/", hs_cell_tests },
  1062. { "hs_common/", hs_common_tests },
  1063. { "hs_config/", hs_config_tests },
  1064. { "hs_control/", hs_control_tests },
  1065. { "hs_descriptor/", hs_descriptor },
  1066. { "hs_ntor/", hs_ntor_tests },
  1067. { "hs_service/", hs_service_tests },
  1068. { "hs_client/", hs_client_tests },
  1069. { "hs_intropoint/", hs_intropoint_tests },
  1070. { "introduce/", introduce_tests },
  1071. { "keypin/", keypin_tests },
  1072. { "link-handshake/", link_handshake_tests },
  1073. { "nodelist/", nodelist_tests },
  1074. { "oom/", oom_tests },
  1075. { "oos/", oos_tests },
  1076. { "options/", options_tests },
  1077. { "policy/" , policy_tests },
  1078. { "procmon/", procmon_tests },
  1079. { "proto/http/", proto_http_tests },
  1080. { "proto/misc/", proto_misc_tests },
  1081. { "protover/", protover_tests },
  1082. { "pt/", pt_tests },
  1083. { "relay/" , relay_tests },
  1084. { "relaycell/", relaycell_tests },
  1085. { "rend_cache/", rend_cache_tests },
  1086. { "replaycache/", replaycache_tests },
  1087. { "router/", router_tests },
  1088. { "routerkeys/", routerkeys_tests },
  1089. { "routerlist/", routerlist_tests },
  1090. { "routerset/" , routerset_tests },
  1091. { "scheduler/", scheduler_tests },
  1092. { "socks/", socks_tests },
  1093. { "shared-random/", sr_tests },
  1094. { "status/" , status_tests },
  1095. { "storagedir/", storagedir_tests },
  1096. { "tortls/", tortls_tests },
  1097. { "util/", util_tests },
  1098. { "util/format/", util_format_tests },
  1099. { "util/logging/", logging_tests },
  1100. { "util/process/", util_process_tests },
  1101. { "util/pubsub/", pubsub_tests },
  1102. { "util/thread/", thread_tests },
  1103. { "util/handle/", handle_tests },
  1104. { "dns/", dns_tests },
  1105. END_OF_GROUPS
  1106. };