test.c 71 KB

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