test.c 44 KB

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