test.c 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942
  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 _WIN32
  18. /* For mkdir() */
  19. #include <direct.h>
  20. #else
  21. #include <dirent.h>
  22. #endif
  23. /* These macros pull in declarations for some functions and structures that
  24. * are typically file-private. */
  25. #define BUFFERS_PRIVATE
  26. #define CONFIG_PRIVATE
  27. #define GEOIP_PRIVATE
  28. #define ROUTER_PRIVATE
  29. #define 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 _WIN32
  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_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_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_pk_new();
  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_t *result;
  165. (void) idx;
  166. result = crypto_pk_new();
  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_pk_free(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. static void
  489. test_buffer_copy(void *arg)
  490. {
  491. generic_buffer_t *buf=NULL, *buf2=NULL;
  492. const char *s;
  493. size_t len;
  494. char b[256];
  495. int i;
  496. (void)arg;
  497. buf = generic_buffer_new();
  498. tt_assert(buf);
  499. /* Copy an empty buffer. */
  500. tt_int_op(0, ==, generic_buffer_set_to_copy(&buf2, buf));
  501. tt_assert(buf2);
  502. tt_int_op(0, ==, generic_buffer_len(buf2));
  503. /* Now try with a short buffer. */
  504. s = "And now comes an act of enormous enormance!";
  505. len = strlen(s);
  506. generic_buffer_add(buf, s, len);
  507. tt_int_op(len, ==, generic_buffer_len(buf));
  508. /* Add junk to buf2 so we can test replacing.*/
  509. generic_buffer_add(buf2, "BLARG", 5);
  510. tt_int_op(0, ==, generic_buffer_set_to_copy(&buf2, buf));
  511. tt_int_op(len, ==, generic_buffer_len(buf2));
  512. generic_buffer_get(buf2, b, len);
  513. test_mem_op(b, ==, s, len);
  514. /* Now free buf2 and retry so we can test allocating */
  515. generic_buffer_free(buf2);
  516. buf2 = NULL;
  517. tt_int_op(0, ==, generic_buffer_set_to_copy(&buf2, buf));
  518. tt_int_op(len, ==, generic_buffer_len(buf2));
  519. generic_buffer_get(buf2, b, len);
  520. test_mem_op(b, ==, s, len);
  521. /* Clear buf for next test */
  522. generic_buffer_get(buf, b, len);
  523. tt_int_op(generic_buffer_len(buf),==,0);
  524. /* Okay, now let's try a bigger buffer. */
  525. s = "Quis autem vel eum iure reprehenderit qui in ea voluptate velit "
  526. "esse quam nihil molestiae consequatur, vel illum qui dolorem eum "
  527. "fugiat quo voluptas nulla pariatur?";
  528. len = strlen(s);
  529. for (i = 0; i < 256; ++i) {
  530. b[0]=i;
  531. generic_buffer_add(buf, b, 1);
  532. generic_buffer_add(buf, s, len);
  533. }
  534. tt_int_op(0, ==, generic_buffer_set_to_copy(&buf2, buf));
  535. tt_int_op(generic_buffer_len(buf2), ==, generic_buffer_len(buf));
  536. for (i = 0; i < 256; ++i) {
  537. generic_buffer_get(buf2, b, len+1);
  538. tt_int_op((unsigned char)b[0],==,i);
  539. test_mem_op(b+1, ==, s, len);
  540. }
  541. done:
  542. if (buf)
  543. generic_buffer_free(buf);
  544. if (buf2)
  545. generic_buffer_free(buf2);
  546. }
  547. /** Run unit tests for buffers.c */
  548. static void
  549. test_buffers(void)
  550. {
  551. char str[256];
  552. char str2[256];
  553. buf_t *buf = NULL, *buf2 = NULL;
  554. const char *cp;
  555. int j;
  556. size_t r;
  557. /****
  558. * buf_new
  559. ****/
  560. if (!(buf = buf_new()))
  561. test_fail();
  562. //test_eq(buf_capacity(buf), 4096);
  563. test_eq(buf_datalen(buf), 0);
  564. /****
  565. * General pointer frobbing
  566. */
  567. for (j=0;j<256;++j) {
  568. str[j] = (char)j;
  569. }
  570. write_to_buf(str, 256, buf);
  571. write_to_buf(str, 256, buf);
  572. test_eq(buf_datalen(buf), 512);
  573. fetch_from_buf(str2, 200, buf);
  574. test_memeq(str, str2, 200);
  575. test_eq(buf_datalen(buf), 312);
  576. memset(str2, 0, sizeof(str2));
  577. fetch_from_buf(str2, 256, buf);
  578. test_memeq(str+200, str2, 56);
  579. test_memeq(str, str2+56, 200);
  580. test_eq(buf_datalen(buf), 56);
  581. memset(str2, 0, sizeof(str2));
  582. /* Okay, now we should be 512 bytes into the 4096-byte buffer. If we add
  583. * another 3584 bytes, we hit the end. */
  584. for (j=0;j<15;++j) {
  585. write_to_buf(str, 256, buf);
  586. }
  587. assert_buf_ok(buf);
  588. test_eq(buf_datalen(buf), 3896);
  589. fetch_from_buf(str2, 56, buf);
  590. test_eq(buf_datalen(buf), 3840);
  591. test_memeq(str+200, str2, 56);
  592. for (j=0;j<15;++j) {
  593. memset(str2, 0, sizeof(str2));
  594. fetch_from_buf(str2, 256, buf);
  595. test_memeq(str, str2, 256);
  596. }
  597. test_eq(buf_datalen(buf), 0);
  598. buf_free(buf);
  599. buf = NULL;
  600. /* Okay, now make sure growing can work. */
  601. buf = buf_new_with_capacity(16);
  602. //test_eq(buf_capacity(buf), 16);
  603. write_to_buf(str+1, 255, buf);
  604. //test_eq(buf_capacity(buf), 256);
  605. fetch_from_buf(str2, 254, buf);
  606. test_memeq(str+1, str2, 254);
  607. //test_eq(buf_capacity(buf), 256);
  608. assert_buf_ok(buf);
  609. write_to_buf(str, 32, buf);
  610. //test_eq(buf_capacity(buf), 256);
  611. assert_buf_ok(buf);
  612. write_to_buf(str, 256, buf);
  613. assert_buf_ok(buf);
  614. //test_eq(buf_capacity(buf), 512);
  615. test_eq(buf_datalen(buf), 33+256);
  616. fetch_from_buf(str2, 33, buf);
  617. test_eq(*str2, str[255]);
  618. test_memeq(str2+1, str, 32);
  619. //test_eq(buf_capacity(buf), 512);
  620. test_eq(buf_datalen(buf), 256);
  621. fetch_from_buf(str2, 256, buf);
  622. test_memeq(str, str2, 256);
  623. /* now try shrinking: case 1. */
  624. buf_free(buf);
  625. buf = buf_new_with_capacity(33668);
  626. for (j=0;j<67;++j) {
  627. write_to_buf(str,255, buf);
  628. }
  629. //test_eq(buf_capacity(buf), 33668);
  630. test_eq(buf_datalen(buf), 17085);
  631. for (j=0; j < 40; ++j) {
  632. fetch_from_buf(str2, 255,buf);
  633. test_memeq(str2, str, 255);
  634. }
  635. /* now try shrinking: case 2. */
  636. buf_free(buf);
  637. buf = buf_new_with_capacity(33668);
  638. for (j=0;j<67;++j) {
  639. write_to_buf(str,255, buf);
  640. }
  641. for (j=0; j < 20; ++j) {
  642. fetch_from_buf(str2, 255,buf);
  643. test_memeq(str2, str, 255);
  644. }
  645. for (j=0;j<80;++j) {
  646. write_to_buf(str,255, buf);
  647. }
  648. //test_eq(buf_capacity(buf),33668);
  649. for (j=0; j < 120; ++j) {
  650. fetch_from_buf(str2, 255,buf);
  651. test_memeq(str2, str, 255);
  652. }
  653. /* Move from buf to buf. */
  654. buf_free(buf);
  655. buf = buf_new_with_capacity(4096);
  656. buf2 = buf_new_with_capacity(4096);
  657. for (j=0;j<100;++j)
  658. write_to_buf(str, 255, buf);
  659. test_eq(buf_datalen(buf), 25500);
  660. for (j=0;j<100;++j) {
  661. r = 10;
  662. move_buf_to_buf(buf2, buf, &r);
  663. test_eq(r, 0);
  664. }
  665. test_eq(buf_datalen(buf), 24500);
  666. test_eq(buf_datalen(buf2), 1000);
  667. for (j=0;j<3;++j) {
  668. fetch_from_buf(str2, 255, buf2);
  669. test_memeq(str2, str, 255);
  670. }
  671. r = 8192; /*big move*/
  672. move_buf_to_buf(buf2, buf, &r);
  673. test_eq(r, 0);
  674. r = 30000; /* incomplete move */
  675. move_buf_to_buf(buf2, buf, &r);
  676. test_eq(r, 13692);
  677. for (j=0;j<97;++j) {
  678. fetch_from_buf(str2, 255, buf2);
  679. test_memeq(str2, str, 255);
  680. }
  681. buf_free(buf);
  682. buf_free(buf2);
  683. buf = buf2 = NULL;
  684. buf = buf_new_with_capacity(5);
  685. cp = "Testing. This is a moderately long Testing string.";
  686. for (j = 0; cp[j]; j++)
  687. write_to_buf(cp+j, 1, buf);
  688. test_eq(0, buf_find_string_offset(buf, "Testing", 7));
  689. test_eq(1, buf_find_string_offset(buf, "esting", 6));
  690. test_eq(1, buf_find_string_offset(buf, "est", 3));
  691. test_eq(39, buf_find_string_offset(buf, "ing str", 7));
  692. test_eq(35, buf_find_string_offset(buf, "Testing str", 11));
  693. test_eq(32, buf_find_string_offset(buf, "ng ", 3));
  694. test_eq(43, buf_find_string_offset(buf, "string.", 7));
  695. test_eq(-1, buf_find_string_offset(buf, "shrdlu", 6));
  696. test_eq(-1, buf_find_string_offset(buf, "Testing thing", 13));
  697. test_eq(-1, buf_find_string_offset(buf, "ngx", 3));
  698. buf_free(buf);
  699. buf = NULL;
  700. done:
  701. if (buf)
  702. buf_free(buf);
  703. if (buf2)
  704. buf_free(buf2);
  705. }
  706. /** Run unit tests for the onion handshake code. */
  707. static void
  708. test_onion_handshake(void)
  709. {
  710. /* client-side */
  711. crypto_dh_t *c_dh = NULL;
  712. char c_buf[ONIONSKIN_CHALLENGE_LEN];
  713. char c_keys[40];
  714. /* server-side */
  715. char s_buf[ONIONSKIN_REPLY_LEN];
  716. char s_keys[40];
  717. /* shared */
  718. crypto_pk_t *pk = NULL;
  719. pk = pk_generate(0);
  720. /* client handshake 1. */
  721. memset(c_buf, 0, ONIONSKIN_CHALLENGE_LEN);
  722. test_assert(! onion_skin_create(pk, &c_dh, c_buf));
  723. /* server handshake */
  724. memset(s_buf, 0, ONIONSKIN_REPLY_LEN);
  725. memset(s_keys, 0, 40);
  726. test_assert(! onion_skin_server_handshake(c_buf, pk, NULL,
  727. s_buf, s_keys, 40));
  728. /* client handshake 2 */
  729. memset(c_keys, 0, 40);
  730. test_assert(! onion_skin_client_handshake(c_dh, s_buf, c_keys, 40));
  731. if (memcmp(c_keys, s_keys, 40)) {
  732. puts("Aiiiie");
  733. exit(1);
  734. }
  735. test_memeq(c_keys, s_keys, 40);
  736. memset(s_buf, 0, 40);
  737. test_memneq(c_keys, s_buf, 40);
  738. done:
  739. if (c_dh)
  740. crypto_dh_free(c_dh);
  741. if (pk)
  742. crypto_pk_free(pk);
  743. }
  744. static void
  745. test_circuit_timeout(void)
  746. {
  747. /* Plan:
  748. * 1. Generate 1000 samples
  749. * 2. Estimate parameters
  750. * 3. If difference, repeat
  751. * 4. Save state
  752. * 5. load state
  753. * 6. Estimate parameters
  754. * 7. compare differences
  755. */
  756. circuit_build_times_t initial;
  757. circuit_build_times_t estimate;
  758. circuit_build_times_t final;
  759. double timeout1, timeout2;
  760. or_state_t state;
  761. int i, runs;
  762. double close_ms;
  763. circuit_build_times_init(&initial);
  764. circuit_build_times_init(&estimate);
  765. circuit_build_times_init(&final);
  766. memset(&state, 0, sizeof(or_state_t));
  767. circuitbuild_running_unit_tests();
  768. #define timeout0 (build_time_t)(30*1000.0)
  769. initial.Xm = 3000;
  770. circuit_build_times_initial_alpha(&initial,
  771. CBT_DEFAULT_QUANTILE_CUTOFF/100.0,
  772. timeout0);
  773. close_ms = MAX(circuit_build_times_calculate_timeout(&initial,
  774. CBT_DEFAULT_CLOSE_QUANTILE/100.0),
  775. CBT_DEFAULT_TIMEOUT_INITIAL_VALUE);
  776. do {
  777. for (i=0; i < CBT_DEFAULT_MIN_CIRCUITS_TO_OBSERVE; i++) {
  778. build_time_t sample = circuit_build_times_generate_sample(&initial,0,1);
  779. if (sample > close_ms) {
  780. circuit_build_times_add_time(&estimate, CBT_BUILD_ABANDONED);
  781. } else {
  782. circuit_build_times_add_time(&estimate, sample);
  783. }
  784. }
  785. circuit_build_times_update_alpha(&estimate);
  786. timeout1 = circuit_build_times_calculate_timeout(&estimate,
  787. CBT_DEFAULT_QUANTILE_CUTOFF/100.0);
  788. circuit_build_times_set_timeout(&estimate);
  789. log_notice(LD_CIRC, "Timeout1 is %f, Xm is %d", timeout1, estimate.Xm);
  790. /* 2% error */
  791. } while (fabs(circuit_build_times_cdf(&initial, timeout0) -
  792. circuit_build_times_cdf(&initial, timeout1)) > 0.02);
  793. test_assert(estimate.total_build_times <= CBT_NCIRCUITS_TO_OBSERVE);
  794. circuit_build_times_update_state(&estimate, &state);
  795. test_assert(circuit_build_times_parse_state(&final, &state) == 0);
  796. circuit_build_times_update_alpha(&final);
  797. timeout2 = circuit_build_times_calculate_timeout(&final,
  798. CBT_DEFAULT_QUANTILE_CUTOFF/100.0);
  799. circuit_build_times_set_timeout(&final);
  800. log_notice(LD_CIRC, "Timeout2 is %f, Xm is %d", timeout2, final.Xm);
  801. /* 5% here because some accuracy is lost due to histogram conversion */
  802. test_assert(fabs(circuit_build_times_cdf(&initial, timeout0) -
  803. circuit_build_times_cdf(&initial, timeout2)) < 0.05);
  804. for (runs = 0; runs < 50; runs++) {
  805. int build_times_idx = 0;
  806. int total_build_times = 0;
  807. final.close_ms = final.timeout_ms = CBT_DEFAULT_TIMEOUT_INITIAL_VALUE;
  808. estimate.close_ms = estimate.timeout_ms
  809. = CBT_DEFAULT_TIMEOUT_INITIAL_VALUE;
  810. for (i = 0; i < CBT_DEFAULT_RECENT_CIRCUITS*2; i++) {
  811. circuit_build_times_network_circ_success(&estimate);
  812. circuit_build_times_add_time(&estimate,
  813. circuit_build_times_generate_sample(&estimate, 0,
  814. CBT_DEFAULT_QUANTILE_CUTOFF/100.0));
  815. circuit_build_times_network_circ_success(&estimate);
  816. circuit_build_times_add_time(&final,
  817. circuit_build_times_generate_sample(&final, 0,
  818. CBT_DEFAULT_QUANTILE_CUTOFF/100.0));
  819. }
  820. test_assert(!circuit_build_times_network_check_changed(&estimate));
  821. test_assert(!circuit_build_times_network_check_changed(&final));
  822. /* Reset liveness to be non-live */
  823. final.liveness.network_last_live = 0;
  824. estimate.liveness.network_last_live = 0;
  825. build_times_idx = estimate.build_times_idx;
  826. total_build_times = estimate.total_build_times;
  827. test_assert(circuit_build_times_network_check_live(&estimate));
  828. test_assert(circuit_build_times_network_check_live(&final));
  829. circuit_build_times_count_close(&estimate, 0,
  830. (time_t)(approx_time()-estimate.close_ms/1000.0-1));
  831. circuit_build_times_count_close(&final, 0,
  832. (time_t)(approx_time()-final.close_ms/1000.0-1));
  833. test_assert(!circuit_build_times_network_check_live(&estimate));
  834. test_assert(!circuit_build_times_network_check_live(&final));
  835. log_info(LD_CIRC, "idx: %d %d, tot: %d %d",
  836. build_times_idx, estimate.build_times_idx,
  837. total_build_times, estimate.total_build_times);
  838. /* Check rollback index. Should match top of loop. */
  839. test_assert(build_times_idx == estimate.build_times_idx);
  840. // This can fail if estimate.total_build_times == 1000, because
  841. // in that case, rewind actually causes us to lose timeouts
  842. if (total_build_times != CBT_NCIRCUITS_TO_OBSERVE)
  843. test_assert(total_build_times == estimate.total_build_times);
  844. /* Now simulate that the network has become live and we need
  845. * a change */
  846. circuit_build_times_network_is_live(&estimate);
  847. circuit_build_times_network_is_live(&final);
  848. for (i = 0; i < CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT; i++) {
  849. circuit_build_times_count_timeout(&estimate, 1);
  850. if (i < CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT-1) {
  851. circuit_build_times_count_timeout(&final, 1);
  852. }
  853. }
  854. test_assert(estimate.liveness.after_firsthop_idx == 0);
  855. test_assert(final.liveness.after_firsthop_idx ==
  856. CBT_DEFAULT_MAX_RECENT_TIMEOUT_COUNT-1);
  857. test_assert(circuit_build_times_network_check_live(&estimate));
  858. test_assert(circuit_build_times_network_check_live(&final));
  859. circuit_build_times_count_timeout(&final, 1);
  860. }
  861. done:
  862. return;
  863. }
  864. /** Helper: Parse the exit policy string in <b>policy_str</b>, and make sure
  865. * that policies_summarize() produces the string <b>expected_summary</b> from
  866. * it. */
  867. static void
  868. test_policy_summary_helper(const char *policy_str,
  869. const char *expected_summary)
  870. {
  871. config_line_t line;
  872. smartlist_t *policy = smartlist_new();
  873. char *summary = NULL;
  874. int r;
  875. short_policy_t *short_policy = NULL;
  876. line.key = (char*)"foo";
  877. line.value = (char *)policy_str;
  878. line.next = NULL;
  879. r = policies_parse_exit_policy(&line, &policy, 0, NULL, 1);
  880. test_eq(r, 0);
  881. summary = policy_summarize(policy);
  882. test_assert(summary != NULL);
  883. test_streq(summary, expected_summary);
  884. short_policy = parse_short_policy(summary);
  885. tt_assert(short_policy);
  886. done:
  887. tor_free(summary);
  888. if (policy)
  889. addr_policy_list_free(policy);
  890. short_policy_free(short_policy);
  891. }
  892. /** Run unit tests for generating summary lines of exit policies */
  893. static void
  894. test_policies(void)
  895. {
  896. int i;
  897. smartlist_t *policy = NULL, *policy2 = NULL, *policy3 = NULL,
  898. *policy4 = NULL, *policy5 = NULL, *policy6 = NULL,
  899. *policy7 = NULL;
  900. addr_policy_t *p;
  901. tor_addr_t tar;
  902. config_line_t line;
  903. smartlist_t *sm = NULL;
  904. char *policy_str = NULL;
  905. policy = smartlist_new();
  906. p = router_parse_addr_policy_item_from_string("reject 192.168.0.0/16:*",-1);
  907. test_assert(p != NULL);
  908. test_eq(ADDR_POLICY_REJECT, p->policy_type);
  909. tor_addr_from_ipv4h(&tar, 0xc0a80000u);
  910. test_eq(0, tor_addr_compare(&p->addr, &tar, CMP_EXACT));
  911. test_eq(16, p->maskbits);
  912. test_eq(1, p->prt_min);
  913. test_eq(65535, p->prt_max);
  914. smartlist_add(policy, p);
  915. tor_addr_from_ipv4h(&tar, 0x01020304u);
  916. test_assert(ADDR_POLICY_ACCEPTED ==
  917. compare_tor_addr_to_addr_policy(&tar, 2, policy));
  918. tor_addr_make_unspec(&tar);
  919. test_assert(ADDR_POLICY_PROBABLY_ACCEPTED ==
  920. compare_tor_addr_to_addr_policy(&tar, 2, policy));
  921. tor_addr_from_ipv4h(&tar, 0xc0a80102);
  922. test_assert(ADDR_POLICY_REJECTED ==
  923. compare_tor_addr_to_addr_policy(&tar, 2, policy));
  924. test_assert(0 == policies_parse_exit_policy(NULL, &policy2, 1, NULL, 1));
  925. test_assert(policy2);
  926. policy3 = smartlist_new();
  927. p = router_parse_addr_policy_item_from_string("reject *:*",-1);
  928. test_assert(p != NULL);
  929. smartlist_add(policy3, p);
  930. p = router_parse_addr_policy_item_from_string("accept *:*",-1);
  931. test_assert(p != NULL);
  932. smartlist_add(policy3, p);
  933. policy4 = smartlist_new();
  934. p = router_parse_addr_policy_item_from_string("accept *:443",-1);
  935. test_assert(p != NULL);
  936. smartlist_add(policy4, p);
  937. p = router_parse_addr_policy_item_from_string("accept *:443",-1);
  938. test_assert(p != NULL);
  939. smartlist_add(policy4, p);
  940. policy5 = smartlist_new();
  941. p = router_parse_addr_policy_item_from_string("reject 0.0.0.0/8:*",-1);
  942. test_assert(p != NULL);
  943. smartlist_add(policy5, p);
  944. p = router_parse_addr_policy_item_from_string("reject 169.254.0.0/16:*",-1);
  945. test_assert(p != NULL);
  946. smartlist_add(policy5, p);
  947. p = router_parse_addr_policy_item_from_string("reject 127.0.0.0/8:*",-1);
  948. test_assert(p != NULL);
  949. smartlist_add(policy5, p);
  950. p = router_parse_addr_policy_item_from_string("reject 192.168.0.0/16:*",-1);
  951. test_assert(p != NULL);
  952. smartlist_add(policy5, p);
  953. p = router_parse_addr_policy_item_from_string("reject 10.0.0.0/8:*",-1);
  954. test_assert(p != NULL);
  955. smartlist_add(policy5, p);
  956. p = router_parse_addr_policy_item_from_string("reject 172.16.0.0/12:*",-1);
  957. test_assert(p != NULL);
  958. smartlist_add(policy5, p);
  959. p = router_parse_addr_policy_item_from_string("reject 80.190.250.90:*",-1);
  960. test_assert(p != NULL);
  961. smartlist_add(policy5, p);
  962. p = router_parse_addr_policy_item_from_string("reject *:1-65534",-1);
  963. test_assert(p != NULL);
  964. smartlist_add(policy5, p);
  965. p = router_parse_addr_policy_item_from_string("reject *:65535",-1);
  966. test_assert(p != NULL);
  967. smartlist_add(policy5, p);
  968. p = router_parse_addr_policy_item_from_string("accept *:1-65535",-1);
  969. test_assert(p != NULL);
  970. smartlist_add(policy5, p);
  971. policy6 = smartlist_new();
  972. p = router_parse_addr_policy_item_from_string("accept 43.3.0.0/9:*",-1);
  973. test_assert(p != NULL);
  974. smartlist_add(policy6, p);
  975. policy7 = smartlist_new();
  976. p = router_parse_addr_policy_item_from_string("accept 0.0.0.0/8:*",-1);
  977. test_assert(p != NULL);
  978. smartlist_add(policy7, p);
  979. test_assert(!exit_policy_is_general_exit(policy));
  980. test_assert(exit_policy_is_general_exit(policy2));
  981. test_assert(!exit_policy_is_general_exit(NULL));
  982. test_assert(!exit_policy_is_general_exit(policy3));
  983. test_assert(!exit_policy_is_general_exit(policy4));
  984. test_assert(!exit_policy_is_general_exit(policy5));
  985. test_assert(!exit_policy_is_general_exit(policy6));
  986. test_assert(!exit_policy_is_general_exit(policy7));
  987. test_assert(cmp_addr_policies(policy, policy2));
  988. test_assert(cmp_addr_policies(policy, NULL));
  989. test_assert(!cmp_addr_policies(policy2, policy2));
  990. test_assert(!cmp_addr_policies(NULL, NULL));
  991. test_assert(!policy_is_reject_star(policy2));
  992. test_assert(policy_is_reject_star(policy));
  993. test_assert(policy_is_reject_star(NULL));
  994. addr_policy_list_free(policy);
  995. policy = NULL;
  996. /* make sure compacting logic works. */
  997. policy = NULL;
  998. line.key = (char*)"foo";
  999. line.value = (char*)"accept *:80,reject private:*,reject *:*";
  1000. line.next = NULL;
  1001. test_assert(0 == policies_parse_exit_policy(&line, &policy, 0, NULL, 1));
  1002. test_assert(policy);
  1003. //test_streq(policy->string, "accept *:80");
  1004. //test_streq(policy->next->string, "reject *:*");
  1005. test_eq(smartlist_len(policy), 2);
  1006. /* test policy summaries */
  1007. /* check if we properly ignore private IP addresses */
  1008. test_policy_summary_helper("reject 192.168.0.0/16:*,"
  1009. "reject 0.0.0.0/8:*,"
  1010. "reject 10.0.0.0/8:*,"
  1011. "accept *:10-30,"
  1012. "accept *:90,"
  1013. "reject *:*",
  1014. "accept 10-30,90");
  1015. /* check all accept policies, and proper counting of rejects */
  1016. test_policy_summary_helper("reject 11.0.0.0/9:80,"
  1017. "reject 12.0.0.0/9:80,"
  1018. "reject 13.0.0.0/9:80,"
  1019. "reject 14.0.0.0/9:80,"
  1020. "accept *:*", "accept 1-65535");
  1021. test_policy_summary_helper("reject 11.0.0.0/9:80,"
  1022. "reject 12.0.0.0/9:80,"
  1023. "reject 13.0.0.0/9:80,"
  1024. "reject 14.0.0.0/9:80,"
  1025. "reject 15.0.0.0:81,"
  1026. "accept *:*", "accept 1-65535");
  1027. test_policy_summary_helper("reject 11.0.0.0/9:80,"
  1028. "reject 12.0.0.0/9:80,"
  1029. "reject 13.0.0.0/9:80,"
  1030. "reject 14.0.0.0/9:80,"
  1031. "reject 15.0.0.0:80,"
  1032. "accept *:*",
  1033. "reject 80");
  1034. /* no exits */
  1035. test_policy_summary_helper("accept 11.0.0.0/9:80,"
  1036. "reject *:*",
  1037. "reject 1-65535");
  1038. /* port merging */
  1039. test_policy_summary_helper("accept *:80,"
  1040. "accept *:81,"
  1041. "accept *:100-110,"
  1042. "accept *:111,"
  1043. "reject *:*",
  1044. "accept 80-81,100-111");
  1045. /* border ports */
  1046. test_policy_summary_helper("accept *:1,"
  1047. "accept *:3,"
  1048. "accept *:65535,"
  1049. "reject *:*",
  1050. "accept 1,3,65535");
  1051. /* holes */
  1052. test_policy_summary_helper("accept *:1,"
  1053. "accept *:3,"
  1054. "accept *:5,"
  1055. "accept *:7,"
  1056. "reject *:*",
  1057. "accept 1,3,5,7");
  1058. test_policy_summary_helper("reject *:1,"
  1059. "reject *:3,"
  1060. "reject *:5,"
  1061. "reject *:7,"
  1062. "accept *:*",
  1063. "reject 1,3,5,7");
  1064. /* truncation ports */
  1065. sm = smartlist_new();
  1066. for (i=1; i<2000; i+=2) {
  1067. char buf[POLICY_BUF_LEN];
  1068. tor_snprintf(buf, sizeof(buf), "reject *:%d", i);
  1069. smartlist_add(sm, tor_strdup(buf));
  1070. }
  1071. smartlist_add(sm, tor_strdup("accept *:*"));
  1072. policy_str = smartlist_join_strings(sm, ",", 0, NULL);
  1073. test_policy_summary_helper( policy_str,
  1074. "accept 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,"
  1075. "46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,"
  1076. "92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,"
  1077. "130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,"
  1078. "166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198,200,"
  1079. "202,204,206,208,210,212,214,216,218,220,222,224,226,228,230,232,234,236,"
  1080. "238,240,242,244,246,248,250,252,254,256,258,260,262,264,266,268,270,272,"
  1081. "274,276,278,280,282,284,286,288,290,292,294,296,298,300,302,304,306,308,"
  1082. "310,312,314,316,318,320,322,324,326,328,330,332,334,336,338,340,342,344,"
  1083. "346,348,350,352,354,356,358,360,362,364,366,368,370,372,374,376,378,380,"
  1084. "382,384,386,388,390,392,394,396,398,400,402,404,406,408,410,412,414,416,"
  1085. "418,420,422,424,426,428,430,432,434,436,438,440,442,444,446,448,450,452,"
  1086. "454,456,458,460,462,464,466,468,470,472,474,476,478,480,482,484,486,488,"
  1087. "490,492,494,496,498,500,502,504,506,508,510,512,514,516,518,520,522");
  1088. done:
  1089. addr_policy_list_free(policy);
  1090. addr_policy_list_free(policy2);
  1091. addr_policy_list_free(policy3);
  1092. addr_policy_list_free(policy4);
  1093. addr_policy_list_free(policy5);
  1094. addr_policy_list_free(policy6);
  1095. addr_policy_list_free(policy7);
  1096. tor_free(policy_str);
  1097. if (sm) {
  1098. SMARTLIST_FOREACH(sm, char *, s, tor_free(s));
  1099. smartlist_free(sm);
  1100. }
  1101. }
  1102. /** Test encoding and parsing of rendezvous service descriptors. */
  1103. static void
  1104. test_rend_fns(void)
  1105. {
  1106. rend_service_descriptor_t *generated = NULL, *parsed = NULL;
  1107. char service_id[DIGEST_LEN];
  1108. char service_id_base32[REND_SERVICE_ID_LEN_BASE32+1];
  1109. const char *next_desc;
  1110. smartlist_t *descs = smartlist_new();
  1111. char computed_desc_id[DIGEST_LEN];
  1112. char parsed_desc_id[DIGEST_LEN];
  1113. crypto_pk_t *pk1 = NULL, *pk2 = NULL;
  1114. time_t now;
  1115. char *intro_points_encrypted = NULL;
  1116. size_t intro_points_size;
  1117. size_t encoded_size;
  1118. int i;
  1119. char address1[] = "fooaddress.onion";
  1120. char address2[] = "aaaaaaaaaaaaaaaa.onion";
  1121. char address3[] = "fooaddress.exit";
  1122. char address4[] = "www.torproject.org";
  1123. test_assert(BAD_HOSTNAME == parse_extended_hostname(address1, 1));
  1124. test_assert(ONION_HOSTNAME == parse_extended_hostname(address2, 1));
  1125. test_assert(EXIT_HOSTNAME == parse_extended_hostname(address3, 1));
  1126. test_assert(NORMAL_HOSTNAME == parse_extended_hostname(address4, 1));
  1127. pk1 = pk_generate(0);
  1128. pk2 = pk_generate(1);
  1129. generated = tor_malloc_zero(sizeof(rend_service_descriptor_t));
  1130. generated->pk = crypto_pk_dup_key(pk1);
  1131. crypto_pk_get_digest(generated->pk, service_id);
  1132. base32_encode(service_id_base32, REND_SERVICE_ID_LEN_BASE32+1,
  1133. service_id, REND_SERVICE_ID_LEN);
  1134. now = time(NULL);
  1135. generated->timestamp = now;
  1136. generated->version = 2;
  1137. generated->protocols = 42;
  1138. generated->intro_nodes = smartlist_new();
  1139. for (i = 0; i < 3; i++) {
  1140. rend_intro_point_t *intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  1141. crypto_pk_t *okey = pk_generate(2 + i);
  1142. intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
  1143. intro->extend_info->onion_key = okey;
  1144. crypto_pk_get_digest(intro->extend_info->onion_key,
  1145. intro->extend_info->identity_digest);
  1146. //crypto_rand(info->identity_digest, DIGEST_LEN); /* Would this work? */
  1147. intro->extend_info->nickname[0] = '$';
  1148. base16_encode(intro->extend_info->nickname + 1,
  1149. sizeof(intro->extend_info->nickname) - 1,
  1150. intro->extend_info->identity_digest, DIGEST_LEN);
  1151. /* Does not cover all IP addresses. */
  1152. tor_addr_from_ipv4h(&intro->extend_info->addr, crypto_rand_int(65536));
  1153. intro->extend_info->port = 1 + crypto_rand_int(65535);
  1154. intro->intro_key = crypto_pk_dup_key(pk2);
  1155. smartlist_add(generated->intro_nodes, intro);
  1156. }
  1157. test_assert(rend_encode_v2_descriptors(descs, generated, now, 0,
  1158. REND_NO_AUTH, NULL, NULL) > 0);
  1159. test_assert(rend_compute_v2_desc_id(computed_desc_id, service_id_base32,
  1160. NULL, now, 0) == 0);
  1161. test_memeq(((rend_encoded_v2_service_descriptor_t *)
  1162. smartlist_get(descs, 0))->desc_id, computed_desc_id, DIGEST_LEN);
  1163. test_assert(rend_parse_v2_service_descriptor(&parsed, parsed_desc_id,
  1164. &intro_points_encrypted,
  1165. &intro_points_size,
  1166. &encoded_size,
  1167. &next_desc,
  1168. ((rend_encoded_v2_service_descriptor_t *)
  1169. smartlist_get(descs, 0))->desc_str) == 0);
  1170. test_assert(parsed);
  1171. test_memeq(((rend_encoded_v2_service_descriptor_t *)
  1172. smartlist_get(descs, 0))->desc_id, parsed_desc_id, DIGEST_LEN);
  1173. test_eq(rend_parse_introduction_points(parsed, intro_points_encrypted,
  1174. intro_points_size), 3);
  1175. test_assert(!crypto_pk_cmp_keys(generated->pk, parsed->pk));
  1176. test_eq(parsed->timestamp, now);
  1177. test_eq(parsed->version, 2);
  1178. test_eq(parsed->protocols, 42);
  1179. test_eq(smartlist_len(parsed->intro_nodes), 3);
  1180. for (i = 0; i < smartlist_len(parsed->intro_nodes); i++) {
  1181. rend_intro_point_t *par_intro = smartlist_get(parsed->intro_nodes, i),
  1182. *gen_intro = smartlist_get(generated->intro_nodes, i);
  1183. extend_info_t *par_info = par_intro->extend_info;
  1184. extend_info_t *gen_info = gen_intro->extend_info;
  1185. test_assert(!crypto_pk_cmp_keys(gen_info->onion_key, par_info->onion_key));
  1186. test_memeq(gen_info->identity_digest, par_info->identity_digest,
  1187. DIGEST_LEN);
  1188. test_streq(gen_info->nickname, par_info->nickname);
  1189. test_assert(tor_addr_eq(&gen_info->addr, &par_info->addr));
  1190. test_eq(gen_info->port, par_info->port);
  1191. }
  1192. rend_service_descriptor_free(parsed);
  1193. rend_service_descriptor_free(generated);
  1194. parsed = generated = NULL;
  1195. done:
  1196. if (descs) {
  1197. for (i = 0; i < smartlist_len(descs); i++)
  1198. rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
  1199. smartlist_free(descs);
  1200. }
  1201. if (parsed)
  1202. rend_service_descriptor_free(parsed);
  1203. if (generated)
  1204. rend_service_descriptor_free(generated);
  1205. if (pk1)
  1206. crypto_pk_free(pk1);
  1207. if (pk2)
  1208. crypto_pk_free(pk2);
  1209. tor_free(intro_points_encrypted);
  1210. }
  1211. /** Run unit tests for GeoIP code. */
  1212. static void
  1213. test_geoip(void)
  1214. {
  1215. int i, j;
  1216. time_t now = 1281533250; /* 2010-08-11 13:27:30 UTC */
  1217. char *s = NULL;
  1218. const char *bridge_stats_1 =
  1219. "bridge-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1220. "bridge-ips zz=24,xy=8\n",
  1221. *dirreq_stats_1 =
  1222. "dirreq-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1223. "dirreq-v3-ips ab=8\n"
  1224. "dirreq-v2-ips \n"
  1225. "dirreq-v3-reqs ab=8\n"
  1226. "dirreq-v2-reqs \n"
  1227. "dirreq-v3-resp ok=0,not-enough-sigs=0,unavailable=0,not-found=0,"
  1228. "not-modified=0,busy=0\n"
  1229. "dirreq-v2-resp ok=0,unavailable=0,not-found=0,not-modified=0,"
  1230. "busy=0\n"
  1231. "dirreq-v3-direct-dl complete=0,timeout=0,running=0\n"
  1232. "dirreq-v2-direct-dl complete=0,timeout=0,running=0\n"
  1233. "dirreq-v3-tunneled-dl complete=0,timeout=0,running=0\n"
  1234. "dirreq-v2-tunneled-dl complete=0,timeout=0,running=0\n",
  1235. *dirreq_stats_2 =
  1236. "dirreq-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1237. "dirreq-v3-ips \n"
  1238. "dirreq-v2-ips \n"
  1239. "dirreq-v3-reqs \n"
  1240. "dirreq-v2-reqs \n"
  1241. "dirreq-v3-resp ok=0,not-enough-sigs=0,unavailable=0,not-found=0,"
  1242. "not-modified=0,busy=0\n"
  1243. "dirreq-v2-resp ok=0,unavailable=0,not-found=0,not-modified=0,"
  1244. "busy=0\n"
  1245. "dirreq-v3-direct-dl complete=0,timeout=0,running=0\n"
  1246. "dirreq-v2-direct-dl complete=0,timeout=0,running=0\n"
  1247. "dirreq-v3-tunneled-dl complete=0,timeout=0,running=0\n"
  1248. "dirreq-v2-tunneled-dl complete=0,timeout=0,running=0\n",
  1249. *dirreq_stats_3 =
  1250. "dirreq-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1251. "dirreq-v3-ips \n"
  1252. "dirreq-v2-ips \n"
  1253. "dirreq-v3-reqs \n"
  1254. "dirreq-v2-reqs \n"
  1255. "dirreq-v3-resp ok=8,not-enough-sigs=0,unavailable=0,not-found=0,"
  1256. "not-modified=0,busy=0\n"
  1257. "dirreq-v2-resp ok=0,unavailable=0,not-found=0,not-modified=0,"
  1258. "busy=0\n"
  1259. "dirreq-v3-direct-dl complete=0,timeout=0,running=0\n"
  1260. "dirreq-v2-direct-dl complete=0,timeout=0,running=0\n"
  1261. "dirreq-v3-tunneled-dl complete=0,timeout=0,running=0\n"
  1262. "dirreq-v2-tunneled-dl complete=0,timeout=0,running=0\n",
  1263. *dirreq_stats_4 =
  1264. "dirreq-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1265. "dirreq-v3-ips \n"
  1266. "dirreq-v2-ips \n"
  1267. "dirreq-v3-reqs \n"
  1268. "dirreq-v2-reqs \n"
  1269. "dirreq-v3-resp ok=8,not-enough-sigs=0,unavailable=0,not-found=0,"
  1270. "not-modified=0,busy=0\n"
  1271. "dirreq-v2-resp ok=0,unavailable=0,not-found=0,not-modified=0,"
  1272. "busy=0\n"
  1273. "dirreq-v3-direct-dl complete=0,timeout=0,running=0\n"
  1274. "dirreq-v2-direct-dl complete=0,timeout=0,running=0\n"
  1275. "dirreq-v3-tunneled-dl complete=0,timeout=0,running=4\n"
  1276. "dirreq-v2-tunneled-dl complete=0,timeout=0,running=0\n",
  1277. *entry_stats_1 =
  1278. "entry-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1279. "entry-ips ab=8\n",
  1280. *entry_stats_2 =
  1281. "entry-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1282. "entry-ips \n";
  1283. /* Populate the DB a bit. Add these in order, since we can't do the final
  1284. * 'sort' step. These aren't very good IP addresses, but they're perfectly
  1285. * fine uint32_t values. */
  1286. test_eq(0, geoip_parse_entry("10,50,AB"));
  1287. test_eq(0, geoip_parse_entry("52,90,XY"));
  1288. test_eq(0, geoip_parse_entry("95,100,AB"));
  1289. test_eq(0, geoip_parse_entry("\"105\",\"140\",\"ZZ\""));
  1290. test_eq(0, geoip_parse_entry("\"150\",\"190\",\"XY\""));
  1291. test_eq(0, geoip_parse_entry("\"200\",\"250\",\"AB\""));
  1292. /* We should have 4 countries: ??, ab, xy, zz. */
  1293. test_eq(4, geoip_get_n_countries());
  1294. /* Make sure that country ID actually works. */
  1295. #define NAMEFOR(x) geoip_get_country_name(geoip_get_country_by_ip(x))
  1296. test_streq("??", NAMEFOR(3));
  1297. test_eq(0, geoip_get_country_by_ip(3));
  1298. test_streq("ab", NAMEFOR(32));
  1299. test_streq("??", NAMEFOR(5));
  1300. test_streq("??", NAMEFOR(51));
  1301. test_streq("xy", NAMEFOR(150));
  1302. test_streq("xy", NAMEFOR(190));
  1303. test_streq("??", NAMEFOR(2000));
  1304. #undef NAMEFOR
  1305. get_options_mutable()->BridgeRelay = 1;
  1306. get_options_mutable()->BridgeRecordUsageByCountry = 1;
  1307. /* Put 9 observations in AB... */
  1308. for (i=32; i < 40; ++i)
  1309. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, i, now-7200);
  1310. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, 225, now-7200);
  1311. /* and 3 observations in XY, several times. */
  1312. for (j=0; j < 10; ++j)
  1313. for (i=52; i < 55; ++i)
  1314. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, i, now-3600);
  1315. /* and 17 observations in ZZ... */
  1316. for (i=110; i < 127; ++i)
  1317. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, i, now);
  1318. s = geoip_get_client_history(GEOIP_CLIENT_CONNECT);
  1319. test_assert(s);
  1320. test_streq("zz=24,ab=16,xy=8", s);
  1321. tor_free(s);
  1322. /* Now clear out all the AB observations. */
  1323. geoip_remove_old_clients(now-6000);
  1324. s = geoip_get_client_history(GEOIP_CLIENT_CONNECT);
  1325. test_assert(s);
  1326. test_streq("zz=24,xy=8", s);
  1327. /* Start testing bridge statistics by making sure that we don't output
  1328. * bridge stats without initializing them. */
  1329. s = geoip_format_bridge_stats(now + 86400);
  1330. test_assert(!s);
  1331. /* Initialize stats and generate the bridge-stats history string out of
  1332. * the connecting clients added above. */
  1333. geoip_bridge_stats_init(now);
  1334. s = geoip_format_bridge_stats(now + 86400);
  1335. test_streq(bridge_stats_1, s);
  1336. tor_free(s);
  1337. /* Stop collecting bridge stats and make sure we don't write a history
  1338. * string anymore. */
  1339. geoip_bridge_stats_term();
  1340. s = geoip_format_bridge_stats(now + 86400);
  1341. test_assert(!s);
  1342. /* Stop being a bridge and start being a directory mirror that gathers
  1343. * directory request statistics. */
  1344. geoip_bridge_stats_term();
  1345. get_options_mutable()->BridgeRelay = 0;
  1346. get_options_mutable()->BridgeRecordUsageByCountry = 0;
  1347. get_options_mutable()->DirReqStatistics = 1;
  1348. /* Start testing dirreq statistics by making sure that we don't collect
  1349. * dirreq stats without initializing them. */
  1350. geoip_note_client_seen(GEOIP_CLIENT_NETWORKSTATUS, 100, now);
  1351. s = geoip_format_dirreq_stats(now + 86400);
  1352. test_assert(!s);
  1353. /* Initialize stats, note one connecting client, and generate the
  1354. * dirreq-stats history string. */
  1355. geoip_dirreq_stats_init(now);
  1356. geoip_note_client_seen(GEOIP_CLIENT_NETWORKSTATUS, 100, now);
  1357. s = geoip_format_dirreq_stats(now + 86400);
  1358. test_streq(dirreq_stats_1, s);
  1359. tor_free(s);
  1360. /* Stop collecting stats, add another connecting client, and ensure we
  1361. * don't generate a history string. */
  1362. geoip_dirreq_stats_term();
  1363. geoip_note_client_seen(GEOIP_CLIENT_NETWORKSTATUS, 101, now);
  1364. s = geoip_format_dirreq_stats(now + 86400);
  1365. test_assert(!s);
  1366. /* Re-start stats, add a connecting client, reset stats, and make sure
  1367. * that we get an all empty history string. */
  1368. geoip_dirreq_stats_init(now);
  1369. geoip_note_client_seen(GEOIP_CLIENT_NETWORKSTATUS, 100, now);
  1370. geoip_reset_dirreq_stats(now);
  1371. s = geoip_format_dirreq_stats(now + 86400);
  1372. test_streq(dirreq_stats_2, s);
  1373. tor_free(s);
  1374. /* Note a successful network status response and make sure that it
  1375. * appears in the history string. */
  1376. geoip_note_ns_response(GEOIP_CLIENT_NETWORKSTATUS, GEOIP_SUCCESS);
  1377. s = geoip_format_dirreq_stats(now + 86400);
  1378. test_streq(dirreq_stats_3, s);
  1379. tor_free(s);
  1380. /* Start a tunneled directory request. */
  1381. geoip_start_dirreq((uint64_t) 1, 1024, GEOIP_CLIENT_NETWORKSTATUS,
  1382. DIRREQ_TUNNELED);
  1383. s = geoip_format_dirreq_stats(now + 86400);
  1384. test_streq(dirreq_stats_4, s);
  1385. /* Stop collecting directory request statistics and start gathering
  1386. * entry stats. */
  1387. geoip_dirreq_stats_term();
  1388. get_options_mutable()->DirReqStatistics = 0;
  1389. get_options_mutable()->EntryStatistics = 1;
  1390. /* Start testing entry statistics by making sure that we don't collect
  1391. * anything without initializing entry stats. */
  1392. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, 100, now);
  1393. s = geoip_format_entry_stats(now + 86400);
  1394. test_assert(!s);
  1395. /* Initialize stats, note one connecting client, and generate the
  1396. * entry-stats history string. */
  1397. geoip_entry_stats_init(now);
  1398. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, 100, now);
  1399. s = geoip_format_entry_stats(now + 86400);
  1400. test_streq(entry_stats_1, s);
  1401. tor_free(s);
  1402. /* Stop collecting stats, add another connecting client, and ensure we
  1403. * don't generate a history string. */
  1404. geoip_entry_stats_term();
  1405. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, 101, now);
  1406. s = geoip_format_entry_stats(now + 86400);
  1407. test_assert(!s);
  1408. /* Re-start stats, add a connecting client, reset stats, and make sure
  1409. * that we get an all empty history string. */
  1410. geoip_entry_stats_init(now);
  1411. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, 100, now);
  1412. geoip_reset_entry_stats(now);
  1413. s = geoip_format_entry_stats(now + 86400);
  1414. test_streq(entry_stats_2, s);
  1415. tor_free(s);
  1416. /* Stop collecting entry statistics. */
  1417. geoip_entry_stats_term();
  1418. get_options_mutable()->EntryStatistics = 0;
  1419. done:
  1420. tor_free(s);
  1421. }
  1422. /** Run unit tests for stats code. */
  1423. static void
  1424. test_stats(void)
  1425. {
  1426. time_t now = 1281533250; /* 2010-08-11 13:27:30 UTC */
  1427. char *s = NULL;
  1428. int i;
  1429. /* Start with testing exit port statistics; we shouldn't collect exit
  1430. * stats without initializing them. */
  1431. rep_hist_note_exit_stream_opened(80);
  1432. rep_hist_note_exit_bytes(80, 100, 10000);
  1433. s = rep_hist_format_exit_stats(now + 86400);
  1434. test_assert(!s);
  1435. /* Initialize stats, note some streams and bytes, and generate history
  1436. * string. */
  1437. rep_hist_exit_stats_init(now);
  1438. rep_hist_note_exit_stream_opened(80);
  1439. rep_hist_note_exit_bytes(80, 100, 10000);
  1440. rep_hist_note_exit_stream_opened(443);
  1441. rep_hist_note_exit_bytes(443, 100, 10000);
  1442. rep_hist_note_exit_bytes(443, 100, 10000);
  1443. s = rep_hist_format_exit_stats(now + 86400);
  1444. test_streq("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1445. "exit-kibibytes-written 80=1,443=1,other=0\n"
  1446. "exit-kibibytes-read 80=10,443=20,other=0\n"
  1447. "exit-streams-opened 80=4,443=4,other=0\n", s);
  1448. tor_free(s);
  1449. /* Add a few bytes on 10 more ports and ensure that only the top 10
  1450. * ports are contained in the history string. */
  1451. for (i = 50; i < 60; i++) {
  1452. rep_hist_note_exit_bytes(i, i, i);
  1453. rep_hist_note_exit_stream_opened(i);
  1454. }
  1455. s = rep_hist_format_exit_stats(now + 86400);
  1456. test_streq("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1457. "exit-kibibytes-written 52=1,53=1,54=1,55=1,56=1,57=1,58=1,"
  1458. "59=1,80=1,443=1,other=1\n"
  1459. "exit-kibibytes-read 52=1,53=1,54=1,55=1,56=1,57=1,58=1,"
  1460. "59=1,80=10,443=20,other=1\n"
  1461. "exit-streams-opened 52=4,53=4,54=4,55=4,56=4,57=4,58=4,"
  1462. "59=4,80=4,443=4,other=4\n", s);
  1463. tor_free(s);
  1464. /* Stop collecting stats, add some bytes, and ensure we don't generate
  1465. * a history string. */
  1466. rep_hist_exit_stats_term();
  1467. rep_hist_note_exit_bytes(80, 100, 10000);
  1468. s = rep_hist_format_exit_stats(now + 86400);
  1469. test_assert(!s);
  1470. /* Re-start stats, add some bytes, reset stats, and see what history we
  1471. * get when observing no streams or bytes at all. */
  1472. rep_hist_exit_stats_init(now);
  1473. rep_hist_note_exit_stream_opened(80);
  1474. rep_hist_note_exit_bytes(80, 100, 10000);
  1475. rep_hist_reset_exit_stats(now);
  1476. s = rep_hist_format_exit_stats(now + 86400);
  1477. test_streq("exit-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1478. "exit-kibibytes-written other=0\n"
  1479. "exit-kibibytes-read other=0\n"
  1480. "exit-streams-opened other=0\n", s);
  1481. tor_free(s);
  1482. /* Continue with testing connection statistics; we shouldn't collect
  1483. * conn stats without initializing them. */
  1484. rep_hist_note_or_conn_bytes(1, 20, 400, now);
  1485. s = rep_hist_format_conn_stats(now + 86400);
  1486. test_assert(!s);
  1487. /* Initialize stats, note bytes, and generate history string. */
  1488. rep_hist_conn_stats_init(now);
  1489. rep_hist_note_or_conn_bytes(1, 30000, 400000, now);
  1490. rep_hist_note_or_conn_bytes(1, 30000, 400000, now + 5);
  1491. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 10);
  1492. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 15);
  1493. s = rep_hist_format_conn_stats(now + 86400);
  1494. test_streq("conn-bi-direct 2010-08-12 13:27:30 (86400 s) 0,0,1,0\n", s);
  1495. tor_free(s);
  1496. /* Stop collecting stats, add some bytes, and ensure we don't generate
  1497. * a history string. */
  1498. rep_hist_conn_stats_term();
  1499. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 15);
  1500. s = rep_hist_format_conn_stats(now + 86400);
  1501. test_assert(!s);
  1502. /* Re-start stats, add some bytes, reset stats, and see what history we
  1503. * get when observing no bytes at all. */
  1504. rep_hist_conn_stats_init(now);
  1505. rep_hist_note_or_conn_bytes(1, 30000, 400000, now);
  1506. rep_hist_note_or_conn_bytes(1, 30000, 400000, now + 5);
  1507. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 10);
  1508. rep_hist_note_or_conn_bytes(2, 400000, 30000, now + 15);
  1509. rep_hist_reset_conn_stats(now);
  1510. s = rep_hist_format_conn_stats(now + 86400);
  1511. test_streq("conn-bi-direct 2010-08-12 13:27:30 (86400 s) 0,0,0,0\n", s);
  1512. tor_free(s);
  1513. /* Continue with testing buffer statistics; we shouldn't collect buffer
  1514. * stats without initializing them. */
  1515. rep_hist_add_buffer_stats(2.0, 2.0, 20);
  1516. s = rep_hist_format_buffer_stats(now + 86400);
  1517. test_assert(!s);
  1518. /* Initialize stats, add statistics for a single circuit, and generate
  1519. * the history string. */
  1520. rep_hist_buffer_stats_init(now);
  1521. rep_hist_add_buffer_stats(2.0, 2.0, 20);
  1522. s = rep_hist_format_buffer_stats(now + 86400);
  1523. test_streq("cell-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1524. "cell-processed-cells 20,0,0,0,0,0,0,0,0,0\n"
  1525. "cell-queued-cells 2.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,"
  1526. "0.00,0.00\n"
  1527. "cell-time-in-queue 2,0,0,0,0,0,0,0,0,0\n"
  1528. "cell-circuits-per-decile 1\n", s);
  1529. tor_free(s);
  1530. /* Add nineteen more circuit statistics to the one that's already in the
  1531. * history to see that the math works correctly. */
  1532. for (i = 21; i < 30; i++)
  1533. rep_hist_add_buffer_stats(2.0, 2.0, i);
  1534. for (i = 20; i < 30; i++)
  1535. rep_hist_add_buffer_stats(3.5, 3.5, i);
  1536. s = rep_hist_format_buffer_stats(now + 86400);
  1537. test_streq("cell-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1538. "cell-processed-cells 29,28,27,26,25,24,23,22,21,20\n"
  1539. "cell-queued-cells 2.75,2.75,2.75,2.75,2.75,2.75,2.75,2.75,"
  1540. "2.75,2.75\n"
  1541. "cell-time-in-queue 3,3,3,3,3,3,3,3,3,3\n"
  1542. "cell-circuits-per-decile 2\n", s);
  1543. tor_free(s);
  1544. /* Stop collecting stats, add statistics for one circuit, and ensure we
  1545. * don't generate a history string. */
  1546. rep_hist_buffer_stats_term();
  1547. rep_hist_add_buffer_stats(2.0, 2.0, 20);
  1548. s = rep_hist_format_buffer_stats(now + 86400);
  1549. test_assert(!s);
  1550. /* Re-start stats, add statistics for one circuit, reset stats, and make
  1551. * sure that the history has all zeros. */
  1552. rep_hist_buffer_stats_init(now);
  1553. rep_hist_add_buffer_stats(2.0, 2.0, 20);
  1554. rep_hist_reset_buffer_stats(now);
  1555. s = rep_hist_format_buffer_stats(now + 86400);
  1556. test_streq("cell-stats-end 2010-08-12 13:27:30 (86400 s)\n"
  1557. "cell-processed-cells 0,0,0,0,0,0,0,0,0,0\n"
  1558. "cell-queued-cells 0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,"
  1559. "0.00,0.00\n"
  1560. "cell-time-in-queue 0,0,0,0,0,0,0,0,0,0\n"
  1561. "cell-circuits-per-decile 0\n", s);
  1562. done:
  1563. tor_free(s);
  1564. }
  1565. static void *
  1566. legacy_test_setup(const struct testcase_t *testcase)
  1567. {
  1568. return testcase->setup_data;
  1569. }
  1570. void
  1571. legacy_test_helper(void *data)
  1572. {
  1573. void (*fn)(void) = data;
  1574. fn();
  1575. }
  1576. static int
  1577. legacy_test_cleanup(const struct testcase_t *testcase, void *ptr)
  1578. {
  1579. (void)ptr;
  1580. (void)testcase;
  1581. return 1;
  1582. }
  1583. const struct testcase_setup_t legacy_setup = {
  1584. legacy_test_setup, legacy_test_cleanup
  1585. };
  1586. #define ENT(name) \
  1587. { #name, legacy_test_helper, 0, &legacy_setup, test_ ## name }
  1588. #define SUBENT(group, name) \
  1589. { #group "_" #name, legacy_test_helper, 0, &legacy_setup, \
  1590. test_ ## group ## _ ## name }
  1591. #define DISABLED(name) \
  1592. { #name, legacy_test_helper, TT_SKIP, &legacy_setup, test_ ## name }
  1593. #define FORK(name) \
  1594. { #name, legacy_test_helper, TT_FORK, &legacy_setup, test_ ## name }
  1595. static struct testcase_t test_array[] = {
  1596. ENT(buffers),
  1597. { "buffer_copy", test_buffer_copy, 0, NULL, NULL },
  1598. ENT(onion_handshake),
  1599. ENT(circuit_timeout),
  1600. ENT(policies),
  1601. ENT(rend_fns),
  1602. ENT(geoip),
  1603. FORK(stats),
  1604. END_OF_TESTCASES
  1605. };
  1606. #define SOCKSENT(name) \
  1607. { #name, test_socks_##name, TT_FORK, &socks_setup, NULL }
  1608. static struct testcase_t socks_tests[] = {
  1609. SOCKSENT(4_unsupported_commands),
  1610. SOCKSENT(4_supported_commands),
  1611. SOCKSENT(5_unsupported_commands),
  1612. SOCKSENT(5_supported_commands),
  1613. SOCKSENT(5_no_authenticate),
  1614. SOCKSENT(5_auth_before_negotiation),
  1615. SOCKSENT(5_authenticate),
  1616. SOCKSENT(5_authenticate_with_data),
  1617. END_OF_TESTCASES
  1618. };
  1619. extern struct testcase_t addr_tests[];
  1620. extern struct testcase_t crypto_tests[];
  1621. extern struct testcase_t container_tests[];
  1622. extern struct testcase_t util_tests[];
  1623. extern struct testcase_t dir_tests[];
  1624. extern struct testcase_t microdesc_tests[];
  1625. extern struct testcase_t pt_tests[];
  1626. extern struct testcase_t config_tests[];
  1627. static struct testgroup_t testgroups[] = {
  1628. { "", test_array },
  1629. { "socks/", socks_tests },
  1630. { "addr/", addr_tests },
  1631. { "crypto/", crypto_tests },
  1632. { "container/", container_tests },
  1633. { "util/", util_tests },
  1634. { "dir/", dir_tests },
  1635. { "dir/md/", microdesc_tests },
  1636. { "pt/", pt_tests },
  1637. { "config/", config_tests },
  1638. END_OF_GROUPS
  1639. };
  1640. /** Main entry point for unit test code: parse the command line, and run
  1641. * some unit tests. */
  1642. int
  1643. main(int c, const char **v)
  1644. {
  1645. or_options_t *options;
  1646. char *errmsg = NULL;
  1647. int i, i_out;
  1648. int loglevel = LOG_ERR;
  1649. #ifdef USE_DMALLOC
  1650. {
  1651. int r = CRYPTO_set_mem_ex_functions(_tor_malloc, _tor_realloc, _tor_free);
  1652. tor_assert(r);
  1653. }
  1654. #endif
  1655. update_approx_time(time(NULL));
  1656. options = options_new();
  1657. tor_threads_init();
  1658. init_logging();
  1659. for (i_out = i = 1; i < c; ++i) {
  1660. if (!strcmp(v[i], "--warn")) {
  1661. loglevel = LOG_WARN;
  1662. } else if (!strcmp(v[i], "--notice")) {
  1663. loglevel = LOG_NOTICE;
  1664. } else if (!strcmp(v[i], "--info")) {
  1665. loglevel = LOG_INFO;
  1666. } else if (!strcmp(v[i], "--debug")) {
  1667. loglevel = LOG_DEBUG;
  1668. } else {
  1669. v[i_out++] = v[i];
  1670. }
  1671. }
  1672. c = i_out;
  1673. {
  1674. log_severity_list_t s;
  1675. memset(&s, 0, sizeof(s));
  1676. set_log_severity_config(loglevel, LOG_ERR, &s);
  1677. add_stream_log(&s, "", fileno(stdout));
  1678. }
  1679. options->command = CMD_RUN_UNITTESTS;
  1680. if (crypto_global_init(0, NULL, NULL)) {
  1681. printf("Can't initialize crypto subsystem; exiting.\n");
  1682. return 1;
  1683. }
  1684. crypto_set_tls_dh_prime(NULL);
  1685. rep_hist_init();
  1686. network_init();
  1687. setup_directory();
  1688. options_init(options);
  1689. options->DataDirectory = tor_strdup(temp_dir);
  1690. options->EntryStatistics = 1;
  1691. if (set_options(options, &errmsg) < 0) {
  1692. printf("Failed to set initial options: %s\n", errmsg);
  1693. tor_free(errmsg);
  1694. return 1;
  1695. }
  1696. crypto_seed_rng(1);
  1697. atexit(remove_directory);
  1698. have_failed = (tinytest_main(c, v, testgroups) != 0);
  1699. free_pregenerated_keys();
  1700. #ifdef USE_DMALLOC
  1701. tor_free_all(0);
  1702. dmalloc_log_unfreed();
  1703. #endif
  1704. if (have_failed)
  1705. return 1;
  1706. else
  1707. return 0;
  1708. }