test.c 47 KB

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