test.c 47 KB

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