test.c 64 KB

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