test.c 47 KB

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