test.c 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219
  1. /* Copyright (c) 2001-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2013, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /* Ordinarily defined in tor_main.c; this bit is just here to provide one
  6. * since we're not linking to tor_main.c */
  7. const char tor_git_revision[] = "";
  8. /**
  9. * \file test.c
  10. * \brief Unit tests for many pieces of the lower level Tor modules.
  11. **/
  12. #include "orconfig.h"
  13. #include <stdio.h>
  14. #ifdef HAVE_FCNTL_H
  15. #include <fcntl.h>
  16. #endif
  17. #ifdef _WIN32
  18. /* For mkdir() */
  19. #include <direct.h>
  20. #else
  21. #include <dirent.h>
  22. #endif
  23. /* These macros pull in declarations for some functions and structures that
  24. * are typically file-private. */
  25. #define BUFFERS_PRIVATE
  26. #define CONFIG_PRIVATE
  27. #define GEOIP_PRIVATE
  28. #define ROUTER_PRIVATE
  29. #define CIRCUITSTATS_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 "circuitstats.h"
  40. #include "config.h"
  41. #include "connection_edge.h"
  42. #include "geoip.h"
  43. #include "rendcommon.h"
  44. #include "test.h"
  45. #include "torgzip.h"
  46. #include "mempool.h"
  47. #include "memarea.h"
  48. #include "onion_tap.h"
  49. #include "policies.h"
  50. #include "rephist.h"
  51. #include "routerparse.h"
  52. #ifdef CURVE25519_ENABLED
  53. #include "crypto_curve25519.h"
  54. #include "onion_ntor.h"
  55. #endif
  56. #ifdef USE_DMALLOC
  57. #include <dmalloc.h>
  58. #include <openssl/crypto.h>
  59. #include "main.h"
  60. #endif
  61. /** Set to true if any unit test has failed. Mostly, this is set by the macros
  62. * in test.h */
  63. int have_failed = 0;
  64. /** Temporary directory (set up by setup_directory) under which we store all
  65. * our files during testing. */
  66. static char temp_dir[256];
  67. #ifdef _WIN32
  68. #define pid_t int
  69. #endif
  70. static pid_t temp_dir_setup_in_pid = 0;
  71. /** Select and create the temporary directory we'll use to run our unit tests.
  72. * Store it in <b>temp_dir</b>. Exit immediately if we can't create it.
  73. * idempotent. */
  74. static void
  75. setup_directory(void)
  76. {
  77. static int is_setup = 0;
  78. int r;
  79. char rnd[256], rnd32[256];
  80. if (is_setup) return;
  81. /* Due to base32 limitation needs to be a multiple of 5. */
  82. #define RAND_PATH_BYTES 5
  83. crypto_rand(rnd, RAND_PATH_BYTES);
  84. base32_encode(rnd32, sizeof(rnd32), rnd, RAND_PATH_BYTES);
  85. #ifdef _WIN32
  86. {
  87. char buf[MAX_PATH];
  88. const char *tmp = buf;
  89. /* If this fails, we're probably screwed anyway */
  90. if (!GetTempPathA(sizeof(buf),buf))
  91. tmp = "c:\\windows\\temp";
  92. tor_snprintf(temp_dir, sizeof(temp_dir),
  93. "%s\\tor_test_%d_%s", tmp, (int)getpid(), rnd32);
  94. r = mkdir(temp_dir);
  95. }
  96. #else
  97. tor_snprintf(temp_dir, sizeof(temp_dir), "/tmp/tor_test_%d_%s", (int) getpid(), rnd32);
  98. r = mkdir(temp_dir, 0700);
  99. #endif
  100. if (r) {
  101. fprintf(stderr, "Can't create directory %s:", temp_dir);
  102. perror("");
  103. exit(1);
  104. }
  105. is_setup = 1;
  106. temp_dir_setup_in_pid = getpid();
  107. }
  108. /** Return a filename relative to our testing temporary directory */
  109. const char *
  110. get_fname(const char *name)
  111. {
  112. static char buf[1024];
  113. setup_directory();
  114. if (!name)
  115. return temp_dir;
  116. tor_snprintf(buf,sizeof(buf),"%s/%s",temp_dir,name);
  117. return buf;
  118. }
  119. /* Remove a directory and all of its subdirectories */
  120. static void
  121. rm_rf(const char *dir)
  122. {
  123. struct stat st;
  124. smartlist_t *elements;
  125. elements = tor_listdir(dir);
  126. if (elements) {
  127. SMARTLIST_FOREACH_BEGIN(elements, const char *, cp) {
  128. char *tmp = NULL;
  129. tor_asprintf(&tmp, "%s"PATH_SEPARATOR"%s", dir, cp);
  130. if (0 == stat(tmp,&st) && (st.st_mode & S_IFDIR)) {
  131. rm_rf(tmp);
  132. } else {
  133. if (unlink(tmp)) {
  134. fprintf(stderr, "Error removing %s: %s\n", tmp, strerror(errno));
  135. }
  136. }
  137. tor_free(tmp);
  138. } SMARTLIST_FOREACH_END(cp);
  139. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  140. smartlist_free(elements);
  141. }
  142. if (rmdir(dir))
  143. fprintf(stderr, "Error removing directory %s: %s\n", dir, strerror(errno));
  144. }
  145. /** Remove all files stored under the temporary directory, and the directory
  146. * itself. Called by atexit(). */
  147. static void
  148. remove_directory(void)
  149. {
  150. if (getpid() != temp_dir_setup_in_pid) {
  151. /* Only clean out the tempdir when the main process is exiting. */
  152. return;
  153. }
  154. rm_rf(temp_dir);
  155. }
  156. /** Define this if unit tests spend too much time generating public keys*/
  157. #undef CACHE_GENERATED_KEYS
  158. static crypto_pk_t *pregen_keys[5] = {NULL, NULL, NULL, NULL, NULL};
  159. #define N_PREGEN_KEYS ((int)(sizeof(pregen_keys)/sizeof(pregen_keys[0])))
  160. /** Generate and return a new keypair for use in unit tests. If we're using
  161. * the key cache optimization, we might reuse keys: we only guarantee that
  162. * keys made with distinct values for <b>idx</b> are different. The value of
  163. * <b>idx</b> must be at least 0, and less than N_PREGEN_KEYS. */
  164. crypto_pk_t *
  165. pk_generate(int idx)
  166. {
  167. #ifdef CACHE_GENERATED_KEYS
  168. tor_assert(idx < N_PREGEN_KEYS);
  169. if (! pregen_keys[idx]) {
  170. pregen_keys[idx] = crypto_pk_new();
  171. tor_assert(!crypto_pk_generate_key(pregen_keys[idx]));
  172. }
  173. return crypto_pk_dup_key(pregen_keys[idx]);
  174. #else
  175. crypto_pk_t *result;
  176. (void) idx;
  177. result = crypto_pk_new();
  178. tor_assert(!crypto_pk_generate_key(result));
  179. return result;
  180. #endif
  181. }
  182. /** Free all storage used for the cached key optimization. */
  183. static void
  184. free_pregenerated_keys(void)
  185. {
  186. unsigned idx;
  187. for (idx = 0; idx < N_PREGEN_KEYS; ++idx) {
  188. if (pregen_keys[idx]) {
  189. crypto_pk_free(pregen_keys[idx]);
  190. pregen_keys[idx] = NULL;
  191. }
  192. }
  193. }
  194. typedef struct socks_test_data_t {
  195. socks_request_t *req;
  196. buf_t *buf;
  197. } socks_test_data_t;
  198. static void *
  199. socks_test_setup(const struct testcase_t *testcase)
  200. {
  201. socks_test_data_t *data = tor_malloc(sizeof(socks_test_data_t));
  202. (void)testcase;
  203. data->buf = buf_new_with_capacity(256);
  204. data->req = socks_request_new();
  205. config_register_addressmaps(get_options());
  206. return data;
  207. }
  208. static int
  209. socks_test_cleanup(const struct testcase_t *testcase, void *ptr)
  210. {
  211. socks_test_data_t *data = ptr;
  212. (void)testcase;
  213. buf_free(data->buf);
  214. socks_request_free(data->req);
  215. tor_free(data);
  216. return 1;
  217. }
  218. const struct testcase_setup_t socks_setup = {
  219. socks_test_setup, socks_test_cleanup
  220. };
  221. #define SOCKS_TEST_INIT() \
  222. socks_test_data_t *testdata = ptr; \
  223. buf_t *buf = testdata->buf; \
  224. socks_request_t *socks = testdata->req;
  225. #define ADD_DATA(buf, s) \
  226. write_to_buf(s, sizeof(s)-1, buf)
  227. static void
  228. socks_request_clear(socks_request_t *socks)
  229. {
  230. tor_free(socks->username);
  231. tor_free(socks->password);
  232. memset(socks, 0, sizeof(socks_request_t));
  233. }
  234. /** Perform unsupported SOCKS 4 commands */
  235. static void
  236. test_socks_4_unsupported_commands(void *ptr)
  237. {
  238. SOCKS_TEST_INIT();
  239. /* SOCKS 4 Send BIND [02] to IP address 2.2.2.2:4369 */
  240. ADD_DATA(buf, "\x04\x02\x11\x11\x02\x02\x02\x02\x00");
  241. test_assert(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
  242. get_options()->SafeSocks) == -1);
  243. test_eq(4, socks->socks_version);
  244. test_eq(0, socks->replylen); /* XXX: shouldn't tor reply? */
  245. done:
  246. ;
  247. }
  248. /** Perform supported SOCKS 4 commands */
  249. static void
  250. test_socks_4_supported_commands(void *ptr)
  251. {
  252. SOCKS_TEST_INIT();
  253. test_eq(0, buf_datalen(buf));
  254. /* SOCKS 4 Send CONNECT [01] to IP address 2.2.2.2:4370 */
  255. ADD_DATA(buf, "\x04\x01\x11\x12\x02\x02\x02\x03\x00");
  256. test_assert(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
  257. get_options()->SafeSocks) == 1);
  258. test_eq(4, socks->socks_version);
  259. test_eq(0, socks->replylen); /* XXX: shouldn't tor reply? */
  260. test_eq(SOCKS_COMMAND_CONNECT, socks->command);
  261. test_streq("2.2.2.3", socks->address);
  262. test_eq(4370, socks->port);
  263. test_assert(socks->got_auth == 0);
  264. test_assert(! socks->username);
  265. test_eq(0, buf_datalen(buf));
  266. socks_request_clear(socks);
  267. /* SOCKS 4 Send CONNECT [01] to IP address 2.2.2.2:4369 with userid*/
  268. ADD_DATA(buf, "\x04\x01\x11\x12\x02\x02\x02\x04me\x00");
  269. test_assert(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
  270. get_options()->SafeSocks) == 1);
  271. test_eq(4, socks->socks_version);
  272. test_eq(0, socks->replylen); /* XXX: shouldn't tor reply? */
  273. test_eq(SOCKS_COMMAND_CONNECT, socks->command);
  274. test_streq("2.2.2.4", socks->address);
  275. test_eq(4370, socks->port);
  276. test_assert(socks->got_auth == 1);
  277. test_assert(socks->username);
  278. test_eq(2, socks->usernamelen);
  279. test_memeq("me", socks->username, 2);
  280. test_eq(0, buf_datalen(buf));
  281. socks_request_clear(socks);
  282. /* SOCKS 4a Send RESOLVE [F0] request for torproject.org */
  283. ADD_DATA(buf, "\x04\xF0\x01\x01\x00\x00\x00\x02me\x00torproject.org\x00");
  284. test_assert(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
  285. get_options()->SafeSocks) == 1);
  286. test_eq(4, socks->socks_version);
  287. test_eq(0, socks->replylen); /* XXX: shouldn't tor reply? */
  288. test_streq("torproject.org", socks->address);
  289. test_eq(0, buf_datalen(buf));
  290. done:
  291. ;
  292. }
  293. /** Perform unsupported SOCKS 5 commands */
  294. static void
  295. test_socks_5_unsupported_commands(void *ptr)
  296. {
  297. SOCKS_TEST_INIT();
  298. /* SOCKS 5 Send unsupported BIND [02] command */
  299. ADD_DATA(buf, "\x05\x02\x00\x01");
  300. test_eq(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
  301. get_options()->SafeSocks), 0);
  302. test_eq(0, buf_datalen(buf));
  303. test_eq(5, socks->socks_version);
  304. test_eq(2, socks->replylen);
  305. test_eq(5, socks->reply[0]);
  306. test_eq(0, socks->reply[1]);
  307. ADD_DATA(buf, "\x05\x02\x00\x01\x02\x02\x02\x01\x01\x01");
  308. test_eq(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
  309. get_options()->SafeSocks), -1);
  310. /* XXX: shouldn't tor reply 'command not supported' [07]? */
  311. buf_clear(buf);
  312. socks_request_clear(socks);
  313. /* SOCKS 5 Send unsupported UDP_ASSOCIATE [03] command */
  314. ADD_DATA(buf, "\x05\x03\x00\x01\x02");
  315. test_eq(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
  316. get_options()->SafeSocks), 0);
  317. test_eq(5, socks->socks_version);
  318. test_eq(2, socks->replylen);
  319. test_eq(5, socks->reply[0]);
  320. test_eq(2, socks->reply[1]);
  321. ADD_DATA(buf, "\x05\x03\x00\x01\x02\x02\x02\x01\x01\x01");
  322. test_eq(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
  323. get_options()->SafeSocks), -1);
  324. /* XXX: shouldn't tor reply 'command not supported' [07]? */
  325. done:
  326. ;
  327. }
  328. /** Perform supported SOCKS 5 commands */
  329. static void
  330. test_socks_5_supported_commands(void *ptr)
  331. {
  332. SOCKS_TEST_INIT();
  333. /* SOCKS 5 Send CONNECT [01] to IP address 2.2.2.2:4369 */
  334. ADD_DATA(buf, "\x05\x01\x00");
  335. test_eq(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
  336. get_options()->SafeSocks), 0);
  337. test_eq(5, socks->socks_version);
  338. test_eq(2, socks->replylen);
  339. test_eq(5, socks->reply[0]);
  340. test_eq(0, socks->reply[1]);
  341. ADD_DATA(buf, "\x05\x01\x00\x01\x02\x02\x02\x02\x11\x11");
  342. test_eq(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
  343. get_options()->SafeSocks), 1);
  344. test_streq("2.2.2.2", socks->address);
  345. test_eq(4369, socks->port);
  346. test_eq(0, buf_datalen(buf));
  347. socks_request_clear(socks);
  348. /* SOCKS 5 Send CONNECT [01] to FQDN torproject.org:4369 */
  349. ADD_DATA(buf, "\x05\x01\x00");
  350. ADD_DATA(buf, "\x05\x01\x00\x03\x0Etorproject.org\x11\x11");
  351. test_eq(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
  352. get_options()->SafeSocks), 1);
  353. test_eq(5, socks->socks_version);
  354. test_eq(2, socks->replylen);
  355. test_eq(5, socks->reply[0]);
  356. test_eq(0, socks->reply[1]);
  357. test_streq("torproject.org", socks->address);
  358. test_eq(4369, socks->port);
  359. test_eq(0, buf_datalen(buf));
  360. socks_request_clear(socks);
  361. /* SOCKS 5 Send RESOLVE [F0] request for torproject.org:4369 */
  362. ADD_DATA(buf, "\x05\x01\x00");
  363. ADD_DATA(buf, "\x05\xF0\x00\x03\x0Etorproject.org\x01\x02");
  364. test_assert(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
  365. get_options()->SafeSocks) == 1);
  366. test_eq(5, socks->socks_version);
  367. test_eq(2, socks->replylen);
  368. test_eq(5, socks->reply[0]);
  369. test_eq(0, socks->reply[1]);
  370. test_streq("torproject.org", socks->address);
  371. test_eq(0, buf_datalen(buf));
  372. socks_request_clear(socks);
  373. /* SOCKS 5 Send RESOLVE_PTR [F1] for IP address 2.2.2.5 */
  374. ADD_DATA(buf, "\x05\x01\x00");
  375. ADD_DATA(buf, "\x05\xF1\x00\x01\x02\x02\x02\x05\x01\x03");
  376. test_assert(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
  377. get_options()->SafeSocks) == 1);
  378. test_eq(5, socks->socks_version);
  379. test_eq(2, socks->replylen);
  380. test_eq(5, socks->reply[0]);
  381. test_eq(0, socks->reply[1]);
  382. test_streq("2.2.2.5", socks->address);
  383. test_eq(0, buf_datalen(buf));
  384. done:
  385. ;
  386. }
  387. /** Perform SOCKS 5 authentication */
  388. static void
  389. test_socks_5_no_authenticate(void *ptr)
  390. {
  391. SOCKS_TEST_INIT();
  392. /*SOCKS 5 No Authentication */
  393. ADD_DATA(buf,"\x05\x01\x00");
  394. test_assert(!fetch_from_buf_socks(buf, socks,
  395. get_options()->TestSocks,
  396. get_options()->SafeSocks));
  397. test_eq(2, socks->replylen);
  398. test_eq(5, socks->reply[0]);
  399. test_eq(SOCKS_NO_AUTH, socks->reply[1]);
  400. test_eq(0, buf_datalen(buf));
  401. /*SOCKS 5 Send username/password anyway - pretend to be broken */
  402. ADD_DATA(buf,"\x01\x02\x01\x01\x02\x01\x01");
  403. test_assert(!fetch_from_buf_socks(buf, socks,
  404. get_options()->TestSocks,
  405. get_options()->SafeSocks));
  406. test_eq(5, socks->socks_version);
  407. test_eq(2, socks->replylen);
  408. test_eq(5, socks->reply[0]);
  409. test_eq(0, socks->reply[1]);
  410. test_eq(2, socks->usernamelen);
  411. test_eq(2, socks->passwordlen);
  412. test_memeq("\x01\x01", socks->username, 2);
  413. test_memeq("\x01\x01", socks->password, 2);
  414. done:
  415. ;
  416. }
  417. /** Perform SOCKS 5 authentication */
  418. static void
  419. test_socks_5_authenticate(void *ptr)
  420. {
  421. SOCKS_TEST_INIT();
  422. /* SOCKS 5 Negotiate username/password authentication */
  423. ADD_DATA(buf, "\x05\x01\x02");
  424. test_assert(!fetch_from_buf_socks(buf, socks,
  425. get_options()->TestSocks,
  426. get_options()->SafeSocks));
  427. test_eq(2, socks->replylen);
  428. test_eq(5, socks->reply[0]);
  429. test_eq(SOCKS_USER_PASS, socks->reply[1]);
  430. test_eq(5, socks->socks_version);
  431. test_eq(0, buf_datalen(buf));
  432. /* SOCKS 5 Send username/password */
  433. ADD_DATA(buf, "\x01\x02me\x08mypasswd");
  434. test_assert(!fetch_from_buf_socks(buf, socks,
  435. get_options()->TestSocks,
  436. get_options()->SafeSocks));
  437. test_eq(5, socks->socks_version);
  438. test_eq(2, socks->replylen);
  439. test_eq(5, socks->reply[0]);
  440. test_eq(0, socks->reply[1]);
  441. test_eq(2, socks->usernamelen);
  442. test_eq(8, socks->passwordlen);
  443. test_memeq("me", socks->username, 2);
  444. test_memeq("mypasswd", socks->password, 8);
  445. done:
  446. ;
  447. }
  448. /** Perform SOCKS 5 authentication and send data all in one go */
  449. static void
  450. test_socks_5_authenticate_with_data(void *ptr)
  451. {
  452. SOCKS_TEST_INIT();
  453. /* SOCKS 5 Negotiate username/password authentication */
  454. ADD_DATA(buf, "\x05\x01\x02");
  455. test_assert(!fetch_from_buf_socks(buf, socks,
  456. get_options()->TestSocks,
  457. get_options()->SafeSocks));
  458. test_eq(2, socks->replylen);
  459. test_eq(5, socks->reply[0]);
  460. test_eq(SOCKS_USER_PASS, socks->reply[1]);
  461. test_eq(5, socks->socks_version);
  462. test_eq(0, buf_datalen(buf));
  463. /* SOCKS 5 Send username/password */
  464. /* SOCKS 5 Send CONNECT [01] to IP address 2.2.2.2:4369 */
  465. ADD_DATA(buf, "\x01\x02me\x03you\x05\x01\x00\x01\x02\x02\x02\x02\x11\x11");
  466. test_assert(fetch_from_buf_socks(buf, socks,
  467. get_options()->TestSocks,
  468. get_options()->SafeSocks) == 1);
  469. test_eq(5, socks->socks_version);
  470. test_eq(2, socks->replylen);
  471. test_eq(5, socks->reply[0]);
  472. test_eq(0, socks->reply[1]);
  473. test_streq("2.2.2.2", socks->address);
  474. test_eq(4369, socks->port);
  475. test_eq(2, socks->usernamelen);
  476. test_eq(3, socks->passwordlen);
  477. test_memeq("me", socks->username, 2);
  478. test_memeq("you", socks->password, 3);
  479. done:
  480. ;
  481. }
  482. /** Perform SOCKS 5 authentication before method negotiated */
  483. static void
  484. test_socks_5_auth_before_negotiation(void *ptr)
  485. {
  486. SOCKS_TEST_INIT();
  487. /* SOCKS 5 Send username/password */
  488. ADD_DATA(buf, "\x01\x02me\x02me");
  489. test_assert(fetch_from_buf_socks(buf, socks,
  490. get_options()->TestSocks,
  491. get_options()->SafeSocks) == -1);
  492. test_eq(0, socks->socks_version);
  493. test_eq(0, socks->replylen);
  494. test_eq(0, socks->reply[0]);
  495. test_eq(0, socks->reply[1]);
  496. done:
  497. ;
  498. }
  499. static void
  500. test_buffer_copy(void *arg)
  501. {
  502. generic_buffer_t *buf=NULL, *buf2=NULL;
  503. const char *s;
  504. size_t len;
  505. char b[256];
  506. int i;
  507. (void)arg;
  508. buf = generic_buffer_new();
  509. tt_assert(buf);
  510. /* Copy an empty buffer. */
  511. tt_int_op(0, ==, generic_buffer_set_to_copy(&buf2, buf));
  512. tt_assert(buf2);
  513. tt_int_op(0, ==, generic_buffer_len(buf2));
  514. /* Now try with a short buffer. */
  515. s = "And now comes an act of enormous enormance!";
  516. len = strlen(s);
  517. generic_buffer_add(buf, s, len);
  518. tt_int_op(len, ==, generic_buffer_len(buf));
  519. /* Add junk to buf2 so we can test replacing.*/
  520. generic_buffer_add(buf2, "BLARG", 5);
  521. tt_int_op(0, ==, generic_buffer_set_to_copy(&buf2, buf));
  522. tt_int_op(len, ==, generic_buffer_len(buf2));
  523. generic_buffer_get(buf2, b, len);
  524. test_mem_op(b, ==, s, len);
  525. /* Now free buf2 and retry so we can test allocating */
  526. generic_buffer_free(buf2);
  527. buf2 = NULL;
  528. tt_int_op(0, ==, generic_buffer_set_to_copy(&buf2, buf));
  529. tt_int_op(len, ==, generic_buffer_len(buf2));
  530. generic_buffer_get(buf2, b, len);
  531. test_mem_op(b, ==, s, len);
  532. /* Clear buf for next test */
  533. generic_buffer_get(buf, b, len);
  534. tt_int_op(generic_buffer_len(buf),==,0);
  535. /* Okay, now let's try a bigger buffer. */
  536. s = "Quis autem vel eum iure reprehenderit qui in ea voluptate velit "
  537. "esse quam nihil molestiae consequatur, vel illum qui dolorem eum "
  538. "fugiat quo voluptas nulla pariatur?";
  539. len = strlen(s);
  540. for (i = 0; i < 256; ++i) {
  541. b[0]=i;
  542. generic_buffer_add(buf, b, 1);
  543. generic_buffer_add(buf, s, len);
  544. }
  545. tt_int_op(0, ==, generic_buffer_set_to_copy(&buf2, buf));
  546. tt_int_op(generic_buffer_len(buf2), ==, generic_buffer_len(buf));
  547. for (i = 0; i < 256; ++i) {
  548. generic_buffer_get(buf2, b, len+1);
  549. tt_int_op((unsigned char)b[0],==,i);
  550. test_mem_op(b+1, ==, s, len);
  551. }
  552. done:
  553. if (buf)
  554. generic_buffer_free(buf);
  555. if (buf2)
  556. generic_buffer_free(buf2);
  557. }
  558. /** Run unit tests for buffers.c */
  559. static void
  560. test_buffers(void)
  561. {
  562. char str[256];
  563. char str2[256];
  564. buf_t *buf = NULL, *buf2 = NULL;
  565. const char *cp;
  566. int j;
  567. size_t r;
  568. /****
  569. * buf_new
  570. ****/
  571. if (!(buf = buf_new()))
  572. test_fail();
  573. //test_eq(buf_capacity(buf), 4096);
  574. test_eq(buf_datalen(buf), 0);
  575. /****
  576. * General pointer frobbing
  577. */
  578. for (j=0;j<256;++j) {
  579. str[j] = (char)j;
  580. }
  581. write_to_buf(str, 256, buf);
  582. write_to_buf(str, 256, buf);
  583. test_eq(buf_datalen(buf), 512);
  584. fetch_from_buf(str2, 200, buf);
  585. test_memeq(str, str2, 200);
  586. test_eq(buf_datalen(buf), 312);
  587. memset(str2, 0, sizeof(str2));
  588. fetch_from_buf(str2, 256, buf);
  589. test_memeq(str+200, str2, 56);
  590. test_memeq(str, str2+56, 200);
  591. test_eq(buf_datalen(buf), 56);
  592. memset(str2, 0, sizeof(str2));
  593. /* Okay, now we should be 512 bytes into the 4096-byte buffer. If we add
  594. * another 3584 bytes, we hit the end. */
  595. for (j=0;j<15;++j) {
  596. write_to_buf(str, 256, buf);
  597. }
  598. assert_buf_ok(buf);
  599. test_eq(buf_datalen(buf), 3896);
  600. fetch_from_buf(str2, 56, buf);
  601. test_eq(buf_datalen(buf), 3840);
  602. test_memeq(str+200, str2, 56);
  603. for (j=0;j<15;++j) {
  604. memset(str2, 0, sizeof(str2));
  605. fetch_from_buf(str2, 256, buf);
  606. test_memeq(str, str2, 256);
  607. }
  608. test_eq(buf_datalen(buf), 0);
  609. buf_free(buf);
  610. buf = NULL;
  611. /* Okay, now make sure growing can work. */
  612. buf = buf_new_with_capacity(16);
  613. //test_eq(buf_capacity(buf), 16);
  614. write_to_buf(str+1, 255, buf);
  615. //test_eq(buf_capacity(buf), 256);
  616. fetch_from_buf(str2, 254, buf);
  617. test_memeq(str+1, str2, 254);
  618. //test_eq(buf_capacity(buf), 256);
  619. assert_buf_ok(buf);
  620. write_to_buf(str, 32, buf);
  621. //test_eq(buf_capacity(buf), 256);
  622. assert_buf_ok(buf);
  623. write_to_buf(str, 256, buf);
  624. assert_buf_ok(buf);
  625. //test_eq(buf_capacity(buf), 512);
  626. test_eq(buf_datalen(buf), 33+256);
  627. fetch_from_buf(str2, 33, buf);
  628. test_eq(*str2, str[255]);
  629. test_memeq(str2+1, str, 32);
  630. //test_eq(buf_capacity(buf), 512);
  631. test_eq(buf_datalen(buf), 256);
  632. fetch_from_buf(str2, 256, buf);
  633. test_memeq(str, str2, 256);
  634. /* now try shrinking: case 1. */
  635. buf_free(buf);
  636. buf = buf_new_with_capacity(33668);
  637. for (j=0;j<67;++j) {
  638. write_to_buf(str,255, buf);
  639. }
  640. //test_eq(buf_capacity(buf), 33668);
  641. test_eq(buf_datalen(buf), 17085);
  642. for (j=0; j < 40; ++j) {
  643. fetch_from_buf(str2, 255,buf);
  644. test_memeq(str2, str, 255);
  645. }
  646. /* now try shrinking: case 2. */
  647. buf_free(buf);
  648. buf = buf_new_with_capacity(33668);
  649. for (j=0;j<67;++j) {
  650. write_to_buf(str,255, buf);
  651. }
  652. for (j=0; j < 20; ++j) {
  653. fetch_from_buf(str2, 255,buf);
  654. test_memeq(str2, str, 255);
  655. }
  656. for (j=0;j<80;++j) {
  657. write_to_buf(str,255, buf);
  658. }
  659. //test_eq(buf_capacity(buf),33668);
  660. for (j=0; j < 120; ++j) {
  661. fetch_from_buf(str2, 255,buf);
  662. test_memeq(str2, str, 255);
  663. }
  664. /* Move from buf to buf. */
  665. buf_free(buf);
  666. buf = buf_new_with_capacity(4096);
  667. buf2 = buf_new_with_capacity(4096);
  668. for (j=0;j<100;++j)
  669. write_to_buf(str, 255, buf);
  670. test_eq(buf_datalen(buf), 25500);
  671. for (j=0;j<100;++j) {
  672. r = 10;
  673. move_buf_to_buf(buf2, buf, &r);
  674. test_eq(r, 0);
  675. }
  676. test_eq(buf_datalen(buf), 24500);
  677. test_eq(buf_datalen(buf2), 1000);
  678. for (j=0;j<3;++j) {
  679. fetch_from_buf(str2, 255, buf2);
  680. test_memeq(str2, str, 255);
  681. }
  682. r = 8192; /*big move*/
  683. move_buf_to_buf(buf2, buf, &r);
  684. test_eq(r, 0);
  685. r = 30000; /* incomplete move */
  686. move_buf_to_buf(buf2, buf, &r);
  687. test_eq(r, 13692);
  688. for (j=0;j<97;++j) {
  689. fetch_from_buf(str2, 255, buf2);
  690. test_memeq(str2, str, 255);
  691. }
  692. buf_free(buf);
  693. buf_free(buf2);
  694. buf = buf2 = NULL;
  695. buf = buf_new_with_capacity(5);
  696. cp = "Testing. This is a moderately long Testing string.";
  697. for (j = 0; cp[j]; j++)
  698. write_to_buf(cp+j, 1, buf);
  699. test_eq(0, buf_find_string_offset(buf, "Testing", 7));
  700. test_eq(1, buf_find_string_offset(buf, "esting", 6));
  701. test_eq(1, buf_find_string_offset(buf, "est", 3));
  702. test_eq(39, buf_find_string_offset(buf, "ing str", 7));
  703. test_eq(35, buf_find_string_offset(buf, "Testing str", 11));
  704. test_eq(32, buf_find_string_offset(buf, "ng ", 3));
  705. test_eq(43, buf_find_string_offset(buf, "string.", 7));
  706. test_eq(-1, buf_find_string_offset(buf, "shrdlu", 6));
  707. test_eq(-1, buf_find_string_offset(buf, "Testing thing", 13));
  708. test_eq(-1, buf_find_string_offset(buf, "ngx", 3));
  709. buf_free(buf);
  710. buf = NULL;
  711. done:
  712. if (buf)
  713. buf_free(buf);
  714. if (buf2)
  715. buf_free(buf2);
  716. }
  717. /** Run unit tests for the onion handshake code. */
  718. static void
  719. test_onion_handshake(void)
  720. {
  721. /* client-side */
  722. crypto_dh_t *c_dh = NULL;
  723. char c_buf[TAP_ONIONSKIN_CHALLENGE_LEN];
  724. char c_keys[40];
  725. /* server-side */
  726. char s_buf[TAP_ONIONSKIN_REPLY_LEN];
  727. char s_keys[40];
  728. int i;
  729. /* shared */
  730. crypto_pk_t *pk = NULL, *pk2 = NULL;
  731. pk = pk_generate(0);
  732. pk2 = pk_generate(1);
  733. /* client handshake 1. */
  734. memset(c_buf, 0, TAP_ONIONSKIN_CHALLENGE_LEN);
  735. test_assert(! onion_skin_TAP_create(pk, &c_dh, c_buf));
  736. for (i = 1; i <= 3; ++i) {
  737. crypto_pk_t *k1, *k2;
  738. if (i==1) {
  739. /* server handshake: only one key known. */
  740. k1 = pk; k2 = NULL;
  741. } else if (i==2) {
  742. /* server handshake: try the right key first. */
  743. k1 = pk; k2 = pk2;
  744. } else {
  745. /* server handshake: try the right key second. */
  746. k1 = pk2; k2 = pk;
  747. }
  748. memset(s_buf, 0, TAP_ONIONSKIN_REPLY_LEN);
  749. memset(s_keys, 0, 40);
  750. test_assert(! onion_skin_TAP_server_handshake(c_buf, k1, k2,
  751. s_buf, s_keys, 40));
  752. /* client handshake 2 */
  753. memset(c_keys, 0, 40);
  754. test_assert(! onion_skin_TAP_client_handshake(c_dh, s_buf, c_keys, 40));
  755. test_memeq(c_keys, s_keys, 40);
  756. memset(s_buf, 0, 40);
  757. test_memneq(c_keys, s_buf, 40);
  758. }
  759. done:
  760. crypto_dh_free(c_dh);
  761. crypto_pk_free(pk);
  762. crypto_pk_free(pk2);
  763. }
  764. static void
  765. test_bad_onion_handshake(void *arg)
  766. {
  767. char junk_buf[TAP_ONIONSKIN_CHALLENGE_LEN];
  768. char junk_buf2[TAP_ONIONSKIN_CHALLENGE_LEN];
  769. /* client-side */
  770. crypto_dh_t *c_dh = NULL;
  771. char c_buf[TAP_ONIONSKIN_CHALLENGE_LEN];
  772. char c_keys[40];
  773. /* server-side */
  774. char s_buf[TAP_ONIONSKIN_REPLY_LEN];
  775. char s_keys[40];
  776. /* shared */
  777. crypto_pk_t *pk = NULL, *pk2 = NULL;
  778. (void)arg;
  779. pk = pk_generate(0);
  780. pk2 = pk_generate(1);
  781. /* Server: Case 1: the encrypted data is degenerate. */
  782. memset(junk_buf, 0, sizeof(junk_buf));
  783. crypto_pk_public_hybrid_encrypt(pk, junk_buf2, TAP_ONIONSKIN_CHALLENGE_LEN,
  784. junk_buf, DH_KEY_LEN, PK_PKCS1_OAEP_PADDING, 1);
  785. tt_int_op(-1, ==,
  786. onion_skin_TAP_server_handshake(junk_buf2, pk, NULL,
  787. s_buf, s_keys, 40));
  788. /* Server: Case 2: the encrypted data is not long enough. */
  789. memset(junk_buf, 0, sizeof(junk_buf));
  790. memset(junk_buf2, 0, sizeof(junk_buf2));
  791. crypto_pk_public_encrypt(pk, junk_buf2, sizeof(junk_buf2),
  792. junk_buf, 48, PK_PKCS1_OAEP_PADDING);
  793. tt_int_op(-1, ==,
  794. onion_skin_TAP_server_handshake(junk_buf2, pk, NULL,
  795. s_buf, s_keys, 40));
  796. /* client handshake 1: do it straight. */
  797. memset(c_buf, 0, TAP_ONIONSKIN_CHALLENGE_LEN);
  798. test_assert(! onion_skin_TAP_create(pk, &c_dh, c_buf));
  799. /* Server: Case 3: we just don't have the right key. */
  800. tt_int_op(-1, ==,
  801. onion_skin_TAP_server_handshake(c_buf, pk2, NULL,
  802. s_buf, s_keys, 40));
  803. /* Server: Case 4: The RSA-encrypted portion is corrupt. */
  804. c_buf[64] ^= 33;
  805. tt_int_op(-1, ==,
  806. onion_skin_TAP_server_handshake(c_buf, pk, NULL,
  807. s_buf, s_keys, 40));
  808. c_buf[64] ^= 33;
  809. /* (Let the server procede) */
  810. tt_int_op(0, ==,
  811. onion_skin_TAP_server_handshake(c_buf, pk, NULL,
  812. s_buf, s_keys, 40));
  813. /* Client: Case 1: The server sent back junk. */
  814. s_buf[64] ^= 33;
  815. tt_int_op(-1, ==,
  816. onion_skin_TAP_client_handshake(c_dh, s_buf, c_keys, 40));
  817. s_buf[64] ^= 33;
  818. /* Let the client finish; make sure it can. */
  819. tt_int_op(0, ==,
  820. onion_skin_TAP_client_handshake(c_dh, s_buf, c_keys, 40));
  821. test_memeq(s_keys, c_keys, 40);
  822. /* Client: Case 2: The server sent back a degenerate DH. */
  823. memset(s_buf, 0, sizeof(s_buf));
  824. tt_int_op(-1, ==,
  825. onion_skin_TAP_client_handshake(c_dh, s_buf, c_keys, 40));
  826. done:
  827. crypto_dh_free(c_dh);
  828. crypto_pk_free(pk);
  829. crypto_pk_free(pk2);
  830. }
  831. #ifdef CURVE25519_ENABLED
  832. static void
  833. test_ntor_handshake(void *arg)
  834. {
  835. /* client-side */
  836. ntor_handshake_state_t *c_state = NULL;
  837. uint8_t c_buf[NTOR_ONIONSKIN_LEN];
  838. uint8_t c_keys[400];
  839. /* server-side */
  840. di_digest256_map_t *s_keymap=NULL;
  841. curve25519_keypair_t s_keypair;
  842. uint8_t s_buf[NTOR_REPLY_LEN];
  843. uint8_t s_keys[400];
  844. /* shared */
  845. const curve25519_public_key_t *server_pubkey;
  846. uint8_t node_id[20] = "abcdefghijklmnopqrst";
  847. (void) arg;
  848. /* Make the server some keys */
  849. curve25519_secret_key_generate(&s_keypair.seckey, 0);
  850. curve25519_public_key_generate(&s_keypair.pubkey, &s_keypair.seckey);
  851. dimap_add_entry(&s_keymap, s_keypair.pubkey.public_key, &s_keypair);
  852. server_pubkey = &s_keypair.pubkey;
  853. /* client handshake 1. */
  854. memset(c_buf, 0, NTOR_ONIONSKIN_LEN);
  855. tt_int_op(0, ==, onion_skin_ntor_create(node_id, server_pubkey,
  856. &c_state, c_buf));
  857. /* server handshake */
  858. memset(s_buf, 0, NTOR_REPLY_LEN);
  859. memset(s_keys, 0, 40);
  860. tt_int_op(0, ==, onion_skin_ntor_server_handshake(c_buf, s_keymap, NULL,
  861. node_id,
  862. s_buf, s_keys, 400));
  863. /* client handshake 2 */
  864. memset(c_keys, 0, 40);
  865. tt_int_op(0, ==, onion_skin_ntor_client_handshake(c_state, s_buf,
  866. c_keys, 400));
  867. test_memeq(c_keys, s_keys, 400);
  868. memset(s_buf, 0, 40);
  869. test_memneq(c_keys, s_buf, 40);
  870. done:
  871. ntor_handshake_state_free(c_state);
  872. dimap_free(s_keymap, NULL);
  873. }
  874. #endif
  875. static void
  876. test_circuit_timeout(void)
  877. {
  878. /* Plan:
  879. * 1. Generate 1000 samples
  880. * 2. Estimate parameters
  881. * 3. If difference, repeat
  882. * 4. Save state
  883. * 5. load state
  884. * 6. Estimate parameters
  885. * 7. compare differences
  886. */
  887. circuit_build_times_t initial;
  888. circuit_build_times_t estimate;
  889. circuit_build_times_t final;
  890. double timeout1, timeout2;
  891. or_state_t state;
  892. int i, runs;
  893. double close_ms;
  894. circuit_build_times_init(&initial);
  895. circuit_build_times_init(&estimate);
  896. circuit_build_times_init(&final);
  897. memset(&state, 0, sizeof(or_state_t));
  898. circuitbuild_running_unit_tests();
  899. #define timeout0 (build_time_t)(30*1000.0)
  900. initial.Xm = 3000;
  901. circuit_build_times_initial_alpha(&initial,
  902. CBT_DEFAULT_QUANTILE_CUTOFF/100.0,
  903. timeout0);
  904. close_ms = MAX(circuit_build_times_calculate_timeout(&initial,
  905. CBT_DEFAULT_CLOSE_QUANTILE/100.0),
  906. CBT_DEFAULT_TIMEOUT_INITIAL_VALUE);
  907. do {
  908. for (i=0; i < CBT_DEFAULT_MIN_CIRCUITS_TO_OBSERVE; i++) {
  909. build_time_t sample = circuit_build_times_generate_sample(&initial,0,1);
  910. if (sample > close_ms) {
  911. circuit_build_times_add_time(&estimate, CBT_BUILD_ABANDONED);
  912. } else {
  913. circuit_build_times_add_time(&estimate, sample);
  914. }
  915. }
  916. circuit_build_times_update_alpha(&estimate);
  917. timeout1 = circuit_build_times_calculate_timeout(&estimate,
  918. CBT_DEFAULT_QUANTILE_CUTOFF/100.0);
  919. circuit_build_times_set_timeout(&estimate);
  920. log_notice(LD_CIRC, "Timeout1 is %f, Xm is %d", timeout1, estimate.Xm);
  921. /* 2% error */
  922. } while (fabs(circuit_build_times_cdf(&initial, timeout0) -
  923. circuit_build_times_cdf(&initial, timeout1)) > 0.02);
  924. test_assert(estimate.total_build_times <= CBT_NCIRCUITS_TO_OBSERVE);
  925. circuit_build_times_update_state(&estimate, &state);
  926. test_assert(circuit_build_times_parse_state(&final, &state) == 0);
  927. circuit_build_times_update_alpha(&final);
  928. timeout2 = circuit_build_times_calculate_timeout(&final,
  929. CBT_DEFAULT_QUANTILE_CUTOFF/100.0);
  930. circuit_build_times_set_timeout(&final);
  931. log_notice(LD_CIRC, "Timeout2 is %f, Xm is %d", timeout2, final.Xm);
  932. /* 5% here because some accuracy is lost due to histogram conversion */
  933. test_assert(fabs(circuit_build_times_cdf(&initial, timeout0) -
  934. circuit_build_times_cdf(&initial, timeout2)) < 0.05);
  935. for (runs = 0; runs < 50; runs++) {
  936. int build_times_idx = 0;
  937. int total_build_times = 0;
  938. final.close_ms = final.timeout_ms = CBT_DEFAULT_TIMEOUT_INITIAL_VALUE;
  939. estimate.close_ms = estimate.timeout_ms
  940. = CBT_DEFAULT_TIMEOUT_INITIAL_VALUE;
  941. for (i = 0; i < CBT_DEFAULT_RECENT_CIRCUITS*2; i++) {
  942. circuit_build_times_network_circ_success(&estimate);
  943. circuit_build_times_add_time(&estimate,
  944. circuit_build_times_generate_sample(&estimate, 0,
  945. CBT_DEFAULT_QUANTILE_CUTOFF/100.0));
  946. circuit_build_times_network_circ_success(&estimate);
  947. circuit_build_times_add_time(&final,
  948. circuit_build_times_generate_sample(&final, 0,
  949. CBT_DEFAULT_QUANTILE_CUTOFF/100.0));
  950. }
  951. test_assert(!circuit_build_times_network_check_changed(&estimate));
  952. test_assert(!circuit_build_times_network_check_changed(&final));
  953. /* Reset liveness to be non-live */
  954. final.liveness.network_last_live = 0;
  955. estimate.liveness.network_last_live = 0;
  956. build_times_idx = estimate.build_times_idx;
  957. total_build_times = estimate.total_build_times;
  958. test_assert(circuit_build_times_network_check_live(&estimate));
  959. test_assert(circuit_build_times_network_check_live(&final));
  960. circuit_build_times_count_close(&estimate, 0,
  961. (time_t)(approx_time()-estimate.close_ms/1000.0-1));
  962. circuit_build_times_count_close(&final, 0,
  963. (time_t)(approx_time()-final.close_ms/1000.0-1));
  964. test_assert(!circuit_build_times_network_check_live(&estimate));
  965. test_assert(!circuit_build_times_network_check_live(&final));
  966. log_info(LD_CIRC, "idx: %d %d, tot: %d %d",
  967. build_times_idx, estimate.build_times_idx,
  968. total_build_times, estimate.total_build_times);
  969. /* Check rollback index. Should match top of loop. */
  970. test_assert(build_times_idx == estimate.build_times_idx);
  971. // This can fail if estimate.total_build_times == 1000, because
  972. // in that case, rewind actually causes us to lose timeouts
  973. if (total_build_times != CBT_NCIRCUITS_TO_OBSERVE)
  974. test_assert(total_build_times == estimate.total_build_times);
  975. /* Now simulate that the network has become live and we need
  976. * a change */
  977. circuit_build_times_network_is_live(&estimate);
  978. circuit_build_times_network_is_live(&final);
  979. for (i = 0; i < CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT; i++) {
  980. circuit_build_times_count_timeout(&estimate, 1);
  981. if (i < CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT-1) {
  982. circuit_build_times_count_timeout(&final, 1);
  983. }
  984. }
  985. test_assert(estimate.liveness.after_firsthop_idx == 0);
  986. test_assert(final.liveness.after_firsthop_idx ==
  987. CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT-1);
  988. test_assert(circuit_build_times_network_check_live(&estimate));
  989. test_assert(circuit_build_times_network_check_live(&final));
  990. circuit_build_times_count_timeout(&final, 1);
  991. }
  992. done:
  993. return;
  994. }
  995. /* Helper: assert that short_policy parses and writes back out as itself,
  996. or as <b>expected</b> if that's provided. */
  997. static void
  998. test_short_policy_parse(const char *input,
  999. const char *expected)
  1000. {
  1001. short_policy_t *short_policy = NULL;
  1002. char *out = NULL;
  1003. if (expected == NULL)
  1004. expected = input;
  1005. short_policy = parse_short_policy(input);
  1006. tt_assert(short_policy);
  1007. out = write_short_policy(short_policy);
  1008. tt_str_op(out, ==, expected);
  1009. done:
  1010. tor_free(out);
  1011. short_policy_free(short_policy);
  1012. }
  1013. /** Helper: Parse the exit policy string in <b>policy_str</b>, and make sure
  1014. * that policies_summarize() produces the string <b>expected_summary</b> from
  1015. * it. */
  1016. static void
  1017. test_policy_summary_helper(const char *policy_str,
  1018. const char *expected_summary)
  1019. {
  1020. config_line_t line;
  1021. smartlist_t *policy = smartlist_new();
  1022. char *summary = NULL;
  1023. char *summary_after = NULL;
  1024. int r;
  1025. short_policy_t *short_policy = NULL;
  1026. line.key = (char*)"foo";
  1027. line.value = (char *)policy_str;
  1028. line.next = NULL;
  1029. r = policies_parse_exit_policy(&line, &policy, 1, 0, NULL, 1);
  1030. test_eq(r, 0);
  1031. summary = policy_summarize(policy, AF_INET);
  1032. test_assert(summary != NULL);
  1033. test_streq(summary, expected_summary);
  1034. short_policy = parse_short_policy(summary);
  1035. tt_assert(short_policy);
  1036. summary_after = write_short_policy(short_policy);
  1037. test_streq(summary, summary_after);
  1038. done:
  1039. tor_free(summary_after);
  1040. tor_free(summary);
  1041. if (policy)
  1042. addr_policy_list_free(policy);
  1043. short_policy_free(short_policy);
  1044. }
  1045. /** Run unit tests for generating summary lines of exit policies */
  1046. static void
  1047. test_policies(void)
  1048. {
  1049. int i;
  1050. smartlist_t *policy = NULL, *policy2 = NULL, *policy3 = NULL,
  1051. *policy4 = NULL, *policy5 = NULL, *policy6 = NULL,
  1052. *policy7 = NULL;
  1053. addr_policy_t *p;
  1054. tor_addr_t tar;
  1055. config_line_t line;
  1056. smartlist_t *sm = NULL;
  1057. char *policy_str = NULL;
  1058. policy = smartlist_new();
  1059. p = router_parse_addr_policy_item_from_string("reject 192.168.0.0/16:*",-1);
  1060. test_assert(p != NULL);
  1061. test_eq(ADDR_POLICY_REJECT, p->policy_type);
  1062. tor_addr_from_ipv4h(&tar, 0xc0a80000u);
  1063. test_eq(0, tor_addr_compare(&p->addr, &tar, CMP_EXACT));
  1064. test_eq(16, p->maskbits);
  1065. test_eq(1, p->prt_min);
  1066. test_eq(65535, p->prt_max);
  1067. smartlist_add(policy, p);
  1068. tor_addr_from_ipv4h(&tar, 0x01020304u);
  1069. test_assert(ADDR_POLICY_ACCEPTED ==
  1070. compare_tor_addr_to_addr_policy(&tar, 2, policy));
  1071. tor_addr_make_unspec(&tar);
  1072. test_assert(ADDR_POLICY_PROBABLY_ACCEPTED ==
  1073. compare_tor_addr_to_addr_policy(&tar, 2, policy));
  1074. tor_addr_from_ipv4h(&tar, 0xc0a80102);
  1075. test_assert(ADDR_POLICY_REJECTED ==
  1076. compare_tor_addr_to_addr_policy(&tar, 2, policy));
  1077. test_assert(0 == policies_parse_exit_policy(NULL, &policy2, 1, 1, NULL, 1));
  1078. test_assert(policy2);
  1079. policy3 = smartlist_new();
  1080. p = router_parse_addr_policy_item_from_string("reject *:*",-1);
  1081. test_assert(p != NULL);
  1082. smartlist_add(policy3, p);
  1083. p = router_parse_addr_policy_item_from_string("accept *:*",-1);
  1084. test_assert(p != NULL);
  1085. smartlist_add(policy3, p);
  1086. policy4 = smartlist_new();
  1087. p = router_parse_addr_policy_item_from_string("accept *:443",-1);
  1088. test_assert(p != NULL);
  1089. smartlist_add(policy4, p);
  1090. p = router_parse_addr_policy_item_from_string("accept *:443",-1);
  1091. test_assert(p != NULL);
  1092. smartlist_add(policy4, p);
  1093. policy5 = smartlist_new();
  1094. p = router_parse_addr_policy_item_from_string("reject 0.0.0.0/8:*",-1);
  1095. test_assert(p != NULL);
  1096. smartlist_add(policy5, p);
  1097. p = router_parse_addr_policy_item_from_string("reject 169.254.0.0/16:*",-1);
  1098. test_assert(p != NULL);
  1099. smartlist_add(policy5, p);
  1100. p = router_parse_addr_policy_item_from_string("reject 127.0.0.0/8:*",-1);
  1101. test_assert(p != NULL);
  1102. smartlist_add(policy5, p);
  1103. p = router_parse_addr_policy_item_from_string("reject 192.168.0.0/16:*",-1);
  1104. test_assert(p != NULL);
  1105. smartlist_add(policy5, p);
  1106. p = router_parse_addr_policy_item_from_string("reject 10.0.0.0/8:*",-1);
  1107. test_assert(p != NULL);
  1108. smartlist_add(policy5, p);
  1109. p = router_parse_addr_policy_item_from_string("reject 172.16.0.0/12:*",-1);
  1110. test_assert(p != NULL);
  1111. smartlist_add(policy5, p);
  1112. p = router_parse_addr_policy_item_from_string("reject 80.190.250.90:*",-1);
  1113. test_assert(p != NULL);
  1114. smartlist_add(policy5, p);
  1115. p = router_parse_addr_policy_item_from_string("reject *:1-65534",-1);
  1116. test_assert(p != NULL);
  1117. smartlist_add(policy5, p);
  1118. p = router_parse_addr_policy_item_from_string("reject *:65535",-1);
  1119. test_assert(p != NULL);
  1120. smartlist_add(policy5, p);
  1121. p = router_parse_addr_policy_item_from_string("accept *:1-65535",-1);
  1122. test_assert(p != NULL);
  1123. smartlist_add(policy5, p);
  1124. policy6 = smartlist_new();
  1125. p = router_parse_addr_policy_item_from_string("accept 43.3.0.0/9:*",-1);
  1126. test_assert(p != NULL);
  1127. smartlist_add(policy6, p);
  1128. policy7 = smartlist_new();
  1129. p = router_parse_addr_policy_item_from_string("accept 0.0.0.0/8:*",-1);
  1130. test_assert(p != NULL);
  1131. smartlist_add(policy7, p);
  1132. test_assert(!exit_policy_is_general_exit(policy));
  1133. test_assert(exit_policy_is_general_exit(policy2));
  1134. test_assert(!exit_policy_is_general_exit(NULL));
  1135. test_assert(!exit_policy_is_general_exit(policy3));
  1136. test_assert(!exit_policy_is_general_exit(policy4));
  1137. test_assert(!exit_policy_is_general_exit(policy5));
  1138. test_assert(!exit_policy_is_general_exit(policy6));
  1139. test_assert(!exit_policy_is_general_exit(policy7));
  1140. test_assert(cmp_addr_policies(policy, policy2));
  1141. test_assert(cmp_addr_policies(policy, NULL));
  1142. test_assert(!cmp_addr_policies(policy2, policy2));
  1143. test_assert(!cmp_addr_policies(NULL, NULL));
  1144. test_assert(!policy_is_reject_star(policy2, AF_INET));
  1145. test_assert(policy_is_reject_star(policy, AF_INET));
  1146. test_assert(policy_is_reject_star(NULL, AF_INET));
  1147. addr_policy_list_free(policy);
  1148. policy = NULL;
  1149. /* make sure compacting logic works. */
  1150. policy = NULL;
  1151. line.key = (char*)"foo";
  1152. line.value = (char*)"accept *:80,reject private:*,reject *:*";
  1153. line.next = NULL;
  1154. test_assert(0 == policies_parse_exit_policy(&line, &policy, 1, 0, NULL, 1));
  1155. test_assert(policy);
  1156. //test_streq(policy->string, "accept *:80");
  1157. //test_streq(policy->next->string, "reject *:*");
  1158. test_eq(smartlist_len(policy), 4);
  1159. /* test policy summaries */
  1160. /* check if we properly ignore private IP addresses */
  1161. test_policy_summary_helper("reject 192.168.0.0/16:*,"
  1162. "reject 0.0.0.0/8:*,"
  1163. "reject 10.0.0.0/8:*,"
  1164. "accept *:10-30,"
  1165. "accept *:90,"
  1166. "reject *:*",
  1167. "accept 10-30,90");
  1168. /* check all accept policies, and proper counting of rejects */
  1169. test_policy_summary_helper("reject 11.0.0.0/9:80,"
  1170. "reject 12.0.0.0/9:80,"
  1171. "reject 13.0.0.0/9:80,"
  1172. "reject 14.0.0.0/9:80,"
  1173. "accept *:*", "accept 1-65535");
  1174. test_policy_summary_helper("reject 11.0.0.0/9:80,"
  1175. "reject 12.0.0.0/9:80,"
  1176. "reject 13.0.0.0/9:80,"
  1177. "reject 14.0.0.0/9:80,"
  1178. "reject 15.0.0.0:81,"
  1179. "accept *:*", "accept 1-65535");
  1180. test_policy_summary_helper("reject 11.0.0.0/9:80,"
  1181. "reject 12.0.0.0/9:80,"
  1182. "reject 13.0.0.0/9:80,"
  1183. "reject 14.0.0.0/9:80,"
  1184. "reject 15.0.0.0:80,"
  1185. "accept *:*",
  1186. "reject 80");
  1187. /* no exits */
  1188. test_policy_summary_helper("accept 11.0.0.0/9:80,"
  1189. "reject *:*",
  1190. "reject 1-65535");
  1191. /* port merging */
  1192. test_policy_summary_helper("accept *:80,"
  1193. "accept *:81,"
  1194. "accept *:100-110,"
  1195. "accept *:111,"
  1196. "reject *:*",
  1197. "accept 80-81,100-111");
  1198. /* border ports */
  1199. test_policy_summary_helper("accept *:1,"
  1200. "accept *:3,"
  1201. "accept *:65535,"
  1202. "reject *:*",
  1203. "accept 1,3,65535");
  1204. /* holes */
  1205. test_policy_summary_helper("accept *:1,"
  1206. "accept *:3,"
  1207. "accept *:5,"
  1208. "accept *:7,"
  1209. "reject *:*",
  1210. "accept 1,3,5,7");
  1211. test_policy_summary_helper("reject *:1,"
  1212. "reject *:3,"
  1213. "reject *:5,"
  1214. "reject *:7,"
  1215. "accept *:*",
  1216. "reject 1,3,5,7");
  1217. /* Short policies with unrecognized formats should get accepted. */
  1218. test_short_policy_parse("accept fred,2,3-5", "accept 2,3-5");
  1219. test_short_policy_parse("accept 2,fred,3", "accept 2,3");
  1220. test_short_policy_parse("accept 2,fred,3,bob", "accept 2,3");
  1221. test_short_policy_parse("accept 2,-3,500-600", "accept 2,500-600");
  1222. /* Short policies with nil entries are accepted too. */
  1223. test_short_policy_parse("accept 1,,3", "accept 1,3");
  1224. test_short_policy_parse("accept 100-200,,", "accept 100-200");
  1225. test_short_policy_parse("reject ,1-10,,,,30-40", "reject 1-10,30-40");
  1226. /* Try parsing various broken short policies */
  1227. tt_ptr_op(NULL, ==, parse_short_policy("accept 200-199"));
  1228. tt_ptr_op(NULL, ==, parse_short_policy(""));
  1229. tt_ptr_op(NULL, ==, parse_short_policy("rejekt 1,2,3"));
  1230. tt_ptr_op(NULL, ==, parse_short_policy("reject "));
  1231. tt_ptr_op(NULL, ==, parse_short_policy("reject"));
  1232. tt_ptr_op(NULL, ==, parse_short_policy("rej"));
  1233. tt_ptr_op(NULL, ==, parse_short_policy("accept 2,3,100000"));
  1234. tt_ptr_op(NULL, ==, parse_short_policy("accept 2,3x,4"));
  1235. tt_ptr_op(NULL, ==, parse_short_policy("accept 2,3x,4"));
  1236. tt_ptr_op(NULL, ==, parse_short_policy("accept 2-"));
  1237. tt_ptr_op(NULL, ==, parse_short_policy("accept 2-x"));
  1238. tt_ptr_op(NULL, ==, parse_short_policy("accept 1-,3"));
  1239. tt_ptr_op(NULL, ==, parse_short_policy("accept 1-,3"));
  1240. /* Test a too-long policy. */
  1241. {
  1242. int i;
  1243. char *policy = NULL;
  1244. smartlist_t *chunks = smartlist_new();
  1245. smartlist_add(chunks, tor_strdup("accept "));
  1246. for (i=1; i<10000; ++i)
  1247. smartlist_add_asprintf(chunks, "%d,", i);
  1248. smartlist_add(chunks, tor_strdup("20000"));
  1249. policy = smartlist_join_strings(chunks, "", 0, NULL);
  1250. SMARTLIST_FOREACH(chunks, char *, ch, tor_free(ch));
  1251. smartlist_free(chunks);
  1252. tt_ptr_op(NULL, ==, parse_short_policy(policy));/* shouldn't be accepted */
  1253. tor_free(policy); /* could leak. */
  1254. }
  1255. /* truncation ports */
  1256. sm = smartlist_new();
  1257. for (i=1; i<2000; i+=2) {
  1258. char buf[POLICY_BUF_LEN];
  1259. tor_snprintf(buf, sizeof(buf), "reject *:%d", i);
  1260. smartlist_add(sm, tor_strdup(buf));
  1261. }
  1262. smartlist_add(sm, tor_strdup("accept *:*"));
  1263. policy_str = smartlist_join_strings(sm, ",", 0, NULL);
  1264. test_policy_summary_helper( policy_str,
  1265. "accept 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,"
  1266. "46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,"
  1267. "92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,"
  1268. "130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,"
  1269. "166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198,200,"
  1270. "202,204,206,208,210,212,214,216,218,220,222,224,226,228,230,232,234,236,"
  1271. "238,240,242,244,246,248,250,252,254,256,258,260,262,264,266,268,270,272,"
  1272. "274,276,278,280,282,284,286,288,290,292,294,296,298,300,302,304,306,308,"
  1273. "310,312,314,316,318,320,322,324,326,328,330,332,334,336,338,340,342,344,"
  1274. "346,348,350,352,354,356,358,360,362,364,366,368,370,372,374,376,378,380,"
  1275. "382,384,386,388,390,392,394,396,398,400,402,404,406,408,410,412,414,416,"
  1276. "418,420,422,424,426,428,430,432,434,436,438,440,442,444,446,448,450,452,"
  1277. "454,456,458,460,462,464,466,468,470,472,474,476,478,480,482,484,486,488,"
  1278. "490,492,494,496,498,500,502,504,506,508,510,512,514,516,518,520,522");
  1279. done:
  1280. addr_policy_list_free(policy);
  1281. addr_policy_list_free(policy2);
  1282. addr_policy_list_free(policy3);
  1283. addr_policy_list_free(policy4);
  1284. addr_policy_list_free(policy5);
  1285. addr_policy_list_free(policy6);
  1286. addr_policy_list_free(policy7);
  1287. tor_free(policy_str);
  1288. if (sm) {
  1289. SMARTLIST_FOREACH(sm, char *, s, tor_free(s));
  1290. smartlist_free(sm);
  1291. }
  1292. }
  1293. /** Test encoding and parsing of rendezvous service descriptors. */
  1294. static void
  1295. test_rend_fns(void)
  1296. {
  1297. rend_service_descriptor_t *generated = NULL, *parsed = NULL;
  1298. char service_id[DIGEST_LEN];
  1299. char service_id_base32[REND_SERVICE_ID_LEN_BASE32+1];
  1300. const char *next_desc;
  1301. smartlist_t *descs = smartlist_new();
  1302. char computed_desc_id[DIGEST_LEN];
  1303. char parsed_desc_id[DIGEST_LEN];
  1304. crypto_pk_t *pk1 = NULL, *pk2 = NULL;
  1305. time_t now;
  1306. char *intro_points_encrypted = NULL;
  1307. size_t intro_points_size;
  1308. size_t encoded_size;
  1309. int i;
  1310. char address1[] = "fooaddress.onion";
  1311. char address2[] = "aaaaaaaaaaaaaaaa.onion";
  1312. char address3[] = "fooaddress.exit";
  1313. char address4[] = "www.torproject.org";
  1314. char address5[] = "foo.abcdefghijklmnop.onion";
  1315. char address6[] = "foo.bar.abcdefghijklmnop.onion";
  1316. char address7[] = ".abcdefghijklmnop.onion";
  1317. test_assert(BAD_HOSTNAME == parse_extended_hostname(address1));
  1318. test_assert(ONION_HOSTNAME == parse_extended_hostname(address2));
  1319. test_streq(address2, "aaaaaaaaaaaaaaaa");
  1320. test_assert(EXIT_HOSTNAME == parse_extended_hostname(address3));
  1321. test_assert(NORMAL_HOSTNAME == parse_extended_hostname(address4));
  1322. test_assert(ONION_HOSTNAME == parse_extended_hostname(address5));
  1323. test_streq(address5, "abcdefghijklmnop");
  1324. test_assert(ONION_HOSTNAME == parse_extended_hostname(address6));
  1325. test_streq(address6, "abcdefghijklmnop");
  1326. test_assert(BAD_HOSTNAME == parse_extended_hostname(address7));
  1327. pk1 = pk_generate(0);
  1328. pk2 = pk_generate(1);
  1329. generated = tor_malloc_zero(sizeof(rend_service_descriptor_t));
  1330. generated->pk = crypto_pk_dup_key(pk1);
  1331. crypto_pk_get_digest(generated->pk, service_id);
  1332. base32_encode(service_id_base32, REND_SERVICE_ID_LEN_BASE32+1,
  1333. service_id, REND_SERVICE_ID_LEN);
  1334. now = time(NULL);
  1335. generated->timestamp = now;
  1336. generated->version = 2;
  1337. generated->protocols = 42;
  1338. generated->intro_nodes = smartlist_new();
  1339. for (i = 0; i < 3; i++) {
  1340. rend_intro_point_t *intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  1341. crypto_pk_t *okey = pk_generate(2 + i);
  1342. intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
  1343. intro->extend_info->onion_key = okey;
  1344. crypto_pk_get_digest(intro->extend_info->onion_key,
  1345. intro->extend_info->identity_digest);
  1346. //crypto_rand(info->identity_digest, DIGEST_LEN); /* Would this work? */
  1347. intro->extend_info->nickname[0] = '$';
  1348. base16_encode(intro->extend_info->nickname + 1,
  1349. sizeof(intro->extend_info->nickname) - 1,
  1350. intro->extend_info->identity_digest, DIGEST_LEN);
  1351. /* Does not cover all IP addresses. */
  1352. tor_addr_from_ipv4h(&intro->extend_info->addr, crypto_rand_int(65536));
  1353. intro->extend_info->port = 1 + crypto_rand_int(65535);
  1354. intro->intro_key = crypto_pk_dup_key(pk2);
  1355. smartlist_add(generated->intro_nodes, intro);
  1356. }
  1357. test_assert(rend_encode_v2_descriptors(descs, generated, now, 0,
  1358. REND_NO_AUTH, NULL, NULL) > 0);
  1359. test_assert(rend_compute_v2_desc_id(computed_desc_id, service_id_base32,
  1360. NULL, now, 0) == 0);
  1361. test_memeq(((rend_encoded_v2_service_descriptor_t *)
  1362. smartlist_get(descs, 0))->desc_id, computed_desc_id, DIGEST_LEN);
  1363. test_assert(rend_parse_v2_service_descriptor(&parsed, parsed_desc_id,
  1364. &intro_points_encrypted,
  1365. &intro_points_size,
  1366. &encoded_size,
  1367. &next_desc,
  1368. ((rend_encoded_v2_service_descriptor_t *)
  1369. smartlist_get(descs, 0))->desc_str) == 0);
  1370. test_assert(parsed);
  1371. test_memeq(((rend_encoded_v2_service_descriptor_t *)
  1372. smartlist_get(descs, 0))->desc_id, parsed_desc_id, DIGEST_LEN);
  1373. test_eq(rend_parse_introduction_points(parsed, intro_points_encrypted,
  1374. intro_points_size), 3);
  1375. test_assert(!crypto_pk_cmp_keys(generated->pk, parsed->pk));
  1376. test_eq(parsed->timestamp, now);
  1377. test_eq(parsed->version, 2);
  1378. test_eq(parsed->protocols, 42);
  1379. test_eq(smartlist_len(parsed->intro_nodes), 3);
  1380. for (i = 0; i < smartlist_len(parsed->intro_nodes); i++) {
  1381. rend_intro_point_t *par_intro = smartlist_get(parsed->intro_nodes, i),
  1382. *gen_intro = smartlist_get(generated->intro_nodes, i);
  1383. extend_info_t *par_info = par_intro->extend_info;
  1384. extend_info_t *gen_info = gen_intro->extend_info;
  1385. test_assert(!crypto_pk_cmp_keys(gen_info->onion_key, par_info->onion_key));
  1386. test_memeq(gen_info->identity_digest, par_info->identity_digest,
  1387. DIGEST_LEN);
  1388. test_streq(gen_info->nickname, par_info->nickname);
  1389. test_assert(tor_addr_eq(&gen_info->addr, &par_info->addr));
  1390. test_eq(gen_info->port, par_info->port);
  1391. }
  1392. rend_service_descriptor_free(parsed);
  1393. rend_service_descriptor_free(generated);
  1394. parsed = generated = NULL;
  1395. done:
  1396. if (descs) {
  1397. for (i = 0; i < smartlist_len(descs); i++)
  1398. rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
  1399. smartlist_free(descs);
  1400. }
  1401. if (parsed)
  1402. rend_service_descriptor_free(parsed);
  1403. if (generated)
  1404. rend_service_descriptor_free(generated);
  1405. if (pk1)
  1406. crypto_pk_free(pk1);
  1407. if (pk2)
  1408. crypto_pk_free(pk2);
  1409. tor_free(intro_points_encrypted);
  1410. }
  1411. /** Run unit tests for GeoIP code. */
  1412. static void
  1413. test_geoip(void)
  1414. {
  1415. int i, j;
  1416. time_t now = 1281533250; /* 2010-08-11 13:27:30 UTC */
  1417. char *s = NULL, *v = NULL;
  1418. const char *bridge_stats_1 =
  1419. "bridge-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1420. "bridge-ips zz=24,xy=8\n"
  1421. "bridge-ip-versions v4=16,v6=16\n",
  1422. *dirreq_stats_1 =
  1423. "dirreq-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1424. "dirreq-v3-ips ab=8\n"
  1425. "dirreq-v3-reqs ab=8\n"
  1426. "dirreq-v3-resp ok=0,not-enough-sigs=0,unavailable=0,not-found=0,"
  1427. "not-modified=0,busy=0\n"
  1428. "dirreq-v3-direct-dl complete=0,timeout=0,running=0\n"
  1429. "dirreq-v3-tunneled-dl complete=0,timeout=0,running=0\n",
  1430. *dirreq_stats_2 =
  1431. "dirreq-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1432. "dirreq-v3-ips \n"
  1433. "dirreq-v3-reqs \n"
  1434. "dirreq-v3-resp ok=0,not-enough-sigs=0,unavailable=0,not-found=0,"
  1435. "not-modified=0,busy=0\n"
  1436. "dirreq-v3-direct-dl complete=0,timeout=0,running=0\n"
  1437. "dirreq-v3-tunneled-dl complete=0,timeout=0,running=0\n",
  1438. *dirreq_stats_3 =
  1439. "dirreq-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1440. "dirreq-v3-ips \n"
  1441. "dirreq-v3-reqs \n"
  1442. "dirreq-v3-resp ok=8,not-enough-sigs=0,unavailable=0,not-found=0,"
  1443. "not-modified=0,busy=0\n"
  1444. "dirreq-v3-direct-dl complete=0,timeout=0,running=0\n"
  1445. "dirreq-v3-tunneled-dl complete=0,timeout=0,running=0\n",
  1446. *dirreq_stats_4 =
  1447. "dirreq-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1448. "dirreq-v3-ips \n"
  1449. "dirreq-v3-reqs \n"
  1450. "dirreq-v3-resp ok=8,not-enough-sigs=0,unavailable=0,not-found=0,"
  1451. "not-modified=0,busy=0\n"
  1452. "dirreq-v3-direct-dl complete=0,timeout=0,running=0\n"
  1453. "dirreq-v3-tunneled-dl complete=0,timeout=0,running=4\n",
  1454. *entry_stats_1 =
  1455. "entry-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1456. "entry-ips ab=8\n",
  1457. *entry_stats_2 =
  1458. "entry-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1459. "entry-ips \n";
  1460. tor_addr_t addr;
  1461. struct in6_addr in6;
  1462. /* Populate the DB a bit. Add these in order, since we can't do the final
  1463. * 'sort' step. These aren't very good IP addresses, but they're perfectly
  1464. * fine uint32_t values. */
  1465. test_eq(0, geoip_parse_entry("10,50,AB", AF_INET));
  1466. test_eq(0, geoip_parse_entry("52,90,XY", AF_INET));
  1467. test_eq(0, geoip_parse_entry("95,100,AB", AF_INET));
  1468. test_eq(0, geoip_parse_entry("\"105\",\"140\",\"ZZ\"", AF_INET));
  1469. test_eq(0, geoip_parse_entry("\"150\",\"190\",\"XY\"", AF_INET));
  1470. test_eq(0, geoip_parse_entry("\"200\",\"250\",\"AB\"", AF_INET));
  1471. /* Populate the IPv6 DB equivalently with fake IPs in the same range */
  1472. test_eq(0, geoip_parse_entry("::a,::32,AB", AF_INET6));
  1473. test_eq(0, geoip_parse_entry("::34,::5a,XY", AF_INET6));
  1474. test_eq(0, geoip_parse_entry("::5f,::64,AB", AF_INET6));
  1475. test_eq(0, geoip_parse_entry("::69,::8c,ZZ", AF_INET6));
  1476. test_eq(0, geoip_parse_entry("::96,::be,XY", AF_INET6));
  1477. test_eq(0, geoip_parse_entry("::c8,::fa,AB", AF_INET6));
  1478. /* We should have 4 countries: ??, ab, xy, zz. */
  1479. test_eq(4, geoip_get_n_countries());
  1480. memset(&in6, 0, sizeof(in6));
  1481. /* Make sure that country ID actually works. */
  1482. #define SET_TEST_IPV6(i) \
  1483. do { \
  1484. set_uint32(in6.s6_addr + 12, htonl((uint32_t) (i))); \
  1485. } while (0)
  1486. #define CHECK_COUNTRY(country, val) do { \
  1487. /* test ipv4 country lookup */ \
  1488. test_streq(country, \
  1489. geoip_get_country_name(geoip_get_country_by_ipv4(val))); \
  1490. /* test ipv6 country lookup */ \
  1491. SET_TEST_IPV6(val); \
  1492. test_streq(country, \
  1493. geoip_get_country_name(geoip_get_country_by_ipv6(&in6))); \
  1494. } while (0)
  1495. CHECK_COUNTRY("??", 3);
  1496. CHECK_COUNTRY("ab", 32);
  1497. CHECK_COUNTRY("??", 5);
  1498. CHECK_COUNTRY("??", 51);
  1499. CHECK_COUNTRY("xy", 150);
  1500. CHECK_COUNTRY("xy", 190);
  1501. CHECK_COUNTRY("??", 2000);
  1502. test_eq(0, geoip_get_country_by_ipv4(3));
  1503. SET_TEST_IPV6(3);
  1504. test_eq(0, geoip_get_country_by_ipv6(&in6));
  1505. #undef CHECK_COUNTRY
  1506. /* Record odd numbered fake-IPs using ipv6, even numbered fake-IPs
  1507. * using ipv4. Since our fake geoip database is the same between
  1508. * ipv4 and ipv6, we should get the same result no matter which
  1509. * address family we pick for each IP. */
  1510. #define SET_TEST_ADDRESS(i) do { \
  1511. if ((i) & 1) { \
  1512. SET_TEST_IPV6(i); \
  1513. tor_addr_from_in6(&addr, &in6); \
  1514. } else { \
  1515. tor_addr_from_ipv4h(&addr, (uint32_t) i); \
  1516. } \
  1517. } while (0)
  1518. get_options_mutable()->BridgeRelay = 1;
  1519. get_options_mutable()->BridgeRecordUsageByCountry = 1;
  1520. /* Put 9 observations in AB... */
  1521. for (i=32; i < 40; ++i) {
  1522. SET_TEST_ADDRESS(i);
  1523. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, now-7200);
  1524. }
  1525. SET_TEST_ADDRESS(225);
  1526. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, now-7200);
  1527. /* and 3 observations in XY, several times. */
  1528. for (j=0; j < 10; ++j)
  1529. for (i=52; i < 55; ++i) {
  1530. SET_TEST_ADDRESS(i);
  1531. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, now-3600);
  1532. }
  1533. /* and 17 observations in ZZ... */
  1534. for (i=110; i < 127; ++i) {
  1535. SET_TEST_ADDRESS(i);
  1536. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, now);
  1537. }
  1538. geoip_get_client_history(GEOIP_CLIENT_CONNECT, &s, &v);
  1539. test_assert(s);
  1540. test_assert(v);
  1541. test_streq("zz=24,ab=16,xy=8", s);
  1542. test_streq("v4=16,v6=16", v);
  1543. tor_free(s);
  1544. tor_free(v);
  1545. /* Now clear out all the AB observations. */
  1546. geoip_remove_old_clients(now-6000);
  1547. geoip_get_client_history(GEOIP_CLIENT_CONNECT, &s, &v);
  1548. test_assert(s);
  1549. test_assert(v);
  1550. test_streq("zz=24,xy=8", s);
  1551. test_streq("v4=16,v6=16", v);
  1552. tor_free(s);
  1553. tor_free(v);
  1554. /* Start testing bridge statistics by making sure that we don't output
  1555. * bridge stats without initializing them. */
  1556. s = geoip_format_bridge_stats(now + 86400);
  1557. test_assert(!s);
  1558. /* Initialize stats and generate the bridge-stats history string out of
  1559. * the connecting clients added above. */
  1560. geoip_bridge_stats_init(now);
  1561. s = geoip_format_bridge_stats(now + 86400);
  1562. test_assert(s);
  1563. test_streq(bridge_stats_1, s);
  1564. tor_free(s);
  1565. /* Stop collecting bridge stats and make sure we don't write a history
  1566. * string anymore. */
  1567. geoip_bridge_stats_term();
  1568. s = geoip_format_bridge_stats(now + 86400);
  1569. test_assert(!s);
  1570. /* Stop being a bridge and start being a directory mirror that gathers
  1571. * directory request statistics. */
  1572. geoip_bridge_stats_term();
  1573. get_options_mutable()->BridgeRelay = 0;
  1574. get_options_mutable()->BridgeRecordUsageByCountry = 0;
  1575. get_options_mutable()->DirReqStatistics = 1;
  1576. /* Start testing dirreq statistics by making sure that we don't collect
  1577. * dirreq stats without initializing them. */
  1578. SET_TEST_ADDRESS(100);
  1579. geoip_note_client_seen(GEOIP_CLIENT_NETWORKSTATUS, &addr, now);
  1580. s = geoip_format_dirreq_stats(now + 86400);
  1581. test_assert(!s);
  1582. /* Initialize stats, note one connecting client, and generate the
  1583. * dirreq-stats history string. */
  1584. geoip_dirreq_stats_init(now);
  1585. SET_TEST_ADDRESS(100);
  1586. geoip_note_client_seen(GEOIP_CLIENT_NETWORKSTATUS, &addr, now);
  1587. s = geoip_format_dirreq_stats(now + 86400);
  1588. test_streq(dirreq_stats_1, s);
  1589. tor_free(s);
  1590. /* Stop collecting stats, add another connecting client, and ensure we
  1591. * don't generate a history string. */
  1592. geoip_dirreq_stats_term();
  1593. SET_TEST_ADDRESS(101);
  1594. geoip_note_client_seen(GEOIP_CLIENT_NETWORKSTATUS, &addr, now);
  1595. s = geoip_format_dirreq_stats(now + 86400);
  1596. test_assert(!s);
  1597. /* Re-start stats, add a connecting client, reset stats, and make sure
  1598. * that we get an all empty history string. */
  1599. geoip_dirreq_stats_init(now);
  1600. SET_TEST_ADDRESS(100);
  1601. geoip_note_client_seen(GEOIP_CLIENT_NETWORKSTATUS, &addr, now);
  1602. geoip_reset_dirreq_stats(now);
  1603. s = geoip_format_dirreq_stats(now + 86400);
  1604. test_streq(dirreq_stats_2, s);
  1605. tor_free(s);
  1606. /* Note a successful network status response and make sure that it
  1607. * appears in the history string. */
  1608. geoip_note_ns_response(GEOIP_SUCCESS);
  1609. s = geoip_format_dirreq_stats(now + 86400);
  1610. test_streq(dirreq_stats_3, s);
  1611. tor_free(s);
  1612. /* Start a tunneled directory request. */
  1613. geoip_start_dirreq((uint64_t) 1, 1024, DIRREQ_TUNNELED);
  1614. s = geoip_format_dirreq_stats(now + 86400);
  1615. test_streq(dirreq_stats_4, s);
  1616. /* Stop collecting directory request statistics and start gathering
  1617. * entry stats. */
  1618. geoip_dirreq_stats_term();
  1619. get_options_mutable()->DirReqStatistics = 0;
  1620. get_options_mutable()->EntryStatistics = 1;
  1621. /* Start testing entry statistics by making sure that we don't collect
  1622. * anything without initializing entry stats. */
  1623. SET_TEST_ADDRESS(100);
  1624. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, now);
  1625. s = geoip_format_entry_stats(now + 86400);
  1626. test_assert(!s);
  1627. /* Initialize stats, note one connecting client, and generate the
  1628. * entry-stats history string. */
  1629. geoip_entry_stats_init(now);
  1630. SET_TEST_ADDRESS(100);
  1631. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, now);
  1632. s = geoip_format_entry_stats(now + 86400);
  1633. test_streq(entry_stats_1, s);
  1634. tor_free(s);
  1635. /* Stop collecting stats, add another connecting client, and ensure we
  1636. * don't generate a history string. */
  1637. geoip_entry_stats_term();
  1638. SET_TEST_ADDRESS(101);
  1639. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, now);
  1640. s = geoip_format_entry_stats(now + 86400);
  1641. test_assert(!s);
  1642. /* Re-start stats, add a connecting client, reset stats, and make sure
  1643. * that we get an all empty history string. */
  1644. geoip_entry_stats_init(now);
  1645. SET_TEST_ADDRESS(100);
  1646. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, now);
  1647. geoip_reset_entry_stats(now);
  1648. s = geoip_format_entry_stats(now + 86400);
  1649. test_streq(entry_stats_2, s);
  1650. tor_free(s);
  1651. #undef SET_TEST_ADDRESS
  1652. #undef SET_TEST_IPV6
  1653. /* Stop collecting entry statistics. */
  1654. geoip_entry_stats_term();
  1655. get_options_mutable()->EntryStatistics = 0;
  1656. done:
  1657. tor_free(s);
  1658. tor_free(v);
  1659. }
  1660. /** Run unit tests for stats code. */
  1661. static void
  1662. test_stats(void)
  1663. {
  1664. time_t now = 1281533250; /* 2010-08-11 13:27:30 UTC */
  1665. char *s = NULL;
  1666. int i;
  1667. /* Start with testing exit port statistics; we shouldn't collect exit
  1668. * stats without initializing them. */
  1669. rep_hist_note_exit_stream_opened(80);
  1670. rep_hist_note_exit_bytes(80, 100, 10000);
  1671. s = rep_hist_format_exit_stats(now + 86400);
  1672. test_assert(!s);
  1673. /* Initialize stats, note some streams and bytes, and generate history
  1674. * string. */
  1675. rep_hist_exit_stats_init(now);
  1676. rep_hist_note_exit_stream_opened(80);
  1677. rep_hist_note_exit_bytes(80, 100, 10000);
  1678. rep_hist_note_exit_stream_opened(443);
  1679. rep_hist_note_exit_bytes(443, 100, 10000);
  1680. rep_hist_note_exit_bytes(443, 100, 10000);
  1681. s = rep_hist_format_exit_stats(now + 86400);
  1682. test_streq("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1683. "exit-kibibytes-written 80=1,443=1,other=0\n"
  1684. "exit-kibibytes-read 80=10,443=20,other=0\n"
  1685. "exit-streams-opened 80=4,443=4,other=0\n", s);
  1686. tor_free(s);
  1687. /* Add a few bytes on 10 more ports and ensure that only the top 10
  1688. * ports are contained in the history string. */
  1689. for (i = 50; i < 60; i++) {
  1690. rep_hist_note_exit_bytes(i, i, i);
  1691. rep_hist_note_exit_stream_opened(i);
  1692. }
  1693. s = rep_hist_format_exit_stats(now + 86400);
  1694. test_streq("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1695. "exit-kibibytes-written 52=1,53=1,54=1,55=1,56=1,57=1,58=1,"
  1696. "59=1,80=1,443=1,other=1\n"
  1697. "exit-kibibytes-read 52=1,53=1,54=1,55=1,56=1,57=1,58=1,"
  1698. "59=1,80=10,443=20,other=1\n"
  1699. "exit-streams-opened 52=4,53=4,54=4,55=4,56=4,57=4,58=4,"
  1700. "59=4,80=4,443=4,other=4\n", s);
  1701. tor_free(s);
  1702. /* Stop collecting stats, add some bytes, and ensure we don't generate
  1703. * a history string. */
  1704. rep_hist_exit_stats_term();
  1705. rep_hist_note_exit_bytes(80, 100, 10000);
  1706. s = rep_hist_format_exit_stats(now + 86400);
  1707. test_assert(!s);
  1708. /* Re-start stats, add some bytes, reset stats, and see what history we
  1709. * get when observing no streams or bytes at all. */
  1710. rep_hist_exit_stats_init(now);
  1711. rep_hist_note_exit_stream_opened(80);
  1712. rep_hist_note_exit_bytes(80, 100, 10000);
  1713. rep_hist_reset_exit_stats(now);
  1714. s = rep_hist_format_exit_stats(now + 86400);
  1715. test_streq("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1716. "exit-kibibytes-written other=0\n"
  1717. "exit-kibibytes-read other=0\n"
  1718. "exit-streams-opened other=0\n", s);
  1719. tor_free(s);
  1720. /* Continue with testing connection statistics; we shouldn't collect
  1721. * conn stats without initializing them. */
  1722. rep_hist_note_or_conn_bytes(1, 20, 400, now);
  1723. s = rep_hist_format_conn_stats(now + 86400);
  1724. test_assert(!s);
  1725. /* Initialize stats, note bytes, and generate history string. */
  1726. rep_hist_conn_stats_init(now);
  1727. rep_hist_note_or_conn_bytes(1, 30000, 400000, now);
  1728. rep_hist_note_or_conn_bytes(1, 30000, 400000, now + 5);
  1729. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 10);
  1730. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 15);
  1731. s = rep_hist_format_conn_stats(now + 86400);
  1732. test_streq("conn-bi-direct 2010-08-12 13:27:30 (86400 s) 0,0,1,0\n", s);
  1733. tor_free(s);
  1734. /* Stop collecting stats, add some bytes, and ensure we don't generate
  1735. * a history string. */
  1736. rep_hist_conn_stats_term();
  1737. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 15);
  1738. s = rep_hist_format_conn_stats(now + 86400);
  1739. test_assert(!s);
  1740. /* Re-start stats, add some bytes, reset stats, and see what history we
  1741. * get when observing no bytes at all. */
  1742. rep_hist_conn_stats_init(now);
  1743. rep_hist_note_or_conn_bytes(1, 30000, 400000, now);
  1744. rep_hist_note_or_conn_bytes(1, 30000, 400000, now + 5);
  1745. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 10);
  1746. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 15);
  1747. rep_hist_reset_conn_stats(now);
  1748. s = rep_hist_format_conn_stats(now + 86400);
  1749. test_streq("conn-bi-direct 2010-08-12 13:27:30 (86400 s) 0,0,0,0\n", s);
  1750. tor_free(s);
  1751. /* Continue with testing buffer statistics; we shouldn't collect buffer
  1752. * stats without initializing them. */
  1753. rep_hist_add_buffer_stats(2.0, 2.0, 20);
  1754. s = rep_hist_format_buffer_stats(now + 86400);
  1755. test_assert(!s);
  1756. /* Initialize stats, add statistics for a single circuit, and generate
  1757. * the history string. */
  1758. rep_hist_buffer_stats_init(now);
  1759. rep_hist_add_buffer_stats(2.0, 2.0, 20);
  1760. s = rep_hist_format_buffer_stats(now + 86400);
  1761. test_streq("cell-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1762. "cell-processed-cells 20,0,0,0,0,0,0,0,0,0\n"
  1763. "cell-queued-cells 2.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,"
  1764. "0.00,0.00\n"
  1765. "cell-time-in-queue 2,0,0,0,0,0,0,0,0,0\n"
  1766. "cell-circuits-per-decile 1\n", s);
  1767. tor_free(s);
  1768. /* Add nineteen more circuit statistics to the one that's already in the
  1769. * history to see that the math works correctly. */
  1770. for (i = 21; i < 30; i++)
  1771. rep_hist_add_buffer_stats(2.0, 2.0, i);
  1772. for (i = 20; i < 30; i++)
  1773. rep_hist_add_buffer_stats(3.5, 3.5, i);
  1774. s = rep_hist_format_buffer_stats(now + 86400);
  1775. test_streq("cell-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1776. "cell-processed-cells 29,28,27,26,25,24,23,22,21,20\n"
  1777. "cell-queued-cells 2.75,2.75,2.75,2.75,2.75,2.75,2.75,2.75,"
  1778. "2.75,2.75\n"
  1779. "cell-time-in-queue 3,3,3,3,3,3,3,3,3,3\n"
  1780. "cell-circuits-per-decile 2\n", s);
  1781. tor_free(s);
  1782. /* Stop collecting stats, add statistics for one circuit, and ensure we
  1783. * don't generate a history string. */
  1784. rep_hist_buffer_stats_term();
  1785. rep_hist_add_buffer_stats(2.0, 2.0, 20);
  1786. s = rep_hist_format_buffer_stats(now + 86400);
  1787. test_assert(!s);
  1788. /* Re-start stats, add statistics for one circuit, reset stats, and make
  1789. * sure that the history has all zeros. */
  1790. rep_hist_buffer_stats_init(now);
  1791. rep_hist_add_buffer_stats(2.0, 2.0, 20);
  1792. rep_hist_reset_buffer_stats(now);
  1793. s = rep_hist_format_buffer_stats(now + 86400);
  1794. test_streq("cell-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1795. "cell-processed-cells 0,0,0,0,0,0,0,0,0,0\n"
  1796. "cell-queued-cells 0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,"
  1797. "0.00,0.00\n"
  1798. "cell-time-in-queue 0,0,0,0,0,0,0,0,0,0\n"
  1799. "cell-circuits-per-decile 0\n", s);
  1800. done:
  1801. tor_free(s);
  1802. }
  1803. static void *
  1804. legacy_test_setup(const struct testcase_t *testcase)
  1805. {
  1806. return testcase->setup_data;
  1807. }
  1808. void
  1809. legacy_test_helper(void *data)
  1810. {
  1811. void (*fn)(void) = data;
  1812. fn();
  1813. }
  1814. static int
  1815. legacy_test_cleanup(const struct testcase_t *testcase, void *ptr)
  1816. {
  1817. (void)ptr;
  1818. (void)testcase;
  1819. return 1;
  1820. }
  1821. const struct testcase_setup_t legacy_setup = {
  1822. legacy_test_setup, legacy_test_cleanup
  1823. };
  1824. #define ENT(name) \
  1825. { #name, legacy_test_helper, 0, &legacy_setup, test_ ## name }
  1826. #define FORK(name) \
  1827. { #name, legacy_test_helper, TT_FORK, &legacy_setup, test_ ## name }
  1828. static struct testcase_t test_array[] = {
  1829. ENT(buffers),
  1830. { "buffer_copy", test_buffer_copy, 0, NULL, NULL },
  1831. ENT(onion_handshake),
  1832. { "bad_onion_handshake", test_bad_onion_handshake, 0, NULL, NULL },
  1833. #ifdef CURVE25519_ENABLED
  1834. { "ntor_handshake", test_ntor_handshake, 0, NULL, NULL },
  1835. #endif
  1836. ENT(circuit_timeout),
  1837. ENT(policies),
  1838. ENT(rend_fns),
  1839. ENT(geoip),
  1840. FORK(stats),
  1841. END_OF_TESTCASES
  1842. };
  1843. #define SOCKSENT(name) \
  1844. { #name, test_socks_##name, TT_FORK, &socks_setup, NULL }
  1845. static struct testcase_t socks_tests[] = {
  1846. SOCKSENT(4_unsupported_commands),
  1847. SOCKSENT(4_supported_commands),
  1848. SOCKSENT(5_unsupported_commands),
  1849. SOCKSENT(5_supported_commands),
  1850. SOCKSENT(5_no_authenticate),
  1851. SOCKSENT(5_auth_before_negotiation),
  1852. SOCKSENT(5_authenticate),
  1853. SOCKSENT(5_authenticate_with_data),
  1854. END_OF_TESTCASES
  1855. };
  1856. extern struct testcase_t addr_tests[];
  1857. extern struct testcase_t crypto_tests[];
  1858. extern struct testcase_t container_tests[];
  1859. extern struct testcase_t util_tests[];
  1860. extern struct testcase_t dir_tests[];
  1861. extern struct testcase_t microdesc_tests[];
  1862. extern struct testcase_t pt_tests[];
  1863. extern struct testcase_t config_tests[];
  1864. extern struct testcase_t introduce_tests[];
  1865. extern struct testcase_t replaycache_tests[];
  1866. extern struct testcase_t cell_format_tests[];
  1867. static struct testgroup_t testgroups[] = {
  1868. { "", test_array },
  1869. { "socks/", socks_tests },
  1870. { "addr/", addr_tests },
  1871. { "crypto/", crypto_tests },
  1872. { "container/", container_tests },
  1873. { "util/", util_tests },
  1874. { "cellfmt/", cell_format_tests },
  1875. { "dir/", dir_tests },
  1876. { "dir/md/", microdesc_tests },
  1877. { "pt/", pt_tests },
  1878. { "config/", config_tests },
  1879. { "replaycache/", replaycache_tests },
  1880. { "introduce/", introduce_tests },
  1881. END_OF_GROUPS
  1882. };
  1883. /** Main entry point for unit test code: parse the command line, and run
  1884. * some unit tests. */
  1885. int
  1886. main(int c, const char **v)
  1887. {
  1888. or_options_t *options;
  1889. char *errmsg = NULL;
  1890. int i, i_out;
  1891. int loglevel = LOG_ERR;
  1892. #ifdef USE_DMALLOC
  1893. {
  1894. int r = CRYPTO_set_mem_ex_functions(tor_malloc_, tor_realloc_, tor_free_);
  1895. tor_assert(r);
  1896. }
  1897. #endif
  1898. update_approx_time(time(NULL));
  1899. options = options_new();
  1900. tor_threads_init();
  1901. init_logging();
  1902. for (i_out = i = 1; i < c; ++i) {
  1903. if (!strcmp(v[i], "--warn")) {
  1904. loglevel = LOG_WARN;
  1905. } else if (!strcmp(v[i], "--notice")) {
  1906. loglevel = LOG_NOTICE;
  1907. } else if (!strcmp(v[i], "--info")) {
  1908. loglevel = LOG_INFO;
  1909. } else if (!strcmp(v[i], "--debug")) {
  1910. loglevel = LOG_DEBUG;
  1911. } else {
  1912. v[i_out++] = v[i];
  1913. }
  1914. }
  1915. c = i_out;
  1916. {
  1917. log_severity_list_t s;
  1918. memset(&s, 0, sizeof(s));
  1919. set_log_severity_config(loglevel, LOG_ERR, &s);
  1920. add_stream_log(&s, "", fileno(stdout));
  1921. }
  1922. options->command = CMD_RUN_UNITTESTS;
  1923. if (crypto_global_init(0, NULL, NULL)) {
  1924. printf("Can't initialize crypto subsystem; exiting.\n");
  1925. return 1;
  1926. }
  1927. crypto_set_tls_dh_prime(NULL);
  1928. crypto_seed_rng(1);
  1929. rep_hist_init();
  1930. network_init();
  1931. setup_directory();
  1932. options_init(options);
  1933. options->DataDirectory = tor_strdup(temp_dir);
  1934. options->EntryStatistics = 1;
  1935. if (set_options(options, &errmsg) < 0) {
  1936. printf("Failed to set initial options: %s\n", errmsg);
  1937. tor_free(errmsg);
  1938. return 1;
  1939. }
  1940. atexit(remove_directory);
  1941. have_failed = (tinytest_main(c, v, testgroups) != 0);
  1942. free_pregenerated_keys();
  1943. #ifdef USE_DMALLOC
  1944. tor_free_all(0);
  1945. dmalloc_log_unfreed();
  1946. #endif
  1947. if (have_failed)
  1948. return 1;
  1949. else
  1950. return 0;
  1951. }