test.c 58 KB

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