test.c 59 KB

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