test.c 48 KB

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