test.c 48 KB

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