test.c 70 KB

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