test.c 44 KB

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