test.c 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741
  1. /* Copyright (c) 2001-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2011, 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 MS_WINDOWS
  18. /* For mkdir() */
  19. #include <direct.h>
  20. #else
  21. #include <dirent.h>
  22. #endif
  23. /* These macros pull in declarations for some functions and structures that
  24. * are typically file-private. */
  25. #define BUFFERS_PRIVATE
  26. #define CONFIG_PRIVATE
  27. #define GEOIP_PRIVATE
  28. #define ROUTER_PRIVATE
  29. #define CIRCUIT_PRIVATE
  30. /*
  31. * Linux doesn't provide lround in math.h by default, but mac os does...
  32. * It's best just to leave math.h out of the picture entirely.
  33. */
  34. //#include <math.h>
  35. long int lround(double x);
  36. double fabs(double x);
  37. #include "or.h"
  38. #include "buffers.h"
  39. #include "circuitbuild.h"
  40. #include "config.h"
  41. #include "connection_edge.h"
  42. #include "geoip.h"
  43. #include "rendcommon.h"
  44. #include "test.h"
  45. #include "torgzip.h"
  46. #include "mempool.h"
  47. #include "memarea.h"
  48. #include "onion.h"
  49. #include "policies.h"
  50. #include "rephist.h"
  51. #include "routerparse.h"
  52. #ifdef USE_DMALLOC
  53. #include <dmalloc.h>
  54. #include <openssl/crypto.h>
  55. #include "main.h"
  56. #endif
  57. /** Set to true if any unit test has failed. Mostly, this is set by the macros
  58. * in test.h */
  59. int have_failed = 0;
  60. /** Temporary directory (set up by setup_directory) under which we store all
  61. * our files during testing. */
  62. static char temp_dir[256];
  63. static pid_t temp_dir_setup_in_pid = 0;
  64. /** Select and create the temporary directory we'll use to run our unit tests.
  65. * Store it in <b>temp_dir</b>. Exit immediately if we can't create it.
  66. * idempotent. */
  67. static void
  68. setup_directory(void)
  69. {
  70. static int is_setup = 0;
  71. int r;
  72. if (is_setup) return;
  73. #ifdef MS_WINDOWS
  74. {
  75. char buf[MAX_PATH];
  76. const char *tmp = buf;
  77. /* If this fails, we're probably screwed anyway */
  78. if (!GetTempPath(sizeof(buf),buf))
  79. tmp = "c:\\windows\\temp";
  80. tor_snprintf(temp_dir, sizeof(temp_dir),
  81. "%s\\tor_test_%d", tmp, (int)getpid());
  82. r = mkdir(temp_dir);
  83. }
  84. #else
  85. tor_snprintf(temp_dir, sizeof(temp_dir), "/tmp/tor_test_%d", (int) getpid());
  86. r = mkdir(temp_dir, 0700);
  87. #endif
  88. if (r) {
  89. fprintf(stderr, "Can't create directory %s:", temp_dir);
  90. perror("");
  91. exit(1);
  92. }
  93. is_setup = 1;
  94. temp_dir_setup_in_pid = getpid();
  95. }
  96. /** Return a filename relative to our testing temporary directory */
  97. const char *
  98. get_fname(const char *name)
  99. {
  100. static char buf[1024];
  101. setup_directory();
  102. if (!name)
  103. return temp_dir;
  104. tor_snprintf(buf,sizeof(buf),"%s/%s",temp_dir,name);
  105. return buf;
  106. }
  107. /* Remove a directory and all of its subdirectories */
  108. static void
  109. rm_rf(const char *dir)
  110. {
  111. struct stat st;
  112. smartlist_t *elements;
  113. elements = tor_listdir(dir);
  114. if (elements) {
  115. SMARTLIST_FOREACH(elements, const char *, cp,
  116. {
  117. char *tmp = NULL;
  118. tor_asprintf(&tmp, "%s"PATH_SEPARATOR"%s", dir, cp);
  119. if (0 == stat(tmp,&st) && (st.st_mode & S_IFDIR)) {
  120. rm_rf(tmp);
  121. } else {
  122. if (unlink(tmp)) {
  123. fprintf(stderr, "Error removing %s: %s\n", tmp, strerror(errno));
  124. }
  125. }
  126. tor_free(tmp);
  127. });
  128. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  129. smartlist_free(elements);
  130. }
  131. if (rmdir(dir))
  132. fprintf(stderr, "Error removing directory %s: %s\n", dir, strerror(errno));
  133. }
  134. /** Remove all files stored under the temporary directory, and the directory
  135. * itself. Called by atexit(). */
  136. static void
  137. remove_directory(void)
  138. {
  139. if (getpid() != temp_dir_setup_in_pid) {
  140. /* Only clean out the tempdir when the main process is exiting. */
  141. return;
  142. }
  143. rm_rf(temp_dir);
  144. }
  145. /** Define this if unit tests spend too much time generating public keys*/
  146. #undef CACHE_GENERATED_KEYS
  147. static crypto_pk_env_t *pregen_keys[5] = {NULL, NULL, NULL, NULL, NULL};
  148. #define N_PREGEN_KEYS ((int)(sizeof(pregen_keys)/sizeof(pregen_keys[0])))
  149. /** Generate and return a new keypair for use in unit tests. If we're using
  150. * the key cache optimization, we might reuse keys: we only guarantee that
  151. * keys made with distinct values for <b>idx</b> are different. The value of
  152. * <b>idx</b> must be at least 0, and less than N_PREGEN_KEYS. */
  153. crypto_pk_env_t *
  154. pk_generate(int idx)
  155. {
  156. #ifdef CACHE_GENERATED_KEYS
  157. tor_assert(idx < N_PREGEN_KEYS);
  158. if (! pregen_keys[idx]) {
  159. pregen_keys[idx] = crypto_new_pk_env();
  160. tor_assert(!crypto_pk_generate_key(pregen_keys[idx]));
  161. }
  162. return crypto_pk_dup_key(pregen_keys[idx]);
  163. #else
  164. crypto_pk_env_t *result;
  165. (void) idx;
  166. result = crypto_new_pk_env();
  167. tor_assert(!crypto_pk_generate_key(result));
  168. return result;
  169. #endif
  170. }
  171. /** Free all storage used for the cached key optimization. */
  172. static void
  173. free_pregenerated_keys(void)
  174. {
  175. unsigned idx;
  176. for (idx = 0; idx < N_PREGEN_KEYS; ++idx) {
  177. if (pregen_keys[idx]) {
  178. crypto_free_pk_env(pregen_keys[idx]);
  179. pregen_keys[idx] = NULL;
  180. }
  181. }
  182. }
  183. typedef struct socks_test_data_t {
  184. socks_request_t *req;
  185. buf_t *buf;
  186. } socks_test_data_t;
  187. static void *
  188. socks_test_setup(const struct testcase_t *testcase)
  189. {
  190. socks_test_data_t *data = tor_malloc(sizeof(socks_test_data_t));
  191. (void)testcase;
  192. data->buf = buf_new_with_capacity(256);
  193. data->req = socks_request_new();
  194. config_register_addressmaps(get_options());
  195. return data;
  196. }
  197. static int
  198. socks_test_cleanup(const struct testcase_t *testcase, void *ptr)
  199. {
  200. socks_test_data_t *data = ptr;
  201. (void)testcase;
  202. buf_free(data->buf);
  203. socks_request_free(data->req);
  204. tor_free(data);
  205. return 1;
  206. }
  207. const struct testcase_setup_t socks_setup = {
  208. socks_test_setup, socks_test_cleanup
  209. };
  210. #define SOCKS_TEST_INIT() \
  211. socks_test_data_t *testdata = ptr; \
  212. buf_t *buf = testdata->buf; \
  213. socks_request_t *socks = testdata->req;
  214. #define ADD_DATA(buf, s) \
  215. write_to_buf(s, sizeof(s)-1, buf)
  216. static void
  217. socks_request_clear(socks_request_t *socks)
  218. {
  219. tor_free(socks->username);
  220. tor_free(socks->password);
  221. memset(socks, 0, sizeof(socks_request_t));
  222. }
  223. /** Perform unsupported SOCKS 4 commands */
  224. static void
  225. test_socks_4_unsupported_commands(void *ptr)
  226. {
  227. SOCKS_TEST_INIT();
  228. /* SOCKS 4 Send BIND [02] to IP address 2.2.2.2:4369 */
  229. ADD_DATA(buf, "\x04\x02\x11\x11\x02\x02\x02\x02\x00");
  230. test_assert(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
  231. get_options()->SafeSocks) == -1);
  232. test_eq(4, socks->socks_version);
  233. test_eq(0, socks->replylen); /* XXX: shouldn't tor reply? */
  234. done:
  235. ;
  236. }
  237. /** Perform supported SOCKS 4 commands */
  238. static void
  239. test_socks_4_supported_commands(void *ptr)
  240. {
  241. SOCKS_TEST_INIT();
  242. test_eq(0, buf_datalen(buf));
  243. /* SOCKS 4 Send CONNECT [01] to IP address 2.2.2.2:4370 */
  244. ADD_DATA(buf, "\x04\x01\x11\x12\x02\x02\x02\x03\x00");
  245. test_assert(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
  246. get_options()->SafeSocks) == 1);
  247. test_eq(4, socks->socks_version);
  248. test_eq(0, socks->replylen); /* XXX: shouldn't tor reply? */
  249. test_eq(SOCKS_COMMAND_CONNECT, socks->command);
  250. test_streq("2.2.2.3", socks->address);
  251. test_eq(4370, socks->port);
  252. test_assert(socks->got_auth == 0);
  253. test_assert(! socks->username);
  254. test_eq(0, buf_datalen(buf));
  255. socks_request_clear(socks);
  256. /* SOCKS 4 Send CONNECT [01] to IP address 2.2.2.2:4369 with userid*/
  257. ADD_DATA(buf, "\x04\x01\x11\x12\x02\x02\x02\x04me\x00");
  258. test_assert(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
  259. get_options()->SafeSocks) == 1);
  260. test_eq(4, socks->socks_version);
  261. test_eq(0, socks->replylen); /* XXX: shouldn't tor reply? */
  262. test_eq(SOCKS_COMMAND_CONNECT, socks->command);
  263. test_streq("2.2.2.4", socks->address);
  264. test_eq(4370, socks->port);
  265. test_assert(socks->got_auth == 1);
  266. test_assert(socks->username);
  267. test_eq(2, socks->usernamelen);
  268. test_memeq("me", socks->username, 2);
  269. test_eq(0, buf_datalen(buf));
  270. socks_request_clear(socks);
  271. /* SOCKS 4a Send RESOLVE [F0] request for torproject.org */
  272. ADD_DATA(buf, "\x04\xF0\x01\x01\x00\x00\x00\x02me\x00torproject.org\x00");
  273. test_assert(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
  274. get_options()->SafeSocks) == 1);
  275. test_eq(4, socks->socks_version);
  276. test_eq(0, socks->replylen); /* XXX: shouldn't tor reply? */
  277. test_streq("torproject.org", socks->address);
  278. test_eq(0, buf_datalen(buf));
  279. done:
  280. ;
  281. }
  282. /** Perform unsupported SOCKS 5 commands */
  283. static void
  284. test_socks_5_unsupported_commands(void *ptr)
  285. {
  286. SOCKS_TEST_INIT();
  287. /* SOCKS 5 Send unsupported BIND [02] command */
  288. ADD_DATA(buf, "\x05\x02\x00\x01");
  289. test_eq(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
  290. get_options()->SafeSocks), 0);
  291. test_eq(0, buf_datalen(buf));
  292. test_eq(5, socks->socks_version);
  293. test_eq(2, socks->replylen);
  294. test_eq(5, socks->reply[0]);
  295. test_eq(0, socks->reply[1]);
  296. ADD_DATA(buf, "\x05\x02\x00\x01\x02\x02\x02\x01\x01\x01");
  297. test_eq(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
  298. get_options()->SafeSocks), -1);
  299. /* XXX: shouldn't tor reply 'command not supported' [07]? */
  300. buf_clear(buf);
  301. socks_request_clear(socks);
  302. /* SOCKS 5 Send unsupported UDP_ASSOCIATE [03] command */
  303. ADD_DATA(buf, "\x05\x03\x00\x01\x02");
  304. test_eq(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
  305. get_options()->SafeSocks), 0);
  306. test_eq(5, socks->socks_version);
  307. test_eq(2, socks->replylen);
  308. test_eq(5, socks->reply[0]);
  309. test_eq(0, socks->reply[1]);
  310. ADD_DATA(buf, "\x05\x03\x00\x01\x02\x02\x02\x01\x01\x01");
  311. test_eq(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
  312. get_options()->SafeSocks), -1);
  313. /* XXX: shouldn't tor reply 'command not supported' [07]? */
  314. done:
  315. ;
  316. }
  317. /** Perform supported SOCKS 5 commands */
  318. static void
  319. test_socks_5_supported_commands(void *ptr)
  320. {
  321. SOCKS_TEST_INIT();
  322. /* SOCKS 5 Send CONNECT [01] to IP address 2.2.2.2:4369 */
  323. ADD_DATA(buf, "\x05\x01\x00");
  324. test_eq(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
  325. get_options()->SafeSocks), 0);
  326. test_eq(5, socks->socks_version);
  327. test_eq(2, socks->replylen);
  328. test_eq(5, socks->reply[0]);
  329. test_eq(0, socks->reply[1]);
  330. ADD_DATA(buf, "\x05\x01\x00\x01\x02\x02\x02\x02\x11\x11");
  331. test_eq(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
  332. get_options()->SafeSocks), 1);
  333. test_streq("2.2.2.2", socks->address);
  334. test_eq(4369, socks->port);
  335. test_eq(0, buf_datalen(buf));
  336. socks_request_clear(socks);
  337. /* SOCKS 5 Send CONNECT [01] to FQDN torproject.org:4369 */
  338. ADD_DATA(buf, "\x05\x01\x00");
  339. ADD_DATA(buf, "\x05\x01\x00\x03\x0Etorproject.org\x11\x11");
  340. test_eq(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
  341. get_options()->SafeSocks), 1);
  342. test_eq(5, socks->socks_version);
  343. test_eq(2, socks->replylen);
  344. test_eq(5, socks->reply[0]);
  345. test_eq(0, socks->reply[1]);
  346. test_streq("torproject.org", socks->address);
  347. test_eq(4369, socks->port);
  348. test_eq(0, buf_datalen(buf));
  349. socks_request_clear(socks);
  350. /* SOCKS 5 Send RESOLVE [F0] request for torproject.org:4369 */
  351. ADD_DATA(buf, "\x05\x01\x00");
  352. ADD_DATA(buf, "\x05\xF0\x00\x03\x0Etorproject.org\x01\x02");
  353. test_assert(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
  354. get_options()->SafeSocks) == 1);
  355. test_eq(5, socks->socks_version);
  356. test_eq(2, socks->replylen);
  357. test_eq(5, socks->reply[0]);
  358. test_eq(0, socks->reply[1]);
  359. test_streq("torproject.org", socks->address);
  360. test_eq(0, buf_datalen(buf));
  361. socks_request_clear(socks);
  362. /* SOCKS 5 Send RESOLVE_PTR [F1] for IP address 2.2.2.5 */
  363. ADD_DATA(buf, "\x05\x01\x00");
  364. ADD_DATA(buf, "\x05\xF1\x00\x01\x02\x02\x02\x05\x01\x03");
  365. test_assert(fetch_from_buf_socks(buf, socks, get_options()->TestSocks,
  366. get_options()->SafeSocks) == 1);
  367. test_eq(5, socks->socks_version);
  368. test_eq(2, socks->replylen);
  369. test_eq(5, socks->reply[0]);
  370. test_eq(0, socks->reply[1]);
  371. test_streq("2.2.2.5", socks->address);
  372. test_eq(0, buf_datalen(buf));
  373. done:
  374. ;
  375. }
  376. /** Perform SOCKS 5 authentication */
  377. static void
  378. test_socks_5_no_authenticate(void *ptr)
  379. {
  380. SOCKS_TEST_INIT();
  381. /*SOCKS 5 No Authentication */
  382. ADD_DATA(buf,"\x05\x01\x00");
  383. test_assert(!fetch_from_buf_socks(buf, socks,
  384. get_options()->TestSocks,
  385. get_options()->SafeSocks));
  386. test_eq(2, socks->replylen);
  387. test_eq(5, socks->reply[0]);
  388. test_eq(SOCKS_NO_AUTH, socks->reply[1]);
  389. test_eq(0, buf_datalen(buf));
  390. /*SOCKS 5 Send username/password anyway - pretend to be broken */
  391. ADD_DATA(buf,"\x01\x02\x01\x01\x02\x01\x01");
  392. test_assert(!fetch_from_buf_socks(buf, socks,
  393. get_options()->TestSocks,
  394. get_options()->SafeSocks));
  395. test_eq(5, socks->socks_version);
  396. test_eq(2, socks->replylen);
  397. test_eq(5, socks->reply[0]);
  398. test_eq(0, socks->reply[1]);
  399. test_eq(2, socks->usernamelen);
  400. test_eq(2, socks->passwordlen);
  401. test_memeq("\x01\x01", socks->username, 2);
  402. test_memeq("\x01\x01", socks->password, 2);
  403. done:
  404. ;
  405. }
  406. /** Perform SOCKS 5 authentication */
  407. static void
  408. test_socks_5_authenticate(void *ptr)
  409. {
  410. SOCKS_TEST_INIT();
  411. /* SOCKS 5 Negotiate username/password authentication */
  412. ADD_DATA(buf, "\x05\x01\x02");
  413. test_assert(!fetch_from_buf_socks(buf, socks,
  414. get_options()->TestSocks,
  415. get_options()->SafeSocks));
  416. test_eq(2, socks->replylen);
  417. test_eq(5, socks->reply[0]);
  418. test_eq(SOCKS_USER_PASS, socks->reply[1]);
  419. test_eq(5, socks->socks_version);
  420. test_eq(0, buf_datalen(buf));
  421. /* SOCKS 5 Send username/password */
  422. ADD_DATA(buf, "\x01\x02me\x08mypasswd");
  423. test_assert(!fetch_from_buf_socks(buf, socks,
  424. get_options()->TestSocks,
  425. get_options()->SafeSocks));
  426. test_eq(5, socks->socks_version);
  427. test_eq(2, socks->replylen);
  428. test_eq(5, socks->reply[0]);
  429. test_eq(0, socks->reply[1]);
  430. test_eq(2, socks->usernamelen);
  431. test_eq(8, socks->passwordlen);
  432. test_memeq("me", socks->username, 2);
  433. test_memeq("mypasswd", socks->password, 8);
  434. done:
  435. ;
  436. }
  437. /** Perform SOCKS 5 authentication and send data all in one go */
  438. static void
  439. test_socks_5_authenticate_with_data(void *ptr)
  440. {
  441. SOCKS_TEST_INIT();
  442. /* SOCKS 5 Negotiate username/password authentication */
  443. ADD_DATA(buf, "\x05\x01\x02");
  444. test_assert(!fetch_from_buf_socks(buf, socks,
  445. get_options()->TestSocks,
  446. get_options()->SafeSocks));
  447. test_eq(2, socks->replylen);
  448. test_eq(5, socks->reply[0]);
  449. test_eq(SOCKS_USER_PASS, socks->reply[1]);
  450. test_eq(5, socks->socks_version);
  451. test_eq(0, buf_datalen(buf));
  452. /* SOCKS 5 Send username/password */
  453. /* SOCKS 5 Send CONNECT [01] to IP address 2.2.2.2:4369 */
  454. ADD_DATA(buf, "\x01\x02me\x03you\x05\x01\x00\x01\x02\x02\x02\x02\x11\x11");
  455. test_assert(fetch_from_buf_socks(buf, socks,
  456. get_options()->TestSocks,
  457. get_options()->SafeSocks) == 1);
  458. test_eq(5, socks->socks_version);
  459. test_eq(2, socks->replylen);
  460. test_eq(5, socks->reply[0]);
  461. test_eq(0, socks->reply[1]);
  462. test_streq("2.2.2.2", socks->address);
  463. test_eq(4369, socks->port);
  464. test_eq(2, socks->usernamelen);
  465. test_eq(3, socks->passwordlen);
  466. test_memeq("me", socks->username, 2);
  467. test_memeq("you", socks->password, 3);
  468. done:
  469. ;
  470. }
  471. /** Perform SOCKS 5 authentication before method negotiated */
  472. static void
  473. test_socks_5_auth_before_negotiation(void *ptr)
  474. {
  475. SOCKS_TEST_INIT();
  476. /* SOCKS 5 Send username/password */
  477. ADD_DATA(buf, "\x01\x02me\x02me");
  478. test_assert(fetch_from_buf_socks(buf, socks,
  479. get_options()->TestSocks,
  480. get_options()->SafeSocks) == -1);
  481. test_eq(0, socks->socks_version);
  482. test_eq(0, socks->replylen);
  483. test_eq(0, socks->reply[0]);
  484. test_eq(0, socks->reply[1]);
  485. done:
  486. ;
  487. }
  488. /** Run unit tests for buffers.c */
  489. static void
  490. test_buffers(void)
  491. {
  492. char str[256];
  493. char str2[256];
  494. buf_t *buf = NULL, *buf2 = NULL;
  495. const char *cp;
  496. int j;
  497. size_t r;
  498. /****
  499. * buf_new
  500. ****/
  501. if (!(buf = buf_new()))
  502. test_fail();
  503. //test_eq(buf_capacity(buf), 4096);
  504. test_eq(buf_datalen(buf), 0);
  505. /****
  506. * General pointer frobbing
  507. */
  508. for (j=0;j<256;++j) {
  509. str[j] = (char)j;
  510. }
  511. write_to_buf(str, 256, buf);
  512. write_to_buf(str, 256, buf);
  513. test_eq(buf_datalen(buf), 512);
  514. fetch_from_buf(str2, 200, buf);
  515. test_memeq(str, str2, 200);
  516. test_eq(buf_datalen(buf), 312);
  517. memset(str2, 0, sizeof(str2));
  518. fetch_from_buf(str2, 256, buf);
  519. test_memeq(str+200, str2, 56);
  520. test_memeq(str, str2+56, 200);
  521. test_eq(buf_datalen(buf), 56);
  522. memset(str2, 0, sizeof(str2));
  523. /* Okay, now we should be 512 bytes into the 4096-byte buffer. If we add
  524. * another 3584 bytes, we hit the end. */
  525. for (j=0;j<15;++j) {
  526. write_to_buf(str, 256, buf);
  527. }
  528. assert_buf_ok(buf);
  529. test_eq(buf_datalen(buf), 3896);
  530. fetch_from_buf(str2, 56, buf);
  531. test_eq(buf_datalen(buf), 3840);
  532. test_memeq(str+200, str2, 56);
  533. for (j=0;j<15;++j) {
  534. memset(str2, 0, sizeof(str2));
  535. fetch_from_buf(str2, 256, buf);
  536. test_memeq(str, str2, 256);
  537. }
  538. test_eq(buf_datalen(buf), 0);
  539. buf_free(buf);
  540. buf = NULL;
  541. /* Okay, now make sure growing can work. */
  542. buf = buf_new_with_capacity(16);
  543. //test_eq(buf_capacity(buf), 16);
  544. write_to_buf(str+1, 255, buf);
  545. //test_eq(buf_capacity(buf), 256);
  546. fetch_from_buf(str2, 254, buf);
  547. test_memeq(str+1, str2, 254);
  548. //test_eq(buf_capacity(buf), 256);
  549. assert_buf_ok(buf);
  550. write_to_buf(str, 32, buf);
  551. //test_eq(buf_capacity(buf), 256);
  552. assert_buf_ok(buf);
  553. write_to_buf(str, 256, buf);
  554. assert_buf_ok(buf);
  555. //test_eq(buf_capacity(buf), 512);
  556. test_eq(buf_datalen(buf), 33+256);
  557. fetch_from_buf(str2, 33, buf);
  558. test_eq(*str2, str[255]);
  559. test_memeq(str2+1, str, 32);
  560. //test_eq(buf_capacity(buf), 512);
  561. test_eq(buf_datalen(buf), 256);
  562. fetch_from_buf(str2, 256, buf);
  563. test_memeq(str, str2, 256);
  564. /* now try shrinking: case 1. */
  565. buf_free(buf);
  566. buf = buf_new_with_capacity(33668);
  567. for (j=0;j<67;++j) {
  568. write_to_buf(str,255, buf);
  569. }
  570. //test_eq(buf_capacity(buf), 33668);
  571. test_eq(buf_datalen(buf), 17085);
  572. for (j=0; j < 40; ++j) {
  573. fetch_from_buf(str2, 255,buf);
  574. test_memeq(str2, str, 255);
  575. }
  576. /* now try shrinking: case 2. */
  577. buf_free(buf);
  578. buf = buf_new_with_capacity(33668);
  579. for (j=0;j<67;++j) {
  580. write_to_buf(str,255, buf);
  581. }
  582. for (j=0; j < 20; ++j) {
  583. fetch_from_buf(str2, 255,buf);
  584. test_memeq(str2, str, 255);
  585. }
  586. for (j=0;j<80;++j) {
  587. write_to_buf(str,255, buf);
  588. }
  589. //test_eq(buf_capacity(buf),33668);
  590. for (j=0; j < 120; ++j) {
  591. fetch_from_buf(str2, 255,buf);
  592. test_memeq(str2, str, 255);
  593. }
  594. /* Move from buf to buf. */
  595. buf_free(buf);
  596. buf = buf_new_with_capacity(4096);
  597. buf2 = buf_new_with_capacity(4096);
  598. for (j=0;j<100;++j)
  599. write_to_buf(str, 255, buf);
  600. test_eq(buf_datalen(buf), 25500);
  601. for (j=0;j<100;++j) {
  602. r = 10;
  603. move_buf_to_buf(buf2, buf, &r);
  604. test_eq(r, 0);
  605. }
  606. test_eq(buf_datalen(buf), 24500);
  607. test_eq(buf_datalen(buf2), 1000);
  608. for (j=0;j<3;++j) {
  609. fetch_from_buf(str2, 255, buf2);
  610. test_memeq(str2, str, 255);
  611. }
  612. r = 8192; /*big move*/
  613. move_buf_to_buf(buf2, buf, &r);
  614. test_eq(r, 0);
  615. r = 30000; /* incomplete move */
  616. move_buf_to_buf(buf2, buf, &r);
  617. test_eq(r, 13692);
  618. for (j=0;j<97;++j) {
  619. fetch_from_buf(str2, 255, buf2);
  620. test_memeq(str2, str, 255);
  621. }
  622. buf_free(buf);
  623. buf_free(buf2);
  624. buf = buf2 = NULL;
  625. buf = buf_new_with_capacity(5);
  626. cp = "Testing. This is a moderately long Testing string.";
  627. for (j = 0; cp[j]; j++)
  628. write_to_buf(cp+j, 1, buf);
  629. test_eq(0, buf_find_string_offset(buf, "Testing", 7));
  630. test_eq(1, buf_find_string_offset(buf, "esting", 6));
  631. test_eq(1, buf_find_string_offset(buf, "est", 3));
  632. test_eq(39, buf_find_string_offset(buf, "ing str", 7));
  633. test_eq(35, buf_find_string_offset(buf, "Testing str", 11));
  634. test_eq(32, buf_find_string_offset(buf, "ng ", 3));
  635. test_eq(43, buf_find_string_offset(buf, "string.", 7));
  636. test_eq(-1, buf_find_string_offset(buf, "shrdlu", 6));
  637. test_eq(-1, buf_find_string_offset(buf, "Testing thing", 13));
  638. test_eq(-1, buf_find_string_offset(buf, "ngx", 3));
  639. buf_free(buf);
  640. buf = NULL;
  641. done:
  642. if (buf)
  643. buf_free(buf);
  644. if (buf2)
  645. buf_free(buf2);
  646. }
  647. /** Run unit tests for the onion handshake code. */
  648. static void
  649. test_onion_handshake(void)
  650. {
  651. /* client-side */
  652. crypto_dh_env_t *c_dh = NULL;
  653. char c_buf[ONIONSKIN_CHALLENGE_LEN];
  654. char c_keys[40];
  655. /* server-side */
  656. char s_buf[ONIONSKIN_REPLY_LEN];
  657. char s_keys[40];
  658. /* shared */
  659. crypto_pk_env_t *pk = NULL;
  660. pk = pk_generate(0);
  661. /* client handshake 1. */
  662. memset(c_buf, 0, ONIONSKIN_CHALLENGE_LEN);
  663. test_assert(! onion_skin_create(pk, &c_dh, c_buf));
  664. /* server handshake */
  665. memset(s_buf, 0, ONIONSKIN_REPLY_LEN);
  666. memset(s_keys, 0, 40);
  667. test_assert(! onion_skin_server_handshake(c_buf, pk, NULL,
  668. s_buf, s_keys, 40));
  669. /* client handshake 2 */
  670. memset(c_keys, 0, 40);
  671. test_assert(! onion_skin_client_handshake(c_dh, s_buf, c_keys, 40));
  672. if (memcmp(c_keys, s_keys, 40)) {
  673. puts("Aiiiie");
  674. exit(1);
  675. }
  676. test_memeq(c_keys, s_keys, 40);
  677. memset(s_buf, 0, 40);
  678. test_memneq(c_keys, s_buf, 40);
  679. done:
  680. if (c_dh)
  681. crypto_dh_free(c_dh);
  682. if (pk)
  683. crypto_free_pk_env(pk);
  684. }
  685. static void
  686. test_circuit_timeout(void)
  687. {
  688. /* Plan:
  689. * 1. Generate 1000 samples
  690. * 2. Estimate parameters
  691. * 3. If difference, repeat
  692. * 4. Save state
  693. * 5. load state
  694. * 6. Estimate parameters
  695. * 7. compare differences
  696. */
  697. circuit_build_times_t initial;
  698. circuit_build_times_t estimate;
  699. circuit_build_times_t final;
  700. double timeout1, timeout2;
  701. or_state_t state;
  702. int i, runs;
  703. double close_ms;
  704. circuit_build_times_init(&initial);
  705. circuit_build_times_init(&estimate);
  706. circuit_build_times_init(&final);
  707. memset(&state, 0, sizeof(or_state_t));
  708. circuitbuild_running_unit_tests();
  709. #define timeout0 (build_time_t)(30*1000.0)
  710. initial.Xm = 3000;
  711. circuit_build_times_initial_alpha(&initial,
  712. CBT_DEFAULT_QUANTILE_CUTOFF/100.0,
  713. timeout0);
  714. close_ms = MAX(circuit_build_times_calculate_timeout(&initial,
  715. CBT_DEFAULT_CLOSE_QUANTILE/100.0),
  716. CBT_DEFAULT_TIMEOUT_INITIAL_VALUE);
  717. do {
  718. for (i=0; i < CBT_DEFAULT_MIN_CIRCUITS_TO_OBSERVE; i++) {
  719. build_time_t sample = circuit_build_times_generate_sample(&initial,0,1);
  720. if (sample > close_ms) {
  721. circuit_build_times_add_time(&estimate, CBT_BUILD_ABANDONED);
  722. } else {
  723. circuit_build_times_add_time(&estimate, sample);
  724. }
  725. }
  726. circuit_build_times_update_alpha(&estimate);
  727. timeout1 = circuit_build_times_calculate_timeout(&estimate,
  728. CBT_DEFAULT_QUANTILE_CUTOFF/100.0);
  729. circuit_build_times_set_timeout(&estimate);
  730. log_notice(LD_CIRC, "Timeout1 is %lf, Xm is %d", timeout1, estimate.Xm);
  731. /* 2% error */
  732. } while (fabs(circuit_build_times_cdf(&initial, timeout0) -
  733. circuit_build_times_cdf(&initial, timeout1)) > 0.02);
  734. test_assert(estimate.total_build_times <= CBT_NCIRCUITS_TO_OBSERVE);
  735. circuit_build_times_update_state(&estimate, &state);
  736. test_assert(circuit_build_times_parse_state(&final, &state) == 0);
  737. circuit_build_times_update_alpha(&final);
  738. timeout2 = circuit_build_times_calculate_timeout(&final,
  739. CBT_DEFAULT_QUANTILE_CUTOFF/100.0);
  740. circuit_build_times_set_timeout(&final);
  741. log_notice(LD_CIRC, "Timeout2 is %lf, Xm is %d", timeout2, final.Xm);
  742. /* 5% here because some accuracy is lost due to histogram conversion */
  743. test_assert(fabs(circuit_build_times_cdf(&initial, timeout0) -
  744. circuit_build_times_cdf(&initial, timeout2)) < 0.05);
  745. for (runs = 0; runs < 50; runs++) {
  746. int build_times_idx = 0;
  747. int total_build_times = 0;
  748. final.close_ms = final.timeout_ms = CBT_DEFAULT_TIMEOUT_INITIAL_VALUE;
  749. estimate.close_ms = estimate.timeout_ms
  750. = CBT_DEFAULT_TIMEOUT_INITIAL_VALUE;
  751. for (i = 0; i < CBT_DEFAULT_RECENT_CIRCUITS*2; i++) {
  752. circuit_build_times_network_circ_success(&estimate);
  753. circuit_build_times_add_time(&estimate,
  754. circuit_build_times_generate_sample(&estimate, 0,
  755. CBT_DEFAULT_QUANTILE_CUTOFF/100.0));
  756. circuit_build_times_network_circ_success(&estimate);
  757. circuit_build_times_add_time(&final,
  758. circuit_build_times_generate_sample(&final, 0,
  759. CBT_DEFAULT_QUANTILE_CUTOFF/100.0));
  760. }
  761. test_assert(!circuit_build_times_network_check_changed(&estimate));
  762. test_assert(!circuit_build_times_network_check_changed(&final));
  763. /* Reset liveness to be non-live */
  764. final.liveness.network_last_live = 0;
  765. estimate.liveness.network_last_live = 0;
  766. build_times_idx = estimate.build_times_idx;
  767. total_build_times = estimate.total_build_times;
  768. test_assert(circuit_build_times_network_check_live(&estimate));
  769. test_assert(circuit_build_times_network_check_live(&final));
  770. circuit_build_times_count_close(&estimate, 0,
  771. (time_t)(approx_time()-estimate.close_ms/1000.0-1));
  772. circuit_build_times_count_close(&final, 0,
  773. (time_t)(approx_time()-final.close_ms/1000.0-1));
  774. test_assert(!circuit_build_times_network_check_live(&estimate));
  775. test_assert(!circuit_build_times_network_check_live(&final));
  776. log_info(LD_CIRC, "idx: %d %d, tot: %d %d",
  777. build_times_idx, estimate.build_times_idx,
  778. total_build_times, estimate.total_build_times);
  779. /* Check rollback index. Should match top of loop. */
  780. test_assert(build_times_idx == estimate.build_times_idx);
  781. // This can fail if estimate.total_build_times == 1000, because
  782. // in that case, rewind actually causes us to lose timeouts
  783. if (total_build_times != CBT_NCIRCUITS_TO_OBSERVE)
  784. test_assert(total_build_times == estimate.total_build_times);
  785. /* Now simulate that the network has become live and we need
  786. * a change */
  787. circuit_build_times_network_is_live(&estimate);
  788. circuit_build_times_network_is_live(&final);
  789. for (i = 0; i < CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT; i++) {
  790. circuit_build_times_count_timeout(&estimate, 1);
  791. if (i < CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT-1) {
  792. circuit_build_times_count_timeout(&final, 1);
  793. }
  794. }
  795. test_assert(estimate.liveness.after_firsthop_idx == 0);
  796. test_assert(final.liveness.after_firsthop_idx ==
  797. CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT-1);
  798. test_assert(circuit_build_times_network_check_live(&estimate));
  799. test_assert(circuit_build_times_network_check_live(&final));
  800. circuit_build_times_count_timeout(&final, 1);
  801. }
  802. done:
  803. return;
  804. }
  805. /** Helper: Parse the exit policy string in <b>policy_str</b>, and make sure
  806. * that policies_summarize() produces the string <b>expected_summary</b> from
  807. * it. */
  808. static void
  809. test_policy_summary_helper(const char *policy_str,
  810. const char *expected_summary)
  811. {
  812. config_line_t line;
  813. smartlist_t *policy = smartlist_create();
  814. char *summary = NULL;
  815. int r;
  816. short_policy_t *short_policy = NULL;
  817. line.key = (char*)"foo";
  818. line.value = (char *)policy_str;
  819. line.next = NULL;
  820. r = policies_parse_exit_policy(&line, &policy, 0, NULL, 1);
  821. test_eq(r, 0);
  822. summary = policy_summarize(policy);
  823. test_assert(summary != NULL);
  824. test_streq(summary, expected_summary);
  825. short_policy = parse_short_policy(summary);
  826. tt_assert(short_policy);
  827. done:
  828. tor_free(summary);
  829. if (policy)
  830. addr_policy_list_free(policy);
  831. short_policy_free(short_policy);
  832. }
  833. /** Run unit tests for generating summary lines of exit policies */
  834. static void
  835. test_policies(void)
  836. {
  837. int i;
  838. smartlist_t *policy = NULL, *policy2 = NULL, *policy3 = NULL,
  839. *policy4 = NULL, *policy5 = NULL, *policy6 = NULL,
  840. *policy7 = NULL;
  841. addr_policy_t *p;
  842. tor_addr_t tar;
  843. config_line_t line;
  844. smartlist_t *sm = NULL;
  845. char *policy_str = NULL;
  846. policy = smartlist_create();
  847. p = router_parse_addr_policy_item_from_string("reject 192.168.0.0/16:*",-1);
  848. test_assert(p != NULL);
  849. test_eq(ADDR_POLICY_REJECT, p->policy_type);
  850. tor_addr_from_ipv4h(&tar, 0xc0a80000u);
  851. test_eq(0, tor_addr_compare(&p->addr, &tar, CMP_EXACT));
  852. test_eq(16, p->maskbits);
  853. test_eq(1, p->prt_min);
  854. test_eq(65535, p->prt_max);
  855. smartlist_add(policy, p);
  856. tor_addr_from_ipv4h(&tar, 0x01020304u);
  857. test_assert(ADDR_POLICY_ACCEPTED ==
  858. compare_tor_addr_to_addr_policy(&tar, 2, policy));
  859. tor_addr_make_unspec(&tar);
  860. test_assert(ADDR_POLICY_PROBABLY_ACCEPTED ==
  861. compare_tor_addr_to_addr_policy(&tar, 2, policy));
  862. tor_addr_from_ipv4h(&tar, 0xc0a80102);
  863. test_assert(ADDR_POLICY_REJECTED ==
  864. compare_tor_addr_to_addr_policy(&tar, 2, policy));
  865. test_assert(0 == policies_parse_exit_policy(NULL, &policy2, 1, NULL, 1));
  866. test_assert(policy2);
  867. policy3 = smartlist_create();
  868. p = router_parse_addr_policy_item_from_string("reject *:*",-1);
  869. test_assert(p != NULL);
  870. smartlist_add(policy3, p);
  871. p = router_parse_addr_policy_item_from_string("accept *:*",-1);
  872. test_assert(p != NULL);
  873. smartlist_add(policy3, p);
  874. policy4 = smartlist_create();
  875. p = router_parse_addr_policy_item_from_string("accept *:443",-1);
  876. test_assert(p != NULL);
  877. smartlist_add(policy4, p);
  878. p = router_parse_addr_policy_item_from_string("accept *:443",-1);
  879. test_assert(p != NULL);
  880. smartlist_add(policy4, p);
  881. policy5 = smartlist_create();
  882. p = router_parse_addr_policy_item_from_string("reject 0.0.0.0/8:*",-1);
  883. test_assert(p != NULL);
  884. smartlist_add(policy5, p);
  885. p = router_parse_addr_policy_item_from_string("reject 169.254.0.0/16:*",-1);
  886. test_assert(p != NULL);
  887. smartlist_add(policy5, p);
  888. p = router_parse_addr_policy_item_from_string("reject 127.0.0.0/8:*",-1);
  889. test_assert(p != NULL);
  890. smartlist_add(policy5, p);
  891. p = router_parse_addr_policy_item_from_string("reject 192.168.0.0/16:*",-1);
  892. test_assert(p != NULL);
  893. smartlist_add(policy5, p);
  894. p = router_parse_addr_policy_item_from_string("reject 10.0.0.0/8:*",-1);
  895. test_assert(p != NULL);
  896. smartlist_add(policy5, p);
  897. p = router_parse_addr_policy_item_from_string("reject 172.16.0.0/12:*",-1);
  898. test_assert(p != NULL);
  899. smartlist_add(policy5, p);
  900. p = router_parse_addr_policy_item_from_string("reject 80.190.250.90:*",-1);
  901. test_assert(p != NULL);
  902. smartlist_add(policy5, p);
  903. p = router_parse_addr_policy_item_from_string("reject *:1-65534",-1);
  904. test_assert(p != NULL);
  905. smartlist_add(policy5, p);
  906. p = router_parse_addr_policy_item_from_string("reject *:65535",-1);
  907. test_assert(p != NULL);
  908. smartlist_add(policy5, p);
  909. p = router_parse_addr_policy_item_from_string("accept *:1-65535",-1);
  910. test_assert(p != NULL);
  911. smartlist_add(policy5, p);
  912. policy6 = smartlist_create();
  913. p = router_parse_addr_policy_item_from_string("accept 43.3.0.0/9:*",-1);
  914. test_assert(p != NULL);
  915. smartlist_add(policy6, p);
  916. policy7 = smartlist_create();
  917. p = router_parse_addr_policy_item_from_string("accept 0.0.0.0/8:*",-1);
  918. test_assert(p != NULL);
  919. smartlist_add(policy7, p);
  920. test_assert(!exit_policy_is_general_exit(policy));
  921. test_assert(exit_policy_is_general_exit(policy2));
  922. test_assert(!exit_policy_is_general_exit(NULL));
  923. test_assert(!exit_policy_is_general_exit(policy3));
  924. test_assert(!exit_policy_is_general_exit(policy4));
  925. test_assert(!exit_policy_is_general_exit(policy5));
  926. test_assert(!exit_policy_is_general_exit(policy6));
  927. test_assert(!exit_policy_is_general_exit(policy7));
  928. test_assert(cmp_addr_policies(policy, policy2));
  929. test_assert(cmp_addr_policies(policy, NULL));
  930. test_assert(!cmp_addr_policies(policy2, policy2));
  931. test_assert(!cmp_addr_policies(NULL, NULL));
  932. test_assert(!policy_is_reject_star(policy2));
  933. test_assert(policy_is_reject_star(policy));
  934. test_assert(policy_is_reject_star(NULL));
  935. addr_policy_list_free(policy);
  936. policy = NULL;
  937. /* make sure compacting logic works. */
  938. policy = NULL;
  939. line.key = (char*)"foo";
  940. line.value = (char*)"accept *:80,reject private:*,reject *:*";
  941. line.next = NULL;
  942. test_assert(0 == policies_parse_exit_policy(&line, &policy, 0, NULL, 1));
  943. test_assert(policy);
  944. //test_streq(policy->string, "accept *:80");
  945. //test_streq(policy->next->string, "reject *:*");
  946. test_eq(smartlist_len(policy), 2);
  947. /* test policy summaries */
  948. /* check if we properly ignore private IP addresses */
  949. test_policy_summary_helper("reject 192.168.0.0/16:*,"
  950. "reject 0.0.0.0/8:*,"
  951. "reject 10.0.0.0/8:*,"
  952. "accept *:10-30,"
  953. "accept *:90,"
  954. "reject *:*",
  955. "accept 10-30,90");
  956. /* check all accept policies, and proper counting of rejects */
  957. test_policy_summary_helper("reject 11.0.0.0/9:80,"
  958. "reject 12.0.0.0/9:80,"
  959. "reject 13.0.0.0/9:80,"
  960. "reject 14.0.0.0/9:80,"
  961. "accept *:*", "accept 1-65535");
  962. test_policy_summary_helper("reject 11.0.0.0/9:80,"
  963. "reject 12.0.0.0/9:80,"
  964. "reject 13.0.0.0/9:80,"
  965. "reject 14.0.0.0/9:80,"
  966. "reject 15.0.0.0:81,"
  967. "accept *:*", "accept 1-65535");
  968. test_policy_summary_helper("reject 11.0.0.0/9:80,"
  969. "reject 12.0.0.0/9:80,"
  970. "reject 13.0.0.0/9:80,"
  971. "reject 14.0.0.0/9:80,"
  972. "reject 15.0.0.0:80,"
  973. "accept *:*",
  974. "reject 80");
  975. /* no exits */
  976. test_policy_summary_helper("accept 11.0.0.0/9:80,"
  977. "reject *:*",
  978. "reject 1-65535");
  979. /* port merging */
  980. test_policy_summary_helper("accept *:80,"
  981. "accept *:81,"
  982. "accept *:100-110,"
  983. "accept *:111,"
  984. "reject *:*",
  985. "accept 80-81,100-111");
  986. /* border ports */
  987. test_policy_summary_helper("accept *:1,"
  988. "accept *:3,"
  989. "accept *:65535,"
  990. "reject *:*",
  991. "accept 1,3,65535");
  992. /* holes */
  993. test_policy_summary_helper("accept *:1,"
  994. "accept *:3,"
  995. "accept *:5,"
  996. "accept *:7,"
  997. "reject *:*",
  998. "accept 1,3,5,7");
  999. test_policy_summary_helper("reject *:1,"
  1000. "reject *:3,"
  1001. "reject *:5,"
  1002. "reject *:7,"
  1003. "accept *:*",
  1004. "reject 1,3,5,7");
  1005. /* truncation ports */
  1006. sm = smartlist_create();
  1007. for (i=1; i<2000; i+=2) {
  1008. char buf[POLICY_BUF_LEN];
  1009. tor_snprintf(buf, sizeof(buf), "reject *:%d", i);
  1010. smartlist_add(sm, tor_strdup(buf));
  1011. }
  1012. smartlist_add(sm, tor_strdup("accept *:*"));
  1013. policy_str = smartlist_join_strings(sm, ",", 0, NULL);
  1014. test_policy_summary_helper( policy_str,
  1015. "accept 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,"
  1016. "46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,"
  1017. "92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,"
  1018. "130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,"
  1019. "166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198,200,"
  1020. "202,204,206,208,210,212,214,216,218,220,222,224,226,228,230,232,234,236,"
  1021. "238,240,242,244,246,248,250,252,254,256,258,260,262,264,266,268,270,272,"
  1022. "274,276,278,280,282,284,286,288,290,292,294,296,298,300,302,304,306,308,"
  1023. "310,312,314,316,318,320,322,324,326,328,330,332,334,336,338,340,342,344,"
  1024. "346,348,350,352,354,356,358,360,362,364,366,368,370,372,374,376,378,380,"
  1025. "382,384,386,388,390,392,394,396,398,400,402,404,406,408,410,412,414,416,"
  1026. "418,420,422,424,426,428,430,432,434,436,438,440,442,444,446,448,450,452,"
  1027. "454,456,458,460,462,464,466,468,470,472,474,476,478,480,482,484,486,488,"
  1028. "490,492,494,496,498,500,502,504,506,508,510,512,514,516,518,520,522");
  1029. done:
  1030. addr_policy_list_free(policy);
  1031. addr_policy_list_free(policy2);
  1032. addr_policy_list_free(policy3);
  1033. addr_policy_list_free(policy4);
  1034. addr_policy_list_free(policy5);
  1035. addr_policy_list_free(policy6);
  1036. addr_policy_list_free(policy7);
  1037. tor_free(policy_str);
  1038. if (sm) {
  1039. SMARTLIST_FOREACH(sm, char *, s, tor_free(s));
  1040. smartlist_free(sm);
  1041. }
  1042. }
  1043. /** Run AES performance benchmarks. */
  1044. static void
  1045. bench_aes(void)
  1046. {
  1047. int len, i;
  1048. char *b1, *b2;
  1049. crypto_cipher_env_t *c;
  1050. struct timeval start, end;
  1051. const int iters = 100000;
  1052. uint64_t nsec;
  1053. c = crypto_new_cipher_env();
  1054. crypto_cipher_generate_key(c);
  1055. crypto_cipher_encrypt_init_cipher(c);
  1056. for (len = 1; len <= 8192; len *= 2) {
  1057. b1 = tor_malloc_zero(len);
  1058. b2 = tor_malloc_zero(len);
  1059. tor_gettimeofday(&start);
  1060. for (i = 0; i < iters; ++i) {
  1061. crypto_cipher_encrypt(c, b1, b2, len);
  1062. }
  1063. tor_gettimeofday(&end);
  1064. tor_free(b1);
  1065. tor_free(b2);
  1066. nsec = (uint64_t) tv_udiff(&start,&end);
  1067. nsec *= 1000;
  1068. nsec /= (iters*len);
  1069. printf("%d bytes: "U64_FORMAT" nsec per byte\n", len,
  1070. U64_PRINTF_ARG(nsec));
  1071. }
  1072. crypto_free_cipher_env(c);
  1073. }
  1074. /** Run digestmap_t performance benchmarks. */
  1075. static void
  1076. bench_dmap(void)
  1077. {
  1078. smartlist_t *sl = smartlist_create();
  1079. smartlist_t *sl2 = smartlist_create();
  1080. struct timeval start, end, pt2, pt3, pt4;
  1081. const int iters = 10000;
  1082. const int elts = 4000;
  1083. const int fpostests = 1000000;
  1084. char d[20];
  1085. int i,n=0, fp = 0;
  1086. digestmap_t *dm = digestmap_new();
  1087. digestset_t *ds = digestset_new(elts);
  1088. for (i = 0; i < elts; ++i) {
  1089. crypto_rand(d, 20);
  1090. smartlist_add(sl, tor_memdup(d, 20));
  1091. }
  1092. for (i = 0; i < elts; ++i) {
  1093. crypto_rand(d, 20);
  1094. smartlist_add(sl2, tor_memdup(d, 20));
  1095. }
  1096. printf("nbits=%d\n", ds->mask+1);
  1097. tor_gettimeofday(&start);
  1098. for (i = 0; i < iters; ++i) {
  1099. SMARTLIST_FOREACH(sl, const char *, cp, digestmap_set(dm, cp, (void*)1));
  1100. }
  1101. tor_gettimeofday(&pt2);
  1102. for (i = 0; i < iters; ++i) {
  1103. SMARTLIST_FOREACH(sl, const char *, cp, digestmap_get(dm, cp));
  1104. SMARTLIST_FOREACH(sl2, const char *, cp, digestmap_get(dm, cp));
  1105. }
  1106. tor_gettimeofday(&pt3);
  1107. for (i = 0; i < iters; ++i) {
  1108. SMARTLIST_FOREACH(sl, const char *, cp, digestset_add(ds, cp));
  1109. }
  1110. tor_gettimeofday(&pt4);
  1111. for (i = 0; i < iters; ++i) {
  1112. SMARTLIST_FOREACH(sl, const char *, cp, n += digestset_isin(ds, cp));
  1113. SMARTLIST_FOREACH(sl2, const char *, cp, n += digestset_isin(ds, cp));
  1114. }
  1115. tor_gettimeofday(&end);
  1116. for (i = 0; i < fpostests; ++i) {
  1117. crypto_rand(d, 20);
  1118. if (digestset_isin(ds, d)) ++fp;
  1119. }
  1120. printf("%ld\n",(unsigned long)tv_udiff(&start, &pt2));
  1121. printf("%ld\n",(unsigned long)tv_udiff(&pt2, &pt3));
  1122. printf("%ld\n",(unsigned long)tv_udiff(&pt3, &pt4));
  1123. printf("%ld\n",(unsigned long)tv_udiff(&pt4, &end));
  1124. printf("-- %d\n", n);
  1125. printf("++ %f\n", fp/(double)fpostests);
  1126. digestmap_free(dm, NULL);
  1127. digestset_free(ds);
  1128. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1129. SMARTLIST_FOREACH(sl2, char *, cp, tor_free(cp));
  1130. smartlist_free(sl);
  1131. smartlist_free(sl2);
  1132. }
  1133. /** Test encoding and parsing of rendezvous service descriptors. */
  1134. static void
  1135. test_rend_fns(void)
  1136. {
  1137. rend_service_descriptor_t *generated = NULL, *parsed = NULL;
  1138. char service_id[DIGEST_LEN];
  1139. char service_id_base32[REND_SERVICE_ID_LEN_BASE32+1];
  1140. const char *next_desc;
  1141. smartlist_t *descs = smartlist_create();
  1142. char computed_desc_id[DIGEST_LEN];
  1143. char parsed_desc_id[DIGEST_LEN];
  1144. crypto_pk_env_t *pk1 = NULL, *pk2 = NULL;
  1145. time_t now;
  1146. char *intro_points_encrypted = NULL;
  1147. size_t intro_points_size;
  1148. size_t encoded_size;
  1149. int i;
  1150. char address1[] = "fooaddress.onion";
  1151. char address2[] = "aaaaaaaaaaaaaaaa.onion";
  1152. char address3[] = "fooaddress.exit";
  1153. char address4[] = "www.torproject.org";
  1154. test_assert(BAD_HOSTNAME == parse_extended_hostname(address1, 1));
  1155. test_assert(ONION_HOSTNAME == parse_extended_hostname(address2, 1));
  1156. test_assert(EXIT_HOSTNAME == parse_extended_hostname(address3, 1));
  1157. test_assert(NORMAL_HOSTNAME == parse_extended_hostname(address4, 1));
  1158. pk1 = pk_generate(0);
  1159. pk2 = pk_generate(1);
  1160. generated = tor_malloc_zero(sizeof(rend_service_descriptor_t));
  1161. generated->pk = crypto_pk_dup_key(pk1);
  1162. crypto_pk_get_digest(generated->pk, service_id);
  1163. base32_encode(service_id_base32, REND_SERVICE_ID_LEN_BASE32+1,
  1164. service_id, REND_SERVICE_ID_LEN);
  1165. now = time(NULL);
  1166. generated->timestamp = now;
  1167. generated->version = 2;
  1168. generated->protocols = 42;
  1169. generated->intro_nodes = smartlist_create();
  1170. for (i = 0; i < 3; i++) {
  1171. rend_intro_point_t *intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  1172. crypto_pk_env_t *okey = pk_generate(2 + i);
  1173. intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
  1174. intro->extend_info->onion_key = okey;
  1175. crypto_pk_get_digest(intro->extend_info->onion_key,
  1176. intro->extend_info->identity_digest);
  1177. //crypto_rand(info->identity_digest, DIGEST_LEN); /* Would this work? */
  1178. intro->extend_info->nickname[0] = '$';
  1179. base16_encode(intro->extend_info->nickname + 1,
  1180. sizeof(intro->extend_info->nickname) - 1,
  1181. intro->extend_info->identity_digest, DIGEST_LEN);
  1182. /* Does not cover all IP addresses. */
  1183. tor_addr_from_ipv4h(&intro->extend_info->addr, crypto_rand_int(65536));
  1184. intro->extend_info->port = 1 + crypto_rand_int(65535);
  1185. intro->intro_key = crypto_pk_dup_key(pk2);
  1186. smartlist_add(generated->intro_nodes, intro);
  1187. }
  1188. test_assert(rend_encode_v2_descriptors(descs, generated, now, 0,
  1189. REND_NO_AUTH, NULL, NULL) > 0);
  1190. test_assert(rend_compute_v2_desc_id(computed_desc_id, service_id_base32,
  1191. NULL, now, 0) == 0);
  1192. test_memeq(((rend_encoded_v2_service_descriptor_t *)
  1193. smartlist_get(descs, 0))->desc_id, computed_desc_id, DIGEST_LEN);
  1194. test_assert(rend_parse_v2_service_descriptor(&parsed, parsed_desc_id,
  1195. &intro_points_encrypted,
  1196. &intro_points_size,
  1197. &encoded_size,
  1198. &next_desc,
  1199. ((rend_encoded_v2_service_descriptor_t *)
  1200. smartlist_get(descs, 0))->desc_str) == 0);
  1201. test_assert(parsed);
  1202. test_memeq(((rend_encoded_v2_service_descriptor_t *)
  1203. smartlist_get(descs, 0))->desc_id, parsed_desc_id, DIGEST_LEN);
  1204. test_eq(rend_parse_introduction_points(parsed, intro_points_encrypted,
  1205. intro_points_size), 3);
  1206. test_assert(!crypto_pk_cmp_keys(generated->pk, parsed->pk));
  1207. test_eq(parsed->timestamp, now);
  1208. test_eq(parsed->version, 2);
  1209. test_eq(parsed->protocols, 42);
  1210. test_eq(smartlist_len(parsed->intro_nodes), 3);
  1211. for (i = 0; i < smartlist_len(parsed->intro_nodes); i++) {
  1212. rend_intro_point_t *par_intro = smartlist_get(parsed->intro_nodes, i),
  1213. *gen_intro = smartlist_get(generated->intro_nodes, i);
  1214. extend_info_t *par_info = par_intro->extend_info;
  1215. extend_info_t *gen_info = gen_intro->extend_info;
  1216. test_assert(!crypto_pk_cmp_keys(gen_info->onion_key, par_info->onion_key));
  1217. test_memeq(gen_info->identity_digest, par_info->identity_digest,
  1218. DIGEST_LEN);
  1219. test_streq(gen_info->nickname, par_info->nickname);
  1220. test_assert(tor_addr_eq(&gen_info->addr, &par_info->addr));
  1221. test_eq(gen_info->port, par_info->port);
  1222. }
  1223. rend_service_descriptor_free(parsed);
  1224. rend_service_descriptor_free(generated);
  1225. parsed = generated = NULL;
  1226. done:
  1227. if (descs) {
  1228. for (i = 0; i < smartlist_len(descs); i++)
  1229. rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
  1230. smartlist_free(descs);
  1231. }
  1232. if (parsed)
  1233. rend_service_descriptor_free(parsed);
  1234. if (generated)
  1235. rend_service_descriptor_free(generated);
  1236. if (pk1)
  1237. crypto_free_pk_env(pk1);
  1238. if (pk2)
  1239. crypto_free_pk_env(pk2);
  1240. tor_free(intro_points_encrypted);
  1241. }
  1242. /** Run unit tests for GeoIP code. */
  1243. static void
  1244. test_geoip(void)
  1245. {
  1246. int i, j;
  1247. time_t now = time(NULL);
  1248. char *s = NULL;
  1249. /* Populate the DB a bit. Add these in order, since we can't do the final
  1250. * 'sort' step. These aren't very good IP addresses, but they're perfectly
  1251. * fine uint32_t values. */
  1252. test_eq(0, geoip_parse_entry("10,50,AB"));
  1253. test_eq(0, geoip_parse_entry("52,90,XY"));
  1254. test_eq(0, geoip_parse_entry("95,100,AB"));
  1255. test_eq(0, geoip_parse_entry("\"105\",\"140\",\"ZZ\""));
  1256. test_eq(0, geoip_parse_entry("\"150\",\"190\",\"XY\""));
  1257. test_eq(0, geoip_parse_entry("\"200\",\"250\",\"AB\""));
  1258. /* We should have 4 countries: ??, ab, xy, zz. */
  1259. test_eq(4, geoip_get_n_countries());
  1260. /* Make sure that country ID actually works. */
  1261. #define NAMEFOR(x) geoip_get_country_name(geoip_get_country_by_ip(x))
  1262. test_streq("??", NAMEFOR(3));
  1263. test_eq(0, geoip_get_country_by_ip(3));
  1264. test_streq("ab", NAMEFOR(32));
  1265. test_streq("??", NAMEFOR(5));
  1266. test_streq("??", NAMEFOR(51));
  1267. test_streq("xy", NAMEFOR(150));
  1268. test_streq("xy", NAMEFOR(190));
  1269. test_streq("??", NAMEFOR(2000));
  1270. #undef NAMEFOR
  1271. get_options_mutable()->BridgeRelay = 1;
  1272. get_options_mutable()->BridgeRecordUsageByCountry = 1;
  1273. /* Put 9 observations in AB... */
  1274. for (i=32; i < 40; ++i)
  1275. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, i, now-7200);
  1276. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, 225, now-7200);
  1277. /* and 3 observations in XY, several times. */
  1278. for (j=0; j < 10; ++j)
  1279. for (i=52; i < 55; ++i)
  1280. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, i, now-3600);
  1281. /* and 17 observations in ZZ... */
  1282. for (i=110; i < 127; ++i)
  1283. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, i, now);
  1284. s = geoip_get_client_history(GEOIP_CLIENT_CONNECT);
  1285. test_assert(s);
  1286. test_streq("zz=24,ab=16,xy=8", s);
  1287. tor_free(s);
  1288. /* Now clear out all the AB observations. */
  1289. geoip_remove_old_clients(now-6000);
  1290. s = geoip_get_client_history(GEOIP_CLIENT_CONNECT);
  1291. test_assert(s);
  1292. test_streq("zz=24,xy=8", s);
  1293. done:
  1294. tor_free(s);
  1295. }
  1296. /** Run unit tests for stats code. */
  1297. static void
  1298. test_stats(void)
  1299. {
  1300. time_t now = 1281533250; /* 2010-08-11 13:27:30 UTC */
  1301. char *s = NULL;
  1302. int i;
  1303. /* Start with testing exit port statistics; we shouldn't collect exit
  1304. * stats without initializing them. */
  1305. rep_hist_note_exit_stream_opened(80);
  1306. rep_hist_note_exit_bytes(80, 100, 10000);
  1307. s = rep_hist_format_exit_stats(now + 86400);
  1308. test_assert(!s);
  1309. /* Initialize stats, note some streams and bytes, and generate history
  1310. * string. */
  1311. rep_hist_exit_stats_init(now);
  1312. rep_hist_note_exit_stream_opened(80);
  1313. rep_hist_note_exit_bytes(80, 100, 10000);
  1314. rep_hist_note_exit_stream_opened(443);
  1315. rep_hist_note_exit_bytes(443, 100, 10000);
  1316. rep_hist_note_exit_bytes(443, 100, 10000);
  1317. s = rep_hist_format_exit_stats(now + 86400);
  1318. test_streq("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1319. "exit-kibibytes-written 80=1,443=1,other=0\n"
  1320. "exit-kibibytes-read 80=10,443=20,other=0\n"
  1321. "exit-streams-opened 80=4,443=4,other=0\n", s);
  1322. tor_free(s);
  1323. /* Add a few bytes on 10 more ports and ensure that only the top 10
  1324. * ports are contained in the history string. */
  1325. for (i = 50; i < 60; i++) {
  1326. rep_hist_note_exit_bytes(i, i, i);
  1327. rep_hist_note_exit_stream_opened(i);
  1328. }
  1329. s = rep_hist_format_exit_stats(now + 86400);
  1330. test_streq("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1331. "exit-kibibytes-written 52=1,53=1,54=1,55=1,56=1,57=1,58=1,"
  1332. "59=1,80=1,443=1,other=1\n"
  1333. "exit-kibibytes-read 52=1,53=1,54=1,55=1,56=1,57=1,58=1,"
  1334. "59=1,80=10,443=20,other=1\n"
  1335. "exit-streams-opened 52=4,53=4,54=4,55=4,56=4,57=4,58=4,"
  1336. "59=4,80=4,443=4,other=4\n", s);
  1337. tor_free(s);
  1338. /* Stop collecting stats, add some bytes, and ensure we don't generate
  1339. * a history string. */
  1340. rep_hist_exit_stats_term();
  1341. rep_hist_note_exit_bytes(80, 100, 10000);
  1342. s = rep_hist_format_exit_stats(now + 86400);
  1343. test_assert(!s);
  1344. /* Re-start stats, add some bytes, reset stats, and see what history we
  1345. * get when observing no streams or bytes at all. */
  1346. rep_hist_exit_stats_init(now);
  1347. rep_hist_note_exit_stream_opened(80);
  1348. rep_hist_note_exit_bytes(80, 100, 10000);
  1349. rep_hist_reset_exit_stats(now);
  1350. s = rep_hist_format_exit_stats(now + 86400);
  1351. test_streq("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1352. "exit-kibibytes-written other=0\n"
  1353. "exit-kibibytes-read other=0\n"
  1354. "exit-streams-opened other=0\n", s);
  1355. tor_free(s);
  1356. /* Continue with testing connection statistics; we shouldn't collect
  1357. * conn stats without initializing them. */
  1358. rep_hist_note_or_conn_bytes(1, 20, 400, now);
  1359. s = rep_hist_format_conn_stats(now + 86400);
  1360. test_assert(!s);
  1361. /* Initialize stats, note bytes, and generate history string. */
  1362. rep_hist_conn_stats_init(now);
  1363. rep_hist_note_or_conn_bytes(1, 30000, 400000, now);
  1364. rep_hist_note_or_conn_bytes(1, 30000, 400000, now + 5);
  1365. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 10);
  1366. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 15);
  1367. s = rep_hist_format_conn_stats(now + 86400);
  1368. test_streq("conn-bi-direct 2010-08-12 13:27:30 (86400 s) 0,0,1,0\n", s);
  1369. tor_free(s);
  1370. /* Stop collecting stats, add some bytes, and ensure we don't generate
  1371. * a history string. */
  1372. rep_hist_conn_stats_term();
  1373. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 15);
  1374. s = rep_hist_format_conn_stats(now + 86400);
  1375. test_assert(!s);
  1376. /* Re-start stats, add some bytes, reset stats, and see what history we
  1377. * get when observing no bytes at all. */
  1378. rep_hist_conn_stats_init(now);
  1379. rep_hist_note_or_conn_bytes(1, 30000, 400000, now);
  1380. rep_hist_note_or_conn_bytes(1, 30000, 400000, now + 5);
  1381. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 10);
  1382. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 15);
  1383. rep_hist_reset_conn_stats(now);
  1384. s = rep_hist_format_conn_stats(now + 86400);
  1385. test_streq("conn-bi-direct 2010-08-12 13:27:30 (86400 s) 0,0,0,0\n", s);
  1386. done:
  1387. tor_free(s);
  1388. }
  1389. static void *
  1390. legacy_test_setup(const struct testcase_t *testcase)
  1391. {
  1392. return testcase->setup_data;
  1393. }
  1394. void
  1395. legacy_test_helper(void *data)
  1396. {
  1397. void (*fn)(void) = data;
  1398. fn();
  1399. }
  1400. static int
  1401. legacy_test_cleanup(const struct testcase_t *testcase, void *ptr)
  1402. {
  1403. (void)ptr;
  1404. (void)testcase;
  1405. return 1;
  1406. }
  1407. const struct testcase_setup_t legacy_setup = {
  1408. legacy_test_setup, legacy_test_cleanup
  1409. };
  1410. #define ENT(name) \
  1411. { #name, legacy_test_helper, 0, &legacy_setup, test_ ## name }
  1412. #define SUBENT(group, name) \
  1413. { #group "_" #name, legacy_test_helper, 0, &legacy_setup, \
  1414. test_ ## group ## _ ## name }
  1415. #define DISABLED(name) \
  1416. { #name, legacy_test_helper, TT_SKIP, &legacy_setup, name }
  1417. #define FORK(name) \
  1418. { #name, legacy_test_helper, TT_FORK, &legacy_setup, test_ ## name }
  1419. static struct testcase_t test_array[] = {
  1420. ENT(buffers),
  1421. ENT(onion_handshake),
  1422. ENT(circuit_timeout),
  1423. ENT(policies),
  1424. ENT(rend_fns),
  1425. ENT(geoip),
  1426. FORK(stats),
  1427. DISABLED(bench_aes),
  1428. DISABLED(bench_dmap),
  1429. END_OF_TESTCASES
  1430. };
  1431. #define SOCKSENT(name) \
  1432. { #name, test_socks_##name, TT_FORK, &socks_setup, NULL }
  1433. static struct testcase_t socks_tests[] = {
  1434. SOCKSENT(4_unsupported_commands),
  1435. SOCKSENT(4_supported_commands),
  1436. SOCKSENT(5_unsupported_commands),
  1437. SOCKSENT(5_supported_commands),
  1438. SOCKSENT(5_no_authenticate),
  1439. SOCKSENT(5_auth_before_negotiation),
  1440. SOCKSENT(5_authenticate),
  1441. SOCKSENT(5_authenticate_with_data),
  1442. END_OF_TESTCASES
  1443. };
  1444. extern struct testcase_t addr_tests[];
  1445. extern struct testcase_t crypto_tests[];
  1446. extern struct testcase_t container_tests[];
  1447. extern struct testcase_t util_tests[];
  1448. extern struct testcase_t dir_tests[];
  1449. extern struct testcase_t microdesc_tests[];
  1450. static struct testgroup_t testgroups[] = {
  1451. { "", test_array },
  1452. { "socks/", socks_tests },
  1453. { "addr/", addr_tests },
  1454. { "crypto/", crypto_tests },
  1455. { "container/", container_tests },
  1456. { "util/", util_tests },
  1457. { "dir/", dir_tests },
  1458. { "dir/md/", microdesc_tests },
  1459. END_OF_GROUPS
  1460. };
  1461. /** Main entry point for unit test code: parse the command line, and run
  1462. * some unit tests. */
  1463. int
  1464. main(int c, const char **v)
  1465. {
  1466. or_options_t *options;
  1467. char *errmsg = NULL;
  1468. int i, i_out;
  1469. int loglevel = LOG_ERR;
  1470. #ifdef USE_DMALLOC
  1471. {
  1472. int r = CRYPTO_set_mem_ex_functions(_tor_malloc, _tor_realloc, _tor_free);
  1473. tor_assert(r);
  1474. }
  1475. #endif
  1476. update_approx_time(time(NULL));
  1477. options = options_new();
  1478. tor_threads_init();
  1479. init_logging();
  1480. for (i_out = i = 1; i < c; ++i) {
  1481. if (!strcmp(v[i], "--warn")) {
  1482. loglevel = LOG_WARN;
  1483. } else if (!strcmp(v[i], "--notice")) {
  1484. loglevel = LOG_NOTICE;
  1485. } else if (!strcmp(v[i], "--info")) {
  1486. loglevel = LOG_INFO;
  1487. } else if (!strcmp(v[i], "--debug")) {
  1488. loglevel = LOG_DEBUG;
  1489. } else {
  1490. v[i_out++] = v[i];
  1491. }
  1492. }
  1493. c = i_out;
  1494. {
  1495. log_severity_list_t s;
  1496. memset(&s, 0, sizeof(s));
  1497. set_log_severity_config(loglevel, LOG_ERR, &s);
  1498. add_stream_log(&s, "", fileno(stdout));
  1499. }
  1500. options->command = CMD_RUN_UNITTESTS;
  1501. if (crypto_global_init(0, NULL, NULL)) {
  1502. printf("Can't initialize crypto subsystem; exiting.\n");
  1503. return 1;
  1504. }
  1505. rep_hist_init();
  1506. network_init();
  1507. setup_directory();
  1508. options_init(options);
  1509. options->DataDirectory = tor_strdup(temp_dir);
  1510. options->EntryStatistics = 1;
  1511. if (set_options(options, &errmsg) < 0) {
  1512. printf("Failed to set initial options: %s\n", errmsg);
  1513. tor_free(errmsg);
  1514. return 1;
  1515. }
  1516. crypto_seed_rng(1);
  1517. atexit(remove_directory);
  1518. have_failed = (tinytest_main(c, v, testgroups) != 0);
  1519. free_pregenerated_keys();
  1520. #ifdef USE_DMALLOC
  1521. tor_free_all(0);
  1522. dmalloc_log_unfreed();
  1523. #endif
  1524. if (have_failed)
  1525. return 1;
  1526. else
  1527. return 0;
  1528. }