test.c 40 KB

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