test.c 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242
  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. /** Run unit tests for GeoIP code. */
  1422. static void
  1423. test_geoip(void)
  1424. {
  1425. int i, j;
  1426. time_t now = 1281533250; /* 2010-08-11 13:27:30 UTC */
  1427. char *s = NULL, *v = NULL;
  1428. const char *bridge_stats_1 =
  1429. "bridge-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1430. "bridge-ips zz=24,xy=8\n"
  1431. "bridge-ip-versions v4=16,v6=16\n",
  1432. *dirreq_stats_1 =
  1433. "dirreq-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1434. "dirreq-v3-ips ab=8\n"
  1435. "dirreq-v3-reqs ab=8\n"
  1436. "dirreq-v3-resp ok=0,not-enough-sigs=0,unavailable=0,not-found=0,"
  1437. "not-modified=0,busy=0\n"
  1438. "dirreq-v3-direct-dl complete=0,timeout=0,running=0\n"
  1439. "dirreq-v3-tunneled-dl complete=0,timeout=0,running=0\n",
  1440. *dirreq_stats_2 =
  1441. "dirreq-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1442. "dirreq-v3-ips \n"
  1443. "dirreq-v3-reqs \n"
  1444. "dirreq-v3-resp ok=0,not-enough-sigs=0,unavailable=0,not-found=0,"
  1445. "not-modified=0,busy=0\n"
  1446. "dirreq-v3-direct-dl complete=0,timeout=0,running=0\n"
  1447. "dirreq-v3-tunneled-dl complete=0,timeout=0,running=0\n",
  1448. *dirreq_stats_3 =
  1449. "dirreq-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1450. "dirreq-v3-ips \n"
  1451. "dirreq-v3-reqs \n"
  1452. "dirreq-v3-resp ok=8,not-enough-sigs=0,unavailable=0,not-found=0,"
  1453. "not-modified=0,busy=0\n"
  1454. "dirreq-v3-direct-dl complete=0,timeout=0,running=0\n"
  1455. "dirreq-v3-tunneled-dl complete=0,timeout=0,running=0\n",
  1456. *dirreq_stats_4 =
  1457. "dirreq-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1458. "dirreq-v3-ips \n"
  1459. "dirreq-v3-reqs \n"
  1460. "dirreq-v3-resp ok=8,not-enough-sigs=0,unavailable=0,not-found=0,"
  1461. "not-modified=0,busy=0\n"
  1462. "dirreq-v3-direct-dl complete=0,timeout=0,running=0\n"
  1463. "dirreq-v3-tunneled-dl complete=0,timeout=0,running=4\n",
  1464. *entry_stats_1 =
  1465. "entry-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1466. "entry-ips ab=8\n",
  1467. *entry_stats_2 =
  1468. "entry-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1469. "entry-ips \n";
  1470. tor_addr_t addr;
  1471. struct in6_addr in6;
  1472. /* Populate the DB a bit. Add these in order, since we can't do the final
  1473. * 'sort' step. These aren't very good IP addresses, but they're perfectly
  1474. * fine uint32_t values. */
  1475. test_eq(0, geoip_parse_entry("10,50,AB", AF_INET));
  1476. test_eq(0, geoip_parse_entry("52,90,XY", AF_INET));
  1477. test_eq(0, geoip_parse_entry("95,100,AB", AF_INET));
  1478. test_eq(0, geoip_parse_entry("\"105\",\"140\",\"ZZ\"", AF_INET));
  1479. test_eq(0, geoip_parse_entry("\"150\",\"190\",\"XY\"", AF_INET));
  1480. test_eq(0, geoip_parse_entry("\"200\",\"250\",\"AB\"", AF_INET));
  1481. /* Populate the IPv6 DB equivalently with fake IPs in the same range */
  1482. test_eq(0, geoip_parse_entry("::a,::32,AB", AF_INET6));
  1483. test_eq(0, geoip_parse_entry("::34,::5a,XY", AF_INET6));
  1484. test_eq(0, geoip_parse_entry("::5f,::64,AB", AF_INET6));
  1485. test_eq(0, geoip_parse_entry("::69,::8c,ZZ", AF_INET6));
  1486. test_eq(0, geoip_parse_entry("::96,::be,XY", AF_INET6));
  1487. test_eq(0, geoip_parse_entry("::c8,::fa,AB", AF_INET6));
  1488. /* We should have 4 countries: ??, ab, xy, zz. */
  1489. test_eq(4, geoip_get_n_countries());
  1490. memset(&in6, 0, sizeof(in6));
  1491. /* Make sure that country ID actually works. */
  1492. #define SET_TEST_IPV6(i) \
  1493. do { \
  1494. set_uint32(in6.s6_addr + 12, htonl((uint32_t) (i))); \
  1495. } while (0)
  1496. #define CHECK_COUNTRY(country, val) do { \
  1497. /* test ipv4 country lookup */ \
  1498. test_streq(country, \
  1499. geoip_get_country_name(geoip_get_country_by_ipv4(val))); \
  1500. /* test ipv6 country lookup */ \
  1501. SET_TEST_IPV6(val); \
  1502. test_streq(country, \
  1503. geoip_get_country_name(geoip_get_country_by_ipv6(&in6))); \
  1504. } while (0)
  1505. CHECK_COUNTRY("??", 3);
  1506. CHECK_COUNTRY("ab", 32);
  1507. CHECK_COUNTRY("??", 5);
  1508. CHECK_COUNTRY("??", 51);
  1509. CHECK_COUNTRY("xy", 150);
  1510. CHECK_COUNTRY("xy", 190);
  1511. CHECK_COUNTRY("??", 2000);
  1512. test_eq(0, geoip_get_country_by_ipv4(3));
  1513. SET_TEST_IPV6(3);
  1514. test_eq(0, geoip_get_country_by_ipv6(&in6));
  1515. #undef CHECK_COUNTRY
  1516. /* Record odd numbered fake-IPs using ipv6, even numbered fake-IPs
  1517. * using ipv4. Since our fake geoip database is the same between
  1518. * ipv4 and ipv6, we should get the same result no matter which
  1519. * address family we pick for each IP. */
  1520. #define SET_TEST_ADDRESS(i) do { \
  1521. if ((i) & 1) { \
  1522. SET_TEST_IPV6(i); \
  1523. tor_addr_from_in6(&addr, &in6); \
  1524. } else { \
  1525. tor_addr_from_ipv4h(&addr, (uint32_t) i); \
  1526. } \
  1527. } while (0)
  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, now-7200);
  1534. }
  1535. SET_TEST_ADDRESS(225);
  1536. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &addr, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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. #undef SET_TEST_ADDRESS
  1662. #undef SET_TEST_IPV6
  1663. /* Stop collecting entry statistics. */
  1664. geoip_entry_stats_term();
  1665. get_options_mutable()->EntryStatistics = 0;
  1666. done:
  1667. tor_free(s);
  1668. tor_free(v);
  1669. }
  1670. /** Run unit tests for stats code. */
  1671. static void
  1672. test_stats(void)
  1673. {
  1674. time_t now = 1281533250; /* 2010-08-11 13:27:30 UTC */
  1675. char *s = NULL;
  1676. int i;
  1677. /* Start with testing exit port statistics; we shouldn't collect exit
  1678. * stats without initializing them. */
  1679. rep_hist_note_exit_stream_opened(80);
  1680. rep_hist_note_exit_bytes(80, 100, 10000);
  1681. s = rep_hist_format_exit_stats(now + 86400);
  1682. test_assert(!s);
  1683. /* Initialize stats, note some streams and bytes, and generate history
  1684. * string. */
  1685. rep_hist_exit_stats_init(now);
  1686. rep_hist_note_exit_stream_opened(80);
  1687. rep_hist_note_exit_bytes(80, 100, 10000);
  1688. rep_hist_note_exit_stream_opened(443);
  1689. rep_hist_note_exit_bytes(443, 100, 10000);
  1690. rep_hist_note_exit_bytes(443, 100, 10000);
  1691. s = rep_hist_format_exit_stats(now + 86400);
  1692. test_streq("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1693. "exit-kibibytes-written 80=1,443=1,other=0\n"
  1694. "exit-kibibytes-read 80=10,443=20,other=0\n"
  1695. "exit-streams-opened 80=4,443=4,other=0\n", s);
  1696. tor_free(s);
  1697. /* Add a few bytes on 10 more ports and ensure that only the top 10
  1698. * ports are contained in the history string. */
  1699. for (i = 50; i < 60; i++) {
  1700. rep_hist_note_exit_bytes(i, i, i);
  1701. rep_hist_note_exit_stream_opened(i);
  1702. }
  1703. s = rep_hist_format_exit_stats(now + 86400);
  1704. test_streq("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1705. "exit-kibibytes-written 52=1,53=1,54=1,55=1,56=1,57=1,58=1,"
  1706. "59=1,80=1,443=1,other=1\n"
  1707. "exit-kibibytes-read 52=1,53=1,54=1,55=1,56=1,57=1,58=1,"
  1708. "59=1,80=10,443=20,other=1\n"
  1709. "exit-streams-opened 52=4,53=4,54=4,55=4,56=4,57=4,58=4,"
  1710. "59=4,80=4,443=4,other=4\n", s);
  1711. tor_free(s);
  1712. /* Stop collecting stats, add some bytes, and ensure we don't generate
  1713. * a history string. */
  1714. rep_hist_exit_stats_term();
  1715. rep_hist_note_exit_bytes(80, 100, 10000);
  1716. s = rep_hist_format_exit_stats(now + 86400);
  1717. test_assert(!s);
  1718. /* Re-start stats, add some bytes, reset stats, and see what history we
  1719. * get when observing no streams or bytes at all. */
  1720. rep_hist_exit_stats_init(now);
  1721. rep_hist_note_exit_stream_opened(80);
  1722. rep_hist_note_exit_bytes(80, 100, 10000);
  1723. rep_hist_reset_exit_stats(now);
  1724. s = rep_hist_format_exit_stats(now + 86400);
  1725. test_streq("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1726. "exit-kibibytes-written other=0\n"
  1727. "exit-kibibytes-read other=0\n"
  1728. "exit-streams-opened other=0\n", s);
  1729. tor_free(s);
  1730. /* Continue with testing connection statistics; we shouldn't collect
  1731. * conn stats without initializing them. */
  1732. rep_hist_note_or_conn_bytes(1, 20, 400, now);
  1733. s = rep_hist_format_conn_stats(now + 86400);
  1734. test_assert(!s);
  1735. /* Initialize stats, note bytes, and generate history string. */
  1736. rep_hist_conn_stats_init(now);
  1737. rep_hist_note_or_conn_bytes(1, 30000, 400000, now);
  1738. rep_hist_note_or_conn_bytes(1, 30000, 400000, now + 5);
  1739. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 10);
  1740. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 15);
  1741. s = rep_hist_format_conn_stats(now + 86400);
  1742. test_streq("conn-bi-direct 2010-08-12 13:27:30 (86400 s) 0,0,1,0\n", s);
  1743. tor_free(s);
  1744. /* Stop collecting stats, add some bytes, and ensure we don't generate
  1745. * a history string. */
  1746. rep_hist_conn_stats_term();
  1747. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 15);
  1748. s = rep_hist_format_conn_stats(now + 86400);
  1749. test_assert(!s);
  1750. /* Re-start stats, add some bytes, reset stats, and see what history we
  1751. * get when observing no bytes at all. */
  1752. rep_hist_conn_stats_init(now);
  1753. rep_hist_note_or_conn_bytes(1, 30000, 400000, now);
  1754. rep_hist_note_or_conn_bytes(1, 30000, 400000, now + 5);
  1755. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 10);
  1756. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 15);
  1757. rep_hist_reset_conn_stats(now);
  1758. s = rep_hist_format_conn_stats(now + 86400);
  1759. test_streq("conn-bi-direct 2010-08-12 13:27:30 (86400 s) 0,0,0,0\n", s);
  1760. tor_free(s);
  1761. /* Continue with testing buffer statistics; we shouldn't collect buffer
  1762. * stats without initializing them. */
  1763. rep_hist_add_buffer_stats(2.0, 2.0, 20);
  1764. s = rep_hist_format_buffer_stats(now + 86400);
  1765. test_assert(!s);
  1766. /* Initialize stats, add statistics for a single circuit, and generate
  1767. * the history string. */
  1768. rep_hist_buffer_stats_init(now);
  1769. rep_hist_add_buffer_stats(2.0, 2.0, 20);
  1770. s = rep_hist_format_buffer_stats(now + 86400);
  1771. test_streq("cell-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1772. "cell-processed-cells 20,0,0,0,0,0,0,0,0,0\n"
  1773. "cell-queued-cells 2.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,"
  1774. "0.00,0.00\n"
  1775. "cell-time-in-queue 2,0,0,0,0,0,0,0,0,0\n"
  1776. "cell-circuits-per-decile 1\n", s);
  1777. tor_free(s);
  1778. /* Add nineteen more circuit statistics to the one that's already in the
  1779. * history to see that the math works correctly. */
  1780. for (i = 21; i < 30; i++)
  1781. rep_hist_add_buffer_stats(2.0, 2.0, i);
  1782. for (i = 20; i < 30; i++)
  1783. rep_hist_add_buffer_stats(3.5, 3.5, i);
  1784. s = rep_hist_format_buffer_stats(now + 86400);
  1785. test_streq("cell-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1786. "cell-processed-cells 29,28,27,26,25,24,23,22,21,20\n"
  1787. "cell-queued-cells 2.75,2.75,2.75,2.75,2.75,2.75,2.75,2.75,"
  1788. "2.75,2.75\n"
  1789. "cell-time-in-queue 3,3,3,3,3,3,3,3,3,3\n"
  1790. "cell-circuits-per-decile 2\n", s);
  1791. tor_free(s);
  1792. /* Stop collecting stats, add statistics for one circuit, and ensure we
  1793. * don't generate a history string. */
  1794. rep_hist_buffer_stats_term();
  1795. rep_hist_add_buffer_stats(2.0, 2.0, 20);
  1796. s = rep_hist_format_buffer_stats(now + 86400);
  1797. test_assert(!s);
  1798. /* Re-start stats, add statistics for one circuit, reset stats, and make
  1799. * sure that the history has all zeros. */
  1800. rep_hist_buffer_stats_init(now);
  1801. rep_hist_add_buffer_stats(2.0, 2.0, 20);
  1802. rep_hist_reset_buffer_stats(now);
  1803. s = rep_hist_format_buffer_stats(now + 86400);
  1804. test_streq("cell-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1805. "cell-processed-cells 0,0,0,0,0,0,0,0,0,0\n"
  1806. "cell-queued-cells 0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,"
  1807. "0.00,0.00\n"
  1808. "cell-time-in-queue 0,0,0,0,0,0,0,0,0,0\n"
  1809. "cell-circuits-per-decile 0\n", s);
  1810. done:
  1811. tor_free(s);
  1812. }
  1813. static void *
  1814. legacy_test_setup(const struct testcase_t *testcase)
  1815. {
  1816. return testcase->setup_data;
  1817. }
  1818. void
  1819. legacy_test_helper(void *data)
  1820. {
  1821. void (*fn)(void) = data;
  1822. fn();
  1823. }
  1824. static int
  1825. legacy_test_cleanup(const struct testcase_t *testcase, void *ptr)
  1826. {
  1827. (void)ptr;
  1828. (void)testcase;
  1829. return 1;
  1830. }
  1831. const struct testcase_setup_t legacy_setup = {
  1832. legacy_test_setup, legacy_test_cleanup
  1833. };
  1834. #define ENT(name) \
  1835. { #name, legacy_test_helper, 0, &legacy_setup, test_ ## name }
  1836. #define FORK(name) \
  1837. { #name, legacy_test_helper, TT_FORK, &legacy_setup, test_ ## name }
  1838. static struct testcase_t test_array[] = {
  1839. ENT(buffers),
  1840. { "buffer_copy", test_buffer_copy, 0, NULL, NULL },
  1841. ENT(onion_handshake),
  1842. { "bad_onion_handshake", test_bad_onion_handshake, 0, NULL, NULL },
  1843. #ifdef CURVE25519_ENABLED
  1844. { "ntor_handshake", test_ntor_handshake, 0, NULL, NULL },
  1845. #endif
  1846. ENT(circuit_timeout),
  1847. ENT(policies),
  1848. ENT(rend_fns),
  1849. ENT(geoip),
  1850. FORK(stats),
  1851. END_OF_TESTCASES
  1852. };
  1853. #define SOCKSENT(name) \
  1854. { #name, test_socks_##name, TT_FORK, &socks_setup, NULL }
  1855. static struct testcase_t socks_tests[] = {
  1856. SOCKSENT(4_unsupported_commands),
  1857. SOCKSENT(4_supported_commands),
  1858. SOCKSENT(5_unsupported_commands),
  1859. SOCKSENT(5_supported_commands),
  1860. SOCKSENT(5_no_authenticate),
  1861. SOCKSENT(5_auth_before_negotiation),
  1862. SOCKSENT(5_authenticate),
  1863. SOCKSENT(5_authenticate_with_data),
  1864. END_OF_TESTCASES
  1865. };
  1866. extern struct testcase_t addr_tests[];
  1867. extern struct testcase_t crypto_tests[];
  1868. extern struct testcase_t container_tests[];
  1869. extern struct testcase_t util_tests[];
  1870. extern struct testcase_t dir_tests[];
  1871. extern struct testcase_t microdesc_tests[];
  1872. extern struct testcase_t pt_tests[];
  1873. extern struct testcase_t config_tests[];
  1874. extern struct testcase_t introduce_tests[];
  1875. extern struct testcase_t replaycache_tests[];
  1876. extern struct testcase_t cell_format_tests[];
  1877. extern struct testcase_t circuitlist_tests[];
  1878. extern struct testcase_t circuitmux_tests[];
  1879. extern struct testcase_t cell_queue_tests[];
  1880. extern struct testcase_t options_tests[];
  1881. extern struct testcase_t logging_tests[];
  1882. extern struct testcase_t backtrace_tests[];
  1883. static struct testgroup_t testgroups[] = {
  1884. { "", test_array },
  1885. { "socks/", socks_tests },
  1886. { "addr/", addr_tests },
  1887. { "crypto/", crypto_tests },
  1888. { "container/", container_tests },
  1889. { "util/", util_tests },
  1890. { "util/logging/", logging_tests },
  1891. { "cellfmt/", cell_format_tests },
  1892. { "cellqueue/", cell_queue_tests },
  1893. { "dir/", dir_tests },
  1894. { "dir/md/", microdesc_tests },
  1895. { "pt/", pt_tests },
  1896. { "config/", config_tests },
  1897. { "replaycache/", replaycache_tests },
  1898. { "introduce/", introduce_tests },
  1899. { "circuitlist/", circuitlist_tests },
  1900. { "circuitmux/", circuitmux_tests },
  1901. { "options/", options_tests },
  1902. END_OF_GROUPS
  1903. };
  1904. /** Main entry point for unit test code: parse the command line, and run
  1905. * some unit tests. */
  1906. int
  1907. main(int c, const char **v)
  1908. {
  1909. or_options_t *options;
  1910. char *errmsg = NULL;
  1911. int i, i_out;
  1912. int loglevel = LOG_ERR;
  1913. #ifdef USE_DMALLOC
  1914. {
  1915. int r = CRYPTO_set_mem_ex_functions(tor_malloc_, tor_realloc_, tor_free_);
  1916. tor_assert(r);
  1917. }
  1918. #endif
  1919. update_approx_time(time(NULL));
  1920. options = options_new();
  1921. tor_threads_init();
  1922. init_logging();
  1923. for (i_out = i = 1; i < c; ++i) {
  1924. if (!strcmp(v[i], "--warn")) {
  1925. loglevel = LOG_WARN;
  1926. } else if (!strcmp(v[i], "--notice")) {
  1927. loglevel = LOG_NOTICE;
  1928. } else if (!strcmp(v[i], "--info")) {
  1929. loglevel = LOG_INFO;
  1930. } else if (!strcmp(v[i], "--debug")) {
  1931. loglevel = LOG_DEBUG;
  1932. } else {
  1933. v[i_out++] = v[i];
  1934. }
  1935. }
  1936. c = i_out;
  1937. {
  1938. log_severity_list_t s;
  1939. memset(&s, 0, sizeof(s));
  1940. set_log_severity_config(loglevel, LOG_ERR, &s);
  1941. add_stream_log(&s, "", fileno(stdout));
  1942. }
  1943. options->command = CMD_RUN_UNITTESTS;
  1944. if (crypto_global_init(0, NULL, NULL)) {
  1945. printf("Can't initialize crypto subsystem; exiting.\n");
  1946. return 1;
  1947. }
  1948. crypto_set_tls_dh_prime(NULL);
  1949. crypto_seed_rng(1);
  1950. rep_hist_init();
  1951. network_init();
  1952. setup_directory();
  1953. options_init(options);
  1954. options->DataDirectory = tor_strdup(temp_dir);
  1955. options->EntryStatistics = 1;
  1956. if (set_options(options, &errmsg) < 0) {
  1957. printf("Failed to set initial options: %s\n", errmsg);
  1958. tor_free(errmsg);
  1959. return 1;
  1960. }
  1961. atexit(remove_directory);
  1962. have_failed = (tinytest_main(c, v, testgroups) != 0);
  1963. free_pregenerated_keys();
  1964. #ifdef USE_DMALLOC
  1965. tor_free_all(0);
  1966. dmalloc_log_unfreed();
  1967. #endif
  1968. if (have_failed)
  1969. return 1;
  1970. else
  1971. return 0;
  1972. }