test.c 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130
  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. 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[TAP_ONIONSKIN_CHALLENGE_LEN];
  719. char c_keys[40];
  720. /* server-side */
  721. char s_buf[TAP_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, TAP_ONIONSKIN_CHALLENGE_LEN);
  728. test_assert(! onion_skin_TAP_create(pk, &c_dh, c_buf));
  729. /* server handshake */
  730. memset(s_buf, 0, TAP_ONIONSKIN_REPLY_LEN);
  731. memset(s_keys, 0, 40);
  732. test_assert(! onion_skin_TAP_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_TAP_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, NULL,
  780. node_id,
  781. s_buf, s_keys, 400));
  782. /* client handshake 2 */
  783. memset(c_keys, 0, 40);
  784. tt_int_op(0, ==, onion_skin_ntor_client_handshake(c_state, s_buf,
  785. c_keys, 400));
  786. test_memeq(c_keys, s_keys, 400);
  787. memset(s_buf, 0, 40);
  788. test_memneq(c_keys, s_buf, 40);
  789. done:
  790. ntor_handshake_state_free(c_state);
  791. dimap_free(s_keymap, NULL);
  792. }
  793. #endif
  794. static void
  795. test_circuit_timeout(void)
  796. {
  797. /* Plan:
  798. * 1. Generate 1000 samples
  799. * 2. Estimate parameters
  800. * 3. If difference, repeat
  801. * 4. Save state
  802. * 5. load state
  803. * 6. Estimate parameters
  804. * 7. compare differences
  805. */
  806. circuit_build_times_t initial;
  807. circuit_build_times_t estimate;
  808. circuit_build_times_t final;
  809. double timeout1, timeout2;
  810. or_state_t state;
  811. int i, runs;
  812. double close_ms;
  813. circuit_build_times_init(&initial);
  814. circuit_build_times_init(&estimate);
  815. circuit_build_times_init(&final);
  816. memset(&state, 0, sizeof(or_state_t));
  817. circuitbuild_running_unit_tests();
  818. #define timeout0 (build_time_t)(30*1000.0)
  819. initial.Xm = 3000;
  820. circuit_build_times_initial_alpha(&initial,
  821. CBT_DEFAULT_QUANTILE_CUTOFF/100.0,
  822. timeout0);
  823. close_ms = MAX(circuit_build_times_calculate_timeout(&initial,
  824. CBT_DEFAULT_CLOSE_QUANTILE/100.0),
  825. CBT_DEFAULT_TIMEOUT_INITIAL_VALUE);
  826. do {
  827. for (i=0; i < CBT_DEFAULT_MIN_CIRCUITS_TO_OBSERVE; i++) {
  828. build_time_t sample = circuit_build_times_generate_sample(&initial,0,1);
  829. if (sample > close_ms) {
  830. circuit_build_times_add_time(&estimate, CBT_BUILD_ABANDONED);
  831. } else {
  832. circuit_build_times_add_time(&estimate, sample);
  833. }
  834. }
  835. circuit_build_times_update_alpha(&estimate);
  836. timeout1 = circuit_build_times_calculate_timeout(&estimate,
  837. CBT_DEFAULT_QUANTILE_CUTOFF/100.0);
  838. circuit_build_times_set_timeout(&estimate);
  839. log_notice(LD_CIRC, "Timeout1 is %f, Xm is %d", timeout1, estimate.Xm);
  840. /* 2% error */
  841. } while (fabs(circuit_build_times_cdf(&initial, timeout0) -
  842. circuit_build_times_cdf(&initial, timeout1)) > 0.02);
  843. test_assert(estimate.total_build_times <= CBT_NCIRCUITS_TO_OBSERVE);
  844. circuit_build_times_update_state(&estimate, &state);
  845. test_assert(circuit_build_times_parse_state(&final, &state) == 0);
  846. circuit_build_times_update_alpha(&final);
  847. timeout2 = circuit_build_times_calculate_timeout(&final,
  848. CBT_DEFAULT_QUANTILE_CUTOFF/100.0);
  849. circuit_build_times_set_timeout(&final);
  850. log_notice(LD_CIRC, "Timeout2 is %f, Xm is %d", timeout2, final.Xm);
  851. /* 5% here because some accuracy is lost due to histogram conversion */
  852. test_assert(fabs(circuit_build_times_cdf(&initial, timeout0) -
  853. circuit_build_times_cdf(&initial, timeout2)) < 0.05);
  854. for (runs = 0; runs < 50; runs++) {
  855. int build_times_idx = 0;
  856. int total_build_times = 0;
  857. final.close_ms = final.timeout_ms = CBT_DEFAULT_TIMEOUT_INITIAL_VALUE;
  858. estimate.close_ms = estimate.timeout_ms
  859. = CBT_DEFAULT_TIMEOUT_INITIAL_VALUE;
  860. for (i = 0; i < CBT_DEFAULT_RECENT_CIRCUITS*2; i++) {
  861. circuit_build_times_network_circ_success(&estimate);
  862. circuit_build_times_add_time(&estimate,
  863. circuit_build_times_generate_sample(&estimate, 0,
  864. CBT_DEFAULT_QUANTILE_CUTOFF/100.0));
  865. circuit_build_times_network_circ_success(&estimate);
  866. circuit_build_times_add_time(&final,
  867. circuit_build_times_generate_sample(&final, 0,
  868. CBT_DEFAULT_QUANTILE_CUTOFF/100.0));
  869. }
  870. test_assert(!circuit_build_times_network_check_changed(&estimate));
  871. test_assert(!circuit_build_times_network_check_changed(&final));
  872. /* Reset liveness to be non-live */
  873. final.liveness.network_last_live = 0;
  874. estimate.liveness.network_last_live = 0;
  875. build_times_idx = estimate.build_times_idx;
  876. total_build_times = estimate.total_build_times;
  877. test_assert(circuit_build_times_network_check_live(&estimate));
  878. test_assert(circuit_build_times_network_check_live(&final));
  879. circuit_build_times_count_close(&estimate, 0,
  880. (time_t)(approx_time()-estimate.close_ms/1000.0-1));
  881. circuit_build_times_count_close(&final, 0,
  882. (time_t)(approx_time()-final.close_ms/1000.0-1));
  883. test_assert(!circuit_build_times_network_check_live(&estimate));
  884. test_assert(!circuit_build_times_network_check_live(&final));
  885. log_info(LD_CIRC, "idx: %d %d, tot: %d %d",
  886. build_times_idx, estimate.build_times_idx,
  887. total_build_times, estimate.total_build_times);
  888. /* Check rollback index. Should match top of loop. */
  889. test_assert(build_times_idx == estimate.build_times_idx);
  890. // This can fail if estimate.total_build_times == 1000, because
  891. // in that case, rewind actually causes us to lose timeouts
  892. if (total_build_times != CBT_NCIRCUITS_TO_OBSERVE)
  893. test_assert(total_build_times == estimate.total_build_times);
  894. /* Now simulate that the network has become live and we need
  895. * a change */
  896. circuit_build_times_network_is_live(&estimate);
  897. circuit_build_times_network_is_live(&final);
  898. for (i = 0; i < CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT; i++) {
  899. circuit_build_times_count_timeout(&estimate, 1);
  900. if (i < CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT-1) {
  901. circuit_build_times_count_timeout(&final, 1);
  902. }
  903. }
  904. test_assert(estimate.liveness.after_firsthop_idx == 0);
  905. test_assert(final.liveness.after_firsthop_idx ==
  906. CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT-1);
  907. test_assert(circuit_build_times_network_check_live(&estimate));
  908. test_assert(circuit_build_times_network_check_live(&final));
  909. circuit_build_times_count_timeout(&final, 1);
  910. }
  911. done:
  912. return;
  913. }
  914. /* Helper: assert that short_policy parses and writes back out as itself,
  915. or as <b>expected</b> if that's provided. */
  916. static void
  917. test_short_policy_parse(const char *input,
  918. const char *expected)
  919. {
  920. short_policy_t *short_policy = NULL;
  921. char *out = NULL;
  922. if (expected == NULL)
  923. expected = input;
  924. short_policy = parse_short_policy(input);
  925. tt_assert(short_policy);
  926. out = write_short_policy(short_policy);
  927. tt_str_op(out, ==, expected);
  928. done:
  929. tor_free(out);
  930. short_policy_free(short_policy);
  931. }
  932. /** Helper: Parse the exit policy string in <b>policy_str</b>, and make sure
  933. * that policies_summarize() produces the string <b>expected_summary</b> from
  934. * it. */
  935. static void
  936. test_policy_summary_helper(const char *policy_str,
  937. const char *expected_summary)
  938. {
  939. config_line_t line;
  940. smartlist_t *policy = smartlist_new();
  941. char *summary = NULL;
  942. char *summary_after = NULL;
  943. int r;
  944. short_policy_t *short_policy = NULL;
  945. line.key = (char*)"foo";
  946. line.value = (char *)policy_str;
  947. line.next = NULL;
  948. r = policies_parse_exit_policy(&line, &policy, 1, 0, NULL, 1);
  949. test_eq(r, 0);
  950. summary = policy_summarize(policy, AF_INET);
  951. test_assert(summary != NULL);
  952. test_streq(summary, expected_summary);
  953. short_policy = parse_short_policy(summary);
  954. tt_assert(short_policy);
  955. summary_after = write_short_policy(short_policy);
  956. test_streq(summary, summary_after);
  957. done:
  958. tor_free(summary_after);
  959. tor_free(summary);
  960. if (policy)
  961. addr_policy_list_free(policy);
  962. short_policy_free(short_policy);
  963. }
  964. /** Run unit tests for generating summary lines of exit policies */
  965. static void
  966. test_policies(void)
  967. {
  968. int i;
  969. smartlist_t *policy = NULL, *policy2 = NULL, *policy3 = NULL,
  970. *policy4 = NULL, *policy5 = NULL, *policy6 = NULL,
  971. *policy7 = NULL;
  972. addr_policy_t *p;
  973. tor_addr_t tar;
  974. config_line_t line;
  975. smartlist_t *sm = NULL;
  976. char *policy_str = NULL;
  977. policy = smartlist_new();
  978. p = router_parse_addr_policy_item_from_string("reject 192.168.0.0/16:*",-1);
  979. test_assert(p != NULL);
  980. test_eq(ADDR_POLICY_REJECT, p->policy_type);
  981. tor_addr_from_ipv4h(&tar, 0xc0a80000u);
  982. test_eq(0, tor_addr_compare(&p->addr, &tar, CMP_EXACT));
  983. test_eq(16, p->maskbits);
  984. test_eq(1, p->prt_min);
  985. test_eq(65535, p->prt_max);
  986. smartlist_add(policy, p);
  987. tor_addr_from_ipv4h(&tar, 0x01020304u);
  988. test_assert(ADDR_POLICY_ACCEPTED ==
  989. compare_tor_addr_to_addr_policy(&tar, 2, policy));
  990. tor_addr_make_unspec(&tar);
  991. test_assert(ADDR_POLICY_PROBABLY_ACCEPTED ==
  992. compare_tor_addr_to_addr_policy(&tar, 2, policy));
  993. tor_addr_from_ipv4h(&tar, 0xc0a80102);
  994. test_assert(ADDR_POLICY_REJECTED ==
  995. compare_tor_addr_to_addr_policy(&tar, 2, policy));
  996. test_assert(0 == policies_parse_exit_policy(NULL, &policy2, 1, 1, NULL, 1));
  997. test_assert(policy2);
  998. policy3 = smartlist_new();
  999. p = router_parse_addr_policy_item_from_string("reject *:*",-1);
  1000. test_assert(p != NULL);
  1001. smartlist_add(policy3, p);
  1002. p = router_parse_addr_policy_item_from_string("accept *:*",-1);
  1003. test_assert(p != NULL);
  1004. smartlist_add(policy3, p);
  1005. policy4 = smartlist_new();
  1006. p = router_parse_addr_policy_item_from_string("accept *:443",-1);
  1007. test_assert(p != NULL);
  1008. smartlist_add(policy4, p);
  1009. p = router_parse_addr_policy_item_from_string("accept *:443",-1);
  1010. test_assert(p != NULL);
  1011. smartlist_add(policy4, p);
  1012. policy5 = smartlist_new();
  1013. p = router_parse_addr_policy_item_from_string("reject 0.0.0.0/8:*",-1);
  1014. test_assert(p != NULL);
  1015. smartlist_add(policy5, p);
  1016. p = router_parse_addr_policy_item_from_string("reject 169.254.0.0/16:*",-1);
  1017. test_assert(p != NULL);
  1018. smartlist_add(policy5, p);
  1019. p = router_parse_addr_policy_item_from_string("reject 127.0.0.0/8:*",-1);
  1020. test_assert(p != NULL);
  1021. smartlist_add(policy5, p);
  1022. p = router_parse_addr_policy_item_from_string("reject 192.168.0.0/16:*",-1);
  1023. test_assert(p != NULL);
  1024. smartlist_add(policy5, p);
  1025. p = router_parse_addr_policy_item_from_string("reject 10.0.0.0/8:*",-1);
  1026. test_assert(p != NULL);
  1027. smartlist_add(policy5, p);
  1028. p = router_parse_addr_policy_item_from_string("reject 172.16.0.0/12:*",-1);
  1029. test_assert(p != NULL);
  1030. smartlist_add(policy5, p);
  1031. p = router_parse_addr_policy_item_from_string("reject 80.190.250.90:*",-1);
  1032. test_assert(p != NULL);
  1033. smartlist_add(policy5, p);
  1034. p = router_parse_addr_policy_item_from_string("reject *:1-65534",-1);
  1035. test_assert(p != NULL);
  1036. smartlist_add(policy5, p);
  1037. p = router_parse_addr_policy_item_from_string("reject *:65535",-1);
  1038. test_assert(p != NULL);
  1039. smartlist_add(policy5, p);
  1040. p = router_parse_addr_policy_item_from_string("accept *:1-65535",-1);
  1041. test_assert(p != NULL);
  1042. smartlist_add(policy5, p);
  1043. policy6 = smartlist_new();
  1044. p = router_parse_addr_policy_item_from_string("accept 43.3.0.0/9:*",-1);
  1045. test_assert(p != NULL);
  1046. smartlist_add(policy6, p);
  1047. policy7 = smartlist_new();
  1048. p = router_parse_addr_policy_item_from_string("accept 0.0.0.0/8:*",-1);
  1049. test_assert(p != NULL);
  1050. smartlist_add(policy7, p);
  1051. test_assert(!exit_policy_is_general_exit(policy));
  1052. test_assert(exit_policy_is_general_exit(policy2));
  1053. test_assert(!exit_policy_is_general_exit(NULL));
  1054. test_assert(!exit_policy_is_general_exit(policy3));
  1055. test_assert(!exit_policy_is_general_exit(policy4));
  1056. test_assert(!exit_policy_is_general_exit(policy5));
  1057. test_assert(!exit_policy_is_general_exit(policy6));
  1058. test_assert(!exit_policy_is_general_exit(policy7));
  1059. test_assert(cmp_addr_policies(policy, policy2));
  1060. test_assert(cmp_addr_policies(policy, NULL));
  1061. test_assert(!cmp_addr_policies(policy2, policy2));
  1062. test_assert(!cmp_addr_policies(NULL, NULL));
  1063. test_assert(!policy_is_reject_star(policy2, AF_INET));
  1064. test_assert(policy_is_reject_star(policy, AF_INET));
  1065. test_assert(policy_is_reject_star(NULL, AF_INET));
  1066. addr_policy_list_free(policy);
  1067. policy = NULL;
  1068. /* make sure compacting logic works. */
  1069. policy = NULL;
  1070. line.key = (char*)"foo";
  1071. line.value = (char*)"accept *:80,reject private:*,reject *:*";
  1072. line.next = NULL;
  1073. test_assert(0 == policies_parse_exit_policy(&line, &policy, 1, 0, NULL, 1));
  1074. test_assert(policy);
  1075. //test_streq(policy->string, "accept *:80");
  1076. //test_streq(policy->next->string, "reject *:*");
  1077. test_eq(smartlist_len(policy), 4);
  1078. /* test policy summaries */
  1079. /* check if we properly ignore private IP addresses */
  1080. test_policy_summary_helper("reject 192.168.0.0/16:*,"
  1081. "reject 0.0.0.0/8:*,"
  1082. "reject 10.0.0.0/8:*,"
  1083. "accept *:10-30,"
  1084. "accept *:90,"
  1085. "reject *:*",
  1086. "accept 10-30,90");
  1087. /* check all accept policies, and proper counting of rejects */
  1088. test_policy_summary_helper("reject 11.0.0.0/9:80,"
  1089. "reject 12.0.0.0/9:80,"
  1090. "reject 13.0.0.0/9:80,"
  1091. "reject 14.0.0.0/9:80,"
  1092. "accept *:*", "accept 1-65535");
  1093. test_policy_summary_helper("reject 11.0.0.0/9:80,"
  1094. "reject 12.0.0.0/9:80,"
  1095. "reject 13.0.0.0/9:80,"
  1096. "reject 14.0.0.0/9:80,"
  1097. "reject 15.0.0.0:81,"
  1098. "accept *:*", "accept 1-65535");
  1099. test_policy_summary_helper("reject 11.0.0.0/9:80,"
  1100. "reject 12.0.0.0/9:80,"
  1101. "reject 13.0.0.0/9:80,"
  1102. "reject 14.0.0.0/9:80,"
  1103. "reject 15.0.0.0:80,"
  1104. "accept *:*",
  1105. "reject 80");
  1106. /* no exits */
  1107. test_policy_summary_helper("accept 11.0.0.0/9:80,"
  1108. "reject *:*",
  1109. "reject 1-65535");
  1110. /* port merging */
  1111. test_policy_summary_helper("accept *:80,"
  1112. "accept *:81,"
  1113. "accept *:100-110,"
  1114. "accept *:111,"
  1115. "reject *:*",
  1116. "accept 80-81,100-111");
  1117. /* border ports */
  1118. test_policy_summary_helper("accept *:1,"
  1119. "accept *:3,"
  1120. "accept *:65535,"
  1121. "reject *:*",
  1122. "accept 1,3,65535");
  1123. /* holes */
  1124. test_policy_summary_helper("accept *:1,"
  1125. "accept *:3,"
  1126. "accept *:5,"
  1127. "accept *:7,"
  1128. "reject *:*",
  1129. "accept 1,3,5,7");
  1130. test_policy_summary_helper("reject *:1,"
  1131. "reject *:3,"
  1132. "reject *:5,"
  1133. "reject *:7,"
  1134. "accept *:*",
  1135. "reject 1,3,5,7");
  1136. /* Short policies with unrecognized formats should get accepted. */
  1137. test_short_policy_parse("accept fred,2,3-5", "accept 2,3-5");
  1138. test_short_policy_parse("accept 2,fred,3", "accept 2,3");
  1139. test_short_policy_parse("accept 2,fred,3,bob", "accept 2,3");
  1140. test_short_policy_parse("accept 2,-3,500-600", "accept 2,500-600");
  1141. /* Short policies with nil entries are accepted too. */
  1142. test_short_policy_parse("accept 1,,3", "accept 1,3");
  1143. test_short_policy_parse("accept 100-200,,", "accept 100-200");
  1144. test_short_policy_parse("reject ,1-10,,,,30-40", "reject 1-10,30-40");
  1145. /* Try parsing various broken short policies */
  1146. tt_ptr_op(NULL, ==, parse_short_policy("accept 200-199"));
  1147. tt_ptr_op(NULL, ==, parse_short_policy(""));
  1148. tt_ptr_op(NULL, ==, parse_short_policy("rejekt 1,2,3"));
  1149. tt_ptr_op(NULL, ==, parse_short_policy("reject "));
  1150. tt_ptr_op(NULL, ==, parse_short_policy("reject"));
  1151. tt_ptr_op(NULL, ==, parse_short_policy("rej"));
  1152. tt_ptr_op(NULL, ==, parse_short_policy("accept 2,3,100000"));
  1153. tt_ptr_op(NULL, ==, parse_short_policy("accept 2,3x,4"));
  1154. tt_ptr_op(NULL, ==, parse_short_policy("accept 2,3x,4"));
  1155. tt_ptr_op(NULL, ==, parse_short_policy("accept 2-"));
  1156. tt_ptr_op(NULL, ==, parse_short_policy("accept 2-x"));
  1157. tt_ptr_op(NULL, ==, parse_short_policy("accept 1-,3"));
  1158. tt_ptr_op(NULL, ==, parse_short_policy("accept 1-,3"));
  1159. /* Test a too-long policy. */
  1160. {
  1161. int i;
  1162. char *policy = NULL;
  1163. smartlist_t *chunks = smartlist_new();
  1164. smartlist_add(chunks, tor_strdup("accept "));
  1165. for (i=1; i<10000; ++i)
  1166. smartlist_add_asprintf(chunks, "%d,", i);
  1167. smartlist_add(chunks, tor_strdup("20000"));
  1168. policy = smartlist_join_strings(chunks, "", 0, NULL);
  1169. SMARTLIST_FOREACH(chunks, char *, ch, tor_free(ch));
  1170. smartlist_free(chunks);
  1171. tt_ptr_op(NULL, ==, parse_short_policy(policy));/* shouldn't be accepted */
  1172. tor_free(policy); /* could leak. */
  1173. }
  1174. /* truncation ports */
  1175. sm = smartlist_new();
  1176. for (i=1; i<2000; i+=2) {
  1177. char buf[POLICY_BUF_LEN];
  1178. tor_snprintf(buf, sizeof(buf), "reject *:%d", i);
  1179. smartlist_add(sm, tor_strdup(buf));
  1180. }
  1181. smartlist_add(sm, tor_strdup("accept *:*"));
  1182. policy_str = smartlist_join_strings(sm, ",", 0, NULL);
  1183. test_policy_summary_helper( policy_str,
  1184. "accept 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,"
  1185. "46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,"
  1186. "92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,"
  1187. "130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,"
  1188. "166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198,200,"
  1189. "202,204,206,208,210,212,214,216,218,220,222,224,226,228,230,232,234,236,"
  1190. "238,240,242,244,246,248,250,252,254,256,258,260,262,264,266,268,270,272,"
  1191. "274,276,278,280,282,284,286,288,290,292,294,296,298,300,302,304,306,308,"
  1192. "310,312,314,316,318,320,322,324,326,328,330,332,334,336,338,340,342,344,"
  1193. "346,348,350,352,354,356,358,360,362,364,366,368,370,372,374,376,378,380,"
  1194. "382,384,386,388,390,392,394,396,398,400,402,404,406,408,410,412,414,416,"
  1195. "418,420,422,424,426,428,430,432,434,436,438,440,442,444,446,448,450,452,"
  1196. "454,456,458,460,462,464,466,468,470,472,474,476,478,480,482,484,486,488,"
  1197. "490,492,494,496,498,500,502,504,506,508,510,512,514,516,518,520,522");
  1198. done:
  1199. addr_policy_list_free(policy);
  1200. addr_policy_list_free(policy2);
  1201. addr_policy_list_free(policy3);
  1202. addr_policy_list_free(policy4);
  1203. addr_policy_list_free(policy5);
  1204. addr_policy_list_free(policy6);
  1205. addr_policy_list_free(policy7);
  1206. tor_free(policy_str);
  1207. if (sm) {
  1208. SMARTLIST_FOREACH(sm, char *, s, tor_free(s));
  1209. smartlist_free(sm);
  1210. }
  1211. }
  1212. /** Test encoding and parsing of rendezvous service descriptors. */
  1213. static void
  1214. test_rend_fns(void)
  1215. {
  1216. rend_service_descriptor_t *generated = NULL, *parsed = NULL;
  1217. char service_id[DIGEST_LEN];
  1218. char service_id_base32[REND_SERVICE_ID_LEN_BASE32+1];
  1219. const char *next_desc;
  1220. smartlist_t *descs = smartlist_new();
  1221. char computed_desc_id[DIGEST_LEN];
  1222. char parsed_desc_id[DIGEST_LEN];
  1223. crypto_pk_t *pk1 = NULL, *pk2 = NULL;
  1224. time_t now;
  1225. char *intro_points_encrypted = NULL;
  1226. size_t intro_points_size;
  1227. size_t encoded_size;
  1228. int i;
  1229. char address1[] = "fooaddress.onion";
  1230. char address2[] = "aaaaaaaaaaaaaaaa.onion";
  1231. char address3[] = "fooaddress.exit";
  1232. char address4[] = "www.torproject.org";
  1233. char address5[] = "foo.abcdefghijklmnop.onion";
  1234. char address6[] = "foo.bar.abcdefghijklmnop.onion";
  1235. char address7[] = ".abcdefghijklmnop.onion";
  1236. test_assert(BAD_HOSTNAME == parse_extended_hostname(address1));
  1237. test_assert(ONION_HOSTNAME == parse_extended_hostname(address2));
  1238. test_streq(address2, "aaaaaaaaaaaaaaaa");
  1239. test_assert(EXIT_HOSTNAME == parse_extended_hostname(address3));
  1240. test_assert(NORMAL_HOSTNAME == parse_extended_hostname(address4));
  1241. test_assert(ONION_HOSTNAME == parse_extended_hostname(address5));
  1242. test_streq(address5, "abcdefghijklmnop");
  1243. test_assert(ONION_HOSTNAME == parse_extended_hostname(address6));
  1244. test_streq(address6, "abcdefghijklmnop");
  1245. test_assert(BAD_HOSTNAME == parse_extended_hostname(address7));
  1246. pk1 = pk_generate(0);
  1247. pk2 = pk_generate(1);
  1248. generated = tor_malloc_zero(sizeof(rend_service_descriptor_t));
  1249. generated->pk = crypto_pk_dup_key(pk1);
  1250. crypto_pk_get_digest(generated->pk, service_id);
  1251. base32_encode(service_id_base32, REND_SERVICE_ID_LEN_BASE32+1,
  1252. service_id, REND_SERVICE_ID_LEN);
  1253. now = time(NULL);
  1254. generated->timestamp = now;
  1255. generated->version = 2;
  1256. generated->protocols = 42;
  1257. generated->intro_nodes = smartlist_new();
  1258. for (i = 0; i < 3; i++) {
  1259. rend_intro_point_t *intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  1260. crypto_pk_t *okey = pk_generate(2 + i);
  1261. intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
  1262. intro->extend_info->onion_key = okey;
  1263. crypto_pk_get_digest(intro->extend_info->onion_key,
  1264. intro->extend_info->identity_digest);
  1265. //crypto_rand(info->identity_digest, DIGEST_LEN); /* Would this work? */
  1266. intro->extend_info->nickname[0] = '$';
  1267. base16_encode(intro->extend_info->nickname + 1,
  1268. sizeof(intro->extend_info->nickname) - 1,
  1269. intro->extend_info->identity_digest, DIGEST_LEN);
  1270. /* Does not cover all IP addresses. */
  1271. tor_addr_from_ipv4h(&intro->extend_info->addr, crypto_rand_int(65536));
  1272. intro->extend_info->port = 1 + crypto_rand_int(65535);
  1273. intro->intro_key = crypto_pk_dup_key(pk2);
  1274. smartlist_add(generated->intro_nodes, intro);
  1275. }
  1276. test_assert(rend_encode_v2_descriptors(descs, generated, now, 0,
  1277. REND_NO_AUTH, NULL, NULL) > 0);
  1278. test_assert(rend_compute_v2_desc_id(computed_desc_id, service_id_base32,
  1279. NULL, now, 0) == 0);
  1280. test_memeq(((rend_encoded_v2_service_descriptor_t *)
  1281. smartlist_get(descs, 0))->desc_id, computed_desc_id, DIGEST_LEN);
  1282. test_assert(rend_parse_v2_service_descriptor(&parsed, parsed_desc_id,
  1283. &intro_points_encrypted,
  1284. &intro_points_size,
  1285. &encoded_size,
  1286. &next_desc,
  1287. ((rend_encoded_v2_service_descriptor_t *)
  1288. smartlist_get(descs, 0))->desc_str) == 0);
  1289. test_assert(parsed);
  1290. test_memeq(((rend_encoded_v2_service_descriptor_t *)
  1291. smartlist_get(descs, 0))->desc_id, parsed_desc_id, DIGEST_LEN);
  1292. test_eq(rend_parse_introduction_points(parsed, intro_points_encrypted,
  1293. intro_points_size), 3);
  1294. test_assert(!crypto_pk_cmp_keys(generated->pk, parsed->pk));
  1295. test_eq(parsed->timestamp, now);
  1296. test_eq(parsed->version, 2);
  1297. test_eq(parsed->protocols, 42);
  1298. test_eq(smartlist_len(parsed->intro_nodes), 3);
  1299. for (i = 0; i < smartlist_len(parsed->intro_nodes); i++) {
  1300. rend_intro_point_t *par_intro = smartlist_get(parsed->intro_nodes, i),
  1301. *gen_intro = smartlist_get(generated->intro_nodes, i);
  1302. extend_info_t *par_info = par_intro->extend_info;
  1303. extend_info_t *gen_info = gen_intro->extend_info;
  1304. test_assert(!crypto_pk_cmp_keys(gen_info->onion_key, par_info->onion_key));
  1305. test_memeq(gen_info->identity_digest, par_info->identity_digest,
  1306. DIGEST_LEN);
  1307. test_streq(gen_info->nickname, par_info->nickname);
  1308. test_assert(tor_addr_eq(&gen_info->addr, &par_info->addr));
  1309. test_eq(gen_info->port, par_info->port);
  1310. }
  1311. rend_service_descriptor_free(parsed);
  1312. rend_service_descriptor_free(generated);
  1313. parsed = generated = NULL;
  1314. done:
  1315. if (descs) {
  1316. for (i = 0; i < smartlist_len(descs); i++)
  1317. rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
  1318. smartlist_free(descs);
  1319. }
  1320. if (parsed)
  1321. rend_service_descriptor_free(parsed);
  1322. if (generated)
  1323. rend_service_descriptor_free(generated);
  1324. if (pk1)
  1325. crypto_pk_free(pk1);
  1326. if (pk2)
  1327. crypto_pk_free(pk2);
  1328. tor_free(intro_points_encrypted);
  1329. }
  1330. /** Run unit tests for GeoIP code. */
  1331. static void
  1332. test_geoip(void)
  1333. {
  1334. int i, j;
  1335. time_t now = 1281533250; /* 2010-08-11 13:27:30 UTC */
  1336. char *s = NULL, *v = NULL;
  1337. const char *bridge_stats_1 =
  1338. "bridge-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1339. "bridge-ips zz=24,xy=8\n"
  1340. "bridge-ip-versions v4=16,v6=16\n",
  1341. *dirreq_stats_1 =
  1342. "dirreq-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1343. "dirreq-v3-ips ab=8\n"
  1344. "dirreq-v3-reqs ab=8\n"
  1345. "dirreq-v3-resp ok=0,not-enough-sigs=0,unavailable=0,not-found=0,"
  1346. "not-modified=0,busy=0\n"
  1347. "dirreq-v3-direct-dl complete=0,timeout=0,running=0\n"
  1348. "dirreq-v3-tunneled-dl complete=0,timeout=0,running=0\n",
  1349. *dirreq_stats_2 =
  1350. "dirreq-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1351. "dirreq-v3-ips \n"
  1352. "dirreq-v3-reqs \n"
  1353. "dirreq-v3-resp ok=0,not-enough-sigs=0,unavailable=0,not-found=0,"
  1354. "not-modified=0,busy=0\n"
  1355. "dirreq-v3-direct-dl complete=0,timeout=0,running=0\n"
  1356. "dirreq-v3-tunneled-dl complete=0,timeout=0,running=0\n",
  1357. *dirreq_stats_3 =
  1358. "dirreq-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1359. "dirreq-v3-ips \n"
  1360. "dirreq-v3-reqs \n"
  1361. "dirreq-v3-resp ok=8,not-enough-sigs=0,unavailable=0,not-found=0,"
  1362. "not-modified=0,busy=0\n"
  1363. "dirreq-v3-direct-dl complete=0,timeout=0,running=0\n"
  1364. "dirreq-v3-tunneled-dl complete=0,timeout=0,running=0\n",
  1365. *dirreq_stats_4 =
  1366. "dirreq-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1367. "dirreq-v3-ips \n"
  1368. "dirreq-v3-reqs \n"
  1369. "dirreq-v3-resp ok=8,not-enough-sigs=0,unavailable=0,not-found=0,"
  1370. "not-modified=0,busy=0\n"
  1371. "dirreq-v3-direct-dl complete=0,timeout=0,running=0\n"
  1372. "dirreq-v3-tunneled-dl complete=0,timeout=0,running=4\n",
  1373. *entry_stats_1 =
  1374. "entry-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1375. "entry-ips ab=8\n",
  1376. *entry_stats_2 =
  1377. "entry-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1378. "entry-ips \n";
  1379. tor_addr_t addr;
  1380. struct in6_addr in6;
  1381. /* Populate the DB a bit. Add these in order, since we can't do the final
  1382. * 'sort' step. These aren't very good IP addresses, but they're perfectly
  1383. * fine uint32_t values. */
  1384. test_eq(0, geoip_parse_entry("10,50,AB", AF_INET));
  1385. test_eq(0, geoip_parse_entry("52,90,XY", AF_INET));
  1386. test_eq(0, geoip_parse_entry("95,100,AB", AF_INET));
  1387. test_eq(0, geoip_parse_entry("\"105\",\"140\",\"ZZ\"", AF_INET));
  1388. test_eq(0, geoip_parse_entry("\"150\",\"190\",\"XY\"", AF_INET));
  1389. test_eq(0, geoip_parse_entry("\"200\",\"250\",\"AB\"", AF_INET));
  1390. /* Populate the IPv6 DB equivalently with fake IPs in the same range */
  1391. test_eq(0, geoip_parse_entry("::a,::32,AB", AF_INET6));
  1392. test_eq(0, geoip_parse_entry("::34,::5a,XY", AF_INET6));
  1393. test_eq(0, geoip_parse_entry("::5f,::64,AB", AF_INET6));
  1394. test_eq(0, geoip_parse_entry("::69,::8c,ZZ", AF_INET6));
  1395. test_eq(0, geoip_parse_entry("::96,::be,XY", AF_INET6));
  1396. test_eq(0, geoip_parse_entry("::c8,::fa,AB", AF_INET6));
  1397. /* We should have 4 countries: ??, ab, xy, zz. */
  1398. test_eq(4, geoip_get_n_countries());
  1399. memset(&in6, 0, sizeof(in6));
  1400. /* Make sure that country ID actually works. */
  1401. #define SET_TEST_IPV6(i) \
  1402. do { \
  1403. set_uint32(in6.s6_addr + 12, htonl((uint32_t) (i))); \
  1404. } while (0)
  1405. #define CHECK_COUNTRY(country, val) do { \
  1406. /* test ipv4 country lookup */ \
  1407. test_streq(country, \
  1408. geoip_get_country_name(geoip_get_country_by_ipv4(val))); \
  1409. /* test ipv6 country lookup */ \
  1410. SET_TEST_IPV6(val); \
  1411. test_streq(country, \
  1412. geoip_get_country_name(geoip_get_country_by_ipv6(&in6))); \
  1413. } while (0)
  1414. CHECK_COUNTRY("??", 3);
  1415. CHECK_COUNTRY("ab", 32);
  1416. CHECK_COUNTRY("??", 5);
  1417. CHECK_COUNTRY("??", 51);
  1418. CHECK_COUNTRY("xy", 150);
  1419. CHECK_COUNTRY("xy", 190);
  1420. CHECK_COUNTRY("??", 2000);
  1421. test_eq(0, geoip_get_country_by_ipv4(3));
  1422. SET_TEST_IPV6(3);
  1423. test_eq(0, geoip_get_country_by_ipv6(&in6));
  1424. #undef CHECK_COUNTRY
  1425. /* Record odd numbered fake-IPs using ipv6, even numbered fake-IPs
  1426. * using ipv4. Since our fake geoip database is the same between
  1427. * ipv4 and ipv6, we should get the same result no matter which
  1428. * address family we pick for each IP. */
  1429. #define SET_TEST_ADDRESS(i) do { \
  1430. if ((i) & 1) { \
  1431. SET_TEST_IPV6(i); \
  1432. tor_addr_from_in6(&addr, &in6); \
  1433. } else { \
  1434. tor_addr_from_ipv4h(&addr, (uint32_t) i); \
  1435. } \
  1436. } while (0)
  1437. get_options_mutable()->BridgeRelay = 1;
  1438. get_options_mutable()->BridgeRecordUsageByCountry = 1;
  1439. /* Put 9 observations in AB... */
  1440. for (i=32; i < 40; ++i) {
  1441. SET_TEST_ADDRESS(i);
  1442. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, now-7200);
  1443. }
  1444. SET_TEST_ADDRESS(225);
  1445. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, now-7200);
  1446. /* and 3 observations in XY, several times. */
  1447. for (j=0; j < 10; ++j)
  1448. for (i=52; i < 55; ++i) {
  1449. SET_TEST_ADDRESS(i);
  1450. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, now-3600);
  1451. }
  1452. /* and 17 observations in ZZ... */
  1453. for (i=110; i < 127; ++i) {
  1454. SET_TEST_ADDRESS(i);
  1455. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, now);
  1456. }
  1457. geoip_get_client_history(GEOIP_CLIENT_CONNECT, &s, &v);
  1458. test_assert(s);
  1459. test_assert(v);
  1460. test_streq("zz=24,ab=16,xy=8", s);
  1461. test_streq("v4=16,v6=16", v);
  1462. tor_free(s);
  1463. tor_free(v);
  1464. /* Now clear out all the AB observations. */
  1465. geoip_remove_old_clients(now-6000);
  1466. geoip_get_client_history(GEOIP_CLIENT_CONNECT, &s, &v);
  1467. test_assert(s);
  1468. test_assert(v);
  1469. test_streq("zz=24,xy=8", s);
  1470. test_streq("v4=16,v6=16", v);
  1471. tor_free(s);
  1472. tor_free(v);
  1473. /* Start testing bridge statistics by making sure that we don't output
  1474. * bridge stats without initializing them. */
  1475. s = geoip_format_bridge_stats(now + 86400);
  1476. test_assert(!s);
  1477. /* Initialize stats and generate the bridge-stats history string out of
  1478. * the connecting clients added above. */
  1479. geoip_bridge_stats_init(now);
  1480. s = geoip_format_bridge_stats(now + 86400);
  1481. test_streq(bridge_stats_1, s);
  1482. tor_free(s);
  1483. /* Stop collecting bridge stats and make sure we don't write a history
  1484. * string anymore. */
  1485. geoip_bridge_stats_term();
  1486. s = geoip_format_bridge_stats(now + 86400);
  1487. test_assert(!s);
  1488. /* Stop being a bridge and start being a directory mirror that gathers
  1489. * directory request statistics. */
  1490. geoip_bridge_stats_term();
  1491. get_options_mutable()->BridgeRelay = 0;
  1492. get_options_mutable()->BridgeRecordUsageByCountry = 0;
  1493. get_options_mutable()->DirReqStatistics = 1;
  1494. /* Start testing dirreq statistics by making sure that we don't collect
  1495. * dirreq stats without initializing them. */
  1496. SET_TEST_ADDRESS(100);
  1497. geoip_note_client_seen(GEOIP_CLIENT_NETWORKSTATUS, &addr, now);
  1498. s = geoip_format_dirreq_stats(now + 86400);
  1499. test_assert(!s);
  1500. /* Initialize stats, note one connecting client, and generate the
  1501. * dirreq-stats history string. */
  1502. geoip_dirreq_stats_init(now);
  1503. SET_TEST_ADDRESS(100);
  1504. geoip_note_client_seen(GEOIP_CLIENT_NETWORKSTATUS, &addr, now);
  1505. s = geoip_format_dirreq_stats(now + 86400);
  1506. test_streq(dirreq_stats_1, s);
  1507. tor_free(s);
  1508. /* Stop collecting stats, add another connecting client, and ensure we
  1509. * don't generate a history string. */
  1510. geoip_dirreq_stats_term();
  1511. SET_TEST_ADDRESS(101);
  1512. geoip_note_client_seen(GEOIP_CLIENT_NETWORKSTATUS, &addr, now);
  1513. s = geoip_format_dirreq_stats(now + 86400);
  1514. test_assert(!s);
  1515. /* Re-start stats, add a connecting client, reset stats, and make sure
  1516. * that we get an all empty history string. */
  1517. geoip_dirreq_stats_init(now);
  1518. SET_TEST_ADDRESS(100);
  1519. geoip_note_client_seen(GEOIP_CLIENT_NETWORKSTATUS, &addr, now);
  1520. geoip_reset_dirreq_stats(now);
  1521. s = geoip_format_dirreq_stats(now + 86400);
  1522. test_streq(dirreq_stats_2, s);
  1523. tor_free(s);
  1524. /* Note a successful network status response and make sure that it
  1525. * appears in the history string. */
  1526. geoip_note_ns_response(GEOIP_SUCCESS);
  1527. s = geoip_format_dirreq_stats(now + 86400);
  1528. test_streq(dirreq_stats_3, s);
  1529. tor_free(s);
  1530. /* Start a tunneled directory request. */
  1531. geoip_start_dirreq((uint64_t) 1, 1024, DIRREQ_TUNNELED);
  1532. s = geoip_format_dirreq_stats(now + 86400);
  1533. test_streq(dirreq_stats_4, s);
  1534. /* Stop collecting directory request statistics and start gathering
  1535. * entry stats. */
  1536. geoip_dirreq_stats_term();
  1537. get_options_mutable()->DirReqStatistics = 0;
  1538. get_options_mutable()->EntryStatistics = 1;
  1539. /* Start testing entry statistics by making sure that we don't collect
  1540. * anything without initializing entry stats. */
  1541. SET_TEST_ADDRESS(100);
  1542. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, now);
  1543. s = geoip_format_entry_stats(now + 86400);
  1544. test_assert(!s);
  1545. /* Initialize stats, note one connecting client, and generate the
  1546. * entry-stats history string. */
  1547. geoip_entry_stats_init(now);
  1548. SET_TEST_ADDRESS(100);
  1549. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, now);
  1550. s = geoip_format_entry_stats(now + 86400);
  1551. test_streq(entry_stats_1, s);
  1552. tor_free(s);
  1553. /* Stop collecting stats, add another connecting client, and ensure we
  1554. * don't generate a history string. */
  1555. geoip_entry_stats_term();
  1556. SET_TEST_ADDRESS(101);
  1557. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, now);
  1558. s = geoip_format_entry_stats(now + 86400);
  1559. test_assert(!s);
  1560. /* Re-start stats, add a connecting client, reset stats, and make sure
  1561. * that we get an all empty history string. */
  1562. geoip_entry_stats_init(now);
  1563. SET_TEST_ADDRESS(100);
  1564. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, now);
  1565. geoip_reset_entry_stats(now);
  1566. s = geoip_format_entry_stats(now + 86400);
  1567. test_streq(entry_stats_2, s);
  1568. tor_free(s);
  1569. #undef SET_TEST_ADDRESS
  1570. #undef SET_TEST_IPV6
  1571. /* Stop collecting entry statistics. */
  1572. geoip_entry_stats_term();
  1573. get_options_mutable()->EntryStatistics = 0;
  1574. done:
  1575. tor_free(s);
  1576. tor_free(v);
  1577. }
  1578. /** Run unit tests for stats code. */
  1579. static void
  1580. test_stats(void)
  1581. {
  1582. time_t now = 1281533250; /* 2010-08-11 13:27:30 UTC */
  1583. char *s = NULL;
  1584. int i;
  1585. /* Start with testing exit port statistics; we shouldn't collect exit
  1586. * stats without initializing them. */
  1587. rep_hist_note_exit_stream_opened(80);
  1588. rep_hist_note_exit_bytes(80, 100, 10000);
  1589. s = rep_hist_format_exit_stats(now + 86400);
  1590. test_assert(!s);
  1591. /* Initialize stats, note some streams and bytes, and generate history
  1592. * string. */
  1593. rep_hist_exit_stats_init(now);
  1594. rep_hist_note_exit_stream_opened(80);
  1595. rep_hist_note_exit_bytes(80, 100, 10000);
  1596. rep_hist_note_exit_stream_opened(443);
  1597. rep_hist_note_exit_bytes(443, 100, 10000);
  1598. rep_hist_note_exit_bytes(443, 100, 10000);
  1599. s = rep_hist_format_exit_stats(now + 86400);
  1600. test_streq("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1601. "exit-kibibytes-written 80=1,443=1,other=0\n"
  1602. "exit-kibibytes-read 80=10,443=20,other=0\n"
  1603. "exit-streams-opened 80=4,443=4,other=0\n", s);
  1604. tor_free(s);
  1605. /* Add a few bytes on 10 more ports and ensure that only the top 10
  1606. * ports are contained in the history string. */
  1607. for (i = 50; i < 60; i++) {
  1608. rep_hist_note_exit_bytes(i, i, i);
  1609. rep_hist_note_exit_stream_opened(i);
  1610. }
  1611. s = rep_hist_format_exit_stats(now + 86400);
  1612. test_streq("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1613. "exit-kibibytes-written 52=1,53=1,54=1,55=1,56=1,57=1,58=1,"
  1614. "59=1,80=1,443=1,other=1\n"
  1615. "exit-kibibytes-read 52=1,53=1,54=1,55=1,56=1,57=1,58=1,"
  1616. "59=1,80=10,443=20,other=1\n"
  1617. "exit-streams-opened 52=4,53=4,54=4,55=4,56=4,57=4,58=4,"
  1618. "59=4,80=4,443=4,other=4\n", s);
  1619. tor_free(s);
  1620. /* Stop collecting stats, add some bytes, and ensure we don't generate
  1621. * a history string. */
  1622. rep_hist_exit_stats_term();
  1623. rep_hist_note_exit_bytes(80, 100, 10000);
  1624. s = rep_hist_format_exit_stats(now + 86400);
  1625. test_assert(!s);
  1626. /* Re-start stats, add some bytes, reset stats, and see what history we
  1627. * get when observing no streams or bytes at all. */
  1628. rep_hist_exit_stats_init(now);
  1629. rep_hist_note_exit_stream_opened(80);
  1630. rep_hist_note_exit_bytes(80, 100, 10000);
  1631. rep_hist_reset_exit_stats(now);
  1632. s = rep_hist_format_exit_stats(now + 86400);
  1633. test_streq("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1634. "exit-kibibytes-written other=0\n"
  1635. "exit-kibibytes-read other=0\n"
  1636. "exit-streams-opened other=0\n", s);
  1637. tor_free(s);
  1638. /* Continue with testing connection statistics; we shouldn't collect
  1639. * conn stats without initializing them. */
  1640. rep_hist_note_or_conn_bytes(1, 20, 400, now);
  1641. s = rep_hist_format_conn_stats(now + 86400);
  1642. test_assert(!s);
  1643. /* Initialize stats, note bytes, and generate history string. */
  1644. rep_hist_conn_stats_init(now);
  1645. rep_hist_note_or_conn_bytes(1, 30000, 400000, now);
  1646. rep_hist_note_or_conn_bytes(1, 30000, 400000, now + 5);
  1647. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 10);
  1648. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 15);
  1649. s = rep_hist_format_conn_stats(now + 86400);
  1650. test_streq("conn-bi-direct 2010-08-12 13:27:30 (86400 s) 0,0,1,0\n", s);
  1651. tor_free(s);
  1652. /* Stop collecting stats, add some bytes, and ensure we don't generate
  1653. * a history string. */
  1654. rep_hist_conn_stats_term();
  1655. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 15);
  1656. s = rep_hist_format_conn_stats(now + 86400);
  1657. test_assert(!s);
  1658. /* Re-start stats, add some bytes, reset stats, and see what history we
  1659. * get when observing no bytes at all. */
  1660. rep_hist_conn_stats_init(now);
  1661. rep_hist_note_or_conn_bytes(1, 30000, 400000, now);
  1662. rep_hist_note_or_conn_bytes(1, 30000, 400000, now + 5);
  1663. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 10);
  1664. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 15);
  1665. rep_hist_reset_conn_stats(now);
  1666. s = rep_hist_format_conn_stats(now + 86400);
  1667. test_streq("conn-bi-direct 2010-08-12 13:27:30 (86400 s) 0,0,0,0\n", s);
  1668. tor_free(s);
  1669. /* Continue with testing buffer statistics; we shouldn't collect buffer
  1670. * stats without initializing them. */
  1671. rep_hist_add_buffer_stats(2.0, 2.0, 20);
  1672. s = rep_hist_format_buffer_stats(now + 86400);
  1673. test_assert(!s);
  1674. /* Initialize stats, add statistics for a single circuit, and generate
  1675. * the history string. */
  1676. rep_hist_buffer_stats_init(now);
  1677. rep_hist_add_buffer_stats(2.0, 2.0, 20);
  1678. s = rep_hist_format_buffer_stats(now + 86400);
  1679. test_streq("cell-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1680. "cell-processed-cells 20,0,0,0,0,0,0,0,0,0\n"
  1681. "cell-queued-cells 2.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,"
  1682. "0.00,0.00\n"
  1683. "cell-time-in-queue 2,0,0,0,0,0,0,0,0,0\n"
  1684. "cell-circuits-per-decile 1\n", s);
  1685. tor_free(s);
  1686. /* Add nineteen more circuit statistics to the one that's already in the
  1687. * history to see that the math works correctly. */
  1688. for (i = 21; i < 30; i++)
  1689. rep_hist_add_buffer_stats(2.0, 2.0, i);
  1690. for (i = 20; i < 30; i++)
  1691. rep_hist_add_buffer_stats(3.5, 3.5, i);
  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 29,28,27,26,25,24,23,22,21,20\n"
  1695. "cell-queued-cells 2.75,2.75,2.75,2.75,2.75,2.75,2.75,2.75,"
  1696. "2.75,2.75\n"
  1697. "cell-time-in-queue 3,3,3,3,3,3,3,3,3,3\n"
  1698. "cell-circuits-per-decile 2\n", s);
  1699. tor_free(s);
  1700. /* Stop collecting stats, add statistics for one circuit, and ensure we
  1701. * don't generate a history string. */
  1702. rep_hist_buffer_stats_term();
  1703. rep_hist_add_buffer_stats(2.0, 2.0, 20);
  1704. s = rep_hist_format_buffer_stats(now + 86400);
  1705. test_assert(!s);
  1706. /* Re-start stats, add statistics for one circuit, reset stats, and make
  1707. * sure that the history has all zeros. */
  1708. rep_hist_buffer_stats_init(now);
  1709. rep_hist_add_buffer_stats(2.0, 2.0, 20);
  1710. rep_hist_reset_buffer_stats(now);
  1711. s = rep_hist_format_buffer_stats(now + 86400);
  1712. test_streq("cell-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1713. "cell-processed-cells 0,0,0,0,0,0,0,0,0,0\n"
  1714. "cell-queued-cells 0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,"
  1715. "0.00,0.00\n"
  1716. "cell-time-in-queue 0,0,0,0,0,0,0,0,0,0\n"
  1717. "cell-circuits-per-decile 0\n", s);
  1718. done:
  1719. tor_free(s);
  1720. }
  1721. static void *
  1722. legacy_test_setup(const struct testcase_t *testcase)
  1723. {
  1724. return testcase->setup_data;
  1725. }
  1726. void
  1727. legacy_test_helper(void *data)
  1728. {
  1729. void (*fn)(void) = data;
  1730. fn();
  1731. }
  1732. static int
  1733. legacy_test_cleanup(const struct testcase_t *testcase, void *ptr)
  1734. {
  1735. (void)ptr;
  1736. (void)testcase;
  1737. return 1;
  1738. }
  1739. const struct testcase_setup_t legacy_setup = {
  1740. legacy_test_setup, legacy_test_cleanup
  1741. };
  1742. #define ENT(name) \
  1743. { #name, legacy_test_helper, 0, &legacy_setup, test_ ## name }
  1744. #define SUBENT(group, name) \
  1745. { #group "_" #name, legacy_test_helper, 0, &legacy_setup, \
  1746. test_ ## group ## _ ## name }
  1747. #define DISABLED(name) \
  1748. { #name, legacy_test_helper, TT_SKIP, &legacy_setup, test_ ## name }
  1749. #define FORK(name) \
  1750. { #name, legacy_test_helper, TT_FORK, &legacy_setup, test_ ## name }
  1751. static struct testcase_t test_array[] = {
  1752. ENT(buffers),
  1753. { "buffer_copy", test_buffer_copy, 0, NULL, NULL },
  1754. ENT(onion_handshake),
  1755. #ifdef CURVE25519_ENABLED
  1756. { "ntor_handshake", test_ntor_handshake, 0, NULL, NULL },
  1757. #endif
  1758. ENT(circuit_timeout),
  1759. ENT(policies),
  1760. ENT(rend_fns),
  1761. ENT(geoip),
  1762. FORK(stats),
  1763. END_OF_TESTCASES
  1764. };
  1765. #define SOCKSENT(name) \
  1766. { #name, test_socks_##name, TT_FORK, &socks_setup, NULL }
  1767. static struct testcase_t socks_tests[] = {
  1768. SOCKSENT(4_unsupported_commands),
  1769. SOCKSENT(4_supported_commands),
  1770. SOCKSENT(5_unsupported_commands),
  1771. SOCKSENT(5_supported_commands),
  1772. SOCKSENT(5_no_authenticate),
  1773. SOCKSENT(5_auth_before_negotiation),
  1774. SOCKSENT(5_authenticate),
  1775. SOCKSENT(5_authenticate_with_data),
  1776. END_OF_TESTCASES
  1777. };
  1778. extern struct testcase_t addr_tests[];
  1779. extern struct testcase_t crypto_tests[];
  1780. extern struct testcase_t container_tests[];
  1781. extern struct testcase_t util_tests[];
  1782. extern struct testcase_t dir_tests[];
  1783. extern struct testcase_t microdesc_tests[];
  1784. extern struct testcase_t pt_tests[];
  1785. extern struct testcase_t config_tests[];
  1786. extern struct testcase_t introduce_tests[];
  1787. extern struct testcase_t replaycache_tests[];
  1788. extern struct testcase_t cell_format_tests[];
  1789. static struct testgroup_t testgroups[] = {
  1790. { "", test_array },
  1791. { "socks/", socks_tests },
  1792. { "addr/", addr_tests },
  1793. { "crypto/", crypto_tests },
  1794. { "container/", container_tests },
  1795. { "util/", util_tests },
  1796. { "cellfmt/", cell_format_tests },
  1797. { "dir/", dir_tests },
  1798. { "dir/md/", microdesc_tests },
  1799. { "pt/", pt_tests },
  1800. { "config/", config_tests },
  1801. { "replaycache/", replaycache_tests },
  1802. { "introduce/", introduce_tests },
  1803. END_OF_GROUPS
  1804. };
  1805. /** Main entry point for unit test code: parse the command line, and run
  1806. * some unit tests. */
  1807. int
  1808. main(int c, const char **v)
  1809. {
  1810. or_options_t *options;
  1811. char *errmsg = NULL;
  1812. int i, i_out;
  1813. int loglevel = LOG_ERR;
  1814. #ifdef USE_DMALLOC
  1815. {
  1816. int r = CRYPTO_set_mem_ex_functions(tor_malloc_, tor_realloc_, tor_free_);
  1817. tor_assert(r);
  1818. }
  1819. #endif
  1820. update_approx_time(time(NULL));
  1821. options = options_new();
  1822. tor_threads_init();
  1823. init_logging();
  1824. for (i_out = i = 1; i < c; ++i) {
  1825. if (!strcmp(v[i], "--warn")) {
  1826. loglevel = LOG_WARN;
  1827. } else if (!strcmp(v[i], "--notice")) {
  1828. loglevel = LOG_NOTICE;
  1829. } else if (!strcmp(v[i], "--info")) {
  1830. loglevel = LOG_INFO;
  1831. } else if (!strcmp(v[i], "--debug")) {
  1832. loglevel = LOG_DEBUG;
  1833. } else {
  1834. v[i_out++] = v[i];
  1835. }
  1836. }
  1837. c = i_out;
  1838. {
  1839. log_severity_list_t s;
  1840. memset(&s, 0, sizeof(s));
  1841. set_log_severity_config(loglevel, LOG_ERR, &s);
  1842. add_stream_log(&s, "", fileno(stdout));
  1843. }
  1844. options->command = CMD_RUN_UNITTESTS;
  1845. if (crypto_global_init(0, NULL, NULL)) {
  1846. printf("Can't initialize crypto subsystem; exiting.\n");
  1847. return 1;
  1848. }
  1849. crypto_set_tls_dh_prime(NULL);
  1850. rep_hist_init();
  1851. network_init();
  1852. setup_directory();
  1853. options_init(options);
  1854. options->DataDirectory = tor_strdup(temp_dir);
  1855. options->EntryStatistics = 1;
  1856. if (set_options(options, &errmsg) < 0) {
  1857. printf("Failed to set initial options: %s\n", errmsg);
  1858. tor_free(errmsg);
  1859. return 1;
  1860. }
  1861. crypto_seed_rng(1);
  1862. atexit(remove_directory);
  1863. have_failed = (tinytest_main(c, v, testgroups) != 0);
  1864. free_pregenerated_keys();
  1865. #ifdef USE_DMALLOC
  1866. tor_free_all(0);
  1867. dmalloc_log_unfreed();
  1868. #endif
  1869. if (have_failed)
  1870. return 1;
  1871. else
  1872. return 0;
  1873. }