test.c 174 KB

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