test.c 47 KB

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