test.c 40 KB

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