test.c 66 KB

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