test.c 75 KB

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