test.c 137 KB

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