test.c 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439
  1. /* Copyright (c) 2001-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2013, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /* Ordinarily defined in tor_main.c; this bit is just here to provide one
  6. * since we're not linking to tor_main.c */
  7. const char tor_git_revision[] = "";
  8. /**
  9. * \file test.c
  10. * \brief Unit tests for many pieces of the lower level Tor modules.
  11. **/
  12. #include "orconfig.h"
  13. #include <stdio.h>
  14. #ifdef HAVE_FCNTL_H
  15. #include <fcntl.h>
  16. #endif
  17. #ifdef _WIN32
  18. /* For mkdir() */
  19. #include <direct.h>
  20. #else
  21. #include <dirent.h>
  22. #endif
  23. /* These macros pull in declarations for some functions and structures that
  24. * are typically file-private. */
  25. #define GEOIP_PRIVATE
  26. #define ROUTER_PRIVATE
  27. #define CIRCUITSTATS_PRIVATE
  28. #define CIRCUITLIST_PRIVATE
  29. #define STATEFILE_PRIVATE
  30. /*
  31. * Linux doesn't provide lround in math.h by default, but mac os does...
  32. * It's best just to leave math.h out of the picture entirely.
  33. */
  34. //#include <math.h>
  35. long int lround(double x);
  36. double fabs(double x);
  37. #include "or.h"
  38. #include "buffers.h"
  39. #include "circuitlist.h"
  40. #include "circuitstats.h"
  41. #include "config.h"
  42. #include "connection_edge.h"
  43. #include "geoip.h"
  44. #include "rendcommon.h"
  45. #include "test.h"
  46. #include "torgzip.h"
  47. #ifdef ENABLE_MEMPOOLS
  48. #include "mempool.h"
  49. #endif
  50. #include "memarea.h"
  51. #include "onion.h"
  52. #include "onion_ntor.h"
  53. #include "onion_tap.h"
  54. #include "policies.h"
  55. #include "rephist.h"
  56. #include "routerparse.h"
  57. #include "statefile.h"
  58. #ifdef CURVE25519_ENABLED
  59. #include "crypto_curve25519.h"
  60. #include "onion_ntor.h"
  61. #endif
  62. #ifdef USE_DMALLOC
  63. #include <dmalloc.h>
  64. #include <openssl/crypto.h>
  65. #include "main.h"
  66. #endif
  67. /** Set to true if any unit test has failed. Mostly, this is set by the macros
  68. * in test.h */
  69. int have_failed = 0;
  70. /** Temporary directory (set up by setup_directory) under which we store all
  71. * our files during testing. */
  72. static char temp_dir[256];
  73. #ifdef _WIN32
  74. #define pid_t int
  75. #endif
  76. static pid_t temp_dir_setup_in_pid = 0;
  77. /** Select and create the temporary directory we'll use to run our unit tests.
  78. * Store it in <b>temp_dir</b>. Exit immediately if we can't create it.
  79. * idempotent. */
  80. static void
  81. setup_directory(void)
  82. {
  83. static int is_setup = 0;
  84. int r;
  85. char rnd[256], rnd32[256];
  86. if (is_setup) return;
  87. /* Due to base32 limitation needs to be a multiple of 5. */
  88. #define RAND_PATH_BYTES 5
  89. crypto_rand(rnd, RAND_PATH_BYTES);
  90. base32_encode(rnd32, sizeof(rnd32), rnd, RAND_PATH_BYTES);
  91. #ifdef _WIN32
  92. {
  93. char buf[MAX_PATH];
  94. const char *tmp = buf;
  95. const char *extra_backslash = "";
  96. /* If this fails, we're probably screwed anyway */
  97. if (!GetTempPathA(sizeof(buf),buf))
  98. tmp = "c:\\windows\\temp\\";
  99. if (strcmpend(tmp, "\\")) {
  100. /* According to MSDN, it should be impossible for GetTempPath to give us
  101. * an answer that doesn't end with \. But let's make sure. */
  102. extra_backslash = "\\";
  103. }
  104. tor_snprintf(temp_dir, sizeof(temp_dir),
  105. "%s%stor_test_%d_%s", tmp, extra_backslash,
  106. (int)getpid(), rnd32);
  107. r = mkdir(temp_dir);
  108. }
  109. #else
  110. tor_snprintf(temp_dir, sizeof(temp_dir), "/tmp/tor_test_%d_%s",
  111. (int) getpid(), rnd32);
  112. r = mkdir(temp_dir, 0700);
  113. #endif
  114. if (r) {
  115. fprintf(stderr, "Can't create directory %s:", temp_dir);
  116. perror("");
  117. exit(1);
  118. }
  119. is_setup = 1;
  120. temp_dir_setup_in_pid = getpid();
  121. }
  122. /** Return a filename relative to our testing temporary directory */
  123. const char *
  124. get_fname(const char *name)
  125. {
  126. static char buf[1024];
  127. setup_directory();
  128. if (!name)
  129. return temp_dir;
  130. tor_snprintf(buf,sizeof(buf),"%s/%s",temp_dir,name);
  131. return buf;
  132. }
  133. /* Remove a directory and all of its subdirectories */
  134. static void
  135. rm_rf(const char *dir)
  136. {
  137. struct stat st;
  138. smartlist_t *elements;
  139. elements = tor_listdir(dir);
  140. if (elements) {
  141. SMARTLIST_FOREACH_BEGIN(elements, const char *, cp) {
  142. char *tmp = NULL;
  143. tor_asprintf(&tmp, "%s"PATH_SEPARATOR"%s", dir, cp);
  144. if (0 == stat(tmp,&st) && (st.st_mode & S_IFDIR)) {
  145. rm_rf(tmp);
  146. } else {
  147. if (unlink(tmp)) {
  148. fprintf(stderr, "Error removing %s: %s\n", tmp, strerror(errno));
  149. }
  150. }
  151. tor_free(tmp);
  152. } SMARTLIST_FOREACH_END(cp);
  153. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  154. smartlist_free(elements);
  155. }
  156. if (rmdir(dir))
  157. fprintf(stderr, "Error removing directory %s: %s\n", dir, strerror(errno));
  158. }
  159. /** Remove all files stored under the temporary directory, and the directory
  160. * itself. Called by atexit(). */
  161. static void
  162. remove_directory(void)
  163. {
  164. if (getpid() != temp_dir_setup_in_pid) {
  165. /* Only clean out the tempdir when the main process is exiting. */
  166. return;
  167. }
  168. rm_rf(temp_dir);
  169. }
  170. /** Define this if unit tests spend too much time generating public keys*/
  171. #undef CACHE_GENERATED_KEYS
  172. static crypto_pk_t *pregen_keys[5] = {NULL, NULL, NULL, NULL, NULL};
  173. #define N_PREGEN_KEYS ((int)(sizeof(pregen_keys)/sizeof(pregen_keys[0])))
  174. /** Generate and return a new keypair for use in unit tests. If we're using
  175. * the key cache optimization, we might reuse keys: we only guarantee that
  176. * keys made with distinct values for <b>idx</b> are different. The value of
  177. * <b>idx</b> must be at least 0, and less than N_PREGEN_KEYS. */
  178. crypto_pk_t *
  179. pk_generate(int idx)
  180. {
  181. #ifdef CACHE_GENERATED_KEYS
  182. tor_assert(idx < N_PREGEN_KEYS);
  183. if (! pregen_keys[idx]) {
  184. pregen_keys[idx] = crypto_pk_new();
  185. tor_assert(!crypto_pk_generate_key(pregen_keys[idx]));
  186. }
  187. return crypto_pk_dup_key(pregen_keys[idx]);
  188. #else
  189. crypto_pk_t *result;
  190. (void) idx;
  191. result = crypto_pk_new();
  192. tor_assert(!crypto_pk_generate_key(result));
  193. return result;
  194. #endif
  195. }
  196. /** Free all storage used for the cached key optimization. */
  197. static void
  198. free_pregenerated_keys(void)
  199. {
  200. unsigned idx;
  201. for (idx = 0; idx < N_PREGEN_KEYS; ++idx) {
  202. if (pregen_keys[idx]) {
  203. crypto_pk_free(pregen_keys[idx]);
  204. pregen_keys[idx] = NULL;
  205. }
  206. }
  207. }
  208. /** Run unit tests for the onion handshake code. */
  209. static void
  210. test_onion_handshake(void)
  211. {
  212. /* client-side */
  213. crypto_dh_t *c_dh = NULL;
  214. char c_buf[TAP_ONIONSKIN_CHALLENGE_LEN];
  215. char c_keys[40];
  216. /* server-side */
  217. char s_buf[TAP_ONIONSKIN_REPLY_LEN];
  218. char s_keys[40];
  219. int i;
  220. /* shared */
  221. crypto_pk_t *pk = NULL, *pk2 = NULL;
  222. pk = pk_generate(0);
  223. pk2 = pk_generate(1);
  224. /* client handshake 1. */
  225. memset(c_buf, 0, TAP_ONIONSKIN_CHALLENGE_LEN);
  226. test_assert(! onion_skin_TAP_create(pk, &c_dh, c_buf));
  227. for (i = 1; i <= 3; ++i) {
  228. crypto_pk_t *k1, *k2;
  229. if (i==1) {
  230. /* server handshake: only one key known. */
  231. k1 = pk; k2 = NULL;
  232. } else if (i==2) {
  233. /* server handshake: try the right key first. */
  234. k1 = pk; k2 = pk2;
  235. } else {
  236. /* server handshake: try the right key second. */
  237. k1 = pk2; k2 = pk;
  238. }
  239. memset(s_buf, 0, TAP_ONIONSKIN_REPLY_LEN);
  240. memset(s_keys, 0, 40);
  241. test_assert(! onion_skin_TAP_server_handshake(c_buf, k1, k2,
  242. s_buf, s_keys, 40));
  243. /* client handshake 2 */
  244. memset(c_keys, 0, 40);
  245. test_assert(! onion_skin_TAP_client_handshake(c_dh, s_buf, c_keys, 40));
  246. test_memeq(c_keys, s_keys, 40);
  247. memset(s_buf, 0, 40);
  248. test_memneq(c_keys, s_buf, 40);
  249. }
  250. done:
  251. crypto_dh_free(c_dh);
  252. crypto_pk_free(pk);
  253. crypto_pk_free(pk2);
  254. }
  255. static void
  256. test_bad_onion_handshake(void *arg)
  257. {
  258. char junk_buf[TAP_ONIONSKIN_CHALLENGE_LEN];
  259. char junk_buf2[TAP_ONIONSKIN_CHALLENGE_LEN];
  260. /* client-side */
  261. crypto_dh_t *c_dh = NULL;
  262. char c_buf[TAP_ONIONSKIN_CHALLENGE_LEN];
  263. char c_keys[40];
  264. /* server-side */
  265. char s_buf[TAP_ONIONSKIN_REPLY_LEN];
  266. char s_keys[40];
  267. /* shared */
  268. crypto_pk_t *pk = NULL, *pk2 = NULL;
  269. (void)arg;
  270. pk = pk_generate(0);
  271. pk2 = pk_generate(1);
  272. /* Server: Case 1: the encrypted data is degenerate. */
  273. memset(junk_buf, 0, sizeof(junk_buf));
  274. crypto_pk_public_hybrid_encrypt(pk, junk_buf2, TAP_ONIONSKIN_CHALLENGE_LEN,
  275. junk_buf, DH_KEY_LEN, PK_PKCS1_OAEP_PADDING, 1);
  276. tt_int_op(-1, ==,
  277. onion_skin_TAP_server_handshake(junk_buf2, pk, NULL,
  278. s_buf, s_keys, 40));
  279. /* Server: Case 2: the encrypted data is not long enough. */
  280. memset(junk_buf, 0, sizeof(junk_buf));
  281. memset(junk_buf2, 0, sizeof(junk_buf2));
  282. crypto_pk_public_encrypt(pk, junk_buf2, sizeof(junk_buf2),
  283. junk_buf, 48, PK_PKCS1_OAEP_PADDING);
  284. tt_int_op(-1, ==,
  285. onion_skin_TAP_server_handshake(junk_buf2, pk, NULL,
  286. s_buf, s_keys, 40));
  287. /* client handshake 1: do it straight. */
  288. memset(c_buf, 0, TAP_ONIONSKIN_CHALLENGE_LEN);
  289. test_assert(! onion_skin_TAP_create(pk, &c_dh, c_buf));
  290. /* Server: Case 3: we just don't have the right key. */
  291. tt_int_op(-1, ==,
  292. onion_skin_TAP_server_handshake(c_buf, pk2, NULL,
  293. s_buf, s_keys, 40));
  294. /* Server: Case 4: The RSA-encrypted portion is corrupt. */
  295. c_buf[64] ^= 33;
  296. tt_int_op(-1, ==,
  297. onion_skin_TAP_server_handshake(c_buf, pk, NULL,
  298. s_buf, s_keys, 40));
  299. c_buf[64] ^= 33;
  300. /* (Let the server procede) */
  301. tt_int_op(0, ==,
  302. onion_skin_TAP_server_handshake(c_buf, pk, NULL,
  303. s_buf, s_keys, 40));
  304. /* Client: Case 1: The server sent back junk. */
  305. s_buf[64] ^= 33;
  306. tt_int_op(-1, ==,
  307. onion_skin_TAP_client_handshake(c_dh, s_buf, c_keys, 40));
  308. s_buf[64] ^= 33;
  309. /* Let the client finish; make sure it can. */
  310. tt_int_op(0, ==,
  311. onion_skin_TAP_client_handshake(c_dh, s_buf, c_keys, 40));
  312. test_memeq(s_keys, c_keys, 40);
  313. /* Client: Case 2: The server sent back a degenerate DH. */
  314. memset(s_buf, 0, sizeof(s_buf));
  315. tt_int_op(-1, ==,
  316. onion_skin_TAP_client_handshake(c_dh, s_buf, c_keys, 40));
  317. done:
  318. crypto_dh_free(c_dh);
  319. crypto_pk_free(pk);
  320. crypto_pk_free(pk2);
  321. }
  322. #ifdef CURVE25519_ENABLED
  323. static void
  324. test_ntor_handshake(void *arg)
  325. {
  326. /* client-side */
  327. ntor_handshake_state_t *c_state = NULL;
  328. uint8_t c_buf[NTOR_ONIONSKIN_LEN];
  329. uint8_t c_keys[400];
  330. /* server-side */
  331. di_digest256_map_t *s_keymap=NULL;
  332. curve25519_keypair_t s_keypair;
  333. uint8_t s_buf[NTOR_REPLY_LEN];
  334. uint8_t s_keys[400];
  335. /* shared */
  336. const curve25519_public_key_t *server_pubkey;
  337. uint8_t node_id[20] = "abcdefghijklmnopqrst";
  338. (void) arg;
  339. /* Make the server some keys */
  340. curve25519_secret_key_generate(&s_keypair.seckey, 0);
  341. curve25519_public_key_generate(&s_keypair.pubkey, &s_keypair.seckey);
  342. dimap_add_entry(&s_keymap, s_keypair.pubkey.public_key, &s_keypair);
  343. server_pubkey = &s_keypair.pubkey;
  344. /* client handshake 1. */
  345. memset(c_buf, 0, NTOR_ONIONSKIN_LEN);
  346. tt_int_op(0, ==, onion_skin_ntor_create(node_id, server_pubkey,
  347. &c_state, c_buf));
  348. /* server handshake */
  349. memset(s_buf, 0, NTOR_REPLY_LEN);
  350. memset(s_keys, 0, 40);
  351. tt_int_op(0, ==, onion_skin_ntor_server_handshake(c_buf, s_keymap, NULL,
  352. node_id,
  353. s_buf, s_keys, 400));
  354. /* client handshake 2 */
  355. memset(c_keys, 0, 40);
  356. tt_int_op(0, ==, onion_skin_ntor_client_handshake(c_state, s_buf,
  357. c_keys, 400));
  358. test_memeq(c_keys, s_keys, 400);
  359. memset(s_buf, 0, 40);
  360. test_memneq(c_keys, s_buf, 40);
  361. done:
  362. ntor_handshake_state_free(c_state);
  363. dimap_free(s_keymap, NULL);
  364. }
  365. #endif
  366. /** Run unit tests for the onion queues. */
  367. static void
  368. test_onion_queues(void)
  369. {
  370. uint8_t buf1[TAP_ONIONSKIN_CHALLENGE_LEN] = {0};
  371. uint8_t buf2[NTOR_ONIONSKIN_LEN] = {0};
  372. or_circuit_t *circ1 = or_circuit_new(0, NULL);
  373. or_circuit_t *circ2 = or_circuit_new(0, NULL);
  374. create_cell_t *onionskin = NULL, *create2_ptr;
  375. create_cell_t *create1 = tor_malloc_zero(sizeof(create_cell_t));
  376. create_cell_t *create2 = tor_malloc_zero(sizeof(create_cell_t));
  377. create2_ptr = create2; /* remember, but do not free */
  378. create_cell_init(create1, CELL_CREATE, ONION_HANDSHAKE_TYPE_TAP,
  379. TAP_ONIONSKIN_CHALLENGE_LEN, buf1);
  380. create_cell_init(create2, CELL_CREATE, ONION_HANDSHAKE_TYPE_NTOR,
  381. NTOR_ONIONSKIN_LEN, buf2);
  382. test_eq(0, onion_num_pending(ONION_HANDSHAKE_TYPE_TAP));
  383. test_eq(0, onion_pending_add(circ1, create1));
  384. create1 = NULL;
  385. test_eq(1, onion_num_pending(ONION_HANDSHAKE_TYPE_TAP));
  386. test_eq(0, onion_num_pending(ONION_HANDSHAKE_TYPE_NTOR));
  387. test_eq(0, onion_pending_add(circ2, create2));
  388. create2 = NULL;
  389. test_eq(1, onion_num_pending(ONION_HANDSHAKE_TYPE_NTOR));
  390. test_eq_ptr(circ2, onion_next_task(&onionskin));
  391. test_eq(1, onion_num_pending(ONION_HANDSHAKE_TYPE_TAP));
  392. test_eq(0, onion_num_pending(ONION_HANDSHAKE_TYPE_NTOR));
  393. tt_ptr_op(onionskin, ==, create2_ptr);
  394. clear_pending_onions();
  395. test_eq(0, onion_num_pending(ONION_HANDSHAKE_TYPE_TAP));
  396. test_eq(0, onion_num_pending(ONION_HANDSHAKE_TYPE_NTOR));
  397. done:
  398. circuit_free(TO_CIRCUIT(circ1));
  399. circuit_free(TO_CIRCUIT(circ2));
  400. tor_free(create1);
  401. tor_free(create2);
  402. tor_free(onionskin);
  403. }
  404. static void
  405. test_circuit_timeout(void)
  406. {
  407. /* Plan:
  408. * 1. Generate 1000 samples
  409. * 2. Estimate parameters
  410. * 3. If difference, repeat
  411. * 4. Save state
  412. * 5. load state
  413. * 6. Estimate parameters
  414. * 7. compare differences
  415. */
  416. circuit_build_times_t initial;
  417. circuit_build_times_t estimate;
  418. circuit_build_times_t final;
  419. double timeout1, timeout2;
  420. or_state_t *state=NULL;
  421. int i, runs;
  422. double close_ms;
  423. circuit_build_times_init(&initial);
  424. circuit_build_times_init(&estimate);
  425. circuit_build_times_init(&final);
  426. state = or_state_new();
  427. circuitbuild_running_unit_tests();
  428. #define timeout0 (build_time_t)(30*1000.0)
  429. initial.Xm = 3000;
  430. circuit_build_times_initial_alpha(&initial,
  431. CBT_DEFAULT_QUANTILE_CUTOFF/100.0,
  432. timeout0);
  433. close_ms = MAX(circuit_build_times_calculate_timeout(&initial,
  434. CBT_DEFAULT_CLOSE_QUANTILE/100.0),
  435. CBT_DEFAULT_TIMEOUT_INITIAL_VALUE);
  436. do {
  437. for (i=0; i < CBT_DEFAULT_MIN_CIRCUITS_TO_OBSERVE; i++) {
  438. build_time_t sample = circuit_build_times_generate_sample(&initial,0,1);
  439. if (sample > close_ms) {
  440. circuit_build_times_add_time(&estimate, CBT_BUILD_ABANDONED);
  441. } else {
  442. circuit_build_times_add_time(&estimate, sample);
  443. }
  444. }
  445. circuit_build_times_update_alpha(&estimate);
  446. timeout1 = circuit_build_times_calculate_timeout(&estimate,
  447. CBT_DEFAULT_QUANTILE_CUTOFF/100.0);
  448. circuit_build_times_set_timeout(&estimate);
  449. log_notice(LD_CIRC, "Timeout1 is %f, Xm is %d", timeout1, estimate.Xm);
  450. /* 2% error */
  451. } while (fabs(circuit_build_times_cdf(&initial, timeout0) -
  452. circuit_build_times_cdf(&initial, timeout1)) > 0.02);
  453. test_assert(estimate.total_build_times <= CBT_NCIRCUITS_TO_OBSERVE);
  454. circuit_build_times_update_state(&estimate, state);
  455. circuit_build_times_free_timeouts(&final);
  456. test_assert(circuit_build_times_parse_state(&final, state) == 0);
  457. circuit_build_times_update_alpha(&final);
  458. timeout2 = circuit_build_times_calculate_timeout(&final,
  459. CBT_DEFAULT_QUANTILE_CUTOFF/100.0);
  460. circuit_build_times_set_timeout(&final);
  461. log_notice(LD_CIRC, "Timeout2 is %f, Xm is %d", timeout2, final.Xm);
  462. /* 5% here because some accuracy is lost due to histogram conversion */
  463. test_assert(fabs(circuit_build_times_cdf(&initial, timeout0) -
  464. circuit_build_times_cdf(&initial, timeout2)) < 0.05);
  465. for (runs = 0; runs < 50; runs++) {
  466. int build_times_idx = 0;
  467. int total_build_times = 0;
  468. final.close_ms = final.timeout_ms = CBT_DEFAULT_TIMEOUT_INITIAL_VALUE;
  469. estimate.close_ms = estimate.timeout_ms
  470. = CBT_DEFAULT_TIMEOUT_INITIAL_VALUE;
  471. for (i = 0; i < CBT_DEFAULT_RECENT_CIRCUITS*2; i++) {
  472. circuit_build_times_network_circ_success(&estimate);
  473. circuit_build_times_add_time(&estimate,
  474. circuit_build_times_generate_sample(&estimate, 0,
  475. CBT_DEFAULT_QUANTILE_CUTOFF/100.0));
  476. circuit_build_times_network_circ_success(&estimate);
  477. circuit_build_times_add_time(&final,
  478. circuit_build_times_generate_sample(&final, 0,
  479. CBT_DEFAULT_QUANTILE_CUTOFF/100.0));
  480. }
  481. test_assert(!circuit_build_times_network_check_changed(&estimate));
  482. test_assert(!circuit_build_times_network_check_changed(&final));
  483. /* Reset liveness to be non-live */
  484. final.liveness.network_last_live = 0;
  485. estimate.liveness.network_last_live = 0;
  486. build_times_idx = estimate.build_times_idx;
  487. total_build_times = estimate.total_build_times;
  488. test_assert(circuit_build_times_network_check_live(&estimate));
  489. test_assert(circuit_build_times_network_check_live(&final));
  490. circuit_build_times_count_close(&estimate, 0,
  491. (time_t)(approx_time()-estimate.close_ms/1000.0-1));
  492. circuit_build_times_count_close(&final, 0,
  493. (time_t)(approx_time()-final.close_ms/1000.0-1));
  494. test_assert(!circuit_build_times_network_check_live(&estimate));
  495. test_assert(!circuit_build_times_network_check_live(&final));
  496. log_info(LD_CIRC, "idx: %d %d, tot: %d %d",
  497. build_times_idx, estimate.build_times_idx,
  498. total_build_times, estimate.total_build_times);
  499. /* Check rollback index. Should match top of loop. */
  500. test_assert(build_times_idx == estimate.build_times_idx);
  501. // This can fail if estimate.total_build_times == 1000, because
  502. // in that case, rewind actually causes us to lose timeouts
  503. if (total_build_times != CBT_NCIRCUITS_TO_OBSERVE)
  504. test_assert(total_build_times == estimate.total_build_times);
  505. /* Now simulate that the network has become live and we need
  506. * a change */
  507. circuit_build_times_network_is_live(&estimate);
  508. circuit_build_times_network_is_live(&final);
  509. for (i = 0; i < CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT; i++) {
  510. circuit_build_times_count_timeout(&estimate, 1);
  511. if (i < CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT-1) {
  512. circuit_build_times_count_timeout(&final, 1);
  513. }
  514. }
  515. test_assert(estimate.liveness.after_firsthop_idx == 0);
  516. test_assert(final.liveness.after_firsthop_idx ==
  517. CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT-1);
  518. test_assert(circuit_build_times_network_check_live(&estimate));
  519. test_assert(circuit_build_times_network_check_live(&final));
  520. circuit_build_times_count_timeout(&final, 1);
  521. }
  522. done:
  523. circuit_build_times_free_timeouts(&initial);
  524. circuit_build_times_free_timeouts(&estimate);
  525. circuit_build_times_free_timeouts(&final);
  526. or_state_free(state);
  527. }
  528. /** Test encoding and parsing of rendezvous service descriptors. */
  529. static void
  530. test_rend_fns(void)
  531. {
  532. rend_service_descriptor_t *generated = NULL, *parsed = NULL;
  533. char service_id[DIGEST_LEN];
  534. char service_id_base32[REND_SERVICE_ID_LEN_BASE32+1];
  535. const char *next_desc;
  536. smartlist_t *descs = smartlist_new();
  537. char computed_desc_id[DIGEST_LEN];
  538. char parsed_desc_id[DIGEST_LEN];
  539. crypto_pk_t *pk1 = NULL, *pk2 = NULL;
  540. time_t now;
  541. char *intro_points_encrypted = NULL;
  542. size_t intro_points_size;
  543. size_t encoded_size;
  544. int i;
  545. char address1[] = "fooaddress.onion";
  546. char address2[] = "aaaaaaaaaaaaaaaa.onion";
  547. char address3[] = "fooaddress.exit";
  548. char address4[] = "www.torproject.org";
  549. char address5[] = "foo.abcdefghijklmnop.onion";
  550. char address6[] = "foo.bar.abcdefghijklmnop.onion";
  551. char address7[] = ".abcdefghijklmnop.onion";
  552. test_assert(BAD_HOSTNAME == parse_extended_hostname(address1));
  553. test_assert(ONION_HOSTNAME == parse_extended_hostname(address2));
  554. test_streq(address2, "aaaaaaaaaaaaaaaa");
  555. test_assert(EXIT_HOSTNAME == parse_extended_hostname(address3));
  556. test_assert(NORMAL_HOSTNAME == parse_extended_hostname(address4));
  557. test_assert(ONION_HOSTNAME == parse_extended_hostname(address5));
  558. test_streq(address5, "abcdefghijklmnop");
  559. test_assert(ONION_HOSTNAME == parse_extended_hostname(address6));
  560. test_streq(address6, "abcdefghijklmnop");
  561. test_assert(BAD_HOSTNAME == parse_extended_hostname(address7));
  562. pk1 = pk_generate(0);
  563. pk2 = pk_generate(1);
  564. generated = tor_malloc_zero(sizeof(rend_service_descriptor_t));
  565. generated->pk = crypto_pk_dup_key(pk1);
  566. crypto_pk_get_digest(generated->pk, service_id);
  567. base32_encode(service_id_base32, REND_SERVICE_ID_LEN_BASE32+1,
  568. service_id, REND_SERVICE_ID_LEN);
  569. now = time(NULL);
  570. generated->timestamp = now;
  571. generated->version = 2;
  572. generated->protocols = 42;
  573. generated->intro_nodes = smartlist_new();
  574. for (i = 0; i < 3; i++) {
  575. rend_intro_point_t *intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  576. crypto_pk_t *okey = pk_generate(2 + i);
  577. intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
  578. intro->extend_info->onion_key = okey;
  579. crypto_pk_get_digest(intro->extend_info->onion_key,
  580. intro->extend_info->identity_digest);
  581. //crypto_rand(info->identity_digest, DIGEST_LEN); /* Would this work? */
  582. intro->extend_info->nickname[0] = '$';
  583. base16_encode(intro->extend_info->nickname + 1,
  584. sizeof(intro->extend_info->nickname) - 1,
  585. intro->extend_info->identity_digest, DIGEST_LEN);
  586. /* Does not cover all IP addresses. */
  587. tor_addr_from_ipv4h(&intro->extend_info->addr, crypto_rand_int(65536));
  588. intro->extend_info->port = 1 + crypto_rand_int(65535);
  589. intro->intro_key = crypto_pk_dup_key(pk2);
  590. smartlist_add(generated->intro_nodes, intro);
  591. }
  592. test_assert(rend_encode_v2_descriptors(descs, generated, now, 0,
  593. REND_NO_AUTH, NULL, NULL) > 0);
  594. test_assert(rend_compute_v2_desc_id(computed_desc_id, service_id_base32,
  595. NULL, now, 0) == 0);
  596. test_memeq(((rend_encoded_v2_service_descriptor_t *)
  597. smartlist_get(descs, 0))->desc_id, computed_desc_id, DIGEST_LEN);
  598. test_assert(rend_parse_v2_service_descriptor(&parsed, parsed_desc_id,
  599. &intro_points_encrypted,
  600. &intro_points_size,
  601. &encoded_size,
  602. &next_desc,
  603. ((rend_encoded_v2_service_descriptor_t *)
  604. smartlist_get(descs, 0))->desc_str) == 0);
  605. test_assert(parsed);
  606. test_memeq(((rend_encoded_v2_service_descriptor_t *)
  607. smartlist_get(descs, 0))->desc_id, parsed_desc_id, DIGEST_LEN);
  608. test_eq(rend_parse_introduction_points(parsed, intro_points_encrypted,
  609. intro_points_size), 3);
  610. test_assert(!crypto_pk_cmp_keys(generated->pk, parsed->pk));
  611. test_eq(parsed->timestamp, now);
  612. test_eq(parsed->version, 2);
  613. test_eq(parsed->protocols, 42);
  614. test_eq(smartlist_len(parsed->intro_nodes), 3);
  615. for (i = 0; i < smartlist_len(parsed->intro_nodes); i++) {
  616. rend_intro_point_t *par_intro = smartlist_get(parsed->intro_nodes, i),
  617. *gen_intro = smartlist_get(generated->intro_nodes, i);
  618. extend_info_t *par_info = par_intro->extend_info;
  619. extend_info_t *gen_info = gen_intro->extend_info;
  620. test_assert(!crypto_pk_cmp_keys(gen_info->onion_key, par_info->onion_key));
  621. test_memeq(gen_info->identity_digest, par_info->identity_digest,
  622. DIGEST_LEN);
  623. test_streq(gen_info->nickname, par_info->nickname);
  624. test_assert(tor_addr_eq(&gen_info->addr, &par_info->addr));
  625. test_eq(gen_info->port, par_info->port);
  626. }
  627. rend_service_descriptor_free(parsed);
  628. rend_service_descriptor_free(generated);
  629. parsed = generated = NULL;
  630. done:
  631. if (descs) {
  632. for (i = 0; i < smartlist_len(descs); i++)
  633. rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
  634. smartlist_free(descs);
  635. }
  636. if (parsed)
  637. rend_service_descriptor_free(parsed);
  638. if (generated)
  639. rend_service_descriptor_free(generated);
  640. if (pk1)
  641. crypto_pk_free(pk1);
  642. if (pk2)
  643. crypto_pk_free(pk2);
  644. tor_free(intro_points_encrypted);
  645. }
  646. /* Record odd numbered fake-IPs using ipv6, even numbered fake-IPs
  647. * using ipv4. Since our fake geoip database is the same between
  648. * ipv4 and ipv6, we should get the same result no matter which
  649. * address family we pick for each IP. */
  650. #define SET_TEST_ADDRESS(i) do { \
  651. if ((i) & 1) { \
  652. SET_TEST_IPV6(i); \
  653. tor_addr_from_in6(&addr, &in6); \
  654. } else { \
  655. tor_addr_from_ipv4h(&addr, (uint32_t) i); \
  656. } \
  657. } while (0)
  658. /* Make sure that country ID actually works. */
  659. #define SET_TEST_IPV6(i) \
  660. do { \
  661. set_uint32(in6.s6_addr + 12, htonl((uint32_t) (i))); \
  662. } while (0)
  663. #define CHECK_COUNTRY(country, val) do { \
  664. /* test ipv4 country lookup */ \
  665. test_streq(country, \
  666. geoip_get_country_name(geoip_get_country_by_ipv4(val))); \
  667. /* test ipv6 country lookup */ \
  668. SET_TEST_IPV6(val); \
  669. test_streq(country, \
  670. geoip_get_country_name(geoip_get_country_by_ipv6(&in6))); \
  671. } while (0)
  672. /** Run unit tests for GeoIP code. */
  673. static void
  674. test_geoip(void)
  675. {
  676. int i, j;
  677. time_t now = 1281533250; /* 2010-08-11 13:27:30 UTC */
  678. char *s = NULL, *v = NULL;
  679. const char *bridge_stats_1 =
  680. "bridge-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  681. "bridge-ips zz=24,xy=8\n"
  682. "bridge-ip-versions v4=16,v6=16\n"
  683. "bridge-ip-transports <OR>=24\n",
  684. *dirreq_stats_1 =
  685. "dirreq-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  686. "dirreq-v3-ips ab=8\n"
  687. "dirreq-v3-reqs ab=8\n"
  688. "dirreq-v3-resp ok=0,not-enough-sigs=0,unavailable=0,not-found=0,"
  689. "not-modified=0,busy=0\n"
  690. "dirreq-v3-direct-dl complete=0,timeout=0,running=0\n"
  691. "dirreq-v3-tunneled-dl complete=0,timeout=0,running=0\n",
  692. *dirreq_stats_2 =
  693. "dirreq-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  694. "dirreq-v3-ips \n"
  695. "dirreq-v3-reqs \n"
  696. "dirreq-v3-resp ok=0,not-enough-sigs=0,unavailable=0,not-found=0,"
  697. "not-modified=0,busy=0\n"
  698. "dirreq-v3-direct-dl complete=0,timeout=0,running=0\n"
  699. "dirreq-v3-tunneled-dl complete=0,timeout=0,running=0\n",
  700. *dirreq_stats_3 =
  701. "dirreq-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  702. "dirreq-v3-ips \n"
  703. "dirreq-v3-reqs \n"
  704. "dirreq-v3-resp ok=8,not-enough-sigs=0,unavailable=0,not-found=0,"
  705. "not-modified=0,busy=0\n"
  706. "dirreq-v3-direct-dl complete=0,timeout=0,running=0\n"
  707. "dirreq-v3-tunneled-dl complete=0,timeout=0,running=0\n",
  708. *dirreq_stats_4 =
  709. "dirreq-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  710. "dirreq-v3-ips \n"
  711. "dirreq-v3-reqs \n"
  712. "dirreq-v3-resp ok=8,not-enough-sigs=0,unavailable=0,not-found=0,"
  713. "not-modified=0,busy=0\n"
  714. "dirreq-v3-direct-dl complete=0,timeout=0,running=0\n"
  715. "dirreq-v3-tunneled-dl complete=0,timeout=0,running=4\n",
  716. *entry_stats_1 =
  717. "entry-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  718. "entry-ips ab=8\n",
  719. *entry_stats_2 =
  720. "entry-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  721. "entry-ips \n";
  722. tor_addr_t addr;
  723. struct in6_addr in6;
  724. /* Populate the DB a bit. Add these in order, since we can't do the final
  725. * 'sort' step. These aren't very good IP addresses, but they're perfectly
  726. * fine uint32_t values. */
  727. test_eq(0, geoip_parse_entry("10,50,AB", AF_INET));
  728. test_eq(0, geoip_parse_entry("52,90,XY", AF_INET));
  729. test_eq(0, geoip_parse_entry("95,100,AB", AF_INET));
  730. test_eq(0, geoip_parse_entry("\"105\",\"140\",\"ZZ\"", AF_INET));
  731. test_eq(0, geoip_parse_entry("\"150\",\"190\",\"XY\"", AF_INET));
  732. test_eq(0, geoip_parse_entry("\"200\",\"250\",\"AB\"", AF_INET));
  733. /* Populate the IPv6 DB equivalently with fake IPs in the same range */
  734. test_eq(0, geoip_parse_entry("::a,::32,AB", AF_INET6));
  735. test_eq(0, geoip_parse_entry("::34,::5a,XY", AF_INET6));
  736. test_eq(0, geoip_parse_entry("::5f,::64,AB", AF_INET6));
  737. test_eq(0, geoip_parse_entry("::69,::8c,ZZ", AF_INET6));
  738. test_eq(0, geoip_parse_entry("::96,::be,XY", AF_INET6));
  739. test_eq(0, geoip_parse_entry("::c8,::fa,AB", AF_INET6));
  740. /* We should have 4 countries: ??, ab, xy, zz. */
  741. test_eq(4, geoip_get_n_countries());
  742. memset(&in6, 0, sizeof(in6));
  743. CHECK_COUNTRY("??", 3);
  744. CHECK_COUNTRY("ab", 32);
  745. CHECK_COUNTRY("??", 5);
  746. CHECK_COUNTRY("??", 51);
  747. CHECK_COUNTRY("xy", 150);
  748. CHECK_COUNTRY("xy", 190);
  749. CHECK_COUNTRY("??", 2000);
  750. test_eq(0, geoip_get_country_by_ipv4(3));
  751. SET_TEST_IPV6(3);
  752. test_eq(0, geoip_get_country_by_ipv6(&in6));
  753. get_options_mutable()->BridgeRelay = 1;
  754. get_options_mutable()->BridgeRecordUsageByCountry = 1;
  755. /* Put 9 observations in AB... */
  756. for (i=32; i < 40; ++i) {
  757. SET_TEST_ADDRESS(i);
  758. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL, now-7200);
  759. }
  760. SET_TEST_ADDRESS(225);
  761. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL, now-7200);
  762. /* and 3 observations in XY, several times. */
  763. for (j=0; j < 10; ++j)
  764. for (i=52; i < 55; ++i) {
  765. SET_TEST_ADDRESS(i);
  766. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL, now-3600);
  767. }
  768. /* and 17 observations in ZZ... */
  769. for (i=110; i < 127; ++i) {
  770. SET_TEST_ADDRESS(i);
  771. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL, now);
  772. }
  773. geoip_get_client_history(GEOIP_CLIENT_CONNECT, &s, &v);
  774. test_assert(s);
  775. test_assert(v);
  776. test_streq("zz=24,ab=16,xy=8", s);
  777. test_streq("v4=16,v6=16", v);
  778. tor_free(s);
  779. tor_free(v);
  780. /* Now clear out all the AB observations. */
  781. geoip_remove_old_clients(now-6000);
  782. geoip_get_client_history(GEOIP_CLIENT_CONNECT, &s, &v);
  783. test_assert(s);
  784. test_assert(v);
  785. test_streq("zz=24,xy=8", s);
  786. test_streq("v4=16,v6=16", v);
  787. tor_free(s);
  788. tor_free(v);
  789. /* Start testing bridge statistics by making sure that we don't output
  790. * bridge stats without initializing them. */
  791. s = geoip_format_bridge_stats(now + 86400);
  792. test_assert(!s);
  793. /* Initialize stats and generate the bridge-stats history string out of
  794. * the connecting clients added above. */
  795. geoip_bridge_stats_init(now);
  796. s = geoip_format_bridge_stats(now + 86400);
  797. test_assert(s);
  798. test_streq(bridge_stats_1, s);
  799. tor_free(s);
  800. /* Stop collecting bridge stats and make sure we don't write a history
  801. * string anymore. */
  802. geoip_bridge_stats_term();
  803. s = geoip_format_bridge_stats(now + 86400);
  804. test_assert(!s);
  805. /* Stop being a bridge and start being a directory mirror that gathers
  806. * directory request statistics. */
  807. geoip_bridge_stats_term();
  808. get_options_mutable()->BridgeRelay = 0;
  809. get_options_mutable()->BridgeRecordUsageByCountry = 0;
  810. get_options_mutable()->DirReqStatistics = 1;
  811. /* Start testing dirreq statistics by making sure that we don't collect
  812. * dirreq stats without initializing them. */
  813. SET_TEST_ADDRESS(100);
  814. geoip_note_client_seen(GEOIP_CLIENT_NETWORKSTATUS, &addr, NULL, now);
  815. s = geoip_format_dirreq_stats(now + 86400);
  816. test_assert(!s);
  817. /* Initialize stats, note one connecting client, and generate the
  818. * dirreq-stats history string. */
  819. geoip_dirreq_stats_init(now);
  820. SET_TEST_ADDRESS(100);
  821. geoip_note_client_seen(GEOIP_CLIENT_NETWORKSTATUS, &addr, NULL, now);
  822. s = geoip_format_dirreq_stats(now + 86400);
  823. test_streq(dirreq_stats_1, s);
  824. tor_free(s);
  825. /* Stop collecting stats, add another connecting client, and ensure we
  826. * don't generate a history string. */
  827. geoip_dirreq_stats_term();
  828. SET_TEST_ADDRESS(101);
  829. geoip_note_client_seen(GEOIP_CLIENT_NETWORKSTATUS, &addr, NULL, now);
  830. s = geoip_format_dirreq_stats(now + 86400);
  831. test_assert(!s);
  832. /* Re-start stats, add a connecting client, reset stats, and make sure
  833. * that we get an all empty history string. */
  834. geoip_dirreq_stats_init(now);
  835. SET_TEST_ADDRESS(100);
  836. geoip_note_client_seen(GEOIP_CLIENT_NETWORKSTATUS, &addr, NULL, now);
  837. geoip_reset_dirreq_stats(now);
  838. s = geoip_format_dirreq_stats(now + 86400);
  839. test_streq(dirreq_stats_2, s);
  840. tor_free(s);
  841. /* Note a successful network status response and make sure that it
  842. * appears in the history string. */
  843. geoip_note_ns_response(GEOIP_SUCCESS);
  844. s = geoip_format_dirreq_stats(now + 86400);
  845. test_streq(dirreq_stats_3, s);
  846. tor_free(s);
  847. /* Start a tunneled directory request. */
  848. geoip_start_dirreq((uint64_t) 1, 1024, DIRREQ_TUNNELED);
  849. s = geoip_format_dirreq_stats(now + 86400);
  850. test_streq(dirreq_stats_4, s);
  851. tor_free(s);
  852. /* Stop collecting directory request statistics and start gathering
  853. * entry stats. */
  854. geoip_dirreq_stats_term();
  855. get_options_mutable()->DirReqStatistics = 0;
  856. get_options_mutable()->EntryStatistics = 1;
  857. /* Start testing entry statistics by making sure that we don't collect
  858. * anything without initializing entry stats. */
  859. SET_TEST_ADDRESS(100);
  860. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL, now);
  861. s = geoip_format_entry_stats(now + 86400);
  862. test_assert(!s);
  863. /* Initialize stats, note one connecting client, and generate the
  864. * entry-stats history string. */
  865. geoip_entry_stats_init(now);
  866. SET_TEST_ADDRESS(100);
  867. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL, now);
  868. s = geoip_format_entry_stats(now + 86400);
  869. test_streq(entry_stats_1, s);
  870. tor_free(s);
  871. /* Stop collecting stats, add another connecting client, and ensure we
  872. * don't generate a history string. */
  873. geoip_entry_stats_term();
  874. SET_TEST_ADDRESS(101);
  875. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL, now);
  876. s = geoip_format_entry_stats(now + 86400);
  877. test_assert(!s);
  878. /* Re-start stats, add a connecting client, reset stats, and make sure
  879. * that we get an all empty history string. */
  880. geoip_entry_stats_init(now);
  881. SET_TEST_ADDRESS(100);
  882. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL, now);
  883. geoip_reset_entry_stats(now);
  884. s = geoip_format_entry_stats(now + 86400);
  885. test_streq(entry_stats_2, s);
  886. tor_free(s);
  887. /* Stop collecting entry statistics. */
  888. geoip_entry_stats_term();
  889. get_options_mutable()->EntryStatistics = 0;
  890. done:
  891. tor_free(s);
  892. tor_free(v);
  893. }
  894. static void
  895. test_geoip_with_pt(void)
  896. {
  897. time_t now = 1281533250; /* 2010-08-11 13:27:30 UTC */
  898. char *s = NULL;
  899. int i;
  900. tor_addr_t addr;
  901. struct in6_addr in6;
  902. get_options_mutable()->BridgeRelay = 1;
  903. get_options_mutable()->BridgeRecordUsageByCountry = 1;
  904. memset(&in6, 0, sizeof(in6));
  905. /* No clients seen yet. */
  906. s = geoip_get_transport_history();
  907. tor_assert(!s);
  908. /* 4 connections without a pluggable transport */
  909. for (i=0; i < 4; ++i) {
  910. SET_TEST_ADDRESS(i);
  911. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, NULL, now-7200);
  912. }
  913. /* 9 connections with "alpha" */
  914. for (i=4; i < 13; ++i) {
  915. SET_TEST_ADDRESS(i);
  916. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, "alpha", now-7200);
  917. }
  918. /* one connection with "beta" */
  919. SET_TEST_ADDRESS(13);
  920. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, "beta", now-7200);
  921. /* 14 connections with "charlie" */
  922. for (i=14; i < 28; ++i) {
  923. SET_TEST_ADDRESS(i);
  924. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, "charlie", now-7200);
  925. }
  926. /* 131 connections with "ddr" */
  927. for (i=28; i < 159; ++i) {
  928. SET_TEST_ADDRESS(i);
  929. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, "ddr", now-7200);
  930. }
  931. /* 8 connections with "entropy" */
  932. for (i=159; i < 167; ++i) {
  933. SET_TEST_ADDRESS(i);
  934. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, "entropy", now-7200);
  935. }
  936. /* 2 connections from the same IP with two different transports. */
  937. SET_TEST_ADDRESS(++i);
  938. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, "fire", now-7200);
  939. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, "google", now-7200);
  940. /* Test the transport history string. */
  941. s = geoip_get_transport_history();
  942. tor_assert(s);
  943. test_streq(s, "<OR>=8,alpha=16,beta=8,charlie=16,ddr=136,"
  944. "entropy=8,fire=8,google=8");
  945. /* Stop collecting entry statistics. */
  946. geoip_entry_stats_term();
  947. get_options_mutable()->EntryStatistics = 0;
  948. done:
  949. tor_free(s);
  950. }
  951. #undef SET_TEST_ADDRESS
  952. #undef SET_TEST_IPV6
  953. #undef CHECK_COUNTRY
  954. /** Run unit tests for stats code. */
  955. static void
  956. test_stats(void)
  957. {
  958. time_t now = 1281533250; /* 2010-08-11 13:27:30 UTC */
  959. char *s = NULL;
  960. int i;
  961. /* Start with testing exit port statistics; we shouldn't collect exit
  962. * stats without initializing them. */
  963. rep_hist_note_exit_stream_opened(80);
  964. rep_hist_note_exit_bytes(80, 100, 10000);
  965. s = rep_hist_format_exit_stats(now + 86400);
  966. test_assert(!s);
  967. /* Initialize stats, note some streams and bytes, and generate history
  968. * string. */
  969. rep_hist_exit_stats_init(now);
  970. rep_hist_note_exit_stream_opened(80);
  971. rep_hist_note_exit_bytes(80, 100, 10000);
  972. rep_hist_note_exit_stream_opened(443);
  973. rep_hist_note_exit_bytes(443, 100, 10000);
  974. rep_hist_note_exit_bytes(443, 100, 10000);
  975. s = rep_hist_format_exit_stats(now + 86400);
  976. test_streq("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  977. "exit-kibibytes-written 80=1,443=1,other=0\n"
  978. "exit-kibibytes-read 80=10,443=20,other=0\n"
  979. "exit-streams-opened 80=4,443=4,other=0\n", s);
  980. tor_free(s);
  981. /* Add a few bytes on 10 more ports and ensure that only the top 10
  982. * ports are contained in the history string. */
  983. for (i = 50; i < 60; i++) {
  984. rep_hist_note_exit_bytes(i, i, i);
  985. rep_hist_note_exit_stream_opened(i);
  986. }
  987. s = rep_hist_format_exit_stats(now + 86400);
  988. test_streq("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  989. "exit-kibibytes-written 52=1,53=1,54=1,55=1,56=1,57=1,58=1,"
  990. "59=1,80=1,443=1,other=1\n"
  991. "exit-kibibytes-read 52=1,53=1,54=1,55=1,56=1,57=1,58=1,"
  992. "59=1,80=10,443=20,other=1\n"
  993. "exit-streams-opened 52=4,53=4,54=4,55=4,56=4,57=4,58=4,"
  994. "59=4,80=4,443=4,other=4\n", s);
  995. tor_free(s);
  996. /* Stop collecting stats, add some bytes, and ensure we don't generate
  997. * a history string. */
  998. rep_hist_exit_stats_term();
  999. rep_hist_note_exit_bytes(80, 100, 10000);
  1000. s = rep_hist_format_exit_stats(now + 86400);
  1001. test_assert(!s);
  1002. /* Re-start stats, add some bytes, reset stats, and see what history we
  1003. * get when observing no streams or bytes at all. */
  1004. rep_hist_exit_stats_init(now);
  1005. rep_hist_note_exit_stream_opened(80);
  1006. rep_hist_note_exit_bytes(80, 100, 10000);
  1007. rep_hist_reset_exit_stats(now);
  1008. s = rep_hist_format_exit_stats(now + 86400);
  1009. test_streq("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1010. "exit-kibibytes-written other=0\n"
  1011. "exit-kibibytes-read other=0\n"
  1012. "exit-streams-opened other=0\n", s);
  1013. tor_free(s);
  1014. /* Continue with testing connection statistics; we shouldn't collect
  1015. * conn stats without initializing them. */
  1016. rep_hist_note_or_conn_bytes(1, 20, 400, now);
  1017. s = rep_hist_format_conn_stats(now + 86400);
  1018. test_assert(!s);
  1019. /* Initialize stats, note bytes, and generate history string. */
  1020. rep_hist_conn_stats_init(now);
  1021. rep_hist_note_or_conn_bytes(1, 30000, 400000, now);
  1022. rep_hist_note_or_conn_bytes(1, 30000, 400000, now + 5);
  1023. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 10);
  1024. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 15);
  1025. s = rep_hist_format_conn_stats(now + 86400);
  1026. test_streq("conn-bi-direct 2010-08-12 13:27:30 (86400 s) 0,0,1,0\n", s);
  1027. tor_free(s);
  1028. /* Stop collecting stats, add some bytes, and ensure we don't generate
  1029. * a history string. */
  1030. rep_hist_conn_stats_term();
  1031. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 15);
  1032. s = rep_hist_format_conn_stats(now + 86400);
  1033. test_assert(!s);
  1034. /* Re-start stats, add some bytes, reset stats, and see what history we
  1035. * get when observing no bytes at all. */
  1036. rep_hist_conn_stats_init(now);
  1037. rep_hist_note_or_conn_bytes(1, 30000, 400000, now);
  1038. rep_hist_note_or_conn_bytes(1, 30000, 400000, now + 5);
  1039. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 10);
  1040. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 15);
  1041. rep_hist_reset_conn_stats(now);
  1042. s = rep_hist_format_conn_stats(now + 86400);
  1043. test_streq("conn-bi-direct 2010-08-12 13:27:30 (86400 s) 0,0,0,0\n", s);
  1044. tor_free(s);
  1045. /* Continue with testing buffer statistics; we shouldn't collect buffer
  1046. * stats without initializing them. */
  1047. rep_hist_add_buffer_stats(2.0, 2.0, 20);
  1048. s = rep_hist_format_buffer_stats(now + 86400);
  1049. test_assert(!s);
  1050. /* Initialize stats, add statistics for a single circuit, and generate
  1051. * the history string. */
  1052. rep_hist_buffer_stats_init(now);
  1053. rep_hist_add_buffer_stats(2.0, 2.0, 20);
  1054. s = rep_hist_format_buffer_stats(now + 86400);
  1055. test_streq("cell-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1056. "cell-processed-cells 20,0,0,0,0,0,0,0,0,0\n"
  1057. "cell-queued-cells 2.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,"
  1058. "0.00,0.00\n"
  1059. "cell-time-in-queue 2,0,0,0,0,0,0,0,0,0\n"
  1060. "cell-circuits-per-decile 1\n", s);
  1061. tor_free(s);
  1062. /* Add nineteen more circuit statistics to the one that's already in the
  1063. * history to see that the math works correctly. */
  1064. for (i = 21; i < 30; i++)
  1065. rep_hist_add_buffer_stats(2.0, 2.0, i);
  1066. for (i = 20; i < 30; i++)
  1067. rep_hist_add_buffer_stats(3.5, 3.5, i);
  1068. s = rep_hist_format_buffer_stats(now + 86400);
  1069. test_streq("cell-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1070. "cell-processed-cells 29,28,27,26,25,24,23,22,21,20\n"
  1071. "cell-queued-cells 2.75,2.75,2.75,2.75,2.75,2.75,2.75,2.75,"
  1072. "2.75,2.75\n"
  1073. "cell-time-in-queue 3,3,3,3,3,3,3,3,3,3\n"
  1074. "cell-circuits-per-decile 2\n", s);
  1075. tor_free(s);
  1076. /* Stop collecting stats, add statistics for one circuit, and ensure we
  1077. * don't generate a history string. */
  1078. rep_hist_buffer_stats_term();
  1079. rep_hist_add_buffer_stats(2.0, 2.0, 20);
  1080. s = rep_hist_format_buffer_stats(now + 86400);
  1081. test_assert(!s);
  1082. /* Re-start stats, add statistics for one circuit, reset stats, and make
  1083. * sure that the history has all zeros. */
  1084. rep_hist_buffer_stats_init(now);
  1085. rep_hist_add_buffer_stats(2.0, 2.0, 20);
  1086. rep_hist_reset_buffer_stats(now);
  1087. s = rep_hist_format_buffer_stats(now + 86400);
  1088. test_streq("cell-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1089. "cell-processed-cells 0,0,0,0,0,0,0,0,0,0\n"
  1090. "cell-queued-cells 0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,"
  1091. "0.00,0.00\n"
  1092. "cell-time-in-queue 0,0,0,0,0,0,0,0,0,0\n"
  1093. "cell-circuits-per-decile 0\n", s);
  1094. done:
  1095. tor_free(s);
  1096. }
  1097. static void *
  1098. legacy_test_setup(const struct testcase_t *testcase)
  1099. {
  1100. return testcase->setup_data;
  1101. }
  1102. void
  1103. legacy_test_helper(void *data)
  1104. {
  1105. void (*fn)(void) = data;
  1106. fn();
  1107. }
  1108. static int
  1109. legacy_test_cleanup(const struct testcase_t *testcase, void *ptr)
  1110. {
  1111. (void)ptr;
  1112. (void)testcase;
  1113. return 1;
  1114. }
  1115. const struct testcase_setup_t legacy_setup = {
  1116. legacy_test_setup, legacy_test_cleanup
  1117. };
  1118. #define ENT(name) \
  1119. { #name, legacy_test_helper, 0, &legacy_setup, test_ ## name }
  1120. #define FORK(name) \
  1121. { #name, legacy_test_helper, TT_FORK, &legacy_setup, test_ ## name }
  1122. static struct testcase_t test_array[] = {
  1123. ENT(onion_handshake),
  1124. { "bad_onion_handshake", test_bad_onion_handshake, 0, NULL, NULL },
  1125. ENT(onion_queues),
  1126. #ifdef CURVE25519_ENABLED
  1127. { "ntor_handshake", test_ntor_handshake, 0, NULL, NULL },
  1128. #endif
  1129. ENT(circuit_timeout),
  1130. ENT(rend_fns),
  1131. ENT(geoip),
  1132. FORK(geoip_with_pt),
  1133. FORK(stats),
  1134. END_OF_TESTCASES
  1135. };
  1136. extern struct testcase_t addr_tests[];
  1137. extern struct testcase_t buffer_tests[];
  1138. extern struct testcase_t crypto_tests[];
  1139. extern struct testcase_t container_tests[];
  1140. extern struct testcase_t util_tests[];
  1141. extern struct testcase_t dir_tests[];
  1142. extern struct testcase_t microdesc_tests[];
  1143. extern struct testcase_t pt_tests[];
  1144. extern struct testcase_t config_tests[];
  1145. extern struct testcase_t introduce_tests[];
  1146. extern struct testcase_t replaycache_tests[];
  1147. extern struct testcase_t relaycell_tests[];
  1148. extern struct testcase_t cell_format_tests[];
  1149. extern struct testcase_t circuitlist_tests[];
  1150. extern struct testcase_t circuitmux_tests[];
  1151. extern struct testcase_t cell_queue_tests[];
  1152. extern struct testcase_t options_tests[];
  1153. extern struct testcase_t socks_tests[];
  1154. extern struct testcase_t extorport_tests[];
  1155. extern struct testcase_t controller_event_tests[];
  1156. extern struct testcase_t logging_tests[];
  1157. extern struct testcase_t hs_tests[];
  1158. extern struct testcase_t nodelist_tests[];
  1159. extern struct testcase_t routerkeys_tests[];
  1160. extern struct testcase_t oom_tests[];
  1161. extern struct testcase_t policy_tests[];
  1162. extern struct testcase_t status_tests[];
  1163. static struct testgroup_t testgroups[] = {
  1164. { "", test_array },
  1165. { "buffer/", buffer_tests },
  1166. { "socks/", socks_tests },
  1167. { "addr/", addr_tests },
  1168. { "crypto/", crypto_tests },
  1169. { "container/", container_tests },
  1170. { "util/", util_tests },
  1171. { "util/logging/", logging_tests },
  1172. { "cellfmt/", cell_format_tests },
  1173. { "cellqueue/", cell_queue_tests },
  1174. { "dir/", dir_tests },
  1175. { "dir/md/", microdesc_tests },
  1176. { "pt/", pt_tests },
  1177. { "config/", config_tests },
  1178. { "replaycache/", replaycache_tests },
  1179. { "relaycell/", relaycell_tests },
  1180. { "introduce/", introduce_tests },
  1181. { "circuitlist/", circuitlist_tests },
  1182. { "circuitmux/", circuitmux_tests },
  1183. { "options/", options_tests },
  1184. { "extorport/", extorport_tests },
  1185. { "control/", controller_event_tests },
  1186. { "hs/", hs_tests },
  1187. { "nodelist/", nodelist_tests },
  1188. { "routerkeys/", routerkeys_tests },
  1189. { "oom/", oom_tests },
  1190. { "policy/" , policy_tests },
  1191. { "status/" , status_tests },
  1192. END_OF_GROUPS
  1193. };
  1194. /** Main entry point for unit test code: parse the command line, and run
  1195. * some unit tests. */
  1196. int
  1197. main(int c, const char **v)
  1198. {
  1199. or_options_t *options;
  1200. char *errmsg = NULL;
  1201. int i, i_out;
  1202. int loglevel = LOG_ERR;
  1203. int accel_crypto = 0;
  1204. #ifdef USE_DMALLOC
  1205. {
  1206. int r = CRYPTO_set_mem_ex_functions(tor_malloc_, tor_realloc_, tor_free_);
  1207. tor_assert(r);
  1208. }
  1209. #endif
  1210. update_approx_time(time(NULL));
  1211. options = options_new();
  1212. tor_threads_init();
  1213. init_logging();
  1214. for (i_out = i = 1; i < c; ++i) {
  1215. if (!strcmp(v[i], "--warn")) {
  1216. loglevel = LOG_WARN;
  1217. } else if (!strcmp(v[i], "--notice")) {
  1218. loglevel = LOG_NOTICE;
  1219. } else if (!strcmp(v[i], "--info")) {
  1220. loglevel = LOG_INFO;
  1221. } else if (!strcmp(v[i], "--debug")) {
  1222. loglevel = LOG_DEBUG;
  1223. } else if (!strcmp(v[i], "--accel")) {
  1224. accel_crypto = 1;
  1225. } else {
  1226. v[i_out++] = v[i];
  1227. }
  1228. }
  1229. c = i_out;
  1230. {
  1231. log_severity_list_t s;
  1232. memset(&s, 0, sizeof(s));
  1233. set_log_severity_config(loglevel, LOG_ERR, &s);
  1234. add_stream_log(&s, "", fileno(stdout));
  1235. }
  1236. options->command = CMD_RUN_UNITTESTS;
  1237. if (crypto_global_init(accel_crypto, NULL, NULL)) {
  1238. printf("Can't initialize crypto subsystem; exiting.\n");
  1239. return 1;
  1240. }
  1241. crypto_set_tls_dh_prime(NULL);
  1242. crypto_seed_rng(1);
  1243. rep_hist_init();
  1244. network_init();
  1245. setup_directory();
  1246. options_init(options);
  1247. options->DataDirectory = tor_strdup(temp_dir);
  1248. options->EntryStatistics = 1;
  1249. if (set_options(options, &errmsg) < 0) {
  1250. printf("Failed to set initial options: %s\n", errmsg);
  1251. tor_free(errmsg);
  1252. return 1;
  1253. }
  1254. atexit(remove_directory);
  1255. have_failed = (tinytest_main(c, v, testgroups) != 0);
  1256. free_pregenerated_keys();
  1257. #ifdef USE_DMALLOC
  1258. tor_free_all(0);
  1259. dmalloc_log_unfreed();
  1260. #endif
  1261. if (have_failed)
  1262. return 1;
  1263. else
  1264. return 0;
  1265. }