test.c 73 KB

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