test.c 121 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652
  1. /* Copyright (c) 2001-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2008, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char test_c_id[] =
  7. "$Id$";
  8. const char tor_svn_revision[] = "";
  9. /**
  10. * \file test.c
  11. * \brief Unit tests for many pieces of the lower level Tor modules.
  12. **/
  13. #include "orconfig.h"
  14. #include <stdio.h>
  15. #ifdef HAVE_FCNTL_H
  16. #include <fcntl.h>
  17. #endif
  18. #ifdef MS_WINDOWS
  19. /* For mkdir() */
  20. #include <direct.h>
  21. #else
  22. #include <dirent.h>
  23. #endif
  24. /* These macros pull in declarations for some functions and structures that
  25. * are typically file-private. */
  26. #define BUFFERS_PRIVATE
  27. #define CONFIG_PRIVATE
  28. #define CONTROL_PRIVATE
  29. #define CRYPTO_PRIVATE
  30. #define DIRSERV_PRIVATE
  31. #define DIRVOTE_PRIVATE
  32. #define GEOIP_PRIVATE
  33. #define MEMPOOL_PRIVATE
  34. #define ROUTER_PRIVATE
  35. #include "or.h"
  36. #include "test.h"
  37. #include "torgzip.h"
  38. #include "mempool.h"
  39. int have_failed = 0;
  40. static char temp_dir[256];
  41. static void
  42. setup_directory(void)
  43. {
  44. static int is_setup = 0;
  45. int r;
  46. if (is_setup) return;
  47. #ifdef MS_WINDOWS
  48. // XXXX
  49. tor_snprintf(temp_dir, sizeof(temp_dir),
  50. "c:\\windows\\temp\\tor_test_%d", (int)getpid());
  51. r = mkdir(temp_dir);
  52. #else
  53. tor_snprintf(temp_dir, sizeof(temp_dir), "/tmp/tor_test_%d", (int) getpid());
  54. r = mkdir(temp_dir, 0700);
  55. #endif
  56. if (r) {
  57. fprintf(stderr, "Can't create directory %s:", temp_dir);
  58. perror("");
  59. exit(1);
  60. }
  61. is_setup = 1;
  62. }
  63. static const char *
  64. get_fname(const char *name)
  65. {
  66. static char buf[1024];
  67. setup_directory();
  68. tor_snprintf(buf,sizeof(buf),"%s/%s",temp_dir,name);
  69. return buf;
  70. }
  71. static void
  72. remove_directory(void)
  73. {
  74. smartlist_t *elements = tor_listdir(temp_dir);
  75. if (elements) {
  76. SMARTLIST_FOREACH(elements, const char *, cp,
  77. {
  78. size_t len = strlen(cp)+strlen(temp_dir)+16;
  79. char *tmp = tor_malloc(len);
  80. tor_snprintf(tmp, len, "%s"PATH_SEPARATOR"%s", temp_dir, cp);
  81. unlink(tmp);
  82. tor_free(tmp);
  83. });
  84. SMARTLIST_FOREACH(elements, char *, cp, tor_free(cp));
  85. smartlist_free(elements);
  86. }
  87. rmdir(temp_dir);
  88. }
  89. static crypto_pk_env_t *
  90. pk_generate(int idx)
  91. {
  92. static crypto_pk_env_t *pregen[5] = {NULL, NULL, NULL, NULL, NULL};
  93. tor_assert(idx < (int)(sizeof(pregen)/sizeof(pregen[0])));
  94. if (! pregen[idx]) {
  95. pregen[idx] = crypto_new_pk_env();
  96. tor_assert(!crypto_pk_generate_key(pregen[idx]));
  97. }
  98. return crypto_pk_dup_key(pregen[idx]);
  99. }
  100. static void
  101. test_buffers(void)
  102. {
  103. char str[256];
  104. char str2[256];
  105. buf_t *buf, *buf2;
  106. const char *cp;
  107. int j;
  108. size_t r;
  109. /****
  110. * buf_new
  111. ****/
  112. if (!(buf = buf_new()))
  113. test_fail();
  114. //test_eq(buf_capacity(buf), 4096);
  115. test_eq(buf_datalen(buf), 0);
  116. /****
  117. * General pointer frobbing
  118. */
  119. for (j=0;j<256;++j) {
  120. str[j] = (char)j;
  121. }
  122. write_to_buf(str, 256, buf);
  123. write_to_buf(str, 256, buf);
  124. test_eq(buf_datalen(buf), 512);
  125. fetch_from_buf(str2, 200, buf);
  126. test_memeq(str, str2, 200);
  127. test_eq(buf_datalen(buf), 312);
  128. memset(str2, 0, sizeof(str2));
  129. fetch_from_buf(str2, 256, buf);
  130. test_memeq(str+200, str2, 56);
  131. test_memeq(str, str2+56, 200);
  132. test_eq(buf_datalen(buf), 56);
  133. memset(str2, 0, sizeof(str2));
  134. /* Okay, now we should be 512 bytes into the 4096-byte buffer. If we add
  135. * another 3584 bytes, we hit the end. */
  136. for (j=0;j<15;++j) {
  137. write_to_buf(str, 256, buf);
  138. }
  139. assert_buf_ok(buf);
  140. test_eq(buf_datalen(buf), 3896);
  141. fetch_from_buf(str2, 56, buf);
  142. test_eq(buf_datalen(buf), 3840);
  143. test_memeq(str+200, str2, 56);
  144. for (j=0;j<15;++j) {
  145. memset(str2, 0, sizeof(str2));
  146. fetch_from_buf(str2, 256, buf);
  147. test_memeq(str, str2, 256);
  148. }
  149. test_eq(buf_datalen(buf), 0);
  150. buf_free(buf);
  151. /* Okay, now make sure growing can work. */
  152. buf = buf_new_with_capacity(16);
  153. //test_eq(buf_capacity(buf), 16);
  154. write_to_buf(str+1, 255, buf);
  155. //test_eq(buf_capacity(buf), 256);
  156. fetch_from_buf(str2, 254, buf);
  157. test_memeq(str+1, str2, 254);
  158. //test_eq(buf_capacity(buf), 256);
  159. assert_buf_ok(buf);
  160. write_to_buf(str, 32, buf);
  161. //test_eq(buf_capacity(buf), 256);
  162. assert_buf_ok(buf);
  163. write_to_buf(str, 256, buf);
  164. assert_buf_ok(buf);
  165. //test_eq(buf_capacity(buf), 512);
  166. test_eq(buf_datalen(buf), 33+256);
  167. fetch_from_buf(str2, 33, buf);
  168. test_eq(*str2, str[255]);
  169. test_memeq(str2+1, str, 32);
  170. //test_eq(buf_capacity(buf), 512);
  171. test_eq(buf_datalen(buf), 256);
  172. fetch_from_buf(str2, 256, buf);
  173. test_memeq(str, str2, 256);
  174. /* now try shrinking: case 1. */
  175. buf_free(buf);
  176. buf = buf_new_with_capacity(33668);
  177. for (j=0;j<67;++j) {
  178. write_to_buf(str,255, buf);
  179. }
  180. //test_eq(buf_capacity(buf), 33668);
  181. test_eq(buf_datalen(buf), 17085);
  182. for (j=0; j < 40; ++j) {
  183. fetch_from_buf(str2, 255,buf);
  184. test_memeq(str2, str, 255);
  185. }
  186. /* now try shrinking: case 2. */
  187. buf_free(buf);
  188. buf = buf_new_with_capacity(33668);
  189. for (j=0;j<67;++j) {
  190. write_to_buf(str,255, buf);
  191. }
  192. for (j=0; j < 20; ++j) {
  193. fetch_from_buf(str2, 255,buf);
  194. test_memeq(str2, str, 255);
  195. }
  196. for (j=0;j<80;++j) {
  197. write_to_buf(str,255, buf);
  198. }
  199. //test_eq(buf_capacity(buf),33668);
  200. for (j=0; j < 120; ++j) {
  201. fetch_from_buf(str2, 255,buf);
  202. test_memeq(str2, str, 255);
  203. }
  204. /* Move from buf to buf. */
  205. buf_free(buf);
  206. buf = buf_new_with_capacity(4096);
  207. buf2 = buf_new_with_capacity(4096);
  208. for (j=0;j<100;++j)
  209. write_to_buf(str, 255, buf);
  210. test_eq(buf_datalen(buf), 25500);
  211. for (j=0;j<100;++j) {
  212. r = 10;
  213. move_buf_to_buf(buf2, buf, &r);
  214. test_eq(r, 0);
  215. }
  216. test_eq(buf_datalen(buf), 24500);
  217. test_eq(buf_datalen(buf2), 1000);
  218. for (j=0;j<3;++j) {
  219. fetch_from_buf(str2, 255, buf2);
  220. test_memeq(str2, str, 255);
  221. }
  222. r = 8192; /*big move*/
  223. move_buf_to_buf(buf2, buf, &r);
  224. test_eq(r, 0);
  225. r = 30000; /* incomplete move */
  226. move_buf_to_buf(buf2, buf, &r);
  227. test_eq(r, 13692);
  228. for (j=0;j<97;++j) {
  229. fetch_from_buf(str2, 255, buf2);
  230. test_memeq(str2, str, 255);
  231. }
  232. buf_free(buf);
  233. buf_free(buf2);
  234. buf = buf_new_with_capacity(5);
  235. cp = "Testing. This is a moderately long Testing string.";
  236. for (j = 0; cp[j]; j++)
  237. write_to_buf(cp+j, 1, buf);
  238. test_eq(0, buf_find_string_offset(buf, "Testing", 7));
  239. test_eq(1, buf_find_string_offset(buf, "esting", 6));
  240. test_eq(1, buf_find_string_offset(buf, "est", 3));
  241. test_eq(39, buf_find_string_offset(buf, "ing str", 7));
  242. test_eq(35, buf_find_string_offset(buf, "Testing str", 11));
  243. test_eq(32, buf_find_string_offset(buf, "ng ", 3));
  244. test_eq(43, buf_find_string_offset(buf, "string.", 7));
  245. test_eq(-1, buf_find_string_offset(buf, "shrdlu", 6));
  246. test_eq(-1, buf_find_string_offset(buf, "Testing thing", 13));
  247. test_eq(-1, buf_find_string_offset(buf, "ngx", 3));
  248. buf_free(buf);
  249. #if 0
  250. {
  251. int s;
  252. int eof;
  253. int i;
  254. buf_t *buf2;
  255. /****
  256. * read_to_buf
  257. ****/
  258. s = open(get_fname("data"), O_WRONLY|O_CREAT|O_TRUNC, 0600);
  259. write(s, str, 256);
  260. close(s);
  261. s = open(get_fname("data"), O_RDONLY, 0);
  262. eof = 0;
  263. errno = 0; /* XXXX */
  264. i = read_to_buf(s, 10, buf, &eof);
  265. printf("%s\n", strerror(errno));
  266. test_eq(i, 10);
  267. test_eq(eof, 0);
  268. //test_eq(buf_capacity(buf), 4096);
  269. test_eq(buf_datalen(buf), 10);
  270. test_memeq(str, (char*)_buf_peek_raw_buffer(buf), 10);
  271. /* Test reading 0 bytes. */
  272. i = read_to_buf(s, 0, buf, &eof);
  273. //test_eq(buf_capacity(buf), 512*1024);
  274. test_eq(buf_datalen(buf), 10);
  275. test_eq(eof, 0);
  276. test_eq(i, 0);
  277. /* Now test when buffer is filled exactly. */
  278. buf2 = buf_new_with_capacity(6);
  279. i = read_to_buf(s, 6, buf2, &eof);
  280. //test_eq(buf_capacity(buf2), 6);
  281. test_eq(buf_datalen(buf2), 6);
  282. test_eq(eof, 0);
  283. test_eq(i, 6);
  284. test_memeq(str+10, (char*)_buf_peek_raw_buffer(buf2), 6);
  285. buf_free(buf2);
  286. /* Now test when buffer is filled with more data to read. */
  287. buf2 = buf_new_with_capacity(32);
  288. i = read_to_buf(s, 128, buf2, &eof);
  289. //test_eq(buf_capacity(buf2), 128);
  290. test_eq(buf_datalen(buf2), 32);
  291. test_eq(eof, 0);
  292. test_eq(i, 32);
  293. buf_free(buf2);
  294. /* Now read to eof. */
  295. test_assert(buf_capacity(buf) > 256);
  296. i = read_to_buf(s, 1024, buf, &eof);
  297. test_eq(i, (256-32-10-6));
  298. test_eq(buf_capacity(buf), MAX_BUF_SIZE);
  299. test_eq(buf_datalen(buf), 256-6-32);
  300. test_memeq(str, (char*)_buf_peek_raw_buffer(buf), 10); /* XXX Check rest. */
  301. test_eq(eof, 0);
  302. i = read_to_buf(s, 1024, buf, &eof);
  303. test_eq(i, 0);
  304. test_eq(buf_capacity(buf), MAX_BUF_SIZE);
  305. test_eq(buf_datalen(buf), 256-6-32);
  306. test_eq(eof, 1);
  307. }
  308. #endif
  309. }
  310. static void
  311. test_crypto_dh(void)
  312. {
  313. crypto_dh_env_t *dh1, *dh2;
  314. char p1[DH_BYTES];
  315. char p2[DH_BYTES];
  316. char s1[DH_BYTES];
  317. char s2[DH_BYTES];
  318. int s1len, s2len;
  319. dh1 = crypto_dh_new();
  320. dh2 = crypto_dh_new();
  321. test_eq(crypto_dh_get_bytes(dh1), DH_BYTES);
  322. test_eq(crypto_dh_get_bytes(dh2), DH_BYTES);
  323. memset(p1, 0, DH_BYTES);
  324. memset(p2, 0, DH_BYTES);
  325. test_memeq(p1, p2, DH_BYTES);
  326. test_assert(! crypto_dh_get_public(dh1, p1, DH_BYTES));
  327. test_memneq(p1, p2, DH_BYTES);
  328. test_assert(! crypto_dh_get_public(dh2, p2, DH_BYTES));
  329. test_memneq(p1, p2, DH_BYTES);
  330. memset(s1, 0, DH_BYTES);
  331. memset(s2, 0xFF, DH_BYTES);
  332. s1len = crypto_dh_compute_secret(dh1, p2, DH_BYTES, s1, 50);
  333. s2len = crypto_dh_compute_secret(dh2, p1, DH_BYTES, s2, 50);
  334. test_assert(s1len > 0);
  335. test_eq(s1len, s2len);
  336. test_memeq(s1, s2, s1len);
  337. crypto_dh_free(dh1);
  338. crypto_dh_free(dh2);
  339. }
  340. static void
  341. test_crypto(void)
  342. {
  343. crypto_cipher_env_t *env1, *env2;
  344. crypto_pk_env_t *pk1, *pk2;
  345. char *data1, *data2, *data3, *cp;
  346. int i, j, p, len, idx;
  347. size_t size;
  348. data1 = tor_malloc(1024);
  349. data2 = tor_malloc(1024);
  350. data3 = tor_malloc(1024);
  351. test_assert(data1 && data2 && data3);
  352. /* Try out RNG. */
  353. test_assert(! crypto_seed_rng());
  354. crypto_rand(data1, 100);
  355. crypto_rand(data2, 100);
  356. test_memneq(data1,data2,100);
  357. /* Now, test encryption and decryption with stream cipher. */
  358. data1[0]='\0';
  359. for (i = 1023; i>0; i -= 35)
  360. strncat(data1, "Now is the time for all good onions", i);
  361. memset(data2, 0, 1024);
  362. memset(data3, 0, 1024);
  363. env1 = crypto_new_cipher_env();
  364. test_neq(env1, 0);
  365. env2 = crypto_new_cipher_env();
  366. test_neq(env2, 0);
  367. j = crypto_cipher_generate_key(env1);
  368. crypto_cipher_set_key(env2, crypto_cipher_get_key(env1));
  369. crypto_cipher_encrypt_init_cipher(env1);
  370. crypto_cipher_decrypt_init_cipher(env2);
  371. /* Try encrypting 512 chars. */
  372. crypto_cipher_encrypt(env1, data2, data1, 512);
  373. crypto_cipher_decrypt(env2, data3, data2, 512);
  374. test_memeq(data1, data3, 512);
  375. test_memneq(data1, data2, 512);
  376. /* Now encrypt 1 at a time, and get 1 at a time. */
  377. for (j = 512; j < 560; ++j) {
  378. crypto_cipher_encrypt(env1, data2+j, data1+j, 1);
  379. }
  380. for (j = 512; j < 560; ++j) {
  381. crypto_cipher_decrypt(env2, data3+j, data2+j, 1);
  382. }
  383. test_memeq(data1, data3, 560);
  384. /* Now encrypt 3 at a time, and get 5 at a time. */
  385. for (j = 560; j < 1024-5; j += 3) {
  386. crypto_cipher_encrypt(env1, data2+j, data1+j, 3);
  387. }
  388. for (j = 560; j < 1024-5; j += 5) {
  389. crypto_cipher_decrypt(env2, data3+j, data2+j, 5);
  390. }
  391. test_memeq(data1, data3, 1024-5);
  392. /* Now make sure that when we encrypt with different chunk sizes, we get
  393. the same results. */
  394. crypto_free_cipher_env(env2);
  395. memset(data3, 0, 1024);
  396. env2 = crypto_new_cipher_env();
  397. test_neq(env2, 0);
  398. crypto_cipher_set_key(env2, crypto_cipher_get_key(env1));
  399. crypto_cipher_encrypt_init_cipher(env2);
  400. for (j = 0; j < 1024-16; j += 17) {
  401. crypto_cipher_encrypt(env2, data3+j, data1+j, 17);
  402. }
  403. for (j= 0; j < 1024-16; ++j) {
  404. if (data2[j] != data3[j]) {
  405. printf("%d: %d\t%d\n", j, (int) data2[j], (int) data3[j]);
  406. }
  407. }
  408. test_memeq(data2, data3, 1024-16);
  409. crypto_free_cipher_env(env1);
  410. crypto_free_cipher_env(env2);
  411. /* Test vectors for stream ciphers. */
  412. /* XXXX Look up some test vectors for the ciphers and make sure we match. */
  413. /* Test SHA-1 with a test vector from the specification. */
  414. i = crypto_digest(data1, "abc", 3);
  415. test_memeq(data1,
  416. "\xA9\x99\x3E\x36\x47\x06\x81\x6A\xBA\x3E\x25\x71\x78"
  417. "\x50\xC2\x6C\x9C\xD0\xD8\x9D", 20);
  418. /* Test HMAC-SHA-1 with test cases from RFC2202. */
  419. {
  420. char key[80];
  421. char digest[20];
  422. char data[50];
  423. /* Case 1. */
  424. memset(key, 0x0b, 20);
  425. crypto_hmac_sha1(digest, key, 20, "Hi There", 8);
  426. test_streq(hex_str(digest, 20),
  427. "B617318655057264E28BC0B6FB378C8EF146BE00");
  428. /* Case 2. */
  429. crypto_hmac_sha1(digest, "Jefe", 4, "what do ya want for nothing?", 28);
  430. test_streq(hex_str(digest, 20),
  431. "EFFCDF6AE5EB2FA2D27416D5F184DF9C259A7C79");
  432. /* Case 4. */
  433. base16_decode(key, 25,
  434. "0102030405060708090a0b0c0d0e0f10111213141516171819", 50);
  435. memset(data, 0xcd, 50);
  436. crypto_hmac_sha1(digest, key, 25, data, 50);
  437. test_streq(hex_str(digest, 20),
  438. "4C9007F4026250C6BC8414F9BF50C86C2D7235DA");
  439. /* Case . */
  440. memset(key, 0xaa, 80);
  441. crypto_hmac_sha1(digest, key, 80,
  442. "Test Using Larger Than Block-Size Key - Hash Key First",
  443. 54);
  444. test_streq(hex_str(digest, 20),
  445. "AA4AE5E15272D00E95705637CE8A3B55ED402112");
  446. }
  447. /* Public-key ciphers */
  448. pk1 = pk_generate(0);
  449. pk2 = crypto_new_pk_env();
  450. test_assert(pk1 && pk2);
  451. test_assert(! crypto_pk_write_public_key_to_string(pk1, &cp, &size));
  452. test_assert(! crypto_pk_read_public_key_from_string(pk2, cp, size));
  453. test_eq(0, crypto_pk_cmp_keys(pk1, pk2));
  454. tor_free(cp);
  455. test_eq(128, crypto_pk_keysize(pk1));
  456. test_eq(128, crypto_pk_keysize(pk2));
  457. test_eq(128, crypto_pk_public_encrypt(pk2, data1, "Hello whirled.", 15,
  458. PK_PKCS1_OAEP_PADDING));
  459. test_eq(128, crypto_pk_public_encrypt(pk1, data2, "Hello whirled.", 15,
  460. PK_PKCS1_OAEP_PADDING));
  461. /* oaep padding should make encryption not match */
  462. test_memneq(data1, data2, 128);
  463. test_eq(15, crypto_pk_private_decrypt(pk1, data3, data1, 128,
  464. PK_PKCS1_OAEP_PADDING,1));
  465. test_streq(data3, "Hello whirled.");
  466. memset(data3, 0, 1024);
  467. test_eq(15, crypto_pk_private_decrypt(pk1, data3, data2, 128,
  468. PK_PKCS1_OAEP_PADDING,1));
  469. test_streq(data3, "Hello whirled.");
  470. /* Can't decrypt with public key. */
  471. test_eq(-1, crypto_pk_private_decrypt(pk2, data3, data2, 128,
  472. PK_PKCS1_OAEP_PADDING,1));
  473. /* Try again with bad padding */
  474. memcpy(data2+1, "XYZZY", 5); /* This has fails ~ once-in-2^40 */
  475. test_eq(-1, crypto_pk_private_decrypt(pk1, data3, data2, 128,
  476. PK_PKCS1_OAEP_PADDING,1));
  477. /* File operations: save and load private key */
  478. test_assert(! crypto_pk_write_private_key_to_filename(pk1,
  479. get_fname("pkey1")));
  480. test_assert(! crypto_pk_read_private_key_from_filename(pk2,
  481. get_fname("pkey1")));
  482. test_eq(15, crypto_pk_private_decrypt(pk2, data3, data1, 128,
  483. PK_PKCS1_OAEP_PADDING,1));
  484. /* Now try signing. */
  485. strlcpy(data1, "Ossifrage", 1024);
  486. test_eq(128, crypto_pk_private_sign(pk1, data2, data1, 10));
  487. test_eq(10, crypto_pk_public_checksig(pk1, data3, data2, 128));
  488. test_streq(data3, "Ossifrage");
  489. /* Try signing digests. */
  490. test_eq(128, crypto_pk_private_sign_digest(pk1, data2, data1, 10));
  491. test_eq(20, crypto_pk_public_checksig(pk1, data3, data2, 128));
  492. test_eq(0, crypto_pk_public_checksig_digest(pk1, data1, 10, data2, 128));
  493. test_eq(-1, crypto_pk_public_checksig_digest(pk1, data1, 11, data2, 128));
  494. /*XXXX test failed signing*/
  495. /* Try encoding */
  496. crypto_free_pk_env(pk2);
  497. pk2 = NULL;
  498. i = crypto_pk_asn1_encode(pk1, data1, 1024);
  499. test_assert(i>0);
  500. pk2 = crypto_pk_asn1_decode(data1, i);
  501. test_assert(crypto_pk_cmp_keys(pk1,pk2) == 0);
  502. /* Try with hybrid encryption wrappers. */
  503. crypto_rand(data1, 1024);
  504. for (i = 0; i < 3; ++i) {
  505. for (j = 85; j < 140; ++j) {
  506. memset(data2,0,1024);
  507. memset(data3,0,1024);
  508. if (i == 0 && j < 129)
  509. continue;
  510. p = (i==0)?PK_NO_PADDING:
  511. (i==1)?PK_PKCS1_PADDING:PK_PKCS1_OAEP_PADDING;
  512. len = crypto_pk_public_hybrid_encrypt(pk1,data2,data1,j,p,0);
  513. test_assert(len>=0);
  514. len = crypto_pk_private_hybrid_decrypt(pk1,data3,data2,len,p,1);
  515. test_eq(len,j);
  516. test_memeq(data1,data3,j);
  517. }
  518. }
  519. crypto_free_pk_env(pk1);
  520. crypto_free_pk_env(pk2);
  521. /* Base64 tests */
  522. memset(data1, 6, 1024);
  523. for (idx = 0; idx < 10; ++idx) {
  524. i = base64_encode(data2, 1024, data1, idx);
  525. j = base64_decode(data3, 1024, data2, i);
  526. test_eq(j,idx);
  527. test_memeq(data3, data1, idx);
  528. }
  529. strlcpy(data1, "Test string that contains 35 chars.", 1024);
  530. strlcat(data1, " 2nd string that contains 35 chars.", 1024);
  531. i = base64_encode(data2, 1024, data1, 71);
  532. j = base64_decode(data3, 1024, data2, i);
  533. test_eq(j, 71);
  534. test_streq(data3, data1);
  535. test_assert(data2[i] == '\0');
  536. crypto_rand(data1, DIGEST_LEN);
  537. memset(data2, 100, 1024);
  538. digest_to_base64(data2, data1);
  539. test_eq(BASE64_DIGEST_LEN, strlen(data2));
  540. test_eq(100, data2[BASE64_DIGEST_LEN+2]);
  541. memset(data3, 99, 1024);
  542. test_eq(digest_from_base64(data3, data2), 0);
  543. test_memeq(data1, data3, DIGEST_LEN);
  544. test_eq(99, data3[DIGEST_LEN+1]);
  545. /* Base32 tests */
  546. strlcpy(data1, "5chrs", 1024);
  547. /* bit pattern is: [35 63 68 72 73] ->
  548. * [00110101 01100011 01101000 01110010 01110011]
  549. * By 5s: [00110 10101 10001 10110 10000 11100 10011 10011]
  550. */
  551. base32_encode(data2, 9, data1, 5);
  552. test_streq(data2, "gvrwq4tt");
  553. strlcpy(data1, "\xFF\xF5\x6D\x44\xAE\x0D\x5C\xC9\x62\xC4", 1024);
  554. base32_encode(data2, 30, data1, 10);
  555. test_streq(data2, "772w2rfobvomsywe");
  556. /* Base16 tests */
  557. strlcpy(data1, "6chrs\xff", 1024);
  558. base16_encode(data2, 13, data1, 6);
  559. test_streq(data2, "3663687273FF");
  560. strlcpy(data1, "f0d678affc000100", 1024);
  561. i = base16_decode(data2, 8, data1, 16);
  562. test_eq(i,0);
  563. test_memeq(data2, "\xf0\xd6\x78\xaf\xfc\x00\x01\x00",8);
  564. /* now try some failing base16 decodes */
  565. test_eq(-1, base16_decode(data2, 8, data1, 15)); /* odd input len */
  566. test_eq(-1, base16_decode(data2, 7, data1, 16)); /* dest too short */
  567. strlcpy(data1, "f0dz!8affc000100", 1024);
  568. test_eq(-1, base16_decode(data2, 8, data1, 16));
  569. tor_free(data1);
  570. tor_free(data2);
  571. tor_free(data3);
  572. /* Add spaces to fingerprint */
  573. {
  574. data1 = tor_strdup("ABCD1234ABCD56780000ABCD1234ABCD56780000");
  575. test_eq(strlen(data1), 40);
  576. data2 = tor_malloc(FINGERPRINT_LEN+1);
  577. add_spaces_to_fp(data2, FINGERPRINT_LEN+1, data1);
  578. test_streq(data2, "ABCD 1234 ABCD 5678 0000 ABCD 1234 ABCD 5678 0000");
  579. tor_free(data1);
  580. tor_free(data2);
  581. }
  582. }
  583. static void
  584. test_crypto_s2k(void)
  585. {
  586. char buf[29];
  587. char buf2[29];
  588. char *buf3;
  589. int i;
  590. memset(buf, 0, sizeof(buf));
  591. memset(buf2, 0, sizeof(buf2));
  592. buf3 = tor_malloc(65536);
  593. memset(buf3, 0, 65536);
  594. secret_to_key(buf+9, 20, "", 0, buf);
  595. crypto_digest(buf2+9, buf3, 1024);
  596. test_memeq(buf, buf2, 29);
  597. memcpy(buf,"vrbacrda",8);
  598. memcpy(buf2,"vrbacrda",8);
  599. buf[8] = 96;
  600. buf2[8] = 96;
  601. secret_to_key(buf+9, 20, "12345678", 8, buf);
  602. for (i = 0; i < 65536; i += 16) {
  603. memcpy(buf3+i, "vrbacrda12345678", 16);
  604. }
  605. crypto_digest(buf2+9, buf3, 65536);
  606. test_memeq(buf, buf2, 29);
  607. tor_free(buf3);
  608. }
  609. static int
  610. _compare_strs(const void **a, const void **b)
  611. {
  612. const char *s1 = *a, *s2 = *b;
  613. return strcmp(s1, s2);
  614. }
  615. static int
  616. _compare_without_first_ch(const void *a, const void **b)
  617. {
  618. const char *s1 = a, *s2 = *b;
  619. return strcasecmp(s1+1, s2);
  620. }
  621. static void
  622. test_util(void)
  623. {
  624. struct timeval start, end;
  625. struct tm a_time;
  626. char timestr[RFC1123_TIME_LEN+1];
  627. char buf[1024];
  628. time_t t_res;
  629. int i;
  630. uint32_t u32;
  631. uint16_t u16;
  632. char *cp, *k, *v;
  633. const char *str;
  634. start.tv_sec = 5;
  635. start.tv_usec = 5000;
  636. end.tv_sec = 5;
  637. end.tv_usec = 5000;
  638. test_eq(0L, tv_udiff(&start, &end));
  639. end.tv_usec = 7000;
  640. test_assert(tv_cmp(&start, &end)<0);
  641. test_assert(tv_cmp(&end, &start)>0);
  642. test_assert(tv_cmp(&end, &end)==0);
  643. test_eq(2000L, tv_udiff(&start, &end));
  644. end.tv_sec = 6;
  645. test_eq(1002000L, tv_udiff(&start, &end));
  646. end.tv_usec = 0;
  647. test_eq(995000L, tv_udiff(&start, &end));
  648. end.tv_sec = 4;
  649. test_eq(-1005000L, tv_udiff(&start, &end));
  650. tv_addms(&end, 5090);
  651. test_eq(end.tv_sec, 9);
  652. test_eq(end.tv_usec, 90000);
  653. end.tv_usec = 999990;
  654. start.tv_sec = 1;
  655. start.tv_usec = 500;
  656. tv_add(&start, &end);
  657. test_eq(start.tv_sec, 11);
  658. test_eq(start.tv_usec, 490);
  659. /* The test values here are confirmed to be correct on a platform
  660. * with a working timegm. */
  661. a_time.tm_year = 2003-1900;
  662. a_time.tm_mon = 7;
  663. a_time.tm_mday = 30;
  664. a_time.tm_hour = 6;
  665. a_time.tm_min = 14;
  666. a_time.tm_sec = 55;
  667. test_eq((time_t) 1062224095UL, tor_timegm(&a_time));
  668. a_time.tm_year = 2004-1900; /* Try a leap year, after feb. */
  669. test_eq((time_t) 1093846495UL, tor_timegm(&a_time));
  670. a_time.tm_mon = 1; /* Try a leap year, in feb. */
  671. a_time.tm_mday = 10;
  672. test_eq((time_t) 1076393695UL, tor_timegm(&a_time));
  673. format_rfc1123_time(timestr, 0);
  674. test_streq("Thu, 01 Jan 1970 00:00:00 GMT", timestr);
  675. format_rfc1123_time(timestr, (time_t)1091580502UL);
  676. test_streq("Wed, 04 Aug 2004 00:48:22 GMT", timestr);
  677. t_res = 0;
  678. i = parse_rfc1123_time(timestr, &t_res);
  679. test_eq(i,0);
  680. test_eq(t_res, (time_t)1091580502UL);
  681. test_eq(-1, parse_rfc1123_time("Wed, zz Aug 2004 99-99x99 GMT", &t_res));
  682. tor_gettimeofday(&start);
  683. /* Test tor_strstrip() */
  684. strlcpy(buf, "Testing 1 2 3", sizeof(buf));
  685. test_eq(0, tor_strstrip(buf, ",!"));
  686. test_streq(buf, "Testing 1 2 3");
  687. strlcpy(buf, "!Testing 1 2 3?", sizeof(buf));
  688. test_eq(5, tor_strstrip(buf, "!? "));
  689. test_streq(buf, "Testing123");
  690. /* Test parse_addr_port */
  691. cp = NULL; u32 = 3; u16 = 3;
  692. test_assert(!parse_addr_port(LOG_WARN, "1.2.3.4", &cp, &u32, &u16));
  693. test_streq(cp, "1.2.3.4");
  694. test_eq(u32, 0x01020304u);
  695. test_eq(u16, 0);
  696. tor_free(cp);
  697. test_assert(!parse_addr_port(LOG_WARN, "4.3.2.1:99", &cp, &u32, &u16));
  698. test_streq(cp, "4.3.2.1");
  699. test_eq(u32, 0x04030201u);
  700. test_eq(u16, 99);
  701. tor_free(cp);
  702. test_assert(!parse_addr_port(LOG_WARN, "nonexistent.address:4040",
  703. &cp, NULL, &u16));
  704. test_streq(cp, "nonexistent.address");
  705. test_eq(u16, 4040);
  706. tor_free(cp);
  707. test_assert(!parse_addr_port(LOG_WARN, "localhost:9999", &cp, &u32, &u16));
  708. test_streq(cp, "localhost");
  709. test_eq(u32, 0x7f000001u);
  710. test_eq(u16, 9999);
  711. tor_free(cp);
  712. u32 = 3;
  713. test_assert(!parse_addr_port(LOG_WARN, "localhost", NULL, &u32, &u16));
  714. test_eq(cp, NULL);
  715. test_eq(u32, 0x7f000001u);
  716. test_eq(u16, 0);
  717. tor_free(cp);
  718. test_eq(0, addr_mask_get_bits(0x0u));
  719. test_eq(32, addr_mask_get_bits(0xFFFFFFFFu));
  720. test_eq(16, addr_mask_get_bits(0xFFFF0000u));
  721. test_eq(31, addr_mask_get_bits(0xFFFFFFFEu));
  722. test_eq(1, addr_mask_get_bits(0x80000000u));
  723. /* Test tor_parse_long. */
  724. test_eq(10L, tor_parse_long("10",10,0,100,NULL,NULL));
  725. test_eq(0L, tor_parse_long("10",10,50,100,NULL,NULL));
  726. test_eq(-50L, tor_parse_long("-50",10,-100,100,NULL,NULL));
  727. /* Test tor_parse_ulong */
  728. test_eq(10UL, tor_parse_ulong("10",10,0,100,NULL,NULL));
  729. test_eq(0UL, tor_parse_ulong("10",10,50,100,NULL,NULL));
  730. /* Test tor_parse_uint64. */
  731. test_assert(U64_LITERAL(10) == tor_parse_uint64("10 x",10,0,100, &i, &cp));
  732. test_assert(i == 1);
  733. test_streq(cp, " x");
  734. test_assert(U64_LITERAL(12345678901) ==
  735. tor_parse_uint64("12345678901",10,0,UINT64_MAX, &i, &cp));
  736. test_assert(i == 1);
  737. test_streq(cp, "");
  738. test_assert(U64_LITERAL(0) ==
  739. tor_parse_uint64("12345678901",10,500,INT32_MAX, &i, &cp));
  740. test_assert(i == 0);
  741. /* Test printf with uint64 */
  742. tor_snprintf(buf, sizeof(buf), "x!"U64_FORMAT"!x",
  743. U64_PRINTF_ARG(U64_LITERAL(12345678901)));
  744. test_streq(buf, "x!12345678901!x");
  745. /* Test parse_config_line_from_str */
  746. strlcpy(buf, "k v\n" " key value with spaces \n" "keykey val\n"
  747. "k2\n"
  748. "k3 \n" "\n" " \n" "#comment\n"
  749. "k4#a\n" "k5#abc\n" "k6 val #with comment\n"
  750. "kseven \"a quoted 'string\"\n"
  751. "k8 \"a \\x71uoted\\n\\\"str\\\\ing\\t\\001\\01\\1\\\"\"\n"
  752. , sizeof(buf));
  753. str = buf;
  754. str = parse_config_line_from_str(str, &k, &v);
  755. test_streq(k, "k");
  756. test_streq(v, "v");
  757. tor_free(k); tor_free(v);
  758. test_assert(!strcmpstart(str, "key value with"));
  759. str = parse_config_line_from_str(str, &k, &v);
  760. test_streq(k, "key");
  761. test_streq(v, "value with spaces");
  762. tor_free(k); tor_free(v);
  763. test_assert(!strcmpstart(str, "keykey"));
  764. str = parse_config_line_from_str(str, &k, &v);
  765. test_streq(k, "keykey");
  766. test_streq(v, "val");
  767. tor_free(k); tor_free(v);
  768. test_assert(!strcmpstart(str, "k2\n"));
  769. str = parse_config_line_from_str(str, &k, &v);
  770. test_streq(k, "k2");
  771. test_streq(v, "");
  772. tor_free(k); tor_free(v);
  773. test_assert(!strcmpstart(str, "k3 \n"));
  774. str = parse_config_line_from_str(str, &k, &v);
  775. test_streq(k, "k3");
  776. test_streq(v, "");
  777. tor_free(k); tor_free(v);
  778. test_assert(!strcmpstart(str, "#comment"));
  779. str = parse_config_line_from_str(str, &k, &v);
  780. test_streq(k, "k4");
  781. test_streq(v, "");
  782. tor_free(k); tor_free(v);
  783. test_assert(!strcmpstart(str, "k5#abc"));
  784. str = parse_config_line_from_str(str, &k, &v);
  785. test_streq(k, "k5");
  786. test_streq(v, "");
  787. tor_free(k); tor_free(v);
  788. test_assert(!strcmpstart(str, "k6"));
  789. str = parse_config_line_from_str(str, &k, &v);
  790. test_streq(k, "k6");
  791. test_streq(v, "val");
  792. tor_free(k); tor_free(v);
  793. test_assert(!strcmpstart(str, "kseven"));
  794. str = parse_config_line_from_str(str, &k, &v);
  795. test_streq(k, "kseven");
  796. test_streq(v, "a quoted 'string");
  797. tor_free(k); tor_free(v);
  798. test_assert(!strcmpstart(str, "k8 "));
  799. str = parse_config_line_from_str(str, &k, &v);
  800. test_streq(k, "k8");
  801. test_streq(v, "a quoted\n\"str\\ing\t\x01\x01\x01\"");
  802. tor_free(k); tor_free(v);
  803. test_streq(str, "");
  804. /* Test for strcmpstart and strcmpend. */
  805. test_assert(strcmpstart("abcdef", "abcdef")==0);
  806. test_assert(strcmpstart("abcdef", "abc")==0);
  807. test_assert(strcmpstart("abcdef", "abd")<0);
  808. test_assert(strcmpstart("abcdef", "abb")>0);
  809. test_assert(strcmpstart("ab", "abb")<0);
  810. test_assert(strcmpend("abcdef", "abcdef")==0);
  811. test_assert(strcmpend("abcdef", "def")==0);
  812. test_assert(strcmpend("abcdef", "deg")<0);
  813. test_assert(strcmpend("abcdef", "dee")>0);
  814. test_assert(strcmpend("ab", "abb")<0);
  815. test_assert(strcasecmpend("AbcDEF", "abcdef")==0);
  816. test_assert(strcasecmpend("abcdef", "dEF")==0);
  817. test_assert(strcasecmpend("abcDEf", "deg")<0);
  818. test_assert(strcasecmpend("abcdef", "DEE")>0);
  819. test_assert(strcasecmpend("ab", "abB")<0);
  820. /* Test mem_is_zero */
  821. memset(buf,0,128);
  822. buf[128] = 'x';
  823. test_assert(tor_digest_is_zero(buf));
  824. test_assert(tor_mem_is_zero(buf, 10));
  825. test_assert(tor_mem_is_zero(buf, 20));
  826. test_assert(tor_mem_is_zero(buf, 128));
  827. test_assert(!tor_mem_is_zero(buf, 129));
  828. buf[60] = (char)255;
  829. test_assert(!tor_mem_is_zero(buf, 128));
  830. buf[0] = (char)1;
  831. test_assert(!tor_mem_is_zero(buf, 10));
  832. /* Test inet_ntop */
  833. {
  834. char tmpbuf[TOR_ADDR_BUF_LEN];
  835. const char *ip = "176.192.208.224";
  836. struct in_addr in;
  837. tor_inet_pton(AF_INET, ip, &in);
  838. tor_inet_ntop(AF_INET, &in, tmpbuf, sizeof(tmpbuf));
  839. test_streq(tmpbuf, ip);
  840. }
  841. /* Test 'escaped' */
  842. test_streq("\"\"", escaped(""));
  843. test_streq("\"abcd\"", escaped("abcd"));
  844. test_streq("\"\\\\\\n\\r\\t\\\"\\'\"", escaped("\\\n\r\t\"\'"));
  845. test_streq("\"z\\001abc\\277d\"", escaped("z\001abc\277d"));
  846. test_assert(NULL == escaped(NULL));
  847. /* Test strndup and memdup */
  848. {
  849. const char *s = "abcdefghijklmnopqrstuvwxyz";
  850. cp = tor_strndup(s, 30);
  851. test_streq(cp, s); /* same string, */
  852. test_neq(cp, s); /* but different pointers. */
  853. tor_free(cp);
  854. cp = tor_strndup(s, 5);
  855. test_streq(cp, "abcde");
  856. tor_free(cp);
  857. s = "a\0b\0c\0d\0e\0";
  858. cp = tor_memdup(s,10);
  859. test_memeq(cp, s, 10); /* same ram, */
  860. test_neq(cp, s); /* but different pointers. */
  861. tor_free(cp);
  862. }
  863. /* Test str-foo functions */
  864. cp = tor_strdup("abcdef");
  865. test_assert(tor_strisnonupper(cp));
  866. cp[3] = 'D';
  867. test_assert(!tor_strisnonupper(cp));
  868. tor_strupper(cp);
  869. test_streq(cp, "ABCDEF");
  870. test_assert(tor_strisprint(cp));
  871. cp[3] = 3;
  872. test_assert(!tor_strisprint(cp));
  873. tor_free(cp);
  874. /* Test eat_whitespace. */
  875. {
  876. const char *s = " \n a";
  877. test_eq_ptr(eat_whitespace(s), s+4);
  878. s = "abcd";
  879. test_eq_ptr(eat_whitespace(s), s);
  880. s = "#xyz\nab";
  881. test_eq_ptr(eat_whitespace(s), s+5);
  882. }
  883. /* Test memmem */
  884. {
  885. const char *haystack = "abcde";
  886. tor_assert(!tor_memmem(haystack, 5, "ef", 2));
  887. test_eq_ptr(tor_memmem(haystack, 5, "cd", 2), haystack + 2);
  888. test_eq_ptr(tor_memmem(haystack, 5, "cde", 3), haystack + 2);
  889. haystack = "ababcad";
  890. test_eq_ptr(tor_memmem(haystack, 7, "abc", 3), haystack + 2);
  891. }
  892. /* Test wrap_string */
  893. {
  894. smartlist_t *sl = smartlist_create();
  895. wrap_string(sl, "This is a test of string wrapping functionality: woot.",
  896. 10, "", "");
  897. cp = smartlist_join_strings(sl, "", 0, NULL);
  898. test_streq(cp,
  899. "This is a\ntest of\nstring\nwrapping\nfunctional\nity: woot.\n");
  900. tor_free(cp);
  901. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  902. smartlist_clear(sl);
  903. wrap_string(sl, "This is a test of string wrapping functionality: woot.",
  904. 16, "### ", "# ");
  905. cp = smartlist_join_strings(sl, "", 0, NULL);
  906. test_streq(cp,
  907. "### This is a\n# test of string\n# wrapping\n# functionality:\n"
  908. "# woot.\n");
  909. tor_free(cp);
  910. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  911. smartlist_free(sl);
  912. }
  913. /* now make sure time works. */
  914. tor_gettimeofday(&end);
  915. /* We might've timewarped a little. */
  916. test_assert(tv_udiff(&start, &end) >= -5000);
  917. /* Test tor_log2(). */
  918. test_eq(tor_log2(64), 6);
  919. test_eq(tor_log2(65), 6);
  920. test_eq(tor_log2(63), 5);
  921. test_eq(tor_log2(1), 0);
  922. test_eq(tor_log2(2), 1);
  923. test_eq(tor_log2(3), 1);
  924. test_eq(tor_log2(4), 2);
  925. test_eq(tor_log2(5), 2);
  926. test_eq(tor_log2(U64_LITERAL(40000000000000000)), 55);
  927. test_eq(tor_log2(UINT64_MAX), 63);
  928. /* Test round_to_power_of_2 */
  929. test_eq(round_to_power_of_2(120), 128);
  930. test_eq(round_to_power_of_2(128), 128);
  931. test_eq(round_to_power_of_2(130), 128);
  932. test_eq(round_to_power_of_2(U64_LITERAL(40000000000000000)),
  933. U64_LITERAL(1)<<55);
  934. test_eq(round_to_power_of_2(0), 2);
  935. }
  936. /** Helper: assert that IPv6 addresses <b>a</b> and <b>b</b> are the same. On
  937. * failure, reports an error, describing the addresses as <b>e1</b> and
  938. * <b>e2</b>, and reporting the line number as <b>line</b>. */
  939. static void
  940. _test_eq_ip6(struct in6_addr *a, struct in6_addr *b, const char *e1,
  941. const char *e2, int line)
  942. {
  943. int i;
  944. int ok = 1;
  945. for (i = 0; i < 16; ++i) {
  946. if (a->s6_addr[i] != b->s6_addr[i]) {
  947. ok = 0;
  948. break;
  949. }
  950. }
  951. if (ok) {
  952. printf("."); fflush(stdout);
  953. } else {
  954. char buf1[128], *cp1;
  955. char buf2[128], *cp2;
  956. have_failed = 1;
  957. cp1 = buf1; cp2 = buf2;
  958. for (i=0; i<16; ++i) {
  959. tor_snprintf(cp1, sizeof(buf1)-(cp1-buf1), "%02x", a->s6_addr[i]);
  960. tor_snprintf(cp2, sizeof(buf2)-(cp2-buf2), "%02x", b->s6_addr[i]);
  961. cp1 += 2; cp2 += 2;
  962. if ((i%2)==1 && i != 15) {
  963. *cp1++ = ':';
  964. *cp2++ = ':';
  965. }
  966. }
  967. *cp1 = *cp2 = '\0';
  968. printf("Line %d: assertion failed: (%s == %s)\n"
  969. " %s != %s\n", line, e1, e2, buf1, buf2);
  970. fflush(stdout);
  971. }
  972. }
  973. /** Helper: Assert that two strings both decode as IPv6 addresses with
  974. * tor_inet_pton(), and both decode to the same address. */
  975. #define test_pton6_same(a,b) STMT_BEGIN \
  976. test_eq(tor_inet_pton(AF_INET6, a, &a1), 1); \
  977. test_eq(tor_inet_pton(AF_INET6, b, &a2), 1); \
  978. _test_eq_ip6(&a1,&a2,#a,#b,__LINE__); \
  979. STMT_END
  980. /** Helper: Assert that <b>a</b> is recognized as a bad IPv6 address by
  981. * tor_inet_pton(). */
  982. #define test_pton6_bad(a) \
  983. test_eq(0, tor_inet_pton(AF_INET6, a, &a1))
  984. /** Helper: assert that <b>a</b>, when parsed by tor_inet_pton() and displayed
  985. * with tor_inet_ntop(), yields <b>b</b>. Also assert that <b>b</b> parses to
  986. * the same value as <b>a</b>. */
  987. #define test_ntop6_reduces(a,b) STMT_BEGIN \
  988. test_eq(tor_inet_pton(AF_INET6, a, &a1), 1); \
  989. test_streq(tor_inet_ntop(AF_INET6, &a1, buf, sizeof(buf)), b); \
  990. test_eq(tor_inet_pton(AF_INET6, b, &a2), 1); \
  991. _test_eq_ip6(&a1, &a2, a, b, __LINE__); \
  992. STMT_END
  993. /** Helper: assert that <b>a</a> parses by tor_inet_pton() into a address that
  994. * passes tor_addr_is_internal() with <b>for_listening</b> */
  995. #define test_internal_ip(a,for_listening) STMT_BEGIN \
  996. test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
  997. t1.family = AF_INET6; \
  998. if (!tor_addr_is_internal(&t1, for_listening)) \
  999. test_fail_msg( a "was not internal."); \
  1000. STMT_END
  1001. /** Helper: assert that <b>a</a> parses by tor_inet_pton() into a address that
  1002. * does not pass tor_addr_is_internal() with <b>for_listening</b>. */
  1003. #define test_external_ip(a,for_listening) STMT_BEGIN \
  1004. test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
  1005. t1.family = AF_INET6; \
  1006. if (tor_addr_is_internal(&t1, for_listening)) \
  1007. test_fail_msg(a "was not external."); \
  1008. STMT_END
  1009. /** Helper: Assert that <b>a</b> and <b>b</b>, when parsed by
  1010. * tor_inet_pton(), give addresses that compare in the order defined by
  1011. * <b>op</b> with tor_addr_compare(). */
  1012. #define test_addr_compare(a, op, b) STMT_BEGIN \
  1013. test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
  1014. test_eq(tor_inet_pton(AF_INET6, b, &t2.addr.in6_addr), 1); \
  1015. t1.family = t2.family = AF_INET6; \
  1016. r = tor_addr_compare(&t1,&t2); \
  1017. if (!(r op 0)) \
  1018. test_fail_msg("failed: tor_addr_compare("a","b") "#op" 0"); \
  1019. STMT_END
  1020. /** Helper: Assert that <b>a</b> and <b>b</b>, when parsed by
  1021. * tor_inet_pton(), give addresses that compare in the order defined by
  1022. * <b>op</b> with tor_addr_compare_masked() with <b>m</b> masked. */
  1023. #define test_addr_compare_masked(a, op, b, m) STMT_BEGIN \
  1024. test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
  1025. test_eq(tor_inet_pton(AF_INET6, b, &t2.addr.in6_addr), 1); \
  1026. t1.family = t2.family = AF_INET6; \
  1027. r = tor_addr_compare_masked(&t1,&t2,m); \
  1028. if (!(r op 0)) \
  1029. test_fail_msg("failed: tor_addr_compare_masked("a","b","#m") "#op" 0"); \
  1030. STMT_END
  1031. /** Helper: assert that <b>xx</b> is parseable as a masked IPv6 address with
  1032. * ports by <b>tor_parse_mask_addr_ports(), with family <b>f</b>, IP address
  1033. * as 4 32-bit words <b>ip1...ip4</b>, mask bits as <b>mm</b>, and port range
  1034. * as <b>pt1..pt2</b>. */
  1035. #define test_addr_mask_ports_parse(xx, f, ip1, ip2, ip3, ip4, mm, pt1, pt2) \
  1036. STMT_BEGIN \
  1037. test_eq(tor_addr_parse_mask_ports(xx, &t1, &mask, &port1, &port2), f); \
  1038. p1=tor_inet_ntop(AF_INET6, &t1.addr.in6_addr, bug, sizeof(bug)); \
  1039. test_eq(htonl(ip1), IN6_ADDRESS32(&t1)[0]); \
  1040. test_eq(htonl(ip2), IN6_ADDRESS32(&t1)[1]); \
  1041. test_eq(htonl(ip3), IN6_ADDRESS32(&t1)[2]); \
  1042. test_eq(htonl(ip4), IN6_ADDRESS32(&t1)[3]); \
  1043. test_eq(mask, mm); \
  1044. test_eq(port1, pt1); \
  1045. test_eq(port2, pt2); \
  1046. STMT_END
  1047. static void
  1048. test_util_ip6_helpers(void)
  1049. {
  1050. char buf[TOR_ADDR_BUF_LEN], bug[TOR_ADDR_BUF_LEN];
  1051. struct in6_addr a1, a2;
  1052. tor_addr_t t1, t2;
  1053. int r, i;
  1054. uint16_t port1, port2;
  1055. maskbits_t mask;
  1056. const char *p1;
  1057. // struct in_addr b1, b2;
  1058. /* Test tor_inet_ntop and tor_inet_pton: IPv6 */
  1059. /* === Test pton: valid af_inet6 */
  1060. /* Simple, valid parsing. */
  1061. r = tor_inet_pton(AF_INET6,
  1062. "0102:0304:0506:0708:090A:0B0C:0D0E:0F10", &a1);
  1063. test_assert(r==1);
  1064. for (i=0;i<16;++i) { test_eq(i+1, (int)a1.s6_addr[i]); }
  1065. /* ipv4 ending. */
  1066. test_pton6_same("0102:0304:0506:0708:090A:0B0C:0D0E:0F10",
  1067. "0102:0304:0506:0708:090A:0B0C:13.14.15.16");
  1068. /* shortened words. */
  1069. test_pton6_same("0001:0099:BEEF:0000:0123:FFFF:0001:0001",
  1070. "1:99:BEEF:0:0123:FFFF:1:1");
  1071. /* zeros at the beginning */
  1072. test_pton6_same("0000:0000:0000:0000:0009:C0A8:0001:0001",
  1073. "::9:c0a8:1:1");
  1074. test_pton6_same("0000:0000:0000:0000:0009:C0A8:0001:0001",
  1075. "::9:c0a8:0.1.0.1");
  1076. /* zeros in the middle. */
  1077. test_pton6_same("fe80:0000:0000:0000:0202:1111:0001:0001",
  1078. "fe80::202:1111:1:1");
  1079. /* zeros at the end. */
  1080. test_pton6_same("1000:0001:0000:0007:0000:0000:0000:0000",
  1081. "1000:1:0:7::");
  1082. /* === Test ntop: af_inet6 */
  1083. test_ntop6_reduces("0:0:0:0:0:0:0:0", "::");
  1084. test_ntop6_reduces("0001:0099:BEEF:0006:0123:FFFF:0001:0001",
  1085. "1:99:beef:6:123:ffff:1:1");
  1086. //test_ntop6_reduces("0:0:0:0:0:0:c0a8:0101", "::192.168.1.1");
  1087. test_ntop6_reduces("0:0:0:0:0:ffff:c0a8:0101", "::ffff:192.168.1.1");
  1088. test_ntop6_reduces("002:0:0000:0:3::4", "2::3:0:0:4");
  1089. test_ntop6_reduces("0:0::1:0:3", "::1:0:3");
  1090. test_ntop6_reduces("008:0::0", "8::");
  1091. test_ntop6_reduces("0:0:0:0:0:ffff::1", "::ffff:0.0.0.1");
  1092. test_ntop6_reduces("abcd:0:0:0:0:0:7f00::", "abcd::7f00:0");
  1093. test_ntop6_reduces("0000:0000:0000:0000:0009:C0A8:0001:0001",
  1094. "::9:c0a8:1:1");
  1095. test_ntop6_reduces("fe80:0000:0000:0000:0202:1111:0001:0001",
  1096. "fe80::202:1111:1:1");
  1097. test_ntop6_reduces("1000:0001:0000:0007:0000:0000:0000:0000",
  1098. "1000:1:0:7::");
  1099. /* === Test pton: invalid in6. */
  1100. test_pton6_bad("foobar.");
  1101. test_pton6_bad("55555::");
  1102. test_pton6_bad("9:-60::");
  1103. test_pton6_bad("1:2:33333:4:0002:3::");
  1104. //test_pton6_bad("1:2:3333:4:00002:3::");// BAD, but glibc doesn't say so.
  1105. test_pton6_bad("1:2:3333:4:fish:3::");
  1106. test_pton6_bad("1:2:3:4:5:6:7:8:9");
  1107. test_pton6_bad("1:2:3:4:5:6:7");
  1108. test_pton6_bad("1:2:3:4:5:6:1.2.3.4.5");
  1109. test_pton6_bad("1:2:3:4:5:6:1.2.3");
  1110. test_pton6_bad("::1.2.3");
  1111. test_pton6_bad("::1.2.3.4.5");
  1112. test_pton6_bad("99");
  1113. test_pton6_bad("");
  1114. test_pton6_bad("1::2::3:4");
  1115. test_pton6_bad("a:::b:c");
  1116. test_pton6_bad(":::a:b:c");
  1117. test_pton6_bad("a:b:c:::");
  1118. /* test internal checking */
  1119. test_external_ip("fbff:ffff::2:7", 0);
  1120. test_internal_ip("fc01::2:7", 0);
  1121. test_internal_ip("fdff:ffff::f:f", 0);
  1122. test_external_ip("fe00::3:f", 0);
  1123. test_external_ip("fe7f:ffff::2:7", 0);
  1124. test_internal_ip("fe80::2:7", 0);
  1125. test_internal_ip("febf:ffff::f:f", 0);
  1126. test_internal_ip("fec0::2:7:7", 0);
  1127. test_internal_ip("feff:ffff::e:7:7", 0);
  1128. test_external_ip("ff00::e:7:7", 0);
  1129. test_internal_ip("::", 0);
  1130. test_internal_ip("::1", 0);
  1131. test_internal_ip("::1", 1);
  1132. test_internal_ip("::", 0);
  1133. test_external_ip("::", 1);
  1134. test_external_ip("::2", 0);
  1135. test_external_ip("2001::", 0);
  1136. test_external_ip("ffff::", 0);
  1137. test_external_ip("::ffff:0.0.0.0", 1);
  1138. test_internal_ip("::ffff:0.0.0.0", 0);
  1139. test_internal_ip("::ffff:0.255.255.255", 0);
  1140. test_external_ip("::ffff:1.0.0.0", 0);
  1141. test_external_ip("::ffff:9.255.255.255", 0);
  1142. test_internal_ip("::ffff:10.0.0.0", 0);
  1143. test_internal_ip("::ffff:10.255.255.255", 0);
  1144. test_external_ip("::ffff:11.0.0.0", 0);
  1145. test_external_ip("::ffff:126.255.255.255", 0);
  1146. test_internal_ip("::ffff:127.0.0.0", 0);
  1147. test_internal_ip("::ffff:127.255.255.255", 0);
  1148. test_external_ip("::ffff:128.0.0.0", 0);
  1149. test_external_ip("::ffff:172.15.255.255", 0);
  1150. test_internal_ip("::ffff:172.16.0.0", 0);
  1151. test_internal_ip("::ffff:172.31.255.255", 0);
  1152. test_external_ip("::ffff:172.32.0.0", 0);
  1153. test_external_ip("::ffff:192.167.255.255", 0);
  1154. test_internal_ip("::ffff:192.168.0.0", 0);
  1155. test_internal_ip("::ffff:192.168.255.255", 0);
  1156. test_external_ip("::ffff:192.169.0.0", 0);
  1157. test_external_ip("::ffff:169.253.255.255", 0);
  1158. test_internal_ip("::ffff:169.254.0.0", 0);
  1159. test_internal_ip("::ffff:169.254.255.255", 0);
  1160. test_external_ip("::ffff:169.255.0.0", 0);
  1161. /* tor_addr_compare(tor_addr_t x2) */
  1162. test_addr_compare("ffff::", ==, "ffff::0");
  1163. test_addr_compare("0::3:2:1", >, "0::ffff:0.3.2.1");
  1164. test_addr_compare("0::2:2:1", >, "0::ffff:0.3.2.1");
  1165. test_addr_compare("0::ffff:0.3.2.1", <, "0::0:0:0");
  1166. test_addr_compare("0::ffff:5.2.2.1", <, "::ffff:6.0.0.0"); /* XXXX wrong. */
  1167. tor_addr_parse_mask_ports("[::ffff:2.3.4.5]", &t1, NULL, NULL, NULL);
  1168. tor_addr_parse_mask_ports("2.3.4.5", &t2, NULL, NULL, NULL);
  1169. test_assert(tor_addr_compare(&t1, &t2) == 0);
  1170. tor_addr_parse_mask_ports("[::ffff:2.3.4.4]", &t1, NULL, NULL, NULL);
  1171. tor_addr_parse_mask_ports("2.3.4.5", &t2, NULL, NULL, NULL);
  1172. test_assert(tor_addr_compare(&t1, &t2) < 0);
  1173. /* test compare_masked */
  1174. test_addr_compare_masked("ffff::", ==, "ffff::0", 128);
  1175. test_addr_compare_masked("ffff::", ==, "ffff::0", 64);
  1176. test_addr_compare_masked("0::2:2:1", <, "0::8000:2:1", 81);
  1177. test_addr_compare_masked("0::2:2:1", ==, "0::8000:2:1", 80);
  1178. /* test tor_addr_parse_mask_ports */
  1179. test_addr_mask_ports_parse("[::f]/17:47-95", AF_INET6,
  1180. 0, 0, 0, 0x0000000f, 17, 47, 95);
  1181. //test_addr_parse("[::fefe:4.1.1.7/120]:999-1000");
  1182. //test_addr_parse_check("::fefe:401:107", 120, 999, 1000);
  1183. test_addr_mask_ports_parse("[::ffff:4.1.1.7]/120:443", AF_INET6,
  1184. 0, 0, 0x0000ffff, 0x04010107, 120, 443, 443);
  1185. test_addr_mask_ports_parse("[abcd:2::44a:0]:2-65000", AF_INET6,
  1186. 0xabcd0002, 0, 0, 0x044a0000, 128, 2, 65000);
  1187. r=tor_addr_parse_mask_ports("[fefef::]/112", &t1, NULL, NULL, NULL);
  1188. test_assert(r == -1);
  1189. r=tor_addr_parse_mask_ports("efef::/112", &t1, NULL, NULL, NULL);
  1190. test_assert(r == -1);
  1191. r=tor_addr_parse_mask_ports("[f:f:f:f:f:f:f:f::]", &t1, NULL, NULL, NULL);
  1192. test_assert(r == -1);
  1193. r=tor_addr_parse_mask_ports("[::f:f:f:f:f:f:f:f]", &t1, NULL, NULL, NULL);
  1194. test_assert(r == -1);
  1195. r=tor_addr_parse_mask_ports("[f:f:f:f:f:f:f:f:f]", &t1, NULL, NULL, NULL);
  1196. test_assert(r == -1);
  1197. /* Test for V4-mapped address with mask < 96. (arguably not valid) */
  1198. r=tor_addr_parse_mask_ports("[::ffff:1.1.2.2/33]", &t1, &mask, NULL, NULL);
  1199. test_assert(r == -1);
  1200. r=tor_addr_parse_mask_ports("1.1.2.2/33", &t1, &mask, NULL, NULL);
  1201. test_assert(r == -1);
  1202. r=tor_addr_parse_mask_ports("1.1.2.2/31", &t1, &mask, NULL, NULL);
  1203. test_assert(r == AF_INET);
  1204. r=tor_addr_parse_mask_ports("[efef::]/112", &t1, &mask, &port1, &port2);
  1205. test_assert(r == AF_INET6);
  1206. test_assert(port1 == 1);
  1207. test_assert(port2 == 65535);
  1208. /* make sure inet address lengths >= max */
  1209. test_assert(INET_NTOA_BUF_LEN >= sizeof("255.255.255.255"));
  1210. test_assert(TOR_ADDR_BUF_LEN >=
  1211. sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"));
  1212. test_assert(sizeof(tor_addr_t) >= sizeof(struct in6_addr));
  1213. /* get interface addresses */
  1214. r = get_interface_address6(0, AF_INET, &t1);
  1215. i = get_interface_address6(0, AF_INET6, &t2);
  1216. #if 0
  1217. tor_inet_ntop(AF_INET, &t1.sa.sin_addr, buf, sizeof(buf));
  1218. printf("\nv4 address: %s (family=%i)", buf, IN_FAMILY(&t1));
  1219. tor_inet_ntop(AF_INET6, &t2.sa6.sin6_addr, buf, sizeof(buf));
  1220. printf("\nv6 address: %s (family=%i)", buf, IN_FAMILY(&t2));
  1221. #endif
  1222. }
  1223. static void
  1224. test_util_smartlist(void)
  1225. {
  1226. smartlist_t *sl;
  1227. char *cp;
  1228. /* XXXX test sort_digests, uniq_strings, uniq_digests */
  1229. /* Test smartlist add, del_keeporder, insert, get. */
  1230. sl = smartlist_create();
  1231. smartlist_add(sl, (void*)1);
  1232. smartlist_add(sl, (void*)2);
  1233. smartlist_add(sl, (void*)3);
  1234. smartlist_add(sl, (void*)4);
  1235. smartlist_del_keeporder(sl, 1);
  1236. smartlist_insert(sl, 1, (void*)22);
  1237. smartlist_insert(sl, 0, (void*)0);
  1238. smartlist_insert(sl, 5, (void*)555);
  1239. test_eq_ptr((void*)0, smartlist_get(sl,0));
  1240. test_eq_ptr((void*)1, smartlist_get(sl,1));
  1241. test_eq_ptr((void*)22, smartlist_get(sl,2));
  1242. test_eq_ptr((void*)3, smartlist_get(sl,3));
  1243. test_eq_ptr((void*)4, smartlist_get(sl,4));
  1244. test_eq_ptr((void*)555, smartlist_get(sl,5));
  1245. /* Try deleting in the middle. */
  1246. smartlist_del(sl, 1);
  1247. test_eq_ptr((void*)555, smartlist_get(sl, 1));
  1248. /* Try deleting at the end. */
  1249. smartlist_del(sl, 4);
  1250. test_eq(4, smartlist_len(sl));
  1251. /* test isin. */
  1252. test_assert(smartlist_isin(sl, (void*)3));
  1253. test_assert(!smartlist_isin(sl, (void*)99));
  1254. /* Test split and join */
  1255. smartlist_clear(sl);
  1256. test_eq(0, smartlist_len(sl));
  1257. smartlist_split_string(sl, "abc", ":", 0, 0);
  1258. test_eq(1, smartlist_len(sl));
  1259. test_streq("abc", smartlist_get(sl, 0));
  1260. smartlist_split_string(sl, "a::bc::", "::", 0, 0);
  1261. test_eq(4, smartlist_len(sl));
  1262. test_streq("a", smartlist_get(sl, 1));
  1263. test_streq("bc", smartlist_get(sl, 2));
  1264. test_streq("", smartlist_get(sl, 3));
  1265. cp = smartlist_join_strings(sl, "", 0, NULL);
  1266. test_streq(cp, "abcabc");
  1267. tor_free(cp);
  1268. cp = smartlist_join_strings(sl, "!", 0, NULL);
  1269. test_streq(cp, "abc!a!bc!");
  1270. tor_free(cp);
  1271. cp = smartlist_join_strings(sl, "XY", 0, NULL);
  1272. test_streq(cp, "abcXYaXYbcXY");
  1273. tor_free(cp);
  1274. cp = smartlist_join_strings(sl, "XY", 1, NULL);
  1275. test_streq(cp, "abcXYaXYbcXYXY");
  1276. tor_free(cp);
  1277. cp = smartlist_join_strings(sl, "", 1, NULL);
  1278. test_streq(cp, "abcabc");
  1279. tor_free(cp);
  1280. smartlist_split_string(sl, "/def/ /ghijk", "/", 0, 0);
  1281. test_eq(8, smartlist_len(sl));
  1282. test_streq("", smartlist_get(sl, 4));
  1283. test_streq("def", smartlist_get(sl, 5));
  1284. test_streq(" ", smartlist_get(sl, 6));
  1285. test_streq("ghijk", smartlist_get(sl, 7));
  1286. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1287. smartlist_clear(sl);
  1288. smartlist_split_string(sl, "a,bbd,cdef", ",", SPLIT_SKIP_SPACE, 0);
  1289. test_eq(3, smartlist_len(sl));
  1290. test_streq("a", smartlist_get(sl,0));
  1291. test_streq("bbd", smartlist_get(sl,1));
  1292. test_streq("cdef", smartlist_get(sl,2));
  1293. smartlist_split_string(sl, " z <> zhasd <> <> bnud<> ", "<>",
  1294. SPLIT_SKIP_SPACE, 0);
  1295. test_eq(8, smartlist_len(sl));
  1296. test_streq("z", smartlist_get(sl,3));
  1297. test_streq("zhasd", smartlist_get(sl,4));
  1298. test_streq("", smartlist_get(sl,5));
  1299. test_streq("bnud", smartlist_get(sl,6));
  1300. test_streq("", smartlist_get(sl,7));
  1301. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1302. smartlist_clear(sl);
  1303. smartlist_split_string(sl, " ab\tc \td ef ", NULL,
  1304. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1305. test_eq(4, smartlist_len(sl));
  1306. test_streq("ab", smartlist_get(sl,0));
  1307. test_streq("c", smartlist_get(sl,1));
  1308. test_streq("d", smartlist_get(sl,2));
  1309. test_streq("ef", smartlist_get(sl,3));
  1310. smartlist_split_string(sl, "ghi\tj", NULL,
  1311. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1312. test_eq(6, smartlist_len(sl));
  1313. test_streq("ghi", smartlist_get(sl,4));
  1314. test_streq("j", smartlist_get(sl,5));
  1315. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1316. smartlist_clear(sl);
  1317. cp = smartlist_join_strings(sl, "XY", 0, NULL);
  1318. test_streq(cp, "");
  1319. tor_free(cp);
  1320. cp = smartlist_join_strings(sl, "XY", 1, NULL);
  1321. test_streq(cp, "XY");
  1322. tor_free(cp);
  1323. smartlist_split_string(sl, " z <> zhasd <> <> bnud<> ", "<>",
  1324. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1325. test_eq(3, smartlist_len(sl));
  1326. test_streq("z", smartlist_get(sl, 0));
  1327. test_streq("zhasd", smartlist_get(sl, 1));
  1328. test_streq("bnud", smartlist_get(sl, 2));
  1329. smartlist_split_string(sl, " z <> zhasd <> <> bnud<> ", "<>",
  1330. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
  1331. test_eq(5, smartlist_len(sl));
  1332. test_streq("z", smartlist_get(sl, 3));
  1333. test_streq("zhasd <> <> bnud<>", smartlist_get(sl, 4));
  1334. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1335. smartlist_clear(sl);
  1336. smartlist_split_string(sl, "abcd\n", "\n",
  1337. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1338. test_eq(1, smartlist_len(sl));
  1339. test_streq("abcd", smartlist_get(sl, 0));
  1340. smartlist_split_string(sl, "efgh", "\n",
  1341. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1342. test_eq(2, smartlist_len(sl));
  1343. test_streq("efgh", smartlist_get(sl, 1));
  1344. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1345. smartlist_clear(sl);
  1346. /* Test swapping, shuffling, and sorting. */
  1347. smartlist_split_string(sl, "the,onion,router,by,arma,and,nickm", ",", 0, 0);
  1348. test_eq(7, smartlist_len(sl));
  1349. smartlist_sort(sl, _compare_strs);
  1350. cp = smartlist_join_strings(sl, ",", 0, NULL);
  1351. test_streq(cp,"and,arma,by,nickm,onion,router,the");
  1352. tor_free(cp);
  1353. smartlist_swap(sl, 1, 5);
  1354. cp = smartlist_join_strings(sl, ",", 0, NULL);
  1355. test_streq(cp,"and,router,by,nickm,onion,arma,the");
  1356. tor_free(cp);
  1357. smartlist_shuffle(sl);
  1358. test_eq(7, smartlist_len(sl));
  1359. test_assert(smartlist_string_isin(sl, "and"));
  1360. test_assert(smartlist_string_isin(sl, "router"));
  1361. test_assert(smartlist_string_isin(sl, "by"));
  1362. test_assert(smartlist_string_isin(sl, "nickm"));
  1363. test_assert(smartlist_string_isin(sl, "onion"));
  1364. test_assert(smartlist_string_isin(sl, "arma"));
  1365. test_assert(smartlist_string_isin(sl, "the"));
  1366. /* Test bsearch. */
  1367. smartlist_sort(sl, _compare_strs);
  1368. test_streq("nickm", smartlist_bsearch(sl, "zNicKM",
  1369. _compare_without_first_ch));
  1370. test_streq("and", smartlist_bsearch(sl, " AND", _compare_without_first_ch));
  1371. test_eq_ptr(NULL, smartlist_bsearch(sl, " ANz", _compare_without_first_ch));
  1372. /* Test bsearch_idx */
  1373. {
  1374. int f;
  1375. test_eq(0, smartlist_bsearch_idx(sl," aaa",_compare_without_first_ch,&f));
  1376. test_eq(f, 0);
  1377. test_eq(0, smartlist_bsearch_idx(sl," and",_compare_without_first_ch,&f));
  1378. test_eq(f, 1);
  1379. test_eq(1, smartlist_bsearch_idx(sl," arm",_compare_without_first_ch,&f));
  1380. test_eq(f, 0);
  1381. test_eq(1, smartlist_bsearch_idx(sl," arma",_compare_without_first_ch,&f));
  1382. test_eq(f, 1);
  1383. test_eq(2, smartlist_bsearch_idx(sl," armb",_compare_without_first_ch,&f));
  1384. test_eq(f, 0);
  1385. test_eq(7, smartlist_bsearch_idx(sl," zzzz",_compare_without_first_ch,&f));
  1386. test_eq(f, 0);
  1387. }
  1388. /* Test reverse() and pop_last() */
  1389. smartlist_reverse(sl);
  1390. cp = smartlist_join_strings(sl, ",", 0, NULL);
  1391. test_streq(cp,"the,router,onion,nickm,by,arma,and");
  1392. tor_free(cp);
  1393. cp = smartlist_pop_last(sl);
  1394. test_streq(cp, "and");
  1395. tor_free(cp);
  1396. test_eq(smartlist_len(sl), 6);
  1397. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1398. smartlist_clear(sl);
  1399. /* Test uniq() */
  1400. smartlist_split_string(sl,
  1401. "50,noon,radar,a,man,a,plan,a,canal,panama,radar,noon,50",
  1402. ",", 0, 0);
  1403. smartlist_sort(sl, _compare_strs);
  1404. smartlist_uniq(sl, _compare_strs, _tor_free);
  1405. cp = smartlist_join_strings(sl, ",", 0, NULL);
  1406. test_streq(cp, "50,a,canal,man,noon,panama,plan,radar");
  1407. tor_free(cp);
  1408. /* Test string_isin and isin_case and num_isin */
  1409. test_assert(smartlist_string_isin(sl, "noon"));
  1410. test_assert(!smartlist_string_isin(sl, "noonoon"));
  1411. test_assert(smartlist_string_isin_case(sl, "nOOn"));
  1412. test_assert(!smartlist_string_isin_case(sl, "nooNooN"));
  1413. test_assert(smartlist_string_num_isin(sl, 50));
  1414. test_assert(!smartlist_string_num_isin(sl, 60));
  1415. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1416. smartlist_clear(sl);
  1417. /* Test string_remove and remove and join_strings2 */
  1418. smartlist_split_string(sl,
  1419. "Some say the Earth will end in ice and some in fire",
  1420. " ", 0, 0);
  1421. cp = smartlist_get(sl, 4);
  1422. test_streq(cp, "will");
  1423. smartlist_add(sl, cp);
  1424. smartlist_remove(sl, cp);
  1425. tor_free(cp);
  1426. cp = smartlist_join_strings(sl, ",", 0, NULL);
  1427. test_streq(cp, "Some,say,the,Earth,fire,end,in,ice,and,some,in");
  1428. tor_free(cp);
  1429. smartlist_string_remove(sl, "in");
  1430. cp = smartlist_join_strings2(sl, "+XX", 1, 0, NULL);
  1431. test_streq(cp, "Some+say+the+Earth+fire+end+some+ice+and");
  1432. tor_free(cp);
  1433. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1434. smartlist_clear(sl);
  1435. {
  1436. smartlist_t *ints = smartlist_create();
  1437. smartlist_t *odds = smartlist_create();
  1438. smartlist_t *evens = smartlist_create();
  1439. smartlist_t *primes = smartlist_create();
  1440. int i;
  1441. for (i=1; i < 10; i += 2)
  1442. smartlist_add(odds, (void*)(uintptr_t)i);
  1443. for (i=0; i < 10; i += 2)
  1444. smartlist_add(evens, (void*)(uintptr_t)i);
  1445. /* add_all */
  1446. smartlist_add_all(ints, odds);
  1447. smartlist_add_all(ints, evens);
  1448. test_eq(smartlist_len(ints), 10);
  1449. smartlist_add(primes, (void*)2);
  1450. smartlist_add(primes, (void*)3);
  1451. smartlist_add(primes, (void*)5);
  1452. smartlist_add(primes, (void*)7);
  1453. /* overlap */
  1454. test_assert(smartlist_overlap(ints, odds));
  1455. test_assert(smartlist_overlap(odds, primes));
  1456. test_assert(smartlist_overlap(evens, primes));
  1457. test_assert(!smartlist_overlap(odds, evens));
  1458. /* intersect */
  1459. smartlist_add_all(sl, odds);
  1460. smartlist_intersect(sl, primes);
  1461. test_eq(smartlist_len(sl), 3);
  1462. test_assert(smartlist_isin(sl, (void*)3));
  1463. test_assert(smartlist_isin(sl, (void*)5));
  1464. test_assert(smartlist_isin(sl, (void*)7));
  1465. /* subtract */
  1466. smartlist_add_all(sl, primes);
  1467. smartlist_subtract(sl, odds);
  1468. test_eq(smartlist_len(sl), 1);
  1469. test_assert(smartlist_isin(sl, (void*)2));
  1470. smartlist_free(odds);
  1471. smartlist_free(evens);
  1472. smartlist_free(ints);
  1473. smartlist_free(primes);
  1474. smartlist_clear(sl);
  1475. }
  1476. smartlist_free(sl);
  1477. }
  1478. static void
  1479. test_util_bitarray(void)
  1480. {
  1481. bitarray_t *ba;
  1482. int i, j, ok=1;
  1483. ba = bitarray_init_zero(1);
  1484. test_assert(! bitarray_is_set(ba, 0));
  1485. bitarray_set(ba, 0);
  1486. test_assert(bitarray_is_set(ba, 0));
  1487. bitarray_clear(ba, 0);
  1488. test_assert(! bitarray_is_set(ba, 0));
  1489. bitarray_free(ba);
  1490. ba = bitarray_init_zero(1023);
  1491. for (i = 1; i < 64; ) {
  1492. for (j = 0; j < 1023; ++j) {
  1493. if (j % i)
  1494. bitarray_set(ba, j);
  1495. else
  1496. bitarray_clear(ba, j);
  1497. }
  1498. for (j = 0; j < 1023; ++j) {
  1499. if (!bool_eq(bitarray_is_set(ba, j), j%i))
  1500. ok = 0;
  1501. }
  1502. test_assert(ok);
  1503. if (i < 7)
  1504. ++i;
  1505. else if (i == 28)
  1506. i = 32;
  1507. else
  1508. i += 7;
  1509. }
  1510. bitarray_free(ba);
  1511. }
  1512. /* stop threads running at once. */
  1513. static tor_mutex_t *_thread_test_mutex = NULL;
  1514. /* make sure that threads have to run at the same time. */
  1515. static tor_mutex_t *_thread_test_start1 = NULL;
  1516. static tor_mutex_t *_thread_test_start2 = NULL;
  1517. static strmap_t *_thread_test_strmap = NULL;
  1518. static void _thread_test_func(void* _s) ATTR_NORETURN;
  1519. static int t1_count = 0;
  1520. static int t2_count = 0;
  1521. static void
  1522. _thread_test_func(void* _s)
  1523. {
  1524. char *s = _s;
  1525. int i, *count;
  1526. tor_mutex_t *m;
  1527. char buf[64];
  1528. char *cp;
  1529. if (!strcmp(s, "thread 1")) {
  1530. m = _thread_test_start1;
  1531. count = &t1_count;
  1532. } else {
  1533. m = _thread_test_start2;
  1534. count = &t2_count;
  1535. }
  1536. tor_mutex_acquire(m);
  1537. tor_snprintf(buf, sizeof(buf), "%lu", tor_get_thread_id());
  1538. cp = tor_strdup(buf);
  1539. for (i=0; i<10000; ++i) {
  1540. tor_mutex_acquire(_thread_test_mutex);
  1541. strmap_set(_thread_test_strmap, "last to run", cp);
  1542. ++*count;
  1543. tor_mutex_release(_thread_test_mutex);
  1544. }
  1545. tor_mutex_acquire(_thread_test_mutex);
  1546. strmap_set(_thread_test_strmap, s, tor_strdup(buf));
  1547. tor_mutex_release(_thread_test_mutex);
  1548. tor_mutex_release(m);
  1549. spawn_exit();
  1550. }
  1551. static void
  1552. test_util_threads(void)
  1553. {
  1554. char *s1, *s2;
  1555. int done = 0, timedout = 0;
  1556. time_t started;
  1557. #ifndef TOR_IS_MULTITHREADED
  1558. /* Skip this test if we aren't threading. We should be threading most
  1559. * everywhere by now. */
  1560. if (1)
  1561. return;
  1562. #endif
  1563. _thread_test_mutex = tor_mutex_new();
  1564. _thread_test_start1 = tor_mutex_new();
  1565. _thread_test_start2 = tor_mutex_new();
  1566. _thread_test_strmap = strmap_new();
  1567. s1 = tor_strdup("thread 1");
  1568. s2 = tor_strdup("thread 2");
  1569. tor_mutex_acquire(_thread_test_start1);
  1570. tor_mutex_acquire(_thread_test_start2);
  1571. spawn_func(_thread_test_func, s1);
  1572. spawn_func(_thread_test_func, s2);
  1573. tor_mutex_release(_thread_test_start2);
  1574. tor_mutex_release(_thread_test_start1);
  1575. started = time(NULL);
  1576. while (!done) {
  1577. tor_mutex_acquire(_thread_test_mutex);
  1578. strmap_assert_ok(_thread_test_strmap);
  1579. if (strmap_get(_thread_test_strmap, "thread 1") &&
  1580. strmap_get(_thread_test_strmap, "thread 2")) {
  1581. done = 1;
  1582. } else if (time(NULL) > started + 25) {
  1583. timedout = done = 1;
  1584. }
  1585. tor_mutex_release(_thread_test_mutex);
  1586. }
  1587. tor_mutex_free(_thread_test_mutex);
  1588. if (timedout) {
  1589. printf("\nTimed out: %d %d", t1_count, t2_count);
  1590. test_assert(strmap_get(_thread_test_strmap, "thread 1"));
  1591. test_assert(strmap_get(_thread_test_strmap, "thread 2"));
  1592. test_assert(!timedout);
  1593. }
  1594. /* different thread IDs. */
  1595. test_assert(strcmp(strmap_get(_thread_test_strmap, "thread 1"),
  1596. strmap_get(_thread_test_strmap, "thread 2")));
  1597. test_assert(!strcmp(strmap_get(_thread_test_strmap, "thread 1"),
  1598. strmap_get(_thread_test_strmap, "last to run")) ||
  1599. !strcmp(strmap_get(_thread_test_strmap, "thread 2"),
  1600. strmap_get(_thread_test_strmap, "last to run")));
  1601. strmap_free(_thread_test_strmap, _tor_free);
  1602. tor_free(s1);
  1603. tor_free(s2);
  1604. }
  1605. static int
  1606. _compare_strings_for_pqueue(const void *s1, const void *s2)
  1607. {
  1608. return strcmp((const char*)s1, (const char*)s2);
  1609. }
  1610. static void
  1611. test_util_pqueue(void)
  1612. {
  1613. smartlist_t *sl;
  1614. int (*cmp)(const void *, const void*);
  1615. #define OK() smartlist_pqueue_assert_ok(sl, cmp)
  1616. cmp = _compare_strings_for_pqueue;
  1617. sl = smartlist_create();
  1618. smartlist_pqueue_add(sl, cmp, (char*)"cows");
  1619. smartlist_pqueue_add(sl, cmp, (char*)"zebras");
  1620. smartlist_pqueue_add(sl, cmp, (char*)"fish");
  1621. smartlist_pqueue_add(sl, cmp, (char*)"frogs");
  1622. smartlist_pqueue_add(sl, cmp, (char*)"apples");
  1623. smartlist_pqueue_add(sl, cmp, (char*)"squid");
  1624. smartlist_pqueue_add(sl, cmp, (char*)"daschunds");
  1625. smartlist_pqueue_add(sl, cmp, (char*)"eggplants");
  1626. smartlist_pqueue_add(sl, cmp, (char*)"weissbier");
  1627. smartlist_pqueue_add(sl, cmp, (char*)"lobsters");
  1628. smartlist_pqueue_add(sl, cmp, (char*)"roquefort");
  1629. OK();
  1630. test_eq(smartlist_len(sl), 11);
  1631. test_streq(smartlist_get(sl, 0), "apples");
  1632. test_streq(smartlist_pqueue_pop(sl, cmp), "apples");
  1633. test_eq(smartlist_len(sl), 10);
  1634. OK();
  1635. test_streq(smartlist_pqueue_pop(sl, cmp), "cows");
  1636. test_streq(smartlist_pqueue_pop(sl, cmp), "daschunds");
  1637. smartlist_pqueue_add(sl, cmp, (char*)"chinchillas");
  1638. OK();
  1639. smartlist_pqueue_add(sl, cmp, (char*)"fireflies");
  1640. OK();
  1641. test_streq(smartlist_pqueue_pop(sl, cmp), "chinchillas");
  1642. test_streq(smartlist_pqueue_pop(sl, cmp), "eggplants");
  1643. test_streq(smartlist_pqueue_pop(sl, cmp), "fireflies");
  1644. OK();
  1645. test_streq(smartlist_pqueue_pop(sl, cmp), "fish");
  1646. test_streq(smartlist_pqueue_pop(sl, cmp), "frogs");
  1647. test_streq(smartlist_pqueue_pop(sl, cmp), "lobsters");
  1648. test_streq(smartlist_pqueue_pop(sl, cmp), "roquefort");
  1649. OK();
  1650. test_eq(smartlist_len(sl), 3);
  1651. test_streq(smartlist_pqueue_pop(sl, cmp), "squid");
  1652. test_streq(smartlist_pqueue_pop(sl, cmp), "weissbier");
  1653. test_streq(smartlist_pqueue_pop(sl, cmp), "zebras");
  1654. test_eq(smartlist_len(sl), 0);
  1655. OK();
  1656. #undef OK
  1657. smartlist_free(sl);
  1658. }
  1659. static void
  1660. test_util_gzip(void)
  1661. {
  1662. char *buf1, *buf2=NULL, *buf3=NULL, *cp1, *cp2;
  1663. const char *ccp2;
  1664. size_t len1, len2;
  1665. tor_zlib_state_t *state;
  1666. buf1 = tor_strdup("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ");
  1667. test_assert(detect_compression_method(buf1, strlen(buf1)) == UNKNOWN_METHOD);
  1668. if (is_gzip_supported()) {
  1669. test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
  1670. GZIP_METHOD));
  1671. test_assert(buf2);
  1672. test_assert(!memcmp(buf2, "\037\213", 2)); /* Gzip magic. */
  1673. test_assert(detect_compression_method(buf2, len1) == GZIP_METHOD);
  1674. test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1,
  1675. GZIP_METHOD, 1, LOG_INFO));
  1676. test_assert(buf3);
  1677. test_streq(buf1,buf3);
  1678. tor_free(buf2);
  1679. tor_free(buf3);
  1680. }
  1681. test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
  1682. ZLIB_METHOD));
  1683. test_assert(buf2);
  1684. test_assert(!memcmp(buf2, "\x78\xDA", 2)); /* deflate magic. */
  1685. test_assert(detect_compression_method(buf2, len1) == ZLIB_METHOD);
  1686. test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1,
  1687. ZLIB_METHOD, 1, LOG_INFO));
  1688. test_assert(buf3);
  1689. test_streq(buf1,buf3);
  1690. /* Check whether we can uncompress concatenated, compresed strings. */
  1691. tor_free(buf3);
  1692. buf2 = tor_realloc(buf2, len1*2);
  1693. memcpy(buf2+len1, buf2, len1);
  1694. test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1*2,
  1695. ZLIB_METHOD, 1, LOG_INFO));
  1696. test_eq(len2, (strlen(buf1)+1)*2);
  1697. test_memeq(buf3,
  1698. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ\0"
  1699. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ\0",
  1700. (strlen(buf1)+1)*2);
  1701. tor_free(buf1);
  1702. tor_free(buf2);
  1703. tor_free(buf3);
  1704. /* Check whether we can uncompress partial strings. */
  1705. buf1 =
  1706. tor_strdup("String with low redundancy that won't be compressed much.");
  1707. test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
  1708. ZLIB_METHOD));
  1709. tor_assert(len1>16);
  1710. /* when we allow an uncomplete string, we should succeed.*/
  1711. tor_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1-16,
  1712. ZLIB_METHOD, 0, LOG_INFO));
  1713. buf3[len2]='\0';
  1714. tor_assert(len2 > 5);
  1715. tor_assert(!strcmpstart(buf1, buf3));
  1716. /* when we demand a complete string, this must fail. */
  1717. tor_free(buf3);
  1718. tor_assert(tor_gzip_uncompress(&buf3, &len2, buf2, len1-16,
  1719. ZLIB_METHOD, 1, LOG_INFO));
  1720. tor_assert(!buf3);
  1721. /* Now, try streaming compression. */
  1722. tor_free(buf1);
  1723. tor_free(buf2);
  1724. tor_free(buf3);
  1725. state = tor_zlib_new(1, ZLIB_METHOD);
  1726. tor_assert(state);
  1727. cp1 = buf1 = tor_malloc(1024);
  1728. len1 = 1024;
  1729. ccp2 = "ABCDEFGHIJABCDEFGHIJ";
  1730. len2 = 21;
  1731. test_assert(tor_zlib_process(state, &cp1, &len1, &ccp2, &len2, 0)
  1732. == TOR_ZLIB_OK);
  1733. test_eq(len2, 0); /* Make sure we compressed it all. */
  1734. test_assert(cp1 > buf1);
  1735. len2 = 0;
  1736. cp2 = cp1;
  1737. test_assert(tor_zlib_process(state, &cp1, &len1, &ccp2, &len2, 1)
  1738. == TOR_ZLIB_DONE);
  1739. test_eq(len2, 0);
  1740. test_assert(cp1 > cp2); /* Make sure we really added something. */
  1741. tor_assert(!tor_gzip_uncompress(&buf3, &len2, buf1, 1024-len1,
  1742. ZLIB_METHOD, 1, LOG_WARN));
  1743. test_streq(buf3, "ABCDEFGHIJABCDEFGHIJ"); /*Make sure it compressed right.*/
  1744. tor_free(buf3);
  1745. tor_zlib_free(state);
  1746. tor_free(buf2);
  1747. tor_free(buf3);
  1748. tor_free(buf1);
  1749. }
  1750. static void
  1751. test_util_strmap(void)
  1752. {
  1753. strmap_t *map;
  1754. strmap_iter_t *iter;
  1755. const char *k;
  1756. void *v;
  1757. char *visited;
  1758. smartlist_t *found_keys;
  1759. map = strmap_new();
  1760. v = strmap_set(map, "K1", (void*)99);
  1761. test_eq(v, NULL);
  1762. v = strmap_set(map, "K2", (void*)101);
  1763. test_eq(v, NULL);
  1764. v = strmap_set(map, "K1", (void*)100);
  1765. test_eq(v, (void*)99);
  1766. test_eq_ptr(strmap_get(map,"K1"), (void*)100);
  1767. test_eq_ptr(strmap_get(map,"K2"), (void*)101);
  1768. test_eq_ptr(strmap_get(map,"K-not-there"), NULL);
  1769. strmap_assert_ok(map);
  1770. v = strmap_remove(map,"K2");
  1771. strmap_assert_ok(map);
  1772. test_eq_ptr(v, (void*)101);
  1773. test_eq_ptr(strmap_get(map,"K2"), NULL);
  1774. test_eq_ptr(strmap_remove(map,"K2"), NULL);
  1775. strmap_set(map, "K2", (void*)101);
  1776. strmap_set(map, "K3", (void*)102);
  1777. strmap_set(map, "K4", (void*)103);
  1778. strmap_assert_ok(map);
  1779. strmap_set(map, "K5", (void*)104);
  1780. strmap_set(map, "K6", (void*)105);
  1781. strmap_assert_ok(map);
  1782. /* Test iterator. */
  1783. iter = strmap_iter_init(map);
  1784. found_keys = smartlist_create();
  1785. while (!strmap_iter_done(iter)) {
  1786. strmap_iter_get(iter,&k,&v);
  1787. smartlist_add(found_keys, tor_strdup(k));
  1788. test_eq_ptr(v, strmap_get(map, k));
  1789. if (!strcmp(k, "K2")) {
  1790. iter = strmap_iter_next_rmv(map,iter);
  1791. } else {
  1792. iter = strmap_iter_next(map,iter);
  1793. }
  1794. }
  1795. /* Make sure we removed K2, but not the others. */
  1796. test_eq_ptr(strmap_get(map, "K2"), NULL);
  1797. test_eq_ptr(strmap_get(map, "K5"), (void*)104);
  1798. /* Make sure we visited everyone once */
  1799. smartlist_sort_strings(found_keys);
  1800. visited = smartlist_join_strings(found_keys, ":", 0, NULL);
  1801. test_streq(visited, "K1:K2:K3:K4:K5:K6");
  1802. tor_free(visited);
  1803. SMARTLIST_FOREACH(found_keys, char *, cp, tor_free(cp));
  1804. smartlist_free(found_keys);
  1805. strmap_assert_ok(map);
  1806. /* Clean up after ourselves. */
  1807. strmap_free(map, NULL);
  1808. /* Now try some lc functions. */
  1809. map = strmap_new();
  1810. strmap_set_lc(map,"Ab.C", (void*)1);
  1811. test_eq_ptr(strmap_get(map,"ab.c"), (void*)1);
  1812. strmap_assert_ok(map);
  1813. test_eq_ptr(strmap_get_lc(map,"AB.C"), (void*)1);
  1814. test_eq_ptr(strmap_get(map,"AB.C"), NULL);
  1815. test_eq_ptr(strmap_remove_lc(map,"aB.C"), (void*)1);
  1816. strmap_assert_ok(map);
  1817. test_eq_ptr(strmap_get_lc(map,"AB.C"), NULL);
  1818. strmap_free(map,NULL);
  1819. }
  1820. static void
  1821. test_util_mmap(void)
  1822. {
  1823. char *fname1 = tor_strdup(get_fname("mapped_1"));
  1824. char *fname2 = tor_strdup(get_fname("mapped_2"));
  1825. char *fname3 = tor_strdup(get_fname("mapped_3"));
  1826. const size_t buflen = 17000;
  1827. char *buf = tor_malloc(17000);
  1828. tor_mmap_t *mapping;
  1829. crypto_rand(buf, buflen);
  1830. write_str_to_file(fname1, "Short file.", 1);
  1831. write_bytes_to_file(fname2, buf, buflen, 1);
  1832. write_bytes_to_file(fname3, buf, 16384, 1);
  1833. mapping = tor_mmap_file(fname1);
  1834. test_assert(mapping);
  1835. test_eq(mapping->size, strlen("Short file."));
  1836. test_streq(mapping->data, "Short file.");
  1837. #ifdef MS_WINDOWS
  1838. tor_munmap_file(mapping);
  1839. test_assert(unlink(fname1) == 0);
  1840. #else
  1841. /* make sure we can unlink. */
  1842. test_assert(unlink(fname1) == 0);
  1843. test_streq(mapping->data, "Short file.");
  1844. tor_munmap_file(mapping);
  1845. #endif
  1846. /* Make sure that we fail to map a no-longer-existent file. */
  1847. mapping = tor_mmap_file(fname1);
  1848. test_assert(mapping == NULL);
  1849. /* Now try a big file that stretches across a few pages and isn't aligned */
  1850. mapping = tor_mmap_file(fname2);
  1851. test_assert(mapping);
  1852. test_eq(mapping->size, buflen);
  1853. test_memeq(mapping->data, buf, buflen);
  1854. tor_munmap_file(mapping);
  1855. /* Now try a big aligned file. */
  1856. mapping = tor_mmap_file(fname3);
  1857. test_assert(mapping);
  1858. test_eq(mapping->size, 16384);
  1859. test_memeq(mapping->data, buf, 16384);
  1860. tor_munmap_file(mapping);
  1861. /* fname1 got unlinked above */
  1862. unlink(fname2);
  1863. unlink(fname3);
  1864. tor_free(fname1);
  1865. tor_free(fname2);
  1866. tor_free(fname3);
  1867. tor_free(buf);
  1868. }
  1869. static void
  1870. test_util_control_formats(void)
  1871. {
  1872. char *out;
  1873. const char *inp =
  1874. "..This is a test\r\nof the emergency \nbroadcast\r\n..system.\r\nZ.\r\n";
  1875. size_t sz;
  1876. sz = read_escaped_data(inp, strlen(inp), &out);
  1877. test_streq(out,
  1878. ".This is a test\nof the emergency \nbroadcast\n.system.\nZ.\n");
  1879. test_eq(sz, strlen(out));
  1880. tor_free(out);
  1881. }
  1882. static void
  1883. test_onion_handshake(void)
  1884. {
  1885. /* client-side */
  1886. crypto_dh_env_t *c_dh = NULL;
  1887. char c_buf[ONIONSKIN_CHALLENGE_LEN];
  1888. char c_keys[40];
  1889. /* server-side */
  1890. char s_buf[ONIONSKIN_REPLY_LEN];
  1891. char s_keys[40];
  1892. /* shared */
  1893. crypto_pk_env_t *pk = NULL;
  1894. pk = pk_generate(0);
  1895. /* client handshake 1. */
  1896. memset(c_buf, 0, ONIONSKIN_CHALLENGE_LEN);
  1897. test_assert(! onion_skin_create(pk, &c_dh, c_buf));
  1898. /* server handshake */
  1899. memset(s_buf, 0, ONIONSKIN_REPLY_LEN);
  1900. memset(s_keys, 0, 40);
  1901. test_assert(! onion_skin_server_handshake(c_buf, pk, NULL,
  1902. s_buf, s_keys, 40));
  1903. /* client handshake 2 */
  1904. memset(c_keys, 0, 40);
  1905. test_assert(! onion_skin_client_handshake(c_dh, s_buf, c_keys, 40));
  1906. crypto_dh_free(c_dh);
  1907. if (memcmp(c_keys, s_keys, 40)) {
  1908. puts("Aiiiie");
  1909. exit(1);
  1910. }
  1911. test_memeq(c_keys, s_keys, 40);
  1912. memset(s_buf, 0, 40);
  1913. test_memneq(c_keys, s_buf, 40);
  1914. crypto_free_pk_env(pk);
  1915. }
  1916. extern smartlist_t *fingerprint_list;
  1917. static void
  1918. test_dir_format(void)
  1919. {
  1920. char buf[8192], buf2[8192];
  1921. char platform[256];
  1922. char fingerprint[FINGERPRINT_LEN+1];
  1923. char *pk1_str = NULL, *pk2_str = NULL, *pk3_str = NULL, *cp;
  1924. size_t pk1_str_len, pk2_str_len, pk3_str_len;
  1925. routerinfo_t *r1, *r2;
  1926. crypto_pk_env_t *pk1 = NULL, *pk2 = NULL, *pk3 = NULL;
  1927. routerinfo_t *rp1 = NULL, *rp2 = NULL;
  1928. addr_policy_t *ex1, *ex2;
  1929. routerlist_t *dir1 = NULL, *dir2 = NULL;
  1930. tor_version_t ver1;
  1931. pk1 = pk_generate(0);
  1932. pk2 = pk_generate(1);
  1933. pk3 = pk_generate(2);
  1934. test_assert( is_legal_nickname("a"));
  1935. test_assert(!is_legal_nickname(""));
  1936. test_assert(!is_legal_nickname("abcdefghijklmnopqrst")); /* 20 chars */
  1937. test_assert(!is_legal_nickname("hyphen-")); /* bad char */
  1938. test_assert( is_legal_nickname("abcdefghijklmnopqrs")); /* 19 chars */
  1939. test_assert(!is_legal_nickname("$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA"));
  1940. /* valid */
  1941. test_assert( is_legal_nickname_or_hexdigest(
  1942. "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA"));
  1943. test_assert( is_legal_nickname_or_hexdigest(
  1944. "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA=fred"));
  1945. test_assert( is_legal_nickname_or_hexdigest(
  1946. "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA~fred"));
  1947. /* too short */
  1948. test_assert(!is_legal_nickname_or_hexdigest(
  1949. "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
  1950. /* illegal char */
  1951. test_assert(!is_legal_nickname_or_hexdigest(
  1952. "$AAAAAAzAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
  1953. /* hex part too long */
  1954. test_assert(!is_legal_nickname_or_hexdigest(
  1955. "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
  1956. test_assert(!is_legal_nickname_or_hexdigest(
  1957. "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=fred"));
  1958. /* Bad nickname */
  1959. test_assert(!is_legal_nickname_or_hexdigest(
  1960. "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="));
  1961. test_assert(!is_legal_nickname_or_hexdigest(
  1962. "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~"));
  1963. test_assert(!is_legal_nickname_or_hexdigest(
  1964. "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~hyphen-"));
  1965. test_assert(!is_legal_nickname_or_hexdigest(
  1966. "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~"
  1967. "abcdefghijklmnoppqrst"));
  1968. /* Bad extra char. */
  1969. test_assert(!is_legal_nickname_or_hexdigest(
  1970. "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA!"));
  1971. test_assert(is_legal_nickname_or_hexdigest("xyzzy"));
  1972. test_assert(is_legal_nickname_or_hexdigest("abcdefghijklmnopqrs"));
  1973. test_assert(!is_legal_nickname_or_hexdigest("abcdefghijklmnopqrst"));
  1974. get_platform_str(platform, sizeof(platform));
  1975. r1 = tor_malloc_zero(sizeof(routerinfo_t));
  1976. r1->address = tor_strdup("18.244.0.1");
  1977. r1->addr = 0xc0a80001u; /* 192.168.0.1 */
  1978. r1->cache_info.published_on = 0;
  1979. r1->or_port = 9000;
  1980. r1->dir_port = 9003;
  1981. r1->onion_pkey = crypto_pk_dup_key(pk1);
  1982. r1->identity_pkey = crypto_pk_dup_key(pk2);
  1983. r1->bandwidthrate = 1000;
  1984. r1->bandwidthburst = 5000;
  1985. r1->bandwidthcapacity = 10000;
  1986. r1->exit_policy = NULL;
  1987. r1->nickname = tor_strdup("Magri");
  1988. r1->platform = tor_strdup(platform);
  1989. ex1 = tor_malloc_zero(sizeof(addr_policy_t));
  1990. ex2 = tor_malloc_zero(sizeof(addr_policy_t));
  1991. ex1->policy_type = ADDR_POLICY_ACCEPT;
  1992. ex1->addr = 0;
  1993. ex1->maskbits = 0;
  1994. ex1->prt_min = ex1->prt_max = 80;
  1995. ex2->policy_type = ADDR_POLICY_REJECT;
  1996. ex2->addr = 18 << 24;
  1997. ex2->maskbits = 8;
  1998. ex2->prt_min = ex2->prt_max = 24;
  1999. r2 = tor_malloc_zero(sizeof(routerinfo_t));
  2000. r2->address = tor_strdup("1.1.1.1");
  2001. r2->addr = 0x0a030201u; /* 10.3.2.1 */
  2002. r2->platform = tor_strdup(platform);
  2003. r2->cache_info.published_on = 5;
  2004. r2->or_port = 9005;
  2005. r2->dir_port = 0;
  2006. r2->onion_pkey = crypto_pk_dup_key(pk2);
  2007. r2->identity_pkey = crypto_pk_dup_key(pk1);
  2008. r2->bandwidthrate = r2->bandwidthburst = r2->bandwidthcapacity = 3000;
  2009. r2->exit_policy = smartlist_create();
  2010. smartlist_add(r2->exit_policy, ex2);
  2011. smartlist_add(r2->exit_policy, ex1);
  2012. r2->nickname = tor_strdup("Fred");
  2013. test_assert(!crypto_pk_write_public_key_to_string(pk1, &pk1_str,
  2014. &pk1_str_len));
  2015. test_assert(!crypto_pk_write_public_key_to_string(pk2 , &pk2_str,
  2016. &pk2_str_len));
  2017. test_assert(!crypto_pk_write_public_key_to_string(pk3 , &pk3_str,
  2018. &pk3_str_len));
  2019. memset(buf, 0, 2048);
  2020. test_assert(router_dump_router_to_string(buf, 2048, r1, pk2)>0);
  2021. strlcpy(buf2, "router Magri 18.244.0.1 9000 0 9003\n"
  2022. "platform Tor "VERSION" on ", sizeof(buf2));
  2023. strlcat(buf2, get_uname(), sizeof(buf2));
  2024. strlcat(buf2, "\n"
  2025. "opt protocols Link 1 Circuit 1\n"
  2026. "published 1970-01-01 00:00:00\n"
  2027. "opt fingerprint ", sizeof(buf2));
  2028. test_assert(!crypto_pk_get_fingerprint(pk2, fingerprint, 1));
  2029. strlcat(buf2, fingerprint, sizeof(buf2));
  2030. strlcat(buf2, "\nuptime 0\n"
  2031. /* XXX the "0" above is hardcoded, but even if we made it reflect
  2032. * uptime, that still wouldn't make it right, because the two
  2033. * descriptors might be made on different seconds... hm. */
  2034. "bandwidth 1000 5000 10000\n"
  2035. "opt extra-info-digest 0000000000000000000000000000000000000000\n"
  2036. "onion-key\n", sizeof(buf2));
  2037. strlcat(buf2, pk1_str, sizeof(buf2));
  2038. strlcat(buf2, "signing-key\n", sizeof(buf2));
  2039. strlcat(buf2, pk2_str, sizeof(buf2));
  2040. strlcat(buf2, "router-signature\n", sizeof(buf2));
  2041. buf[strlen(buf2)] = '\0'; /* Don't compare the sig; it's never the same
  2042. * twice */
  2043. test_streq(buf, buf2);
  2044. test_assert(router_dump_router_to_string(buf, 2048, r1, pk2)>0);
  2045. cp = buf;
  2046. rp1 = router_parse_entry_from_string((const char*)cp,NULL,1,0,NULL);
  2047. test_assert(rp1);
  2048. test_streq(rp1->address, r1->address);
  2049. test_eq(rp1->or_port, r1->or_port);
  2050. //test_eq(rp1->dir_port, r1->dir_port);
  2051. test_eq(rp1->bandwidthrate, r1->bandwidthrate);
  2052. test_eq(rp1->bandwidthburst, r1->bandwidthburst);
  2053. test_eq(rp1->bandwidthcapacity, r1->bandwidthcapacity);
  2054. test_assert(crypto_pk_cmp_keys(rp1->onion_pkey, pk1) == 0);
  2055. test_assert(crypto_pk_cmp_keys(rp1->identity_pkey, pk2) == 0);
  2056. test_assert(rp1->exit_policy == NULL);
  2057. #if 0
  2058. /* XXX Once we have exit policies, test this again. XXX */
  2059. strlcpy(buf2, "router tor.tor.tor 9005 0 0 3000\n", sizeof(buf2));
  2060. strlcat(buf2, pk2_str, sizeof(buf2));
  2061. strlcat(buf2, "signing-key\n", sizeof(buf2));
  2062. strlcat(buf2, pk1_str, sizeof(buf2));
  2063. strlcat(buf2, "accept *:80\nreject 18.*:24\n\n", sizeof(buf2));
  2064. test_assert(router_dump_router_to_string(buf, 2048, &r2, pk2)>0);
  2065. test_streq(buf, buf2);
  2066. cp = buf;
  2067. rp2 = router_parse_entry_from_string(&cp,1);
  2068. test_assert(rp2);
  2069. test_streq(rp2->address, r2.address);
  2070. test_eq(rp2->or_port, r2.or_port);
  2071. test_eq(rp2->dir_port, r2.dir_port);
  2072. test_eq(rp2->bandwidth, r2.bandwidth);
  2073. test_assert(crypto_pk_cmp_keys(rp2->onion_pkey, pk2) == 0);
  2074. test_assert(crypto_pk_cmp_keys(rp2->identity_pkey, pk1) == 0);
  2075. test_eq(rp2->exit_policy->policy_type, EXIT_POLICY_ACCEPT);
  2076. test_streq(rp2->exit_policy->string, "accept *:80");
  2077. test_streq(rp2->exit_policy->address, "*");
  2078. test_streq(rp2->exit_policy->port, "80");
  2079. test_eq(rp2->exit_policy->next->policy_type, EXIT_POLICY_REJECT);
  2080. test_streq(rp2->exit_policy->next->string, "reject 18.*:24");
  2081. test_streq(rp2->exit_policy->next->address, "18.*");
  2082. test_streq(rp2->exit_policy->next->port, "24");
  2083. test_assert(rp2->exit_policy->next->next == NULL);
  2084. /* Okay, now for the directories. */
  2085. {
  2086. fingerprint_list = smartlist_create();
  2087. crypto_pk_get_fingerprint(pk2, buf, 1);
  2088. add_fingerprint_to_dir("Magri", buf, fingerprint_list);
  2089. crypto_pk_get_fingerprint(pk1, buf, 1);
  2090. add_fingerprint_to_dir("Fred", buf, fingerprint_list);
  2091. }
  2092. {
  2093. char d[DIGEST_LEN];
  2094. const char *m;
  2095. /* XXXX NM re-enable. */
  2096. /* Make sure routers aren't too far in the past any more. */
  2097. r1->cache_info.published_on = time(NULL);
  2098. r2->cache_info.published_on = time(NULL)-3*60*60;
  2099. test_assert(router_dump_router_to_string(buf, 2048, r1, pk2)>0);
  2100. test_eq(dirserv_add_descriptor(buf,&m), 2);
  2101. test_assert(router_dump_router_to_string(buf, 2048, r2, pk1)>0);
  2102. test_eq(dirserv_add_descriptor(buf,&m), 2);
  2103. get_options()->Nickname = tor_strdup("DirServer");
  2104. test_assert(!dirserv_dump_directory_to_string(&cp,pk3, 0));
  2105. crypto_pk_get_digest(pk3, d);
  2106. test_assert(!router_parse_directory(cp));
  2107. test_eq(2, smartlist_len(dir1->routers));
  2108. tor_free(cp);
  2109. }
  2110. #endif
  2111. dirserv_free_fingerprint_list();
  2112. tor_free(pk1_str);
  2113. tor_free(pk2_str);
  2114. tor_free(pk3_str);
  2115. if (pk1) crypto_free_pk_env(pk1);
  2116. if (pk2) crypto_free_pk_env(pk2);
  2117. if (pk3) crypto_free_pk_env(pk3);
  2118. if (rp1) routerinfo_free(rp1);
  2119. if (rp2) routerinfo_free(rp2);
  2120. tor_free(dir1); /* XXXX And more !*/
  2121. tor_free(dir2); /* And more !*/
  2122. routerinfo_free(r1);
  2123. routerinfo_free(r2);
  2124. /* Try out version parsing functionality */
  2125. test_eq(0, tor_version_parse("0.3.4pre2-cvs", &ver1));
  2126. test_eq(0, ver1.major);
  2127. test_eq(3, ver1.minor);
  2128. test_eq(4, ver1.micro);
  2129. test_eq(VER_PRE, ver1.status);
  2130. test_eq(2, ver1.patchlevel);
  2131. test_eq(0, tor_version_parse("0.3.4rc1", &ver1));
  2132. test_eq(0, ver1.major);
  2133. test_eq(3, ver1.minor);
  2134. test_eq(4, ver1.micro);
  2135. test_eq(VER_RC, ver1.status);
  2136. test_eq(1, ver1.patchlevel);
  2137. test_eq(0, tor_version_parse("1.3.4", &ver1));
  2138. test_eq(1, ver1.major);
  2139. test_eq(3, ver1.minor);
  2140. test_eq(4, ver1.micro);
  2141. test_eq(VER_RELEASE, ver1.status);
  2142. test_eq(0, ver1.patchlevel);
  2143. test_eq(0, tor_version_parse("1.3.4.999", &ver1));
  2144. test_eq(1, ver1.major);
  2145. test_eq(3, ver1.minor);
  2146. test_eq(4, ver1.micro);
  2147. test_eq(VER_RELEASE, ver1.status);
  2148. test_eq(999, ver1.patchlevel);
  2149. test_eq(0, tor_version_parse("0.1.2.4-alpha", &ver1));
  2150. test_eq(0, ver1.major);
  2151. test_eq(1, ver1.minor);
  2152. test_eq(2, ver1.micro);
  2153. test_eq(4, ver1.patchlevel);
  2154. test_eq(VER_RELEASE, ver1.status);
  2155. test_streq("alpha", ver1.status_tag);
  2156. test_eq(0, tor_version_parse("0.1.2.4", &ver1));
  2157. test_eq(0, ver1.major);
  2158. test_eq(1, ver1.minor);
  2159. test_eq(2, ver1.micro);
  2160. test_eq(4, ver1.patchlevel);
  2161. test_eq(VER_RELEASE, ver1.status);
  2162. test_streq("", ver1.status_tag);
  2163. #define test_eq_vs(vs1, vs2) test_eq_type(version_status_t, "%d", (vs1), (vs2))
  2164. #define test_v_i_o(val, ver, lst) \
  2165. test_eq_vs(val, tor_version_is_obsolete(ver, lst))
  2166. /* make sure tor_version_is_obsolete() works */
  2167. test_v_i_o(VS_OLD, "0.0.1", "Tor 0.0.2");
  2168. test_v_i_o(VS_OLD, "0.0.1", "0.0.2, Tor 0.0.3");
  2169. test_v_i_o(VS_OLD, "0.0.1", "0.0.2,Tor 0.0.3");
  2170. test_v_i_o(VS_OLD, "0.0.1","0.0.3,BetterTor 0.0.1");
  2171. test_v_i_o(VS_RECOMMENDED, "0.0.2", "Tor 0.0.2,Tor 0.0.3");
  2172. test_v_i_o(VS_NEW_IN_SERIES, "0.0.2", "Tor 0.0.2pre1,Tor 0.0.3");
  2173. test_v_i_o(VS_OLD, "0.0.2", "Tor 0.0.2.1,Tor 0.0.3");
  2174. test_v_i_o(VS_NEW, "0.1.0", "Tor 0.0.2,Tor 0.0.3");
  2175. test_v_i_o(VS_RECOMMENDED, "0.0.7rc2", "0.0.7,Tor 0.0.7rc2,Tor 0.0.8");
  2176. test_v_i_o(VS_OLD, "0.0.5.0", "0.0.5.1-cvs");
  2177. test_v_i_o(VS_NEW_IN_SERIES, "0.0.5.1-cvs", "0.0.5, 0.0.6");
  2178. /* Not on list, but newer than any in same series. */
  2179. test_v_i_o(VS_NEW_IN_SERIES, "0.1.0.3",
  2180. "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
  2181. /* Series newer than any on list. */
  2182. test_v_i_o(VS_NEW, "0.1.2.3", "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
  2183. /* Series older than any on list. */
  2184. test_v_i_o(VS_OLD, "0.0.1.3", "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
  2185. /* Not on list, not newer than any on same series. */
  2186. test_v_i_o(VS_UNRECOMMENDED, "0.1.0.1",
  2187. "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
  2188. /* On list, not newer than any on same series. */
  2189. test_v_i_o(VS_UNRECOMMENDED,
  2190. "0.1.0.1", "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
  2191. test_eq(0, tor_version_as_new_as("Tor 0.0.5", "0.0.9pre1-cvs"));
  2192. test_eq(1, tor_version_as_new_as(
  2193. "Tor 0.0.8 on Darwin 64-121-192-100.c3-0."
  2194. "sfpo-ubr1.sfrn-sfpo.ca.cable.rcn.com Power Macintosh",
  2195. "0.0.8rc2"));
  2196. test_eq(0, tor_version_as_new_as(
  2197. "Tor 0.0.8 on Darwin 64-121-192-100.c3-0."
  2198. "sfpo-ubr1.sfrn-sfpo.ca.cable.rcn.com Power Macintosh", "0.0.8.2"));
  2199. /* Now try svn revisions. */
  2200. test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100)",
  2201. "Tor 0.2.1.0-dev (r99)"));
  2202. test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100) on Banana Jr",
  2203. "Tor 0.2.1.0-dev (r99) on Hal 9000"));
  2204. test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100)",
  2205. "Tor 0.2.1.0-dev on Colossus"));
  2206. test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev (r99)",
  2207. "Tor 0.2.1.0-dev (r100)"));
  2208. test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev (r99) on MCP",
  2209. "Tor 0.2.1.0-dev (r100) on AM"));
  2210. test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev",
  2211. "Tor 0.2.1.0-dev (r99)"));
  2212. test_eq(1, tor_version_as_new_as("Tor 0.2.1.1",
  2213. "Tor 0.2.1.0-dev (r99)"));
  2214. }
  2215. extern const char AUTHORITY_CERT_1[];
  2216. extern const char AUTHORITY_SIGNKEY_1[];
  2217. extern const char AUTHORITY_CERT_2[];
  2218. extern const char AUTHORITY_SIGNKEY_2[];
  2219. extern const char AUTHORITY_CERT_3[];
  2220. extern const char AUTHORITY_SIGNKEY_3[];
  2221. static void
  2222. test_same_voter(networkstatus_voter_info_t *v1,
  2223. networkstatus_voter_info_t *v2)
  2224. {
  2225. test_streq(v1->nickname, v2->nickname);
  2226. test_memeq(v1->identity_digest, v2->identity_digest, DIGEST_LEN);
  2227. test_streq(v1->address, v2->address);
  2228. test_eq(v1->addr, v2->addr);
  2229. test_eq(v1->dir_port, v2->dir_port);
  2230. test_eq(v1->or_port, v2->or_port);
  2231. test_streq(v1->contact, v2->contact);
  2232. test_memeq(v1->vote_digest, v2->vote_digest, DIGEST_LEN);
  2233. }
  2234. static void
  2235. test_util_order_functions(void)
  2236. {
  2237. int lst[25], n = 0;
  2238. // int a=12,b=24,c=25,d=60,e=77;
  2239. #define median() median_int(lst, n)
  2240. lst[n++] = 12;
  2241. test_eq(12, median()); /* 12 */
  2242. lst[n++] = 77;
  2243. //smartlist_shuffle(sl);
  2244. test_eq(12, median()); /* 12, 77 */
  2245. lst[n++] = 77;
  2246. //smartlist_shuffle(sl);
  2247. test_eq(77, median()); /* 12, 77, 77 */
  2248. lst[n++] = 24;
  2249. test_eq(24, median()); /* 12,24,77,77 */
  2250. lst[n++] = 60;
  2251. lst[n++] = 12;
  2252. lst[n++] = 25;
  2253. //smartlist_shuffle(sl);
  2254. test_eq(25, median()); /* 12,12,24,25,60,77,77 */
  2255. #undef median
  2256. }
  2257. static void
  2258. test_v3_networkstatus(void)
  2259. {
  2260. authority_cert_t *cert1, *cert2, *cert3;
  2261. crypto_pk_env_t *sign_skey_1, *sign_skey_2, *sign_skey_3;
  2262. time_t now = time(NULL);
  2263. networkstatus_voter_info_t *voter;
  2264. networkstatus_t *vote, *v1, *v2, *v3, *con;
  2265. vote_routerstatus_t *vrs;
  2266. routerstatus_t *rs;
  2267. char *v1_text, *v2_text, *v3_text, *consensus_text, *cp;
  2268. smartlist_t *votes = smartlist_create();
  2269. /* Parse certificates and keys. */
  2270. cert1 = authority_cert_parse_from_string(AUTHORITY_CERT_1, NULL);
  2271. test_assert(cert1);
  2272. cert2 = authority_cert_parse_from_string(AUTHORITY_CERT_2, NULL);
  2273. test_assert(cert2);
  2274. cert3 = authority_cert_parse_from_string(AUTHORITY_CERT_3, NULL);
  2275. test_assert(cert3);
  2276. sign_skey_1 = crypto_new_pk_env();
  2277. sign_skey_2 = crypto_new_pk_env();
  2278. sign_skey_3 = crypto_new_pk_env();
  2279. test_assert(!crypto_pk_read_private_key_from_string(sign_skey_1,
  2280. AUTHORITY_SIGNKEY_1));
  2281. test_assert(!crypto_pk_read_private_key_from_string(sign_skey_2,
  2282. AUTHORITY_SIGNKEY_2));
  2283. test_assert(!crypto_pk_read_private_key_from_string(sign_skey_3,
  2284. AUTHORITY_SIGNKEY_3));
  2285. test_assert(!crypto_pk_cmp_keys(sign_skey_1, cert1->signing_key));
  2286. test_assert(!crypto_pk_cmp_keys(sign_skey_2, cert2->signing_key));
  2287. /*
  2288. * Set up a vote; generate it; try to parse it.
  2289. */
  2290. vote = tor_malloc_zero(sizeof(networkstatus_t));
  2291. vote->is_vote = 1;
  2292. vote->published = now;
  2293. vote->valid_after = now+1000;
  2294. vote->fresh_until = now+2000;
  2295. vote->valid_until = now+3000;
  2296. vote->vote_seconds = 100;
  2297. vote->dist_seconds = 200;
  2298. vote->client_versions = tor_strdup("0.1.2.14,0.1.2.15");
  2299. vote->server_versions = tor_strdup("0.1.2.14,0.1.2.15,0.1.2.16");
  2300. vote->known_flags = smartlist_create();
  2301. smartlist_split_string(vote->known_flags,
  2302. "Authority Exit Fast Guard Running Stable V2Dir Valid",
  2303. 0, SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2304. vote->voters = smartlist_create();
  2305. voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
  2306. voter->nickname = tor_strdup("Voter1");
  2307. voter->address = tor_strdup("1.2.3.4");
  2308. voter->addr = 0x01020304;
  2309. voter->dir_port = 80;
  2310. voter->or_port = 9000;
  2311. voter->contact = tor_strdup("voter@example.com");
  2312. crypto_pk_get_digest(cert1->identity_key, voter->identity_digest);
  2313. smartlist_add(vote->voters, voter);
  2314. vote->cert = authority_cert_dup(cert1);
  2315. vote->routerstatus_list = smartlist_create();
  2316. /* add the first routerstatus. */
  2317. vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
  2318. rs = &vrs->status;
  2319. vrs->version = tor_strdup("0.1.2.14");
  2320. rs->published_on = now-1500;
  2321. strlcpy(rs->nickname, "router2", sizeof(rs->nickname));
  2322. memset(rs->identity_digest, 3, DIGEST_LEN);
  2323. memset(rs->descriptor_digest, 78, DIGEST_LEN);
  2324. rs->addr = 0x99008801;
  2325. rs->or_port = 443;
  2326. rs->dir_port = 8000;
  2327. /* all flags cleared */
  2328. smartlist_add(vote->routerstatus_list, vrs);
  2329. /* add the second routerstatus. */
  2330. vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
  2331. rs = &vrs->status;
  2332. vrs->version = tor_strdup("0.2.0.5");
  2333. rs->published_on = now-1000;
  2334. strlcpy(rs->nickname, "router1", sizeof(rs->nickname));
  2335. memset(rs->identity_digest, 5, DIGEST_LEN);
  2336. memset(rs->descriptor_digest, 77, DIGEST_LEN);
  2337. rs->addr = 0x99009901;
  2338. rs->or_port = 443;
  2339. rs->dir_port = 0;
  2340. rs->is_exit = rs->is_stable = rs->is_fast = rs->is_running =
  2341. rs->is_valid = rs->is_v2_dir = rs->is_possible_guard = 1;
  2342. smartlist_add(vote->routerstatus_list, vrs);
  2343. /* add the third routerstatus. */
  2344. vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
  2345. rs = &vrs->status;
  2346. vrs->version = tor_strdup("0.1.0.3");
  2347. rs->published_on = now-1000;
  2348. strlcpy(rs->nickname, "router3", sizeof(rs->nickname));
  2349. memset(rs->identity_digest, 33, DIGEST_LEN);
  2350. memset(rs->descriptor_digest, 78, DIGEST_LEN);
  2351. rs->addr = 0xAA009901;
  2352. rs->or_port = 400;
  2353. rs->dir_port = 9999;
  2354. rs->is_authority = rs->is_exit = rs->is_stable = rs->is_fast =
  2355. rs->is_running = rs->is_valid = rs->is_v2_dir = rs->is_possible_guard = 1;
  2356. smartlist_add(vote->routerstatus_list, vrs);
  2357. /* dump the vote and try to parse it. */
  2358. v1_text = format_networkstatus_vote(sign_skey_1, vote);
  2359. test_assert(v1_text);
  2360. v1 = networkstatus_parse_vote_from_string(v1_text, NULL, 1);
  2361. test_assert(v1);
  2362. /* Make sure the parsed thing was right. */
  2363. test_eq(v1->is_vote, 1);
  2364. test_eq(v1->published, vote->published);
  2365. test_eq(v1->valid_after, vote->valid_after);
  2366. test_eq(v1->fresh_until, vote->fresh_until);
  2367. test_eq(v1->valid_until, vote->valid_until);
  2368. test_eq(v1->vote_seconds, vote->vote_seconds);
  2369. test_eq(v1->dist_seconds, vote->dist_seconds);
  2370. test_streq(v1->client_versions, vote->client_versions);
  2371. test_streq(v1->server_versions, vote->server_versions);
  2372. test_assert(v1->voters && smartlist_len(v1->voters));
  2373. voter = smartlist_get(v1->voters, 0);
  2374. test_streq(voter->nickname, "Voter1");
  2375. test_streq(voter->address, "1.2.3.4");
  2376. test_eq(voter->addr, 0x01020304);
  2377. test_eq(voter->dir_port, 80);
  2378. test_eq(voter->or_port, 9000);
  2379. test_streq(voter->contact, "voter@example.com");
  2380. test_assert(v1->cert);
  2381. test_assert(!crypto_pk_cmp_keys(sign_skey_1, v1->cert->signing_key));
  2382. cp = smartlist_join_strings(v1->known_flags, ":", 0, NULL);
  2383. test_streq(cp, "Authority:Exit:Fast:Guard:Running:Stable:V2Dir:Valid");
  2384. tor_free(cp);
  2385. test_eq(smartlist_len(v1->routerstatus_list), 3);
  2386. /* Check the first routerstatus. */
  2387. vrs = smartlist_get(v1->routerstatus_list, 0);
  2388. rs = &vrs->status;
  2389. test_streq(vrs->version, "0.1.2.14");
  2390. test_eq(rs->published_on, now-1500);
  2391. test_streq(rs->nickname, "router2");
  2392. test_memeq(rs->identity_digest,
  2393. "\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3",
  2394. DIGEST_LEN);
  2395. test_memeq(rs->descriptor_digest, "NNNNNNNNNNNNNNNNNNNN", DIGEST_LEN);
  2396. test_eq(rs->addr, 0x99008801);
  2397. test_eq(rs->or_port, 443);
  2398. test_eq(rs->dir_port, 8000);
  2399. test_eq(vrs->flags, U64_LITERAL(0));
  2400. /* Check the second routerstatus. */
  2401. vrs = smartlist_get(v1->routerstatus_list, 1);
  2402. rs = &vrs->status;
  2403. test_streq(vrs->version, "0.2.0.5");
  2404. test_eq(rs->published_on, now-1000);
  2405. test_streq(rs->nickname, "router1");
  2406. test_memeq(rs->identity_digest,
  2407. "\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5",
  2408. DIGEST_LEN);
  2409. test_memeq(rs->descriptor_digest, "MMMMMMMMMMMMMMMMMMMM", DIGEST_LEN);
  2410. test_eq(rs->addr, 0x99009901);
  2411. test_eq(rs->or_port, 443);
  2412. test_eq(rs->dir_port, 0);
  2413. test_eq(vrs->flags, U64_LITERAL(254)); // all flags except "authority."
  2414. /* Generate second vote. It disagrees on some of the times,
  2415. * and doesn't list versions, and knows some crazy flags */
  2416. vote->published = now+1;
  2417. vote->fresh_until = now+3005;
  2418. vote->dist_seconds = 300;
  2419. authority_cert_free(vote->cert);
  2420. vote->cert = authority_cert_dup(cert2);
  2421. tor_free(vote->client_versions);
  2422. tor_free(vote->server_versions);
  2423. voter = smartlist_get(vote->voters, 0);
  2424. tor_free(voter->nickname);
  2425. tor_free(voter->address);
  2426. voter->nickname = tor_strdup("Voter2");
  2427. voter->address = tor_strdup("2.3.4.5");
  2428. voter->addr = 0x02030405;
  2429. crypto_pk_get_digest(cert2->identity_key, voter->identity_digest);
  2430. smartlist_add(vote->known_flags, tor_strdup("MadeOfCheese"));
  2431. smartlist_add(vote->known_flags, tor_strdup("MadeOfTin"));
  2432. smartlist_sort_strings(vote->known_flags);
  2433. vrs = smartlist_get(vote->routerstatus_list, 2);
  2434. smartlist_del_keeporder(vote->routerstatus_list, 2);
  2435. tor_free(vrs->version);
  2436. tor_free(vrs);
  2437. vrs = smartlist_get(vote->routerstatus_list, 0);
  2438. vrs->status.is_fast = 1;
  2439. /* generate and parse. */
  2440. v2_text = format_networkstatus_vote(sign_skey_2, vote);
  2441. test_assert(v2_text);
  2442. v2 = networkstatus_parse_vote_from_string(v2_text, NULL, 1);
  2443. test_assert(v2);
  2444. /* Check that flags come out right.*/
  2445. cp = smartlist_join_strings(v2->known_flags, ":", 0, NULL);
  2446. test_streq(cp, "Authority:Exit:Fast:Guard:MadeOfCheese:MadeOfTin:"
  2447. "Running:Stable:V2Dir:Valid");
  2448. tor_free(cp);
  2449. vrs = smartlist_get(v2->routerstatus_list, 1);
  2450. /* 1023 - authority(1) - madeofcheese(16) - madeoftin(32) */
  2451. test_eq(vrs->flags, U64_LITERAL(974));
  2452. /* Generate the third vote. */
  2453. vote->published = now;
  2454. vote->fresh_until = now+2003;
  2455. vote->dist_seconds = 250;
  2456. authority_cert_free(vote->cert);
  2457. vote->cert = authority_cert_dup(cert3);
  2458. vote->client_versions = tor_strdup("0.1.2.14,0.1.2.17");
  2459. vote->server_versions = tor_strdup("0.1.2.10,0.1.2.15,0.1.2.16");
  2460. voter = smartlist_get(vote->voters, 0);
  2461. tor_free(voter->nickname);
  2462. tor_free(voter->address);
  2463. voter->nickname = tor_strdup("Voter3");
  2464. voter->address = tor_strdup("3.4.5.6");
  2465. voter->addr = 0x03040506;
  2466. crypto_pk_get_digest(cert3->identity_key, voter->identity_digest);
  2467. vrs = smartlist_get(vote->routerstatus_list, 0);
  2468. smartlist_del_keeporder(vote->routerstatus_list, 0);
  2469. tor_free(vrs->version);
  2470. tor_free(vrs);
  2471. vrs = smartlist_get(vote->routerstatus_list, 0);
  2472. memset(vrs->status.descriptor_digest, (int)'Z', DIGEST_LEN);
  2473. v3_text = format_networkstatus_vote(sign_skey_3, vote);
  2474. test_assert(v3_text);
  2475. v3 = networkstatus_parse_vote_from_string(v3_text, NULL, 1);
  2476. test_assert(v3);
  2477. /* Compute a consensus as voter 3. */
  2478. smartlist_add(votes, v3);
  2479. smartlist_add(votes, v1);
  2480. smartlist_add(votes, v2);
  2481. consensus_text = networkstatus_compute_consensus(votes, 3,
  2482. cert3->identity_key,
  2483. sign_skey_3);
  2484. test_assert(consensus_text);
  2485. con = networkstatus_parse_vote_from_string(consensus_text, NULL, 0);
  2486. test_assert(con);
  2487. //log_notice(LD_GENERAL, "<<%s>>\n<<%s>>\n<<%s>>\n",
  2488. // v1_text, v2_text, v3_text);
  2489. /* Check consensus contents. */
  2490. test_assert(!con->is_vote);
  2491. test_eq(con->published, 0); /* this field only appears in votes. */
  2492. test_eq(con->valid_after, now+1000);
  2493. test_eq(con->fresh_until, now+2003); /* median */
  2494. test_eq(con->valid_until, now+3000);
  2495. test_eq(con->vote_seconds, 100);
  2496. test_eq(con->dist_seconds, 250); /* median */
  2497. test_streq(con->client_versions, "0.1.2.14");
  2498. test_streq(con->server_versions, "0.1.2.15,0.1.2.16");
  2499. cp = smartlist_join_strings(v2->known_flags, ":", 0, NULL);
  2500. test_streq(cp, "Authority:Exit:Fast:Guard:MadeOfCheese:MadeOfTin:"
  2501. "Running:Stable:V2Dir:Valid");
  2502. tor_free(cp);
  2503. test_eq(3, smartlist_len(con->voters));
  2504. /* The voter id digests should be in this order. */
  2505. test_assert(memcmp(cert2->cache_info.identity_digest,
  2506. cert3->cache_info.identity_digest,DIGEST_LEN)<0);
  2507. test_assert(memcmp(cert3->cache_info.identity_digest,
  2508. cert1->cache_info.identity_digest,DIGEST_LEN)<0);
  2509. test_same_voter(smartlist_get(con->voters, 0),
  2510. smartlist_get(v2->voters, 0));
  2511. test_same_voter(smartlist_get(con->voters, 1),
  2512. smartlist_get(v3->voters, 0));
  2513. test_same_voter(smartlist_get(con->voters, 2),
  2514. smartlist_get(v1->voters, 0));
  2515. test_assert(!con->cert);
  2516. test_eq(2, smartlist_len(con->routerstatus_list));
  2517. /* There should be two listed routers: one with identity 3, one with
  2518. * identity 5. */
  2519. /* This one showed up in 2 digests. */
  2520. rs = smartlist_get(con->routerstatus_list, 0);
  2521. test_memeq(rs->identity_digest,
  2522. "\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3",
  2523. DIGEST_LEN);
  2524. test_memeq(rs->descriptor_digest, "NNNNNNNNNNNNNNNNNNNN", DIGEST_LEN);
  2525. test_assert(!rs->is_authority);
  2526. test_assert(!rs->is_exit);
  2527. test_assert(!rs->is_fast);
  2528. test_assert(!rs->is_possible_guard);
  2529. test_assert(!rs->is_stable);
  2530. test_assert(!rs->is_running);
  2531. test_assert(!rs->is_v2_dir);
  2532. test_assert(!rs->is_valid);
  2533. test_assert(!rs->is_named);
  2534. /* XXXX check version */
  2535. rs = smartlist_get(con->routerstatus_list, 1);
  2536. /* This one showed up in 3 digests. Twice with ID 'M', once with 'Z'. */
  2537. test_memeq(rs->identity_digest,
  2538. "\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5",
  2539. DIGEST_LEN);
  2540. test_streq(rs->nickname, "router1");
  2541. test_memeq(rs->descriptor_digest, "MMMMMMMMMMMMMMMMMMMM", DIGEST_LEN);
  2542. test_eq(rs->published_on, now-1000);
  2543. test_eq(rs->addr, 0x99009901);
  2544. test_eq(rs->or_port, 443);
  2545. test_eq(rs->dir_port, 0);
  2546. test_assert(!rs->is_authority);
  2547. test_assert(rs->is_exit);
  2548. test_assert(rs->is_fast);
  2549. test_assert(rs->is_possible_guard);
  2550. test_assert(rs->is_stable);
  2551. test_assert(rs->is_running);
  2552. test_assert(rs->is_v2_dir);
  2553. test_assert(rs->is_valid);
  2554. test_assert(!rs->is_named);
  2555. /* XXXX check version */
  2556. /* Check signatures. the first voter hasn't got one. The second one
  2557. * does: validate it. */
  2558. voter = smartlist_get(con->voters, 0);
  2559. test_assert(!voter->signature);
  2560. test_assert(!voter->good_signature);
  2561. test_assert(!voter->bad_signature);
  2562. voter = smartlist_get(con->voters, 1);
  2563. test_assert(voter->signature);
  2564. test_assert(!voter->good_signature);
  2565. test_assert(!voter->bad_signature);
  2566. test_assert(!networkstatus_check_voter_signature(con,
  2567. smartlist_get(con->voters, 1),
  2568. cert3));
  2569. test_assert(voter->signature);
  2570. test_assert(voter->good_signature);
  2571. test_assert(!voter->bad_signature);
  2572. {
  2573. char *consensus_text2, *consensus_text3;
  2574. networkstatus_t *con2, *con3;
  2575. char *detached_text1, *detached_text2;
  2576. ns_detached_signatures_t *dsig1, *dsig2;
  2577. const char *msg=NULL;
  2578. /* Compute the other two signed consensuses. */
  2579. smartlist_shuffle(votes);
  2580. consensus_text2 = networkstatus_compute_consensus(votes, 3,
  2581. cert2->identity_key,
  2582. sign_skey_2);
  2583. smartlist_shuffle(votes);
  2584. consensus_text3 = networkstatus_compute_consensus(votes, 3,
  2585. cert1->identity_key,
  2586. sign_skey_1);
  2587. test_assert(consensus_text2);
  2588. test_assert(consensus_text3);
  2589. con2 = networkstatus_parse_vote_from_string(consensus_text2, NULL, 0);
  2590. con3 = networkstatus_parse_vote_from_string(consensus_text3, NULL, 0);
  2591. test_assert(con2);
  2592. test_assert(con3);
  2593. /* All three should have the same digest. */
  2594. test_memeq(con->networkstatus_digest, con2->networkstatus_digest,
  2595. DIGEST_LEN);
  2596. test_memeq(con->networkstatus_digest, con3->networkstatus_digest,
  2597. DIGEST_LEN);
  2598. /* Extract a detached signature from con3. */
  2599. detached_text1 = networkstatus_get_detached_signatures(con3);
  2600. tor_assert(detached_text1);
  2601. /* Try to parse it. */
  2602. dsig1 = networkstatus_parse_detached_signatures(detached_text1, NULL);
  2603. tor_assert(dsig1);
  2604. /* Are parsed values as expected? */
  2605. test_eq(dsig1->valid_after, con3->valid_after);
  2606. test_eq(dsig1->fresh_until, con3->fresh_until);
  2607. test_eq(dsig1->valid_until, con3->valid_until);
  2608. test_memeq(dsig1->networkstatus_digest, con3->networkstatus_digest,
  2609. DIGEST_LEN);
  2610. test_eq(1, smartlist_len(dsig1->signatures));
  2611. voter = smartlist_get(dsig1->signatures, 0);
  2612. test_memeq(voter->identity_digest, cert1->cache_info.identity_digest,
  2613. DIGEST_LEN);
  2614. /* Try adding it to con2. */
  2615. detached_text2 = networkstatus_get_detached_signatures(con2);
  2616. test_eq(1, networkstatus_add_detached_signatures(con2, dsig1, &msg));
  2617. tor_free(detached_text2);
  2618. detached_text2 = networkstatus_get_detached_signatures(con2);
  2619. //printf("\n<%s>\n", detached_text2);
  2620. dsig2 = networkstatus_parse_detached_signatures(detached_text2, NULL);
  2621. test_assert(dsig2);
  2622. /*
  2623. printf("\n");
  2624. SMARTLIST_FOREACH(dsig2->signatures, networkstatus_voter_info_t *, vi, {
  2625. char hd[64];
  2626. base16_encode(hd, sizeof(hd), vi->identity_digest, DIGEST_LEN);
  2627. printf("%s\n", hd);
  2628. });
  2629. */
  2630. test_eq(2, smartlist_len(dsig2->signatures));
  2631. /* Try adding to con2 twice; verify that nothing changes. */
  2632. test_eq(0, networkstatus_add_detached_signatures(con2, dsig1, &msg));
  2633. /* Add to con. */
  2634. test_eq(2, networkstatus_add_detached_signatures(con, dsig2, &msg));
  2635. /* Check signatures */
  2636. test_assert(!networkstatus_check_voter_signature(con,
  2637. smartlist_get(con->voters, 0),
  2638. cert2));
  2639. test_assert(!networkstatus_check_voter_signature(con,
  2640. smartlist_get(con->voters, 2),
  2641. cert1));
  2642. networkstatus_vote_free(con2);
  2643. networkstatus_vote_free(con3);
  2644. tor_free(consensus_text2);
  2645. tor_free(consensus_text3);
  2646. tor_free(detached_text1);
  2647. tor_free(detached_text2);
  2648. ns_detached_signatures_free(dsig1);
  2649. ns_detached_signatures_free(dsig2);
  2650. }
  2651. smartlist_free(votes);
  2652. tor_free(v1_text);
  2653. tor_free(v2_text);
  2654. tor_free(v3_text);
  2655. tor_free(consensus_text);
  2656. networkstatus_vote_free(vote);
  2657. networkstatus_vote_free(v1);
  2658. networkstatus_vote_free(v2);
  2659. networkstatus_vote_free(v3);
  2660. networkstatus_vote_free(con);
  2661. crypto_free_pk_env(sign_skey_1);
  2662. crypto_free_pk_env(sign_skey_2);
  2663. crypto_free_pk_env(sign_skey_3);
  2664. authority_cert_free(cert1);
  2665. authority_cert_free(cert2);
  2666. authority_cert_free(cert3);
  2667. }
  2668. static void
  2669. test_policies(void)
  2670. {
  2671. smartlist_t *policy, *policy2;
  2672. addr_policy_t *p;
  2673. tor_addr_t tar;
  2674. config_line_t line;
  2675. policy = smartlist_create();
  2676. p = router_parse_addr_policy_item_from_string("reject 192.168.0.0/16:*",-1);
  2677. test_eq(ADDR_POLICY_REJECT, p->policy_type);
  2678. tor_addr_from_ipv4(&tar, 0xc0a80000u);
  2679. test_assert(p->addr == 0xc0a80000u);
  2680. test_eq(16, p->maskbits);
  2681. test_eq(1, p->prt_min);
  2682. test_eq(65535, p->prt_max);
  2683. smartlist_add(policy, p);
  2684. test_assert(ADDR_POLICY_ACCEPTED ==
  2685. compare_addr_to_addr_policy(0x01020304u, 2, policy));
  2686. test_assert(ADDR_POLICY_PROBABLY_ACCEPTED ==
  2687. compare_addr_to_addr_policy(0, 2, policy));
  2688. test_assert(ADDR_POLICY_REJECTED ==
  2689. compare_addr_to_addr_policy(0xc0a80102, 2, policy));
  2690. policy2 = NULL;
  2691. test_assert(0 == policies_parse_exit_policy(NULL, &policy2, 1, NULL));
  2692. test_assert(policy2);
  2693. test_assert(!exit_policy_is_general_exit(policy));
  2694. test_assert(exit_policy_is_general_exit(policy2));
  2695. test_assert(cmp_addr_policies(policy, policy2));
  2696. test_assert(!cmp_addr_policies(policy2, policy2));
  2697. test_assert(!policy_is_reject_star(policy2));
  2698. test_assert(policy_is_reject_star(policy));
  2699. addr_policy_list_free(policy);
  2700. addr_policy_list_free(policy2);
  2701. /* make sure compacting logic works. */
  2702. policy = NULL;
  2703. line.key = (char*)"foo";
  2704. line.value = (char*)"accept *:80,reject private:*,reject *:*";
  2705. line.next = NULL;
  2706. test_assert(0 == policies_parse_exit_policy(&line, &policy, 0, NULL));
  2707. test_assert(policy);
  2708. //test_streq(policy->string, "accept *:80");
  2709. //test_streq(policy->next->string, "reject *:*");
  2710. test_eq(smartlist_len(policy), 2);
  2711. addr_policy_list_free(policy);
  2712. }
  2713. static void
  2714. test_rend_fns(void)
  2715. {
  2716. char address1[] = "fooaddress.onion";
  2717. char address2[] = "aaaaaaaaaaaaaaaa.onion";
  2718. char address3[] = "fooaddress.exit";
  2719. char address4[] = "www.torproject.org";
  2720. rend_service_descriptor_t *d1, *d2;
  2721. char *encoded;
  2722. size_t len;
  2723. crypto_pk_env_t *pk1, *pk2;
  2724. time_t now;
  2725. int i;
  2726. pk1 = pk_generate(0);
  2727. pk2 = pk_generate(1);
  2728. /* Test unversioned (v0) descriptor */
  2729. d1 = tor_malloc_zero(sizeof(rend_service_descriptor_t));
  2730. d1->pk = crypto_pk_dup_key(pk1);
  2731. now = time(NULL);
  2732. d1->timestamp = now;
  2733. d1->version = 0;
  2734. d1->intro_nodes = smartlist_create();
  2735. for (i = 0; i < 3; i++) {
  2736. rend_intro_point_t *intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  2737. intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
  2738. crypto_rand(intro->extend_info->identity_digest, DIGEST_LEN);
  2739. intro->extend_info->nickname[0] = '$';
  2740. base16_encode(intro->extend_info->nickname+1, HEX_DIGEST_LEN+1,
  2741. intro->extend_info->identity_digest, DIGEST_LEN);
  2742. smartlist_add(d1->intro_nodes, intro);
  2743. }
  2744. test_assert(! rend_encode_service_descriptor(d1, pk1, &encoded, &len));
  2745. d2 = rend_parse_service_descriptor(encoded, len);
  2746. test_assert(d2);
  2747. test_assert(!crypto_pk_cmp_keys(d1->pk, d2->pk));
  2748. test_eq(d2->timestamp, now);
  2749. test_eq(d2->version, 0);
  2750. test_eq(d2->protocols, 1<<2);
  2751. test_eq(smartlist_len(d2->intro_nodes), 3);
  2752. for (i = 0; i < 3; i++) {
  2753. rend_intro_point_t *intro1 = smartlist_get(d1->intro_nodes, i);
  2754. rend_intro_point_t *intro2 = smartlist_get(d2->intro_nodes, i);
  2755. test_streq(intro1->extend_info->nickname,
  2756. intro2->extend_info->nickname);
  2757. }
  2758. rend_service_descriptor_free(d1);
  2759. rend_service_descriptor_free(d2);
  2760. tor_free(encoded);
  2761. test_assert(BAD_HOSTNAME == parse_extended_hostname(address1));
  2762. test_assert(ONION_HOSTNAME == parse_extended_hostname(address2));
  2763. test_assert(EXIT_HOSTNAME == parse_extended_hostname(address3));
  2764. test_assert(NORMAL_HOSTNAME == parse_extended_hostname(address4));
  2765. crypto_free_pk_env(pk1);
  2766. crypto_free_pk_env(pk2);
  2767. }
  2768. static void
  2769. bench_aes(void)
  2770. {
  2771. int len, i;
  2772. char *b1, *b2;
  2773. crypto_cipher_env_t *c;
  2774. struct timeval start, end;
  2775. const int iters = 100000;
  2776. uint64_t nsec;
  2777. c = crypto_new_cipher_env();
  2778. crypto_cipher_generate_key(c);
  2779. crypto_cipher_encrypt_init_cipher(c);
  2780. for (len = 1; len <= 8192; len *= 2) {
  2781. b1 = tor_malloc_zero(len);
  2782. b2 = tor_malloc_zero(len);
  2783. tor_gettimeofday(&start);
  2784. for (i = 0; i < iters; ++i) {
  2785. crypto_cipher_encrypt(c, b1, b2, len);
  2786. }
  2787. tor_gettimeofday(&end);
  2788. tor_free(b1);
  2789. tor_free(b2);
  2790. nsec = (uint64_t) tv_udiff(&start,&end);
  2791. nsec *= 1000;
  2792. nsec /= (iters*len);
  2793. printf("%d bytes: "U64_FORMAT" nsec per byte\n", len,
  2794. U64_PRINTF_ARG(nsec));
  2795. }
  2796. crypto_free_cipher_env(c);
  2797. }
  2798. static void
  2799. test_util_mempool(void)
  2800. {
  2801. mp_pool_t *pool;
  2802. smartlist_t *allocated;
  2803. int i;
  2804. pool = mp_pool_new(1, 100);
  2805. test_assert(pool->new_chunk_capacity >= 100);
  2806. test_assert(pool->item_alloc_size >= sizeof(void*)+1);
  2807. mp_pool_destroy(pool);
  2808. pool = mp_pool_new(241, 2500);
  2809. test_assert(pool->new_chunk_capacity >= 10);
  2810. test_assert(pool->item_alloc_size >= sizeof(void*)+241);
  2811. test_eq(pool->item_alloc_size & 0x03, 0);
  2812. test_assert(pool->new_chunk_capacity < 60);
  2813. allocated = smartlist_create();
  2814. for (i = 0; i < 100000; ++i) {
  2815. if (smartlist_len(allocated) < 20 || crypto_rand_int(2)) {
  2816. void *m = mp_pool_get(pool);
  2817. memset(m, 0x09, 241);
  2818. smartlist_add(allocated, m);
  2819. //printf("%d: %p\n", i, m);
  2820. //mp_pool_assert_ok(pool);
  2821. } else {
  2822. int idx = crypto_rand_int(smartlist_len(allocated));
  2823. void *m = smartlist_get(allocated, idx);
  2824. //printf("%d: free %p\n", i, m);
  2825. smartlist_del(allocated, idx);
  2826. mp_pool_release(m);
  2827. //mp_pool_assert_ok(pool);
  2828. }
  2829. if (crypto_rand_int(777)==0)
  2830. mp_pool_clean(pool, 1, 1);
  2831. if (i % 777)
  2832. mp_pool_assert_ok(pool);
  2833. }
  2834. SMARTLIST_FOREACH(allocated, void *, m, mp_pool_release(m));
  2835. mp_pool_assert_ok(pool);
  2836. mp_pool_clean(pool, 0, 0);
  2837. mp_pool_assert_ok(pool);
  2838. mp_pool_destroy(pool);
  2839. smartlist_free(allocated);
  2840. }
  2841. static void
  2842. test_util_datadir(void)
  2843. {
  2844. char buf[1024];
  2845. char *f;
  2846. f = get_datadir_fname(NULL);
  2847. test_streq(f, temp_dir);
  2848. tor_free(f);
  2849. f = get_datadir_fname("state");
  2850. tor_snprintf(buf, sizeof(buf), "%s"PATH_SEPARATOR"state", temp_dir);
  2851. test_streq(f, buf);
  2852. tor_free(f);
  2853. f = get_datadir_fname2("cache", "thingy");
  2854. tor_snprintf(buf, sizeof(buf),
  2855. "%s"PATH_SEPARATOR"cache"PATH_SEPARATOR"thingy", temp_dir);
  2856. test_streq(f, buf);
  2857. tor_free(f);
  2858. f = get_datadir_fname2_suffix("cache", "thingy", ".foo");
  2859. tor_snprintf(buf, sizeof(buf),
  2860. "%s"PATH_SEPARATOR"cache"PATH_SEPARATOR"thingy.foo", temp_dir);
  2861. test_streq(f, buf);
  2862. tor_free(f);
  2863. f = get_datadir_fname_suffix("cache", ".foo");
  2864. tor_snprintf(buf, sizeof(buf), "%s"PATH_SEPARATOR"cache.foo",
  2865. temp_dir);
  2866. test_streq(f, buf);
  2867. tor_free(f);
  2868. }
  2869. /* Test AES-CTR encryption and decryption with IV. */
  2870. static void
  2871. test_crypto_aes_iv(void)
  2872. {
  2873. crypto_cipher_env_t *cipher;
  2874. char *plain, *encrypted1, *encrypted2, *decrypted1, *decrypted2;
  2875. char plain_1[1], plain_15[15], plain_16[16], plain_17[17];
  2876. char key1[16], key2[16];
  2877. size_t encrypted_size, decrypted_size;
  2878. plain = tor_malloc(4095);
  2879. encrypted1 = tor_malloc(4095 + 1 + 16);
  2880. encrypted2 = tor_malloc(4095 + 1 + 16);
  2881. decrypted1 = tor_malloc(4095 + 1);
  2882. decrypted2 = tor_malloc(4095 + 1);
  2883. crypto_rand(plain, 4095);
  2884. crypto_rand(key1, 16);
  2885. crypto_rand(key2, 16);
  2886. crypto_rand(plain_1, 1);
  2887. crypto_rand(plain_15, 15);
  2888. crypto_rand(plain_16, 16);
  2889. crypto_rand(plain_17, 17);
  2890. key1[0] = key2[0] + 128; /* Make sure that contents are different. */
  2891. /* Encrypt and decrypt with the same key. */
  2892. cipher = crypto_create_init_cipher(key1, 1);
  2893. encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 4095,
  2894. plain, 4095);
  2895. crypto_free_cipher_env(cipher);
  2896. test_eq(encrypted_size, 16 + 4095);
  2897. cipher = crypto_create_init_cipher(key1, 0);
  2898. decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 4095,
  2899. encrypted1, encrypted_size);
  2900. crypto_free_cipher_env(cipher);
  2901. test_eq(decrypted_size, 4095);
  2902. test_memeq(plain, decrypted1, 4095);
  2903. /* Encrypt a second time (with a new random initialization vector). */
  2904. cipher = crypto_create_init_cipher(key1, 1);
  2905. encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted2, 16 + 4095,
  2906. plain, 4095);
  2907. crypto_free_cipher_env(cipher);
  2908. test_eq(encrypted_size, 16 + 4095);
  2909. cipher = crypto_create_init_cipher(key1, 0);
  2910. decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted2, 4095,
  2911. encrypted2, encrypted_size);
  2912. crypto_free_cipher_env(cipher);
  2913. test_eq(decrypted_size, 4095);
  2914. test_memeq(plain, decrypted2, 4095);
  2915. test_memneq(encrypted1, encrypted2, encrypted_size);
  2916. /* Decrypt with the wrong key. */
  2917. cipher = crypto_create_init_cipher(key2, 0);
  2918. decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted2, 4095,
  2919. encrypted1, encrypted_size);
  2920. crypto_free_cipher_env(cipher);
  2921. test_memneq(plain, decrypted2, encrypted_size);
  2922. /* Alter the initialization vector. */
  2923. encrypted1[0] += 42;
  2924. cipher = crypto_create_init_cipher(key1, 0);
  2925. decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 4095,
  2926. encrypted1, encrypted_size);
  2927. crypto_free_cipher_env(cipher);
  2928. test_memneq(plain, decrypted2, 4095);
  2929. /* Special length case: 1. */
  2930. cipher = crypto_create_init_cipher(key1, 1);
  2931. encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 1,
  2932. plain_1, 1);
  2933. crypto_free_cipher_env(cipher);
  2934. test_eq(encrypted_size, 16 + 1);
  2935. cipher = crypto_create_init_cipher(key1, 0);
  2936. decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 1,
  2937. encrypted1, encrypted_size);
  2938. crypto_free_cipher_env(cipher);
  2939. test_eq(decrypted_size, 1);
  2940. test_memeq(plain_1, decrypted1, 1);
  2941. /* Special length case: 15. */
  2942. cipher = crypto_create_init_cipher(key1, 1);
  2943. encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 15,
  2944. plain_15, 15);
  2945. crypto_free_cipher_env(cipher);
  2946. test_eq(encrypted_size, 16 + 15);
  2947. cipher = crypto_create_init_cipher(key1, 0);
  2948. decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 15,
  2949. encrypted1, encrypted_size);
  2950. crypto_free_cipher_env(cipher);
  2951. test_eq(decrypted_size, 15);
  2952. test_memeq(plain_15, decrypted1, 15);
  2953. /* Special length case: 16. */
  2954. cipher = crypto_create_init_cipher(key1, 1);
  2955. encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 16,
  2956. plain_16, 16);
  2957. crypto_free_cipher_env(cipher);
  2958. test_eq(encrypted_size, 16 + 16);
  2959. cipher = crypto_create_init_cipher(key1, 0);
  2960. decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 16,
  2961. encrypted1, encrypted_size);
  2962. crypto_free_cipher_env(cipher);
  2963. test_eq(decrypted_size, 16);
  2964. test_memeq(plain_16, decrypted1, 16);
  2965. /* Special length case: 17. */
  2966. cipher = crypto_create_init_cipher(key1, 1);
  2967. encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 17,
  2968. plain_17, 17);
  2969. crypto_free_cipher_env(cipher);
  2970. test_eq(encrypted_size, 16 + 17);
  2971. cipher = crypto_create_init_cipher(key1, 0);
  2972. decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 17,
  2973. encrypted1, encrypted_size);
  2974. crypto_free_cipher_env(cipher);
  2975. test_eq(decrypted_size, 17);
  2976. test_memeq(plain_17, decrypted1, 17);
  2977. /* Free memory. */
  2978. tor_free(plain);
  2979. tor_free(encrypted1);
  2980. tor_free(encrypted2);
  2981. tor_free(decrypted1);
  2982. tor_free(decrypted2);
  2983. }
  2984. /* Test base32 decoding. */
  2985. static void
  2986. test_crypto_base32_decode(void)
  2987. {
  2988. char plain[60], encoded[96 + 1], decoded[60];
  2989. int res;
  2990. crypto_rand(plain, 60);
  2991. /* Encode and decode a random string. */
  2992. base32_encode(encoded, 96 + 1, plain, 60);
  2993. res = base32_decode(decoded, 60, encoded, 96);
  2994. test_eq(res, 0);
  2995. test_memeq(plain, decoded, 60);
  2996. /* Encode, uppercase, and decode a random string. */
  2997. base32_encode(encoded, 96 + 1, plain, 60);
  2998. tor_strupper(encoded);
  2999. res = base32_decode(decoded, 60, encoded, 96);
  3000. test_eq(res, 0);
  3001. test_memeq(plain, decoded, 60);
  3002. /* Change encoded string and decode. */
  3003. if (encoded[0] == 'A' || encoded[0] == 'a')
  3004. encoded[0] = 'B';
  3005. else
  3006. encoded[0] = 'A';
  3007. res = base32_decode(decoded, 60, encoded, 96);
  3008. test_eq(res, 0);
  3009. test_memneq(plain, decoded, 60);
  3010. }
  3011. /* Test encoding and parsing of v2 rendezvous service descriptors. */
  3012. static void
  3013. test_rend_fns_v2(void)
  3014. {
  3015. rend_service_descriptor_t *generated, *parsed;
  3016. char service_id[DIGEST_LEN];
  3017. char service_id_base32[REND_SERVICE_ID_LEN_BASE32+1];
  3018. const char *next_desc;
  3019. smartlist_t *descs = smartlist_create();
  3020. char computed_desc_id[DIGEST_LEN];
  3021. char parsed_desc_id[DIGEST_LEN];
  3022. crypto_pk_env_t *pk1, *pk2;
  3023. time_t now;
  3024. char *intro_points_encrypted;
  3025. size_t intro_points_size;
  3026. size_t encoded_size;
  3027. int i;
  3028. pk1 = pk_generate(0);
  3029. pk2 = pk_generate(1);
  3030. generated = tor_malloc_zero(sizeof(rend_service_descriptor_t));
  3031. generated->pk = crypto_pk_dup_key(pk1);
  3032. crypto_pk_get_digest(generated->pk, service_id);
  3033. base32_encode(service_id_base32, REND_SERVICE_ID_LEN_BASE32+1,
  3034. service_id, REND_SERVICE_ID_LEN);
  3035. now = time(NULL);
  3036. generated->timestamp = now;
  3037. generated->version = 2;
  3038. generated->protocols = 42;
  3039. generated->intro_nodes = smartlist_create();
  3040. for (i = 0; i < 3; i++) {
  3041. rend_intro_point_t *intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  3042. crypto_pk_env_t *okey = pk_generate(2 + i);
  3043. intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
  3044. intro->extend_info->onion_key = crypto_pk_dup_key(okey);
  3045. crypto_pk_get_digest(intro->extend_info->onion_key,
  3046. intro->extend_info->identity_digest);
  3047. //crypto_rand(info->identity_digest, DIGEST_LEN); /* Would this work? */
  3048. intro->extend_info->nickname[0] = '$';
  3049. base16_encode(intro->extend_info->nickname + 1,
  3050. sizeof(intro->extend_info->nickname) - 1,
  3051. intro->extend_info->identity_digest, DIGEST_LEN);
  3052. intro->extend_info->addr = crypto_rand_int(65536); /* Does not cover all
  3053. * IP addresses. */
  3054. intro->extend_info->port = crypto_rand_int(65536);
  3055. intro->intro_key = crypto_pk_dup_key(pk2);
  3056. smartlist_add(generated->intro_nodes, intro);
  3057. }
  3058. test_assert(rend_encode_v2_descriptors(descs, generated, now,
  3059. NULL, 0) > 0);
  3060. test_assert(rend_compute_v2_desc_id(computed_desc_id, service_id_base32,
  3061. NULL, now, 0) == 0);
  3062. test_memeq(((rend_encoded_v2_service_descriptor_t *)
  3063. smartlist_get(descs, 0))->desc_id, computed_desc_id, DIGEST_LEN);
  3064. test_assert(rend_parse_v2_service_descriptor(&parsed, parsed_desc_id,
  3065. &intro_points_encrypted,
  3066. &intro_points_size,
  3067. &encoded_size,
  3068. &next_desc,
  3069. ((rend_encoded_v2_service_descriptor_t *)
  3070. smartlist_get(descs, 0))->desc_str) == 0);
  3071. test_assert(parsed);
  3072. test_memeq(((rend_encoded_v2_service_descriptor_t *)
  3073. smartlist_get(descs, 0))->desc_id, parsed_desc_id, DIGEST_LEN);
  3074. test_assert(rend_decrypt_introduction_points(parsed, NULL,
  3075. intro_points_encrypted,
  3076. intro_points_size) == 3);
  3077. test_assert(!crypto_pk_cmp_keys(generated->pk, parsed->pk));
  3078. test_eq(parsed->timestamp, now);
  3079. test_eq(parsed->version, 2);
  3080. test_eq(parsed->protocols, 42);
  3081. test_eq(smartlist_len(parsed->intro_nodes), 3);
  3082. for (i = 0; i < smartlist_len(parsed->intro_nodes); i++) {
  3083. rend_intro_point_t *par_intro = smartlist_get(parsed->intro_nodes, i),
  3084. *gen_intro = smartlist_get(generated->intro_nodes, i);
  3085. extend_info_t *par_info = par_intro->extend_info;
  3086. extend_info_t *gen_info = gen_intro->extend_info;
  3087. test_assert(!crypto_pk_cmp_keys(gen_info->onion_key, par_info->onion_key));
  3088. test_memeq(gen_info->identity_digest, par_info->identity_digest,
  3089. DIGEST_LEN);
  3090. test_streq(gen_info->nickname, par_info->nickname);
  3091. test_eq(gen_info->addr, par_info->addr);
  3092. test_eq(gen_info->port, par_info->port);
  3093. }
  3094. tor_free(intro_points_encrypted);
  3095. for (i = 0; i < smartlist_len(descs); i++)
  3096. rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
  3097. smartlist_free(descs);
  3098. rend_service_descriptor_free(parsed);
  3099. rend_service_descriptor_free(generated);
  3100. }
  3101. static void
  3102. test_geoip(void)
  3103. {
  3104. int i, j;
  3105. time_t now = time(NULL);
  3106. char *s;
  3107. /* Populate the DB a bit. Add these in order, since we can't do the final
  3108. * 'sort' step. These aren't very good IP addresses, but they're perfectly
  3109. * fine uint32_t values. */
  3110. test_eq(0, geoip_parse_entry("10,50,AB"));
  3111. test_eq(0, geoip_parse_entry("52,90,XY"));
  3112. test_eq(0, geoip_parse_entry("95,100,AB"));
  3113. test_eq(0, geoip_parse_entry("\"105\",\"140\",\"ZZ\""));
  3114. test_eq(0, geoip_parse_entry("\"150\",\"190\",\"XY\""));
  3115. test_eq(0, geoip_parse_entry("\"200\",\"250\",\"AB\""));
  3116. /* We should have 3 countries: ab, xy, zz. */
  3117. test_eq(3, geoip_get_n_countries());
  3118. /* Make sure that country ID actually works. */
  3119. #define NAMEFOR(x) geoip_get_country_name(geoip_get_country_by_ip(x))
  3120. test_streq("ab", NAMEFOR(32));
  3121. test_streq("??", NAMEFOR(5));
  3122. test_streq("??", NAMEFOR(51));
  3123. test_streq("xy", NAMEFOR(150));
  3124. test_streq("xy", NAMEFOR(190));
  3125. test_streq("??", NAMEFOR(2000));
  3126. #undef NAMEFOR
  3127. get_options()->BridgeRelay = 1;
  3128. get_options()->BridgeRecordUsageByCountry = 1;
  3129. /* Put 9 observations in AB... */
  3130. for (i=32; i < 40; ++i)
  3131. geoip_note_client_seen(i, now);
  3132. geoip_note_client_seen(225, now);
  3133. /* and 3 observations in XY, several times. */
  3134. for (j=0; j < 10; ++j)
  3135. for (i=52; i < 55; ++i)
  3136. geoip_note_client_seen(i, now-3600);
  3137. /* and 17 observations in ZZ... */
  3138. for (i=110; i < 127; ++i)
  3139. geoip_note_client_seen(i, now-7200);
  3140. s = geoip_get_client_history(now+5*24*60*60);
  3141. test_assert(s);
  3142. test_streq("zz=24,ab=16", s);
  3143. tor_free(s);
  3144. /* Now clear out all the zz observations. */
  3145. geoip_remove_old_clients(now-6000);
  3146. s = geoip_get_client_history(now+5*24*60*60);
  3147. test_assert(! s); /* There are only 12 observations left. Not enough to
  3148. build an answer. Add 4 more in XY... */
  3149. for (i=55; i < 59; ++i)
  3150. geoip_note_client_seen(i, now-3600);
  3151. s = geoip_get_client_history(now+5*24*60*60);
  3152. test_assert(s);
  3153. test_streq("ab=16", s);
  3154. tor_free(s);
  3155. }
  3156. #define ENT(x) { #x, test_ ## x, 0, 0 }
  3157. #define SUBENT(x,y) { #x "/" #y, test_ ## x ## _ ## y, 1, 0 }
  3158. static struct {
  3159. const char *test_name;
  3160. void (*test_fn)(void);
  3161. int is_subent;
  3162. int selected;
  3163. } test_array[] = {
  3164. ENT(buffers),
  3165. ENT(crypto),
  3166. SUBENT(crypto, dh),
  3167. SUBENT(crypto, s2k),
  3168. SUBENT(crypto, aes_iv),
  3169. SUBENT(crypto, base32_decode),
  3170. ENT(util),
  3171. SUBENT(util, ip6_helpers),
  3172. SUBENT(util, gzip),
  3173. SUBENT(util, datadir),
  3174. SUBENT(util, smartlist),
  3175. SUBENT(util, bitarray),
  3176. SUBENT(util, mempool),
  3177. SUBENT(util, strmap),
  3178. SUBENT(util, control_formats),
  3179. SUBENT(util, pqueue),
  3180. SUBENT(util, mmap),
  3181. SUBENT(util, threads),
  3182. SUBENT(util, order_functions),
  3183. ENT(onion_handshake),
  3184. ENT(dir_format),
  3185. ENT(v3_networkstatus),
  3186. ENT(policies),
  3187. ENT(rend_fns),
  3188. SUBENT(rend_fns, v2),
  3189. ENT(geoip),
  3190. { NULL, NULL, 0, 0 },
  3191. };
  3192. static void syntax(void) ATTR_NORETURN;
  3193. static void
  3194. syntax(void)
  3195. {
  3196. int i;
  3197. printf("Syntax:\n"
  3198. " test [-v|--verbose] [--warn|--notice|--info|--debug]\n"
  3199. " [testname...]\n"
  3200. "Recognized tests are:\n");
  3201. for (i = 0; test_array[i].test_name; ++i) {
  3202. printf(" %s\n", test_array[i].test_name);
  3203. }
  3204. exit(0);
  3205. }
  3206. int
  3207. main(int c, char**v)
  3208. {
  3209. or_options_t *options = options_new();
  3210. char *errmsg = NULL;
  3211. int i;
  3212. int verbose = 0, any_selected = 0;
  3213. int loglevel = LOG_ERR;
  3214. init_logging();
  3215. for (i = 1; i < c; ++i) {
  3216. if (!strcmp(v[i], "-v") || !strcmp(v[i], "--verbose"))
  3217. verbose++;
  3218. else if (!strcmp(v[i], "--warn"))
  3219. loglevel = LOG_WARN;
  3220. else if (!strcmp(v[i], "--notice"))
  3221. loglevel = LOG_NOTICE;
  3222. else if (!strcmp(v[i], "--info"))
  3223. loglevel = LOG_INFO;
  3224. else if (!strcmp(v[i], "--debug"))
  3225. loglevel = LOG_DEBUG;
  3226. else if (!strcmp(v[i], "--help") || !strcmp(v[i], "-h") || v[i][0] == '-')
  3227. syntax();
  3228. else {
  3229. int j, found=0;
  3230. for (j = 0; test_array[j].test_name; ++j) {
  3231. if (!strcmp(v[i], test_array[j].test_name) ||
  3232. (test_array[j].is_subent &&
  3233. !strcmpstart(test_array[j].test_name, v[i]) &&
  3234. test_array[j].test_name[strlen(v[i])] == '/') ||
  3235. (v[i][0] == '=' && !strcmp(v[i]+1, test_array[j].test_name))) {
  3236. test_array[j].selected = 1;
  3237. any_selected = 1;
  3238. found = 1;
  3239. }
  3240. }
  3241. if (!found) {
  3242. printf("Unknown test: %s\n", v[i]);
  3243. syntax();
  3244. }
  3245. }
  3246. }
  3247. if (!any_selected) {
  3248. for (i = 0; test_array[i].test_name; ++i) {
  3249. test_array[i].selected = 1;
  3250. }
  3251. }
  3252. add_stream_log(loglevel, LOG_ERR, "", stdout);
  3253. options->command = CMD_RUN_UNITTESTS;
  3254. rep_hist_init();
  3255. network_init();
  3256. setup_directory();
  3257. options_init(options);
  3258. options->DataDirectory = tor_strdup(temp_dir);
  3259. if (set_options(options, &errmsg) < 0) {
  3260. printf("Failed to set initial options: %s\n", errmsg);
  3261. tor_free(errmsg);
  3262. return 1;
  3263. }
  3264. crypto_seed_rng();
  3265. if (0) {
  3266. bench_aes();
  3267. return 0;
  3268. }
  3269. atexit(remove_directory);
  3270. printf("Running Tor unit tests on %s\n", get_uname());
  3271. for (i = 0; test_array[i].test_name; ++i) {
  3272. if (!test_array[i].selected)
  3273. continue;
  3274. if (!test_array[i].is_subent) {
  3275. printf("\n============================== %s\n",test_array[i].test_name);
  3276. } else if (test_array[i].is_subent && verbose) {
  3277. printf("\n%s", test_array[i].test_name);
  3278. }
  3279. test_array[i].test_fn();
  3280. }
  3281. puts("");
  3282. if (have_failed)
  3283. return 1;
  3284. else
  3285. return 0;
  3286. }