test.c 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292
  1. /* Copyright (c) 2001-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2010, 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 MS_WINDOWS
  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 BUFFERS_PRIVATE
  26. #define CONFIG_PRIVATE
  27. #define GEOIP_PRIVATE
  28. #define ROUTER_PRIVATE
  29. #define CIRCUIT_PRIVATE
  30. /*
  31. * Linux doesn't provide lround in math.h by default, but mac os does...
  32. * It's best just to leave math.h out of the picture entirely.
  33. */
  34. //#include <math.h>
  35. long int lround(double x);
  36. double fabs(double x);
  37. #include "or.h"
  38. #include "buffers.h"
  39. #include "circuitbuild.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 "policies.h"
  50. #include "rephist.h"
  51. #include "routerparse.h"
  52. #ifdef USE_DMALLOC
  53. #include <dmalloc.h>
  54. #include <openssl/crypto.h>
  55. #include "main.h"
  56. #endif
  57. /** Set to true if any unit test has failed. Mostly, this is set by the macros
  58. * in test.h */
  59. int have_failed = 0;
  60. /** Temporary directory (set up by setup_directory) under which we store all
  61. * our files during testing. */
  62. static char temp_dir[256];
  63. static pid_t temp_dir_setup_in_pid = 0;
  64. /** Select and create the temporary directory we'll use to run our unit tests.
  65. * Store it in <b>temp_dir</b>. Exit immediately if we can't create it.
  66. * idempotent. */
  67. static void
  68. setup_directory(void)
  69. {
  70. static int is_setup = 0;
  71. int r;
  72. if (is_setup) return;
  73. #ifdef MS_WINDOWS
  74. // XXXX
  75. tor_snprintf(temp_dir, sizeof(temp_dir),
  76. "c:\\windows\\temp\\tor_test_%d", (int)getpid());
  77. r = mkdir(temp_dir);
  78. #else
  79. tor_snprintf(temp_dir, sizeof(temp_dir), "/tmp/tor_test_%d", (int) getpid());
  80. r = mkdir(temp_dir, 0700);
  81. #endif
  82. if (r) {
  83. fprintf(stderr, "Can't create directory %s:", temp_dir);
  84. perror("");
  85. exit(1);
  86. }
  87. is_setup = 1;
  88. temp_dir_setup_in_pid = getpid();
  89. }
  90. /** Return a filename relative to our testing temporary directory */
  91. const char *
  92. get_fname(const char *name)
  93. {
  94. static char buf[1024];
  95. setup_directory();
  96. if (!name)
  97. return temp_dir;
  98. tor_snprintf(buf,sizeof(buf),"%s/%s",temp_dir,name);
  99. return buf;
  100. }
  101. /* Remove a directory and all of its subdirectories */
  102. static void
  103. rm_rf(const char *dir)
  104. {
  105. struct stat st;
  106. smartlist_t *elements;
  107. elements = tor_listdir(dir);
  108. if (elements) {
  109. SMARTLIST_FOREACH(elements, const char *, cp,
  110. {
  111. char *tmp = NULL;
  112. tor_asprintf(&tmp, "%s"PATH_SEPARATOR"%s", dir, cp);
  113. if (0 == stat(tmp,&st) && (st.st_mode & S_IFDIR)) {
  114. rm_rf(tmp);
  115. } else {
  116. if (unlink(tmp)) {
  117. fprintf(stderr, "Error removing %s: %s\n", tmp, strerror(errno));
  118. }
  119. }
  120. tor_free(tmp);
  121. });
  122. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  123. smartlist_free(elements);
  124. }
  125. if (rmdir(dir))
  126. fprintf(stderr, "Error removing directory %s: %s\n", dir, strerror(errno));
  127. }
  128. /** Remove all files stored under the temporary directory, and the directory
  129. * itself. Called by atexit(). */
  130. static void
  131. remove_directory(void)
  132. {
  133. if (getpid() != temp_dir_setup_in_pid) {
  134. /* Only clean out the tempdir when the main process is exiting. */
  135. return;
  136. }
  137. rm_rf(temp_dir);
  138. }
  139. /** Define this if unit tests spend too much time generating public keys*/
  140. #undef CACHE_GENERATED_KEYS
  141. static crypto_pk_env_t *pregen_keys[5] = {NULL, NULL, NULL, NULL, NULL};
  142. #define N_PREGEN_KEYS ((int)(sizeof(pregen_keys)/sizeof(pregen_keys[0])))
  143. /** Generate and return a new keypair for use in unit tests. If we're using
  144. * the key cache optimization, we might reuse keys: we only guarantee that
  145. * keys made with distinct values for <b>idx</b> are different. The value of
  146. * <b>idx</b> must be at least 0, and less than N_PREGEN_KEYS. */
  147. crypto_pk_env_t *
  148. pk_generate(int idx)
  149. {
  150. #ifdef CACHE_GENERATED_KEYS
  151. tor_assert(idx < N_PREGEN_KEYS);
  152. if (! pregen_keys[idx]) {
  153. pregen_keys[idx] = crypto_new_pk_env();
  154. tor_assert(!crypto_pk_generate_key(pregen_keys[idx]));
  155. }
  156. return crypto_pk_dup_key(pregen_keys[idx]);
  157. #else
  158. crypto_pk_env_t *result;
  159. (void) idx;
  160. result = crypto_new_pk_env();
  161. tor_assert(!crypto_pk_generate_key(result));
  162. return result;
  163. #endif
  164. }
  165. /** Free all storage used for the cached key optimization. */
  166. static void
  167. free_pregenerated_keys(void)
  168. {
  169. unsigned idx;
  170. for (idx = 0; idx < N_PREGEN_KEYS; ++idx) {
  171. if (pregen_keys[idx]) {
  172. crypto_free_pk_env(pregen_keys[idx]);
  173. pregen_keys[idx] = NULL;
  174. }
  175. }
  176. }
  177. /** Run unit tests for buffers.c */
  178. static void
  179. test_buffers(void)
  180. {
  181. char str[256];
  182. char str2[256];
  183. buf_t *buf = NULL, *buf2 = NULL;
  184. const char *cp;
  185. int j;
  186. size_t r;
  187. /****
  188. * buf_new
  189. ****/
  190. if (!(buf = buf_new()))
  191. test_fail();
  192. //test_eq(buf_capacity(buf), 4096);
  193. test_eq(buf_datalen(buf), 0);
  194. /****
  195. * General pointer frobbing
  196. */
  197. for (j=0;j<256;++j) {
  198. str[j] = (char)j;
  199. }
  200. write_to_buf(str, 256, buf);
  201. write_to_buf(str, 256, buf);
  202. test_eq(buf_datalen(buf), 512);
  203. fetch_from_buf(str2, 200, buf);
  204. test_memeq(str, str2, 200);
  205. test_eq(buf_datalen(buf), 312);
  206. memset(str2, 0, sizeof(str2));
  207. fetch_from_buf(str2, 256, buf);
  208. test_memeq(str+200, str2, 56);
  209. test_memeq(str, str2+56, 200);
  210. test_eq(buf_datalen(buf), 56);
  211. memset(str2, 0, sizeof(str2));
  212. /* Okay, now we should be 512 bytes into the 4096-byte buffer. If we add
  213. * another 3584 bytes, we hit the end. */
  214. for (j=0;j<15;++j) {
  215. write_to_buf(str, 256, buf);
  216. }
  217. assert_buf_ok(buf);
  218. test_eq(buf_datalen(buf), 3896);
  219. fetch_from_buf(str2, 56, buf);
  220. test_eq(buf_datalen(buf), 3840);
  221. test_memeq(str+200, str2, 56);
  222. for (j=0;j<15;++j) {
  223. memset(str2, 0, sizeof(str2));
  224. fetch_from_buf(str2, 256, buf);
  225. test_memeq(str, str2, 256);
  226. }
  227. test_eq(buf_datalen(buf), 0);
  228. buf_free(buf);
  229. buf = NULL;
  230. /* Okay, now make sure growing can work. */
  231. buf = buf_new_with_capacity(16);
  232. //test_eq(buf_capacity(buf), 16);
  233. write_to_buf(str+1, 255, buf);
  234. //test_eq(buf_capacity(buf), 256);
  235. fetch_from_buf(str2, 254, buf);
  236. test_memeq(str+1, str2, 254);
  237. //test_eq(buf_capacity(buf), 256);
  238. assert_buf_ok(buf);
  239. write_to_buf(str, 32, buf);
  240. //test_eq(buf_capacity(buf), 256);
  241. assert_buf_ok(buf);
  242. write_to_buf(str, 256, buf);
  243. assert_buf_ok(buf);
  244. //test_eq(buf_capacity(buf), 512);
  245. test_eq(buf_datalen(buf), 33+256);
  246. fetch_from_buf(str2, 33, buf);
  247. test_eq(*str2, str[255]);
  248. test_memeq(str2+1, str, 32);
  249. //test_eq(buf_capacity(buf), 512);
  250. test_eq(buf_datalen(buf), 256);
  251. fetch_from_buf(str2, 256, buf);
  252. test_memeq(str, str2, 256);
  253. /* now try shrinking: case 1. */
  254. buf_free(buf);
  255. buf = buf_new_with_capacity(33668);
  256. for (j=0;j<67;++j) {
  257. write_to_buf(str,255, buf);
  258. }
  259. //test_eq(buf_capacity(buf), 33668);
  260. test_eq(buf_datalen(buf), 17085);
  261. for (j=0; j < 40; ++j) {
  262. fetch_from_buf(str2, 255,buf);
  263. test_memeq(str2, str, 255);
  264. }
  265. /* now try shrinking: case 2. */
  266. buf_free(buf);
  267. buf = buf_new_with_capacity(33668);
  268. for (j=0;j<67;++j) {
  269. write_to_buf(str,255, buf);
  270. }
  271. for (j=0; j < 20; ++j) {
  272. fetch_from_buf(str2, 255,buf);
  273. test_memeq(str2, str, 255);
  274. }
  275. for (j=0;j<80;++j) {
  276. write_to_buf(str,255, buf);
  277. }
  278. //test_eq(buf_capacity(buf),33668);
  279. for (j=0; j < 120; ++j) {
  280. fetch_from_buf(str2, 255,buf);
  281. test_memeq(str2, str, 255);
  282. }
  283. /* Move from buf to buf. */
  284. buf_free(buf);
  285. buf = buf_new_with_capacity(4096);
  286. buf2 = buf_new_with_capacity(4096);
  287. for (j=0;j<100;++j)
  288. write_to_buf(str, 255, buf);
  289. test_eq(buf_datalen(buf), 25500);
  290. for (j=0;j<100;++j) {
  291. r = 10;
  292. move_buf_to_buf(buf2, buf, &r);
  293. test_eq(r, 0);
  294. }
  295. test_eq(buf_datalen(buf), 24500);
  296. test_eq(buf_datalen(buf2), 1000);
  297. for (j=0;j<3;++j) {
  298. fetch_from_buf(str2, 255, buf2);
  299. test_memeq(str2, str, 255);
  300. }
  301. r = 8192; /*big move*/
  302. move_buf_to_buf(buf2, buf, &r);
  303. test_eq(r, 0);
  304. r = 30000; /* incomplete move */
  305. move_buf_to_buf(buf2, buf, &r);
  306. test_eq(r, 13692);
  307. for (j=0;j<97;++j) {
  308. fetch_from_buf(str2, 255, buf2);
  309. test_memeq(str2, str, 255);
  310. }
  311. buf_free(buf);
  312. buf_free(buf2);
  313. buf = buf2 = NULL;
  314. buf = buf_new_with_capacity(5);
  315. cp = "Testing. This is a moderately long Testing string.";
  316. for (j = 0; cp[j]; j++)
  317. write_to_buf(cp+j, 1, buf);
  318. test_eq(0, buf_find_string_offset(buf, "Testing", 7));
  319. test_eq(1, buf_find_string_offset(buf, "esting", 6));
  320. test_eq(1, buf_find_string_offset(buf, "est", 3));
  321. test_eq(39, buf_find_string_offset(buf, "ing str", 7));
  322. test_eq(35, buf_find_string_offset(buf, "Testing str", 11));
  323. test_eq(32, buf_find_string_offset(buf, "ng ", 3));
  324. test_eq(43, buf_find_string_offset(buf, "string.", 7));
  325. test_eq(-1, buf_find_string_offset(buf, "shrdlu", 6));
  326. test_eq(-1, buf_find_string_offset(buf, "Testing thing", 13));
  327. test_eq(-1, buf_find_string_offset(buf, "ngx", 3));
  328. buf_free(buf);
  329. buf = NULL;
  330. done:
  331. if (buf)
  332. buf_free(buf);
  333. if (buf2)
  334. buf_free(buf2);
  335. }
  336. /** Run unit tests for the onion handshake code. */
  337. static void
  338. test_onion_handshake(void)
  339. {
  340. /* client-side */
  341. crypto_dh_env_t *c_dh = NULL;
  342. char c_buf[ONIONSKIN_CHALLENGE_LEN];
  343. char c_keys[40];
  344. /* server-side */
  345. char s_buf[ONIONSKIN_REPLY_LEN];
  346. char s_keys[40];
  347. /* shared */
  348. crypto_pk_env_t *pk = NULL;
  349. pk = pk_generate(0);
  350. /* client handshake 1. */
  351. memset(c_buf, 0, ONIONSKIN_CHALLENGE_LEN);
  352. test_assert(! onion_skin_create(pk, &c_dh, c_buf));
  353. /* server handshake */
  354. memset(s_buf, 0, ONIONSKIN_REPLY_LEN);
  355. memset(s_keys, 0, 40);
  356. test_assert(! onion_skin_server_handshake(c_buf, pk, NULL,
  357. s_buf, s_keys, 40));
  358. /* client handshake 2 */
  359. memset(c_keys, 0, 40);
  360. test_assert(! onion_skin_client_handshake(c_dh, s_buf, c_keys, 40));
  361. if (memcmp(c_keys, s_keys, 40)) {
  362. puts("Aiiiie");
  363. exit(1);
  364. }
  365. test_memeq(c_keys, s_keys, 40);
  366. memset(s_buf, 0, 40);
  367. test_memneq(c_keys, s_buf, 40);
  368. done:
  369. if (c_dh)
  370. crypto_dh_free(c_dh);
  371. if (pk)
  372. crypto_free_pk_env(pk);
  373. }
  374. static void
  375. test_circuit_timeout(void)
  376. {
  377. /* Plan:
  378. * 1. Generate 1000 samples
  379. * 2. Estimate parameters
  380. * 3. If difference, repeat
  381. * 4. Save state
  382. * 5. load state
  383. * 6. Estimate parameters
  384. * 7. compare differences
  385. */
  386. circuit_build_times_t initial;
  387. circuit_build_times_t estimate;
  388. circuit_build_times_t final;
  389. double timeout1, timeout2;
  390. or_state_t state;
  391. int i, runs;
  392. double close_ms;
  393. circuit_build_times_init(&initial);
  394. circuit_build_times_init(&estimate);
  395. circuit_build_times_init(&final);
  396. memset(&state, 0, sizeof(or_state_t));
  397. circuitbuild_running_unit_tests();
  398. #define timeout0 (build_time_t)(30*1000.0)
  399. initial.Xm = 3000;
  400. circuit_build_times_initial_alpha(&initial,
  401. CBT_DEFAULT_QUANTILE_CUTOFF/100.0,
  402. timeout0);
  403. close_ms = MAX(circuit_build_times_calculate_timeout(&initial,
  404. CBT_DEFAULT_CLOSE_QUANTILE/100.0),
  405. CBT_DEFAULT_TIMEOUT_INITIAL_VALUE);
  406. do {
  407. for (i=0; i < CBT_DEFAULT_MIN_CIRCUITS_TO_OBSERVE; i++) {
  408. build_time_t sample = circuit_build_times_generate_sample(&initial,0,1);
  409. if (sample > close_ms) {
  410. circuit_build_times_add_time(&estimate, CBT_BUILD_ABANDONED);
  411. } else {
  412. circuit_build_times_add_time(&estimate, sample);
  413. }
  414. }
  415. circuit_build_times_update_alpha(&estimate);
  416. timeout1 = circuit_build_times_calculate_timeout(&estimate,
  417. CBT_DEFAULT_QUANTILE_CUTOFF/100.0);
  418. circuit_build_times_set_timeout(&estimate);
  419. log_notice(LD_CIRC, "Timeout1 is %lf, Xm is %d", timeout1, estimate.Xm);
  420. /* 2% error */
  421. } while (fabs(circuit_build_times_cdf(&initial, timeout0) -
  422. circuit_build_times_cdf(&initial, timeout1)) > 0.02);
  423. test_assert(estimate.total_build_times <= CBT_NCIRCUITS_TO_OBSERVE);
  424. circuit_build_times_update_state(&estimate, &state);
  425. test_assert(circuit_build_times_parse_state(&final, &state) == 0);
  426. circuit_build_times_update_alpha(&final);
  427. timeout2 = circuit_build_times_calculate_timeout(&final,
  428. CBT_DEFAULT_QUANTILE_CUTOFF/100.0);
  429. circuit_build_times_set_timeout(&final);
  430. log_notice(LD_CIRC, "Timeout2 is %lf, Xm is %d", timeout2, final.Xm);
  431. /* 5% here because some accuracy is lost due to histogram conversion */
  432. test_assert(fabs(circuit_build_times_cdf(&initial, timeout0) -
  433. circuit_build_times_cdf(&initial, timeout2)) < 0.05);
  434. for (runs = 0; runs < 50; runs++) {
  435. int build_times_idx = 0;
  436. int total_build_times = 0;
  437. final.close_ms = final.timeout_ms = CBT_DEFAULT_TIMEOUT_INITIAL_VALUE;
  438. estimate.close_ms = estimate.timeout_ms
  439. = CBT_DEFAULT_TIMEOUT_INITIAL_VALUE;
  440. for (i = 0; i < CBT_DEFAULT_RECENT_CIRCUITS*2; i++) {
  441. circuit_build_times_network_circ_success(&estimate);
  442. circuit_build_times_add_time(&estimate,
  443. circuit_build_times_generate_sample(&estimate, 0,
  444. CBT_DEFAULT_QUANTILE_CUTOFF/100.0));
  445. circuit_build_times_network_circ_success(&estimate);
  446. circuit_build_times_add_time(&final,
  447. circuit_build_times_generate_sample(&final, 0,
  448. CBT_DEFAULT_QUANTILE_CUTOFF/100.0));
  449. }
  450. test_assert(!circuit_build_times_network_check_changed(&estimate));
  451. test_assert(!circuit_build_times_network_check_changed(&final));
  452. /* Reset liveness to be non-live */
  453. final.liveness.network_last_live = 0;
  454. estimate.liveness.network_last_live = 0;
  455. build_times_idx = estimate.build_times_idx;
  456. total_build_times = estimate.total_build_times;
  457. test_assert(circuit_build_times_network_check_live(&estimate));
  458. test_assert(circuit_build_times_network_check_live(&final));
  459. circuit_build_times_count_close(&estimate, 0,
  460. (time_t)(approx_time()-estimate.close_ms/1000.0-1));
  461. circuit_build_times_count_close(&final, 0,
  462. (time_t)(approx_time()-final.close_ms/1000.0-1));
  463. test_assert(!circuit_build_times_network_check_live(&estimate));
  464. test_assert(!circuit_build_times_network_check_live(&final));
  465. log_info(LD_CIRC, "idx: %d %d, tot: %d %d",
  466. build_times_idx, estimate.build_times_idx,
  467. total_build_times, estimate.total_build_times);
  468. /* Check rollback index. Should match top of loop. */
  469. test_assert(build_times_idx == estimate.build_times_idx);
  470. // This can fail if estimate.total_build_times == 1000, because
  471. // in that case, rewind actually causes us to lose timeouts
  472. if (total_build_times != CBT_NCIRCUITS_TO_OBSERVE)
  473. test_assert(total_build_times == estimate.total_build_times);
  474. /* Now simulate that the network has become live and we need
  475. * a change */
  476. circuit_build_times_network_is_live(&estimate);
  477. circuit_build_times_network_is_live(&final);
  478. for (i = 0; i < CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT; i++) {
  479. circuit_build_times_count_timeout(&estimate, 1);
  480. if (i < CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT-1) {
  481. circuit_build_times_count_timeout(&final, 1);
  482. }
  483. }
  484. test_assert(estimate.liveness.after_firsthop_idx == 0);
  485. test_assert(final.liveness.after_firsthop_idx ==
  486. CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT-1);
  487. test_assert(circuit_build_times_network_check_live(&estimate));
  488. test_assert(circuit_build_times_network_check_live(&final));
  489. circuit_build_times_count_timeout(&final, 1);
  490. }
  491. done:
  492. return;
  493. }
  494. /** Helper: Parse the exit policy string in <b>policy_str</b>, and make sure
  495. * that policies_summarize() produces the string <b>expected_summary</b> from
  496. * it. */
  497. static void
  498. test_policy_summary_helper(const char *policy_str,
  499. const char *expected_summary)
  500. {
  501. config_line_t line;
  502. smartlist_t *policy = smartlist_create();
  503. char *summary = NULL;
  504. int r;
  505. short_policy_t *short_policy = NULL;
  506. line.key = (char*)"foo";
  507. line.value = (char *)policy_str;
  508. line.next = NULL;
  509. r = policies_parse_exit_policy(&line, &policy, 0, NULL, 1);
  510. test_eq(r, 0);
  511. summary = policy_summarize(policy);
  512. test_assert(summary != NULL);
  513. test_streq(summary, expected_summary);
  514. short_policy = parse_short_policy(summary);
  515. tt_assert(short_policy);
  516. done:
  517. tor_free(summary);
  518. if (policy)
  519. addr_policy_list_free(policy);
  520. short_policy_free(short_policy);
  521. }
  522. /** Run unit tests for generating summary lines of exit policies */
  523. static void
  524. test_policies(void)
  525. {
  526. int i;
  527. smartlist_t *policy = NULL, *policy2 = NULL, *policy3 = NULL,
  528. *policy4 = NULL, *policy5 = NULL, *policy6 = NULL,
  529. *policy7 = NULL;
  530. addr_policy_t *p;
  531. tor_addr_t tar;
  532. config_line_t line;
  533. smartlist_t *sm = NULL;
  534. char *policy_str = NULL;
  535. policy = smartlist_create();
  536. p = router_parse_addr_policy_item_from_string("reject 192.168.0.0/16:*",-1);
  537. test_assert(p != NULL);
  538. test_eq(ADDR_POLICY_REJECT, p->policy_type);
  539. tor_addr_from_ipv4h(&tar, 0xc0a80000u);
  540. test_eq(0, tor_addr_compare(&p->addr, &tar, CMP_EXACT));
  541. test_eq(16, p->maskbits);
  542. test_eq(1, p->prt_min);
  543. test_eq(65535, p->prt_max);
  544. smartlist_add(policy, p);
  545. test_assert(ADDR_POLICY_ACCEPTED ==
  546. compare_addr_to_addr_policy(0x01020304u, 2, policy));
  547. test_assert(ADDR_POLICY_PROBABLY_ACCEPTED ==
  548. compare_addr_to_addr_policy(0, 2, policy));
  549. test_assert(ADDR_POLICY_REJECTED ==
  550. compare_addr_to_addr_policy(0xc0a80102, 2, policy));
  551. test_assert(0 == policies_parse_exit_policy(NULL, &policy2, 1, NULL, 1));
  552. test_assert(policy2);
  553. policy3 = smartlist_create();
  554. p = router_parse_addr_policy_item_from_string("reject *:*",-1);
  555. test_assert(p != NULL);
  556. smartlist_add(policy3, p);
  557. p = router_parse_addr_policy_item_from_string("accept *:*",-1);
  558. test_assert(p != NULL);
  559. smartlist_add(policy3, p);
  560. policy4 = smartlist_create();
  561. p = router_parse_addr_policy_item_from_string("accept *:443",-1);
  562. test_assert(p != NULL);
  563. smartlist_add(policy4, p);
  564. p = router_parse_addr_policy_item_from_string("accept *:443",-1);
  565. test_assert(p != NULL);
  566. smartlist_add(policy4, p);
  567. policy5 = smartlist_create();
  568. p = router_parse_addr_policy_item_from_string("reject 0.0.0.0/8:*",-1);
  569. test_assert(p != NULL);
  570. smartlist_add(policy5, p);
  571. p = router_parse_addr_policy_item_from_string("reject 169.254.0.0/16:*",-1);
  572. test_assert(p != NULL);
  573. smartlist_add(policy5, p);
  574. p = router_parse_addr_policy_item_from_string("reject 127.0.0.0/8:*",-1);
  575. test_assert(p != NULL);
  576. smartlist_add(policy5, p);
  577. p = router_parse_addr_policy_item_from_string("reject 192.168.0.0/16:*",-1);
  578. test_assert(p != NULL);
  579. smartlist_add(policy5, p);
  580. p = router_parse_addr_policy_item_from_string("reject 10.0.0.0/8:*",-1);
  581. test_assert(p != NULL);
  582. smartlist_add(policy5, p);
  583. p = router_parse_addr_policy_item_from_string("reject 172.16.0.0/12:*",-1);
  584. test_assert(p != NULL);
  585. smartlist_add(policy5, p);
  586. p = router_parse_addr_policy_item_from_string("reject 80.190.250.90:*",-1);
  587. test_assert(p != NULL);
  588. smartlist_add(policy5, p);
  589. p = router_parse_addr_policy_item_from_string("reject *:1-65534",-1);
  590. test_assert(p != NULL);
  591. smartlist_add(policy5, p);
  592. p = router_parse_addr_policy_item_from_string("reject *:65535",-1);
  593. test_assert(p != NULL);
  594. smartlist_add(policy5, p);
  595. p = router_parse_addr_policy_item_from_string("accept *:1-65535",-1);
  596. test_assert(p != NULL);
  597. smartlist_add(policy5, p);
  598. policy6 = smartlist_create();
  599. p = router_parse_addr_policy_item_from_string("accept 43.3.0.0/9:*",-1);
  600. test_assert(p != NULL);
  601. smartlist_add(policy6, p);
  602. policy7 = smartlist_create();
  603. p = router_parse_addr_policy_item_from_string("accept 0.0.0.0/8:*",-1);
  604. test_assert(p != NULL);
  605. smartlist_add(policy7, p);
  606. test_assert(!exit_policy_is_general_exit(policy));
  607. test_assert(exit_policy_is_general_exit(policy2));
  608. test_assert(!exit_policy_is_general_exit(NULL));
  609. test_assert(!exit_policy_is_general_exit(policy3));
  610. test_assert(!exit_policy_is_general_exit(policy4));
  611. test_assert(!exit_policy_is_general_exit(policy5));
  612. test_assert(!exit_policy_is_general_exit(policy6));
  613. test_assert(!exit_policy_is_general_exit(policy7));
  614. test_assert(cmp_addr_policies(policy, policy2));
  615. test_assert(cmp_addr_policies(policy, NULL));
  616. test_assert(!cmp_addr_policies(policy2, policy2));
  617. test_assert(!cmp_addr_policies(NULL, NULL));
  618. test_assert(!policy_is_reject_star(policy2));
  619. test_assert(policy_is_reject_star(policy));
  620. test_assert(policy_is_reject_star(NULL));
  621. addr_policy_list_free(policy);
  622. policy = NULL;
  623. /* make sure compacting logic works. */
  624. policy = NULL;
  625. line.key = (char*)"foo";
  626. line.value = (char*)"accept *:80,reject private:*,reject *:*";
  627. line.next = NULL;
  628. test_assert(0 == policies_parse_exit_policy(&line, &policy, 0, NULL, 1));
  629. test_assert(policy);
  630. //test_streq(policy->string, "accept *:80");
  631. //test_streq(policy->next->string, "reject *:*");
  632. test_eq(smartlist_len(policy), 2);
  633. /* test policy summaries */
  634. /* check if we properly ignore private IP addresses */
  635. test_policy_summary_helper("reject 192.168.0.0/16:*,"
  636. "reject 0.0.0.0/8:*,"
  637. "reject 10.0.0.0/8:*,"
  638. "accept *:10-30,"
  639. "accept *:90,"
  640. "reject *:*",
  641. "accept 10-30,90");
  642. /* check all accept policies, and proper counting of rejects */
  643. test_policy_summary_helper("reject 11.0.0.0/9:80,"
  644. "reject 12.0.0.0/9:80,"
  645. "reject 13.0.0.0/9:80,"
  646. "reject 14.0.0.0/9:80,"
  647. "accept *:*", "accept 1-65535");
  648. test_policy_summary_helper("reject 11.0.0.0/9:80,"
  649. "reject 12.0.0.0/9:80,"
  650. "reject 13.0.0.0/9:80,"
  651. "reject 14.0.0.0/9:80,"
  652. "reject 15.0.0.0:81,"
  653. "accept *:*", "accept 1-65535");
  654. test_policy_summary_helper("reject 11.0.0.0/9:80,"
  655. "reject 12.0.0.0/9:80,"
  656. "reject 13.0.0.0/9:80,"
  657. "reject 14.0.0.0/9:80,"
  658. "reject 15.0.0.0:80,"
  659. "accept *:*",
  660. "reject 80");
  661. /* no exits */
  662. test_policy_summary_helper("accept 11.0.0.0/9:80,"
  663. "reject *:*",
  664. "reject 1-65535");
  665. /* port merging */
  666. test_policy_summary_helper("accept *:80,"
  667. "accept *:81,"
  668. "accept *:100-110,"
  669. "accept *:111,"
  670. "reject *:*",
  671. "accept 80-81,100-111");
  672. /* border ports */
  673. test_policy_summary_helper("accept *:1,"
  674. "accept *:3,"
  675. "accept *:65535,"
  676. "reject *:*",
  677. "accept 1,3,65535");
  678. /* holes */
  679. test_policy_summary_helper("accept *:1,"
  680. "accept *:3,"
  681. "accept *:5,"
  682. "accept *:7,"
  683. "reject *:*",
  684. "accept 1,3,5,7");
  685. test_policy_summary_helper("reject *:1,"
  686. "reject *:3,"
  687. "reject *:5,"
  688. "reject *:7,"
  689. "accept *:*",
  690. "reject 1,3,5,7");
  691. /* truncation ports */
  692. sm = smartlist_create();
  693. for (i=1; i<2000; i+=2) {
  694. char buf[POLICY_BUF_LEN];
  695. tor_snprintf(buf, sizeof(buf), "reject *:%d", i);
  696. smartlist_add(sm, tor_strdup(buf));
  697. }
  698. smartlist_add(sm, tor_strdup("accept *:*"));
  699. policy_str = smartlist_join_strings(sm, ",", 0, NULL);
  700. test_policy_summary_helper( policy_str,
  701. "accept 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,"
  702. "46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,"
  703. "92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,"
  704. "130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,"
  705. "166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198,200,"
  706. "202,204,206,208,210,212,214,216,218,220,222,224,226,228,230,232,234,236,"
  707. "238,240,242,244,246,248,250,252,254,256,258,260,262,264,266,268,270,272,"
  708. "274,276,278,280,282,284,286,288,290,292,294,296,298,300,302,304,306,308,"
  709. "310,312,314,316,318,320,322,324,326,328,330,332,334,336,338,340,342,344,"
  710. "346,348,350,352,354,356,358,360,362,364,366,368,370,372,374,376,378,380,"
  711. "382,384,386,388,390,392,394,396,398,400,402,404,406,408,410,412,414,416,"
  712. "418,420,422,424,426,428,430,432,434,436,438,440,442,444,446,448,450,452,"
  713. "454,456,458,460,462,464,466,468,470,472,474,476,478,480,482,484,486,488,"
  714. "490,492,494,496,498,500,502,504,506,508,510,512,514,516,518,520,522");
  715. done:
  716. addr_policy_list_free(policy);
  717. addr_policy_list_free(policy2);
  718. addr_policy_list_free(policy3);
  719. addr_policy_list_free(policy4);
  720. addr_policy_list_free(policy5);
  721. addr_policy_list_free(policy6);
  722. addr_policy_list_free(policy7);
  723. tor_free(policy_str);
  724. if (sm) {
  725. SMARTLIST_FOREACH(sm, char *, s, tor_free(s));
  726. smartlist_free(sm);
  727. }
  728. }
  729. /** Run AES performance benchmarks. */
  730. static void
  731. bench_aes(void)
  732. {
  733. int len, i;
  734. char *b1, *b2;
  735. crypto_cipher_env_t *c;
  736. struct timeval start, end;
  737. const int iters = 100000;
  738. uint64_t nsec;
  739. c = crypto_new_cipher_env();
  740. crypto_cipher_generate_key(c);
  741. crypto_cipher_encrypt_init_cipher(c);
  742. for (len = 1; len <= 8192; len *= 2) {
  743. b1 = tor_malloc_zero(len);
  744. b2 = tor_malloc_zero(len);
  745. tor_gettimeofday(&start);
  746. for (i = 0; i < iters; ++i) {
  747. crypto_cipher_encrypt(c, b1, b2, len);
  748. }
  749. tor_gettimeofday(&end);
  750. tor_free(b1);
  751. tor_free(b2);
  752. nsec = (uint64_t) tv_udiff(&start,&end);
  753. nsec *= 1000;
  754. nsec /= (iters*len);
  755. printf("%d bytes: "U64_FORMAT" nsec per byte\n", len,
  756. U64_PRINTF_ARG(nsec));
  757. }
  758. crypto_free_cipher_env(c);
  759. }
  760. /** Run digestmap_t performance benchmarks. */
  761. static void
  762. bench_dmap(void)
  763. {
  764. smartlist_t *sl = smartlist_create();
  765. smartlist_t *sl2 = smartlist_create();
  766. struct timeval start, end, pt2, pt3, pt4;
  767. const int iters = 10000;
  768. const int elts = 4000;
  769. const int fpostests = 1000000;
  770. char d[20];
  771. int i,n=0, fp = 0;
  772. digestmap_t *dm = digestmap_new();
  773. digestset_t *ds = digestset_new(elts);
  774. for (i = 0; i < elts; ++i) {
  775. crypto_rand(d, 20);
  776. smartlist_add(sl, tor_memdup(d, 20));
  777. }
  778. for (i = 0; i < elts; ++i) {
  779. crypto_rand(d, 20);
  780. smartlist_add(sl2, tor_memdup(d, 20));
  781. }
  782. printf("nbits=%d\n", ds->mask+1);
  783. tor_gettimeofday(&start);
  784. for (i = 0; i < iters; ++i) {
  785. SMARTLIST_FOREACH(sl, const char *, cp, digestmap_set(dm, cp, (void*)1));
  786. }
  787. tor_gettimeofday(&pt2);
  788. for (i = 0; i < iters; ++i) {
  789. SMARTLIST_FOREACH(sl, const char *, cp, digestmap_get(dm, cp));
  790. SMARTLIST_FOREACH(sl2, const char *, cp, digestmap_get(dm, cp));
  791. }
  792. tor_gettimeofday(&pt3);
  793. for (i = 0; i < iters; ++i) {
  794. SMARTLIST_FOREACH(sl, const char *, cp, digestset_add(ds, cp));
  795. }
  796. tor_gettimeofday(&pt4);
  797. for (i = 0; i < iters; ++i) {
  798. SMARTLIST_FOREACH(sl, const char *, cp, n += digestset_isin(ds, cp));
  799. SMARTLIST_FOREACH(sl2, const char *, cp, n += digestset_isin(ds, cp));
  800. }
  801. tor_gettimeofday(&end);
  802. for (i = 0; i < fpostests; ++i) {
  803. crypto_rand(d, 20);
  804. if (digestset_isin(ds, d)) ++fp;
  805. }
  806. printf("%ld\n",(unsigned long)tv_udiff(&start, &pt2));
  807. printf("%ld\n",(unsigned long)tv_udiff(&pt2, &pt3));
  808. printf("%ld\n",(unsigned long)tv_udiff(&pt3, &pt4));
  809. printf("%ld\n",(unsigned long)tv_udiff(&pt4, &end));
  810. printf("-- %d\n", n);
  811. printf("++ %f\n", fp/(double)fpostests);
  812. digestmap_free(dm, NULL);
  813. digestset_free(ds);
  814. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  815. SMARTLIST_FOREACH(sl2, char *, cp, tor_free(cp));
  816. smartlist_free(sl);
  817. smartlist_free(sl2);
  818. }
  819. /** Test encoding and parsing of rendezvous service descriptors. */
  820. static void
  821. test_rend_fns(void)
  822. {
  823. rend_service_descriptor_t *generated = NULL, *parsed = NULL;
  824. char service_id[DIGEST_LEN];
  825. char service_id_base32[REND_SERVICE_ID_LEN_BASE32+1];
  826. const char *next_desc;
  827. smartlist_t *descs = smartlist_create();
  828. char computed_desc_id[DIGEST_LEN];
  829. char parsed_desc_id[DIGEST_LEN];
  830. crypto_pk_env_t *pk1 = NULL, *pk2 = NULL;
  831. time_t now;
  832. char *intro_points_encrypted = NULL;
  833. size_t intro_points_size;
  834. size_t encoded_size;
  835. int i;
  836. char address1[] = "fooaddress.onion";
  837. char address2[] = "aaaaaaaaaaaaaaaa.onion";
  838. char address3[] = "fooaddress.exit";
  839. char address4[] = "www.torproject.org";
  840. test_assert(BAD_HOSTNAME == parse_extended_hostname(address1, 1));
  841. test_assert(ONION_HOSTNAME == parse_extended_hostname(address2, 1));
  842. test_assert(EXIT_HOSTNAME == parse_extended_hostname(address3, 1));
  843. test_assert(NORMAL_HOSTNAME == parse_extended_hostname(address4, 1));
  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_create();
  856. for (i = 0; i < 3; i++) {
  857. rend_intro_point_t *intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  858. crypto_pk_env_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_free_pk_env(pk1);
  924. if (pk2)
  925. crypto_free_pk_env(pk2);
  926. tor_free(intro_points_encrypted);
  927. }
  928. /** Run unit tests for GeoIP code. */
  929. static void
  930. test_geoip(void)
  931. {
  932. int i, j;
  933. time_t now = time(NULL);
  934. char *s = NULL;
  935. /* Populate the DB a bit. Add these in order, since we can't do the final
  936. * 'sort' step. These aren't very good IP addresses, but they're perfectly
  937. * fine uint32_t values. */
  938. test_eq(0, geoip_parse_entry("10,50,AB"));
  939. test_eq(0, geoip_parse_entry("52,90,XY"));
  940. test_eq(0, geoip_parse_entry("95,100,AB"));
  941. test_eq(0, geoip_parse_entry("\"105\",\"140\",\"ZZ\""));
  942. test_eq(0, geoip_parse_entry("\"150\",\"190\",\"XY\""));
  943. test_eq(0, geoip_parse_entry("\"200\",\"250\",\"AB\""));
  944. /* We should have 4 countries: ??, ab, xy, zz. */
  945. test_eq(4, geoip_get_n_countries());
  946. /* Make sure that country ID actually works. */
  947. #define NAMEFOR(x) geoip_get_country_name(geoip_get_country_by_ip(x))
  948. test_streq("??", NAMEFOR(3));
  949. test_eq(0, geoip_get_country_by_ip(3));
  950. test_streq("ab", NAMEFOR(32));
  951. test_streq("??", NAMEFOR(5));
  952. test_streq("??", NAMEFOR(51));
  953. test_streq("xy", NAMEFOR(150));
  954. test_streq("xy", NAMEFOR(190));
  955. test_streq("??", NAMEFOR(2000));
  956. #undef NAMEFOR
  957. get_options()->BridgeRelay = 1;
  958. get_options()->BridgeRecordUsageByCountry = 1;
  959. /* Put 9 observations in AB... */
  960. for (i=32; i < 40; ++i)
  961. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, i, now-7200);
  962. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, 225, now-7200);
  963. /* and 3 observations in XY, several times. */
  964. for (j=0; j < 10; ++j)
  965. for (i=52; i < 55; ++i)
  966. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, i, now-3600);
  967. /* and 17 observations in ZZ... */
  968. for (i=110; i < 127; ++i)
  969. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, i, now);
  970. s = geoip_get_client_history(GEOIP_CLIENT_CONNECT);
  971. test_assert(s);
  972. test_streq("zz=24,ab=16,xy=8", s);
  973. tor_free(s);
  974. /* Now clear out all the AB observations. */
  975. geoip_remove_old_clients(now-6000);
  976. s = geoip_get_client_history(GEOIP_CLIENT_CONNECT);
  977. test_assert(s);
  978. test_streq("zz=24,xy=8", s);
  979. done:
  980. tor_free(s);
  981. }
  982. /** Run unit tests for stats code. */
  983. static void
  984. test_stats(void)
  985. {
  986. time_t now = 1281533250; /* 2010-08-11 13:27:30 UTC */
  987. char *s = NULL;
  988. /* We shouldn't collect exit stats without initializing them. */
  989. rep_hist_note_exit_stream_opened(80);
  990. rep_hist_note_exit_bytes(80, 100, 10000);
  991. s = rep_hist_format_exit_stats(now + 86400);
  992. test_assert(!s);
  993. /* Initialize stats, note some streams and bytes, and generate history
  994. * string. */
  995. rep_hist_exit_stats_init(now);
  996. rep_hist_note_exit_stream_opened(80);
  997. rep_hist_note_exit_bytes(80, 100, 10000);
  998. rep_hist_note_exit_stream_opened(443);
  999. rep_hist_note_exit_bytes(443, 100, 10000);
  1000. rep_hist_note_exit_bytes(443, 100, 10000);
  1001. s = rep_hist_format_exit_stats(now + 86400);
  1002. test_streq("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1003. "exit-kibibytes-written 80=1,443=1,other=0\n"
  1004. "exit-kibibytes-read 80=10,443=20,other=0\n"
  1005. "exit-streams-opened 80=4,443=4,other=0\n", s);
  1006. tor_free(s);
  1007. /* Stop collecting stats, add some bytes, and ensure we don't generate
  1008. * a history string. */
  1009. rep_hist_exit_stats_term();
  1010. rep_hist_note_exit_bytes(80, 100, 10000);
  1011. s = rep_hist_format_exit_stats(now + 86400);
  1012. test_assert(!s);
  1013. /* Re-start stats, add some bytes, reset stats, and see what history we
  1014. * get when observing no streams or bytes at all. */
  1015. rep_hist_exit_stats_init(now);
  1016. rep_hist_note_exit_stream_opened(80);
  1017. rep_hist_note_exit_bytes(80, 100, 10000);
  1018. rep_hist_reset_exit_stats(now);
  1019. s = rep_hist_format_exit_stats(now + 86400);
  1020. test_streq("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1021. "exit-kibibytes-written other=0\n"
  1022. "exit-kibibytes-read other=0\n"
  1023. "exit-streams-opened other=0\n", s);
  1024. done:
  1025. tor_free(s);
  1026. }
  1027. static void *
  1028. legacy_test_setup(const struct testcase_t *testcase)
  1029. {
  1030. return testcase->setup_data;
  1031. }
  1032. void
  1033. legacy_test_helper(void *data)
  1034. {
  1035. void (*fn)(void) = data;
  1036. fn();
  1037. }
  1038. static int
  1039. legacy_test_cleanup(const struct testcase_t *testcase, void *ptr)
  1040. {
  1041. (void)ptr;
  1042. (void)testcase;
  1043. return 1;
  1044. }
  1045. const struct testcase_setup_t legacy_setup = {
  1046. legacy_test_setup, legacy_test_cleanup
  1047. };
  1048. #define ENT(name) \
  1049. { #name, legacy_test_helper, 0, &legacy_setup, test_ ## name }
  1050. #define SUBENT(group, name) \
  1051. { #group "_" #name, legacy_test_helper, 0, &legacy_setup, \
  1052. test_ ## group ## _ ## name }
  1053. #define DISABLED(name) \
  1054. { #name, legacy_test_helper, TT_SKIP, &legacy_setup, name }
  1055. #define FORK(name) \
  1056. { #name, legacy_test_helper, TT_FORK, &legacy_setup, test_ ## name }
  1057. static struct testcase_t test_array[] = {
  1058. ENT(buffers),
  1059. ENT(onion_handshake),
  1060. ENT(circuit_timeout),
  1061. ENT(policies),
  1062. ENT(rend_fns),
  1063. ENT(geoip),
  1064. FORK(stats),
  1065. DISABLED(bench_aes),
  1066. DISABLED(bench_dmap),
  1067. END_OF_TESTCASES
  1068. };
  1069. extern struct testcase_t addr_tests[];
  1070. extern struct testcase_t crypto_tests[];
  1071. extern struct testcase_t container_tests[];
  1072. extern struct testcase_t util_tests[];
  1073. extern struct testcase_t dir_tests[];
  1074. extern struct testcase_t microdesc_tests[];
  1075. static struct testgroup_t testgroups[] = {
  1076. { "", test_array },
  1077. { "addr/", addr_tests },
  1078. { "crypto/", crypto_tests },
  1079. { "container/", container_tests },
  1080. { "util/", util_tests },
  1081. { "dir/", dir_tests },
  1082. { "dir/md/", microdesc_tests },
  1083. END_OF_GROUPS
  1084. };
  1085. /** Main entry point for unit test code: parse the command line, and run
  1086. * some unit tests. */
  1087. int
  1088. main(int c, const char **v)
  1089. {
  1090. or_options_t *options;
  1091. char *errmsg = NULL;
  1092. int i, i_out;
  1093. int loglevel = LOG_ERR;
  1094. #ifdef USE_DMALLOC
  1095. {
  1096. int r = CRYPTO_set_mem_ex_functions(_tor_malloc, _tor_realloc, _tor_free);
  1097. tor_assert(r);
  1098. }
  1099. #endif
  1100. update_approx_time(time(NULL));
  1101. options = options_new();
  1102. tor_threads_init();
  1103. init_logging();
  1104. for (i_out = i = 1; i < c; ++i) {
  1105. if (!strcmp(v[i], "--warn")) {
  1106. loglevel = LOG_WARN;
  1107. } else if (!strcmp(v[i], "--notice")) {
  1108. loglevel = LOG_NOTICE;
  1109. } else if (!strcmp(v[i], "--info")) {
  1110. loglevel = LOG_INFO;
  1111. } else if (!strcmp(v[i], "--debug")) {
  1112. loglevel = LOG_DEBUG;
  1113. } else {
  1114. v[i_out++] = v[i];
  1115. }
  1116. }
  1117. c = i_out;
  1118. {
  1119. log_severity_list_t s;
  1120. memset(&s, 0, sizeof(s));
  1121. set_log_severity_config(loglevel, LOG_ERR, &s);
  1122. add_stream_log(&s, "", fileno(stdout));
  1123. }
  1124. options->command = CMD_RUN_UNITTESTS;
  1125. crypto_global_init(0, NULL, NULL);
  1126. rep_hist_init();
  1127. network_init();
  1128. setup_directory();
  1129. options_init(options);
  1130. options->DataDirectory = tor_strdup(temp_dir);
  1131. options->EntryStatistics = 1;
  1132. if (set_options(options, &errmsg) < 0) {
  1133. printf("Failed to set initial options: %s\n", errmsg);
  1134. tor_free(errmsg);
  1135. return 1;
  1136. }
  1137. crypto_seed_rng(1);
  1138. atexit(remove_directory);
  1139. have_failed = (tinytest_main(c, v, testgroups) != 0);
  1140. free_pregenerated_keys();
  1141. #ifdef USE_DMALLOC
  1142. tor_free_all(0);
  1143. dmalloc_log_unfreed();
  1144. #endif
  1145. if (have_failed)
  1146. return 1;
  1147. else
  1148. return 0;
  1149. }