test.c 149 KB

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