test.c 47 KB

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