test.c 43 KB

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