test.c 176 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247
  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. /** Helper: assert that IPv6 addresses <b>a</b> and <b>b</b> are the same. On
  1219. * failure, reports an error, describing the addresses as <b>e1</b> and
  1220. * <b>e2</b>, and reporting the line number as <b>line</b>. */
  1221. static void
  1222. _test_eq_ip6(struct in6_addr *a, struct in6_addr *b, const char *e1,
  1223. const char *e2, int line)
  1224. {
  1225. int i;
  1226. int ok = 1;
  1227. for (i = 0; i < 16; ++i) {
  1228. if (a->s6_addr[i] != b->s6_addr[i]) {
  1229. ok = 0;
  1230. break;
  1231. }
  1232. }
  1233. if (ok) {
  1234. printf("."); fflush(stdout);
  1235. } else {
  1236. char buf1[128], *cp1;
  1237. char buf2[128], *cp2;
  1238. have_failed = 1;
  1239. cp1 = buf1; cp2 = buf2;
  1240. for (i=0; i<16; ++i) {
  1241. tor_snprintf(cp1, sizeof(buf1)-(cp1-buf1), "%02x", a->s6_addr[i]);
  1242. tor_snprintf(cp2, sizeof(buf2)-(cp2-buf2), "%02x", b->s6_addr[i]);
  1243. cp1 += 2; cp2 += 2;
  1244. if ((i%2)==1 && i != 15) {
  1245. *cp1++ = ':';
  1246. *cp2++ = ':';
  1247. }
  1248. }
  1249. *cp1 = *cp2 = '\0';
  1250. printf("Line %d: assertion failed: (%s == %s)\n"
  1251. " %s != %s\n", line, e1, e2, buf1, buf2);
  1252. fflush(stdout);
  1253. }
  1254. }
  1255. /** Helper: Assert that two strings both decode as IPv6 addresses with
  1256. * tor_inet_pton(), and both decode to the same address. */
  1257. #define test_pton6_same(a,b) STMT_BEGIN \
  1258. test_eq(tor_inet_pton(AF_INET6, a, &a1), 1); \
  1259. test_eq(tor_inet_pton(AF_INET6, b, &a2), 1); \
  1260. _test_eq_ip6(&a1,&a2,#a,#b,__LINE__); \
  1261. STMT_END
  1262. /** Helper: Assert that <b>a</b> is recognized as a bad IPv6 address by
  1263. * tor_inet_pton(). */
  1264. #define test_pton6_bad(a) \
  1265. test_eq(0, tor_inet_pton(AF_INET6, a, &a1))
  1266. /** Helper: assert that <b>a</b>, when parsed by tor_inet_pton() and displayed
  1267. * with tor_inet_ntop(), yields <b>b</b>. Also assert that <b>b</b> parses to
  1268. * the same value as <b>a</b>. */
  1269. #define test_ntop6_reduces(a,b) STMT_BEGIN \
  1270. test_eq(tor_inet_pton(AF_INET6, a, &a1), 1); \
  1271. test_streq(tor_inet_ntop(AF_INET6, &a1, buf, sizeof(buf)), b); \
  1272. test_eq(tor_inet_pton(AF_INET6, b, &a2), 1); \
  1273. _test_eq_ip6(&a1, &a2, a, b, __LINE__); \
  1274. STMT_END
  1275. /** Helper: assert that <b>a</b> parses by tor_inet_pton() into a address that
  1276. * passes tor_addr_is_internal() with <b>for_listening</b>. */
  1277. #define test_internal_ip(a,for_listening) STMT_BEGIN \
  1278. test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
  1279. t1.family = AF_INET6; \
  1280. if (!tor_addr_is_internal(&t1, for_listening)) \
  1281. test_fail_msg( a "was not internal."); \
  1282. STMT_END
  1283. /** Helper: assert that <b>a</b> parses by tor_inet_pton() into a address that
  1284. * does not pass tor_addr_is_internal() with <b>for_listening</b>. */
  1285. #define test_external_ip(a,for_listening) STMT_BEGIN \
  1286. test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
  1287. t1.family = AF_INET6; \
  1288. if (tor_addr_is_internal(&t1, for_listening)) \
  1289. test_fail_msg(a "was not external."); \
  1290. STMT_END
  1291. /** Helper: Assert that <b>a</b> and <b>b</b>, when parsed by
  1292. * tor_inet_pton(), give addresses that compare in the order defined by
  1293. * <b>op</b> with tor_addr_compare(). */
  1294. #define test_addr_compare(a, op, b) STMT_BEGIN \
  1295. test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
  1296. test_eq(tor_inet_pton(AF_INET6, b, &t2.addr.in6_addr), 1); \
  1297. t1.family = t2.family = AF_INET6; \
  1298. r = tor_addr_compare(&t1,&t2,CMP_SEMANTIC); \
  1299. if (!(r op 0)) \
  1300. test_fail_msg("failed: tor_addr_compare("a","b") "#op" 0"); \
  1301. STMT_END
  1302. /** Helper: Assert that <b>a</b> and <b>b</b>, when parsed by
  1303. * tor_inet_pton(), give addresses that compare in the order defined by
  1304. * <b>op</b> with tor_addr_compare_masked() with <b>m</b> masked. */
  1305. #define test_addr_compare_masked(a, op, b, m) STMT_BEGIN \
  1306. test_eq(tor_inet_pton(AF_INET6, a, &t1.addr.in6_addr), 1); \
  1307. test_eq(tor_inet_pton(AF_INET6, b, &t2.addr.in6_addr), 1); \
  1308. t1.family = t2.family = AF_INET6; \
  1309. r = tor_addr_compare_masked(&t1,&t2,m,CMP_SEMANTIC); \
  1310. if (!(r op 0)) \
  1311. test_fail_msg("failed: tor_addr_compare_masked("a","b","#m") "#op" 0"); \
  1312. STMT_END
  1313. /** Helper: assert that <b>xx</b> is parseable as a masked IPv6 address with
  1314. * ports by tor_parse_mask_addr_ports(), with family <b>f</b>, IP address
  1315. * as 4 32-bit words <b>ip1...ip4</b>, mask bits as <b>mm</b>, and port range
  1316. * as <b>pt1..pt2</b>. */
  1317. #define test_addr_mask_ports_parse(xx, f, ip1, ip2, ip3, ip4, mm, pt1, pt2) \
  1318. STMT_BEGIN \
  1319. test_eq(tor_addr_parse_mask_ports(xx, &t1, &mask, &port1, &port2), f); \
  1320. p1=tor_inet_ntop(AF_INET6, &t1.addr.in6_addr, bug, sizeof(bug)); \
  1321. test_eq(htonl(ip1), tor_addr_to_in6_addr32(&t1)[0]); \
  1322. test_eq(htonl(ip2), tor_addr_to_in6_addr32(&t1)[1]); \
  1323. test_eq(htonl(ip3), tor_addr_to_in6_addr32(&t1)[2]); \
  1324. test_eq(htonl(ip4), tor_addr_to_in6_addr32(&t1)[3]); \
  1325. test_eq(mask, mm); \
  1326. test_eq(port1, pt1); \
  1327. test_eq(port2, pt2); \
  1328. STMT_END
  1329. /** Run unit tests for IPv6 encoding/decoding/manipulation functions. */
  1330. static void
  1331. test_util_ip6_helpers(void)
  1332. {
  1333. char buf[TOR_ADDR_BUF_LEN], bug[TOR_ADDR_BUF_LEN];
  1334. struct in6_addr a1, a2;
  1335. tor_addr_t t1, t2;
  1336. int r, i;
  1337. uint16_t port1, port2;
  1338. maskbits_t mask;
  1339. const char *p1;
  1340. struct sockaddr_storage sa_storage;
  1341. struct sockaddr_in *sin;
  1342. struct sockaddr_in6 *sin6;
  1343. // struct in_addr b1, b2;
  1344. /* Test tor_inet_ntop and tor_inet_pton: IPv6 */
  1345. /* ==== Converting to and from sockaddr_t. */
  1346. sin = (struct sockaddr_in *)&sa_storage;
  1347. sin->sin_family = AF_INET;
  1348. sin->sin_port = 9090;
  1349. sin->sin_addr.s_addr = htonl(0x7f7f0102); /*127.127.1.2*/
  1350. tor_addr_from_sockaddr(&t1, (struct sockaddr *)sin, NULL);
  1351. test_eq(tor_addr_family(&t1), AF_INET);
  1352. test_eq(tor_addr_to_ipv4h(&t1), 0x7f7f0102);
  1353. memset(&sa_storage, 0, sizeof(sa_storage));
  1354. test_eq(sizeof(struct sockaddr_in),
  1355. tor_addr_to_sockaddr(&t1, 1234, (struct sockaddr *)&sa_storage,
  1356. sizeof(sa_storage)));
  1357. test_eq(1234, ntohs(sin->sin_port));
  1358. test_eq(0x7f7f0102, ntohl(sin->sin_addr.s_addr));
  1359. memset(&sa_storage, 0, sizeof(sa_storage));
  1360. sin6 = (struct sockaddr_in6 *)&sa_storage;
  1361. sin6->sin6_family = AF_INET6;
  1362. sin6->sin6_port = htons(7070);
  1363. sin6->sin6_addr.s6_addr[0] = 128;
  1364. tor_addr_from_sockaddr(&t1, (struct sockaddr *)sin6, NULL);
  1365. test_eq(tor_addr_family(&t1), AF_INET6);
  1366. p1 = tor_addr_to_str(buf, &t1, sizeof(buf), 0);
  1367. test_streq(p1, "8000::");
  1368. memset(&sa_storage, 0, sizeof(sa_storage));
  1369. test_eq(sizeof(struct sockaddr_in6),
  1370. tor_addr_to_sockaddr(&t1, 9999, (struct sockaddr *)&sa_storage,
  1371. sizeof(sa_storage)));
  1372. test_eq(AF_INET6, sin6->sin6_family);
  1373. test_eq(9999, ntohs(sin6->sin6_port));
  1374. test_eq(0x80000000, ntohl(S6_ADDR32(sin6->sin6_addr)[0]));
  1375. /* ==== tor_addr_lookup: static cases. (Can't test dns without knowing we
  1376. * have a good resolver. */
  1377. test_eq(0, tor_addr_lookup("127.128.129.130", AF_UNSPEC, &t1));
  1378. test_eq(AF_INET, tor_addr_family(&t1));
  1379. test_eq(tor_addr_to_ipv4h(&t1), 0x7f808182);
  1380. test_eq(0, tor_addr_lookup("9000::5", AF_UNSPEC, &t1));
  1381. test_eq(AF_INET6, tor_addr_family(&t1));
  1382. test_eq(0x90, tor_addr_to_in6_addr8(&t1)[0]);
  1383. test_assert(tor_mem_is_zero((char*)tor_addr_to_in6_addr8(&t1)+1, 14));
  1384. test_eq(0x05, tor_addr_to_in6_addr8(&t1)[15]);
  1385. /* === Test pton: valid af_inet6 */
  1386. /* Simple, valid parsing. */
  1387. r = tor_inet_pton(AF_INET6,
  1388. "0102:0304:0506:0708:090A:0B0C:0D0E:0F10", &a1);
  1389. test_assert(r==1);
  1390. for (i=0;i<16;++i) { test_eq(i+1, (int)a1.s6_addr[i]); }
  1391. /* ipv4 ending. */
  1392. test_pton6_same("0102:0304:0506:0708:090A:0B0C:0D0E:0F10",
  1393. "0102:0304:0506:0708:090A:0B0C:13.14.15.16");
  1394. /* shortened words. */
  1395. test_pton6_same("0001:0099:BEEF:0000:0123:FFFF:0001:0001",
  1396. "1:99:BEEF:0:0123:FFFF:1:1");
  1397. /* zeros at the beginning */
  1398. test_pton6_same("0000:0000:0000:0000:0009:C0A8:0001:0001",
  1399. "::9:c0a8:1:1");
  1400. test_pton6_same("0000:0000:0000:0000:0009:C0A8:0001:0001",
  1401. "::9:c0a8:0.1.0.1");
  1402. /* zeros in the middle. */
  1403. test_pton6_same("fe80:0000:0000:0000:0202:1111:0001:0001",
  1404. "fe80::202:1111:1:1");
  1405. /* zeros at the end. */
  1406. test_pton6_same("1000:0001:0000:0007:0000:0000:0000:0000",
  1407. "1000:1:0:7::");
  1408. /* === Test ntop: af_inet6 */
  1409. test_ntop6_reduces("0:0:0:0:0:0:0:0", "::");
  1410. test_ntop6_reduces("0001:0099:BEEF:0006:0123:FFFF:0001:0001",
  1411. "1:99:beef:6:123:ffff:1:1");
  1412. //test_ntop6_reduces("0:0:0:0:0:0:c0a8:0101", "::192.168.1.1");
  1413. test_ntop6_reduces("0:0:0:0:0:ffff:c0a8:0101", "::ffff:192.168.1.1");
  1414. test_ntop6_reduces("002:0:0000:0:3::4", "2::3:0:0:4");
  1415. test_ntop6_reduces("0:0::1:0:3", "::1:0:3");
  1416. test_ntop6_reduces("008:0::0", "8::");
  1417. test_ntop6_reduces("0:0:0:0:0:ffff::1", "::ffff:0.0.0.1");
  1418. test_ntop6_reduces("abcd:0:0:0:0:0:7f00::", "abcd::7f00:0");
  1419. test_ntop6_reduces("0000:0000:0000:0000:0009:C0A8:0001:0001",
  1420. "::9:c0a8:1:1");
  1421. test_ntop6_reduces("fe80:0000:0000:0000:0202:1111:0001:0001",
  1422. "fe80::202:1111:1:1");
  1423. test_ntop6_reduces("1000:0001:0000:0007:0000:0000:0000:0000",
  1424. "1000:1:0:7::");
  1425. /* === Test pton: invalid in6. */
  1426. test_pton6_bad("foobar.");
  1427. test_pton6_bad("55555::");
  1428. test_pton6_bad("9:-60::");
  1429. test_pton6_bad("1:2:33333:4:0002:3::");
  1430. //test_pton6_bad("1:2:3333:4:00002:3::");// BAD, but glibc doesn't say so.
  1431. test_pton6_bad("1:2:3333:4:fish:3::");
  1432. test_pton6_bad("1:2:3:4:5:6:7:8:9");
  1433. test_pton6_bad("1:2:3:4:5:6:7");
  1434. test_pton6_bad("1:2:3:4:5:6:1.2.3.4.5");
  1435. test_pton6_bad("1:2:3:4:5:6:1.2.3");
  1436. test_pton6_bad("::1.2.3");
  1437. test_pton6_bad("::1.2.3.4.5");
  1438. test_pton6_bad("99");
  1439. test_pton6_bad("");
  1440. test_pton6_bad("1::2::3:4");
  1441. test_pton6_bad("a:::b:c");
  1442. test_pton6_bad(":::a:b:c");
  1443. test_pton6_bad("a:b:c:::");
  1444. /* test internal checking */
  1445. test_external_ip("fbff:ffff::2:7", 0);
  1446. test_internal_ip("fc01::2:7", 0);
  1447. test_internal_ip("fdff:ffff::f:f", 0);
  1448. test_external_ip("fe00::3:f", 0);
  1449. test_external_ip("fe7f:ffff::2:7", 0);
  1450. test_internal_ip("fe80::2:7", 0);
  1451. test_internal_ip("febf:ffff::f:f", 0);
  1452. test_internal_ip("fec0::2:7:7", 0);
  1453. test_internal_ip("feff:ffff::e:7:7", 0);
  1454. test_external_ip("ff00::e:7:7", 0);
  1455. test_internal_ip("::", 0);
  1456. test_internal_ip("::1", 0);
  1457. test_internal_ip("::1", 1);
  1458. test_internal_ip("::", 0);
  1459. test_external_ip("::", 1);
  1460. test_external_ip("::2", 0);
  1461. test_external_ip("2001::", 0);
  1462. test_external_ip("ffff::", 0);
  1463. test_external_ip("::ffff:0.0.0.0", 1);
  1464. test_internal_ip("::ffff:0.0.0.0", 0);
  1465. test_internal_ip("::ffff:0.255.255.255", 0);
  1466. test_external_ip("::ffff:1.0.0.0", 0);
  1467. test_external_ip("::ffff:9.255.255.255", 0);
  1468. test_internal_ip("::ffff:10.0.0.0", 0);
  1469. test_internal_ip("::ffff:10.255.255.255", 0);
  1470. test_external_ip("::ffff:11.0.0.0", 0);
  1471. test_external_ip("::ffff:126.255.255.255", 0);
  1472. test_internal_ip("::ffff:127.0.0.0", 0);
  1473. test_internal_ip("::ffff:127.255.255.255", 0);
  1474. test_external_ip("::ffff:128.0.0.0", 0);
  1475. test_external_ip("::ffff:172.15.255.255", 0);
  1476. test_internal_ip("::ffff:172.16.0.0", 0);
  1477. test_internal_ip("::ffff:172.31.255.255", 0);
  1478. test_external_ip("::ffff:172.32.0.0", 0);
  1479. test_external_ip("::ffff:192.167.255.255", 0);
  1480. test_internal_ip("::ffff:192.168.0.0", 0);
  1481. test_internal_ip("::ffff:192.168.255.255", 0);
  1482. test_external_ip("::ffff:192.169.0.0", 0);
  1483. test_external_ip("::ffff:169.253.255.255", 0);
  1484. test_internal_ip("::ffff:169.254.0.0", 0);
  1485. test_internal_ip("::ffff:169.254.255.255", 0);
  1486. test_external_ip("::ffff:169.255.0.0", 0);
  1487. test_assert(is_internal_IP(0x7f000001, 0));
  1488. /* tor_addr_compare(tor_addr_t x2) */
  1489. test_addr_compare("ffff::", ==, "ffff::0");
  1490. test_addr_compare("0::3:2:1", <, "0::ffff:0.3.2.1");
  1491. test_addr_compare("0::2:2:1", <, "0::ffff:0.3.2.1");
  1492. test_addr_compare("0::ffff:0.3.2.1", >, "0::0:0:0");
  1493. test_addr_compare("0::ffff:5.2.2.1", <, "::ffff:6.0.0.0"); /* XXXX wrong. */
  1494. tor_addr_parse_mask_ports("[::ffff:2.3.4.5]", &t1, NULL, NULL, NULL);
  1495. tor_addr_parse_mask_ports("2.3.4.5", &t2, NULL, NULL, NULL);
  1496. test_assert(tor_addr_compare(&t1, &t2, CMP_SEMANTIC) == 0);
  1497. tor_addr_parse_mask_ports("[::ffff:2.3.4.4]", &t1, NULL, NULL, NULL);
  1498. tor_addr_parse_mask_ports("2.3.4.5", &t2, NULL, NULL, NULL);
  1499. test_assert(tor_addr_compare(&t1, &t2, CMP_SEMANTIC) < 0);
  1500. /* test compare_masked */
  1501. test_addr_compare_masked("ffff::", ==, "ffff::0", 128);
  1502. test_addr_compare_masked("ffff::", ==, "ffff::0", 64);
  1503. test_addr_compare_masked("0::2:2:1", <, "0::8000:2:1", 81);
  1504. test_addr_compare_masked("0::2:2:1", ==, "0::8000:2:1", 80);
  1505. /* Test decorated addr_to_string. */
  1506. test_eq(AF_INET6, tor_addr_from_str(&t1, "[123:45:6789::5005:11]"));
  1507. p1 = tor_addr_to_str(buf, &t1, sizeof(buf), 1);
  1508. test_streq(p1, "[123:45:6789::5005:11]");
  1509. test_eq(AF_INET, tor_addr_from_str(&t1, "18.0.0.1"));
  1510. p1 = tor_addr_to_str(buf, &t1, sizeof(buf), 1);
  1511. test_streq(p1, "18.0.0.1");
  1512. /* Test tor_addr_parse_reverse_lookup_name */
  1513. i = tor_addr_parse_reverse_lookup_name(&t1, "Foobar.baz", AF_UNSPEC, 0);
  1514. test_eq(0, i);
  1515. i = tor_addr_parse_reverse_lookup_name(&t1, "Foobar.baz", AF_UNSPEC, 1);
  1516. test_eq(0, i);
  1517. i = tor_addr_parse_reverse_lookup_name(&t1, "1.0.168.192.in-addr.arpa",
  1518. AF_UNSPEC, 1);
  1519. test_eq(1, i);
  1520. test_eq(tor_addr_family(&t1), AF_INET);
  1521. p1 = tor_addr_to_str(buf, &t1, sizeof(buf), 1);
  1522. test_streq(p1, "192.168.0.1");
  1523. i = tor_addr_parse_reverse_lookup_name(&t1, "192.168.0.99", AF_UNSPEC, 0);
  1524. test_eq(0, i);
  1525. i = tor_addr_parse_reverse_lookup_name(&t1, "192.168.0.99", AF_UNSPEC, 1);
  1526. test_eq(1, i);
  1527. p1 = tor_addr_to_str(buf, &t1, sizeof(buf), 1);
  1528. test_streq(p1, "192.168.0.99");
  1529. memset(&t1, 0, sizeof(t1));
  1530. i = tor_addr_parse_reverse_lookup_name(&t1,
  1531. "0.1.2.3.4.5.6.7.8.9.a.b.c.d.e.f."
  1532. "f.e.e.b.1.e.b.e.e.f.f.e.e.e.d.9."
  1533. "ip6.ARPA",
  1534. AF_UNSPEC, 0);
  1535. test_eq(1, i);
  1536. p1 = tor_addr_to_str(buf, &t1, sizeof(buf), 1);
  1537. test_streq(p1, "[9dee:effe:ebe1:beef:fedc:ba98:7654:3210]");
  1538. /* Failing cases. */
  1539. i = tor_addr_parse_reverse_lookup_name(&t1,
  1540. "6.7.8.9.a.b.c.d.e.f."
  1541. "f.e.e.b.1.e.b.e.e.f.f.e.e.e.d.9."
  1542. "ip6.ARPA",
  1543. AF_UNSPEC, 0);
  1544. test_eq(i, -1);
  1545. i = tor_addr_parse_reverse_lookup_name(&t1,
  1546. "6.7.8.9.a.b.c.d.e.f.a.b.c.d.e.f.0."
  1547. "f.e.e.b.1.e.b.e.e.f.f.e.e.e.d.9."
  1548. "ip6.ARPA",
  1549. AF_UNSPEC, 0);
  1550. test_eq(i, -1);
  1551. i = tor_addr_parse_reverse_lookup_name(&t1,
  1552. "6.7.8.9.a.b.c.d.e.f.X.0.0.0.0.9."
  1553. "f.e.e.b.1.e.b.e.e.f.f.e.e.e.d.9."
  1554. "ip6.ARPA",
  1555. AF_UNSPEC, 0);
  1556. test_eq(i, -1);
  1557. i = tor_addr_parse_reverse_lookup_name(&t1, "32.1.1.in-addr.arpa",
  1558. AF_UNSPEC, 0);
  1559. test_eq(i, -1);
  1560. i = tor_addr_parse_reverse_lookup_name(&t1, ".in-addr.arpa",
  1561. AF_UNSPEC, 0);
  1562. test_eq(i, -1);
  1563. i = tor_addr_parse_reverse_lookup_name(&t1, "1.2.3.4.5.in-addr.arpa",
  1564. AF_UNSPEC, 0);
  1565. test_eq(i, -1);
  1566. i = tor_addr_parse_reverse_lookup_name(&t1, "1.2.3.4.5.in-addr.arpa",
  1567. AF_INET6, 0);
  1568. test_eq(i, -1);
  1569. i = tor_addr_parse_reverse_lookup_name(&t1,
  1570. "6.7.8.9.a.b.c.d.e.f.a.b.c.d.e.0."
  1571. "f.e.e.b.1.e.b.e.e.f.f.e.e.e.d.9."
  1572. "ip6.ARPA",
  1573. AF_INET, 0);
  1574. test_eq(i, -1);
  1575. /* test tor_addr_parse_mask_ports */
  1576. test_addr_mask_ports_parse("[::f]/17:47-95", AF_INET6,
  1577. 0, 0, 0, 0x0000000f, 17, 47, 95);
  1578. //test_addr_parse("[::fefe:4.1.1.7/120]:999-1000");
  1579. //test_addr_parse_check("::fefe:401:107", 120, 999, 1000);
  1580. test_addr_mask_ports_parse("[::ffff:4.1.1.7]/120:443", AF_INET6,
  1581. 0, 0, 0x0000ffff, 0x04010107, 120, 443, 443);
  1582. test_addr_mask_ports_parse("[abcd:2::44a:0]:2-65000", AF_INET6,
  1583. 0xabcd0002, 0, 0, 0x044a0000, 128, 2, 65000);
  1584. r=tor_addr_parse_mask_ports("[fefef::]/112", &t1, NULL, NULL, NULL);
  1585. test_assert(r == -1);
  1586. r=tor_addr_parse_mask_ports("efef::/112", &t1, NULL, NULL, NULL);
  1587. test_assert(r == -1);
  1588. r=tor_addr_parse_mask_ports("[f:f:f:f:f:f:f:f::]", &t1, NULL, NULL, NULL);
  1589. test_assert(r == -1);
  1590. r=tor_addr_parse_mask_ports("[::f:f:f:f:f:f:f:f]", &t1, NULL, NULL, NULL);
  1591. test_assert(r == -1);
  1592. r=tor_addr_parse_mask_ports("[f:f:f:f:f:f:f:f:f]", &t1, NULL, NULL, NULL);
  1593. test_assert(r == -1);
  1594. /* Test for V4-mapped address with mask < 96. (arguably not valid) */
  1595. r=tor_addr_parse_mask_ports("[::ffff:1.1.2.2/33]", &t1, &mask, NULL, NULL);
  1596. test_assert(r == -1);
  1597. r=tor_addr_parse_mask_ports("1.1.2.2/33", &t1, &mask, NULL, NULL);
  1598. test_assert(r == -1);
  1599. r=tor_addr_parse_mask_ports("1.1.2.2/31", &t1, &mask, NULL, NULL);
  1600. test_assert(r == AF_INET);
  1601. r=tor_addr_parse_mask_ports("[efef::]/112", &t1, &mask, &port1, &port2);
  1602. test_assert(r == AF_INET6);
  1603. test_assert(port1 == 1);
  1604. test_assert(port2 == 65535);
  1605. /* make sure inet address lengths >= max */
  1606. test_assert(INET_NTOA_BUF_LEN >= sizeof("255.255.255.255"));
  1607. test_assert(TOR_ADDR_BUF_LEN >=
  1608. sizeof("ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"));
  1609. test_assert(sizeof(tor_addr_t) >= sizeof(struct in6_addr));
  1610. /* get interface addresses */
  1611. r = get_interface_address6(LOG_DEBUG, AF_INET, &t1);
  1612. i = get_interface_address6(LOG_DEBUG, AF_INET6, &t2);
  1613. #if 0
  1614. tor_inet_ntop(AF_INET, &t1.sa.sin_addr, buf, sizeof(buf));
  1615. printf("\nv4 address: %s (family=%i)", buf, IN_FAMILY(&t1));
  1616. tor_inet_ntop(AF_INET6, &t2.sa6.sin6_addr, buf, sizeof(buf));
  1617. printf("\nv6 address: %s (family=%i)", buf, IN_FAMILY(&t2));
  1618. #endif
  1619. done:
  1620. ;
  1621. }
  1622. /** Run unit tests for basic dynamic-sized array functionality. */
  1623. static void
  1624. test_util_smartlist_basic(void)
  1625. {
  1626. smartlist_t *sl;
  1627. /* XXXX test sort_digests, uniq_strings, uniq_digests */
  1628. /* Test smartlist add, del_keeporder, insert, get. */
  1629. sl = smartlist_create();
  1630. smartlist_add(sl, (void*)1);
  1631. smartlist_add(sl, (void*)2);
  1632. smartlist_add(sl, (void*)3);
  1633. smartlist_add(sl, (void*)4);
  1634. smartlist_del_keeporder(sl, 1);
  1635. smartlist_insert(sl, 1, (void*)22);
  1636. smartlist_insert(sl, 0, (void*)0);
  1637. smartlist_insert(sl, 5, (void*)555);
  1638. test_eq_ptr((void*)0, smartlist_get(sl,0));
  1639. test_eq_ptr((void*)1, smartlist_get(sl,1));
  1640. test_eq_ptr((void*)22, smartlist_get(sl,2));
  1641. test_eq_ptr((void*)3, smartlist_get(sl,3));
  1642. test_eq_ptr((void*)4, smartlist_get(sl,4));
  1643. test_eq_ptr((void*)555, smartlist_get(sl,5));
  1644. /* Try deleting in the middle. */
  1645. smartlist_del(sl, 1);
  1646. test_eq_ptr((void*)555, smartlist_get(sl, 1));
  1647. /* Try deleting at the end. */
  1648. smartlist_del(sl, 4);
  1649. test_eq(4, smartlist_len(sl));
  1650. /* test isin. */
  1651. test_assert(smartlist_isin(sl, (void*)3));
  1652. test_assert(!smartlist_isin(sl, (void*)99));
  1653. done:
  1654. smartlist_free(sl);
  1655. }
  1656. /** Run unit tests for smartlist-of-strings functionality. */
  1657. static void
  1658. test_util_smartlist_strings(void)
  1659. {
  1660. smartlist_t *sl = smartlist_create();
  1661. char *cp=NULL, *cp_alloc=NULL;
  1662. size_t sz;
  1663. /* Test split and join */
  1664. test_eq(0, smartlist_len(sl));
  1665. smartlist_split_string(sl, "abc", ":", 0, 0);
  1666. test_eq(1, smartlist_len(sl));
  1667. test_streq("abc", smartlist_get(sl, 0));
  1668. smartlist_split_string(sl, "a::bc::", "::", 0, 0);
  1669. test_eq(4, smartlist_len(sl));
  1670. test_streq("a", smartlist_get(sl, 1));
  1671. test_streq("bc", smartlist_get(sl, 2));
  1672. test_streq("", smartlist_get(sl, 3));
  1673. cp_alloc = smartlist_join_strings(sl, "", 0, NULL);
  1674. test_streq(cp_alloc, "abcabc");
  1675. tor_free(cp_alloc);
  1676. cp_alloc = smartlist_join_strings(sl, "!", 0, NULL);
  1677. test_streq(cp_alloc, "abc!a!bc!");
  1678. tor_free(cp_alloc);
  1679. cp_alloc = smartlist_join_strings(sl, "XY", 0, NULL);
  1680. test_streq(cp_alloc, "abcXYaXYbcXY");
  1681. tor_free(cp_alloc);
  1682. cp_alloc = smartlist_join_strings(sl, "XY", 1, NULL);
  1683. test_streq(cp_alloc, "abcXYaXYbcXYXY");
  1684. tor_free(cp_alloc);
  1685. cp_alloc = smartlist_join_strings(sl, "", 1, NULL);
  1686. test_streq(cp_alloc, "abcabc");
  1687. tor_free(cp_alloc);
  1688. smartlist_split_string(sl, "/def/ /ghijk", "/", 0, 0);
  1689. test_eq(8, smartlist_len(sl));
  1690. test_streq("", smartlist_get(sl, 4));
  1691. test_streq("def", smartlist_get(sl, 5));
  1692. test_streq(" ", smartlist_get(sl, 6));
  1693. test_streq("ghijk", smartlist_get(sl, 7));
  1694. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1695. smartlist_clear(sl);
  1696. smartlist_split_string(sl, "a,bbd,cdef", ",", SPLIT_SKIP_SPACE, 0);
  1697. test_eq(3, smartlist_len(sl));
  1698. test_streq("a", smartlist_get(sl,0));
  1699. test_streq("bbd", smartlist_get(sl,1));
  1700. test_streq("cdef", smartlist_get(sl,2));
  1701. smartlist_split_string(sl, " z <> zhasd <> <> bnud<> ", "<>",
  1702. SPLIT_SKIP_SPACE, 0);
  1703. test_eq(8, smartlist_len(sl));
  1704. test_streq("z", smartlist_get(sl,3));
  1705. test_streq("zhasd", smartlist_get(sl,4));
  1706. test_streq("", smartlist_get(sl,5));
  1707. test_streq("bnud", smartlist_get(sl,6));
  1708. test_streq("", smartlist_get(sl,7));
  1709. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1710. smartlist_clear(sl);
  1711. smartlist_split_string(sl, " ab\tc \td ef ", NULL,
  1712. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1713. test_eq(4, smartlist_len(sl));
  1714. test_streq("ab", smartlist_get(sl,0));
  1715. test_streq("c", smartlist_get(sl,1));
  1716. test_streq("d", smartlist_get(sl,2));
  1717. test_streq("ef", smartlist_get(sl,3));
  1718. smartlist_split_string(sl, "ghi\tj", NULL,
  1719. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1720. test_eq(6, smartlist_len(sl));
  1721. test_streq("ghi", smartlist_get(sl,4));
  1722. test_streq("j", smartlist_get(sl,5));
  1723. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1724. smartlist_clear(sl);
  1725. cp_alloc = smartlist_join_strings(sl, "XY", 0, NULL);
  1726. test_streq(cp_alloc, "");
  1727. tor_free(cp_alloc);
  1728. cp_alloc = smartlist_join_strings(sl, "XY", 1, NULL);
  1729. test_streq(cp_alloc, "XY");
  1730. tor_free(cp_alloc);
  1731. smartlist_split_string(sl, " z <> zhasd <> <> bnud<> ", "<>",
  1732. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1733. test_eq(3, smartlist_len(sl));
  1734. test_streq("z", smartlist_get(sl, 0));
  1735. test_streq("zhasd", smartlist_get(sl, 1));
  1736. test_streq("bnud", smartlist_get(sl, 2));
  1737. smartlist_split_string(sl, " z <> zhasd <> <> bnud<> ", "<>",
  1738. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 2);
  1739. test_eq(5, smartlist_len(sl));
  1740. test_streq("z", smartlist_get(sl, 3));
  1741. test_streq("zhasd <> <> bnud<>", smartlist_get(sl, 4));
  1742. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1743. smartlist_clear(sl);
  1744. smartlist_split_string(sl, "abcd\n", "\n",
  1745. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1746. test_eq(1, smartlist_len(sl));
  1747. test_streq("abcd", smartlist_get(sl, 0));
  1748. smartlist_split_string(sl, "efgh", "\n",
  1749. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1750. test_eq(2, smartlist_len(sl));
  1751. test_streq("efgh", smartlist_get(sl, 1));
  1752. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1753. smartlist_clear(sl);
  1754. /* Test swapping, shuffling, and sorting. */
  1755. smartlist_split_string(sl, "the,onion,router,by,arma,and,nickm", ",", 0, 0);
  1756. test_eq(7, smartlist_len(sl));
  1757. smartlist_sort(sl, _compare_strs);
  1758. cp_alloc = smartlist_join_strings(sl, ",", 0, NULL);
  1759. test_streq(cp_alloc,"and,arma,by,nickm,onion,router,the");
  1760. tor_free(cp_alloc);
  1761. smartlist_swap(sl, 1, 5);
  1762. cp_alloc = smartlist_join_strings(sl, ",", 0, NULL);
  1763. test_streq(cp_alloc,"and,router,by,nickm,onion,arma,the");
  1764. tor_free(cp_alloc);
  1765. smartlist_shuffle(sl);
  1766. test_eq(7, smartlist_len(sl));
  1767. test_assert(smartlist_string_isin(sl, "and"));
  1768. test_assert(smartlist_string_isin(sl, "router"));
  1769. test_assert(smartlist_string_isin(sl, "by"));
  1770. test_assert(smartlist_string_isin(sl, "nickm"));
  1771. test_assert(smartlist_string_isin(sl, "onion"));
  1772. test_assert(smartlist_string_isin(sl, "arma"));
  1773. test_assert(smartlist_string_isin(sl, "the"));
  1774. /* Test bsearch. */
  1775. smartlist_sort(sl, _compare_strs);
  1776. test_streq("nickm", smartlist_bsearch(sl, "zNicKM",
  1777. _compare_without_first_ch));
  1778. test_streq("and", smartlist_bsearch(sl, " AND", _compare_without_first_ch));
  1779. test_eq_ptr(NULL, smartlist_bsearch(sl, " ANz", _compare_without_first_ch));
  1780. /* Test bsearch_idx */
  1781. {
  1782. int f;
  1783. test_eq(0, smartlist_bsearch_idx(sl," aaa",_compare_without_first_ch,&f));
  1784. test_eq(f, 0);
  1785. test_eq(0, smartlist_bsearch_idx(sl," and",_compare_without_first_ch,&f));
  1786. test_eq(f, 1);
  1787. test_eq(1, smartlist_bsearch_idx(sl," arm",_compare_without_first_ch,&f));
  1788. test_eq(f, 0);
  1789. test_eq(1, smartlist_bsearch_idx(sl," arma",_compare_without_first_ch,&f));
  1790. test_eq(f, 1);
  1791. test_eq(2, smartlist_bsearch_idx(sl," armb",_compare_without_first_ch,&f));
  1792. test_eq(f, 0);
  1793. test_eq(7, smartlist_bsearch_idx(sl," zzzz",_compare_without_first_ch,&f));
  1794. test_eq(f, 0);
  1795. }
  1796. /* Test reverse() and pop_last() */
  1797. smartlist_reverse(sl);
  1798. cp_alloc = smartlist_join_strings(sl, ",", 0, NULL);
  1799. test_streq(cp_alloc,"the,router,onion,nickm,by,arma,and");
  1800. tor_free(cp_alloc);
  1801. cp_alloc = smartlist_pop_last(sl);
  1802. test_streq(cp_alloc, "and");
  1803. tor_free(cp_alloc);
  1804. test_eq(smartlist_len(sl), 6);
  1805. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1806. smartlist_clear(sl);
  1807. cp_alloc = smartlist_pop_last(sl);
  1808. test_eq(cp_alloc, NULL);
  1809. /* Test uniq() */
  1810. smartlist_split_string(sl,
  1811. "50,noon,radar,a,man,a,plan,a,canal,panama,radar,noon,50",
  1812. ",", 0, 0);
  1813. smartlist_sort(sl, _compare_strs);
  1814. smartlist_uniq(sl, _compare_strs, _tor_free);
  1815. cp_alloc = smartlist_join_strings(sl, ",", 0, NULL);
  1816. test_streq(cp_alloc, "50,a,canal,man,noon,panama,plan,radar");
  1817. tor_free(cp_alloc);
  1818. /* Test string_isin and isin_case and num_isin */
  1819. test_assert(smartlist_string_isin(sl, "noon"));
  1820. test_assert(!smartlist_string_isin(sl, "noonoon"));
  1821. test_assert(smartlist_string_isin_case(sl, "nOOn"));
  1822. test_assert(!smartlist_string_isin_case(sl, "nooNooN"));
  1823. test_assert(smartlist_string_num_isin(sl, 50));
  1824. test_assert(!smartlist_string_num_isin(sl, 60));
  1825. /* Test smartlist_choose */
  1826. {
  1827. int i;
  1828. int allsame = 1;
  1829. int allin = 1;
  1830. void *first = smartlist_choose(sl);
  1831. test_assert(smartlist_isin(sl, first));
  1832. for (i = 0; i < 100; ++i) {
  1833. void *second = smartlist_choose(sl);
  1834. if (second != first)
  1835. allsame = 0;
  1836. if (!smartlist_isin(sl, second))
  1837. allin = 0;
  1838. }
  1839. test_assert(!allsame);
  1840. test_assert(allin);
  1841. }
  1842. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1843. smartlist_clear(sl);
  1844. /* Test string_remove and remove and join_strings2 */
  1845. smartlist_split_string(sl,
  1846. "Some say the Earth will end in ice and some in fire",
  1847. " ", 0, 0);
  1848. cp = smartlist_get(sl, 4);
  1849. test_streq(cp, "will");
  1850. smartlist_add(sl, cp);
  1851. smartlist_remove(sl, cp);
  1852. tor_free(cp);
  1853. cp_alloc = smartlist_join_strings(sl, ",", 0, NULL);
  1854. test_streq(cp_alloc, "Some,say,the,Earth,fire,end,in,ice,and,some,in");
  1855. tor_free(cp_alloc);
  1856. smartlist_string_remove(sl, "in");
  1857. cp_alloc = smartlist_join_strings2(sl, "+XX", 1, 0, &sz);
  1858. test_streq(cp_alloc, "Some+say+the+Earth+fire+end+some+ice+and");
  1859. test_eq((int)sz, 40);
  1860. done:
  1861. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1862. smartlist_free(sl);
  1863. tor_free(cp_alloc);
  1864. }
  1865. /** Run unit tests for smartlist set manipulation functions. */
  1866. static void
  1867. test_util_smartlist_overlap(void)
  1868. {
  1869. smartlist_t *sl = smartlist_create();
  1870. smartlist_t *ints = smartlist_create();
  1871. smartlist_t *odds = smartlist_create();
  1872. smartlist_t *evens = smartlist_create();
  1873. smartlist_t *primes = smartlist_create();
  1874. int i;
  1875. for (i=1; i < 10; i += 2)
  1876. smartlist_add(odds, (void*)(uintptr_t)i);
  1877. for (i=0; i < 10; i += 2)
  1878. smartlist_add(evens, (void*)(uintptr_t)i);
  1879. /* add_all */
  1880. smartlist_add_all(ints, odds);
  1881. smartlist_add_all(ints, evens);
  1882. test_eq(smartlist_len(ints), 10);
  1883. smartlist_add(primes, (void*)2);
  1884. smartlist_add(primes, (void*)3);
  1885. smartlist_add(primes, (void*)5);
  1886. smartlist_add(primes, (void*)7);
  1887. /* overlap */
  1888. test_assert(smartlist_overlap(ints, odds));
  1889. test_assert(smartlist_overlap(odds, primes));
  1890. test_assert(smartlist_overlap(evens, primes));
  1891. test_assert(!smartlist_overlap(odds, evens));
  1892. /* intersect */
  1893. smartlist_add_all(sl, odds);
  1894. smartlist_intersect(sl, primes);
  1895. test_eq(smartlist_len(sl), 3);
  1896. test_assert(smartlist_isin(sl, (void*)3));
  1897. test_assert(smartlist_isin(sl, (void*)5));
  1898. test_assert(smartlist_isin(sl, (void*)7));
  1899. /* subtract */
  1900. smartlist_add_all(sl, primes);
  1901. smartlist_subtract(sl, odds);
  1902. test_eq(smartlist_len(sl), 1);
  1903. test_assert(smartlist_isin(sl, (void*)2));
  1904. done:
  1905. smartlist_free(odds);
  1906. smartlist_free(evens);
  1907. smartlist_free(ints);
  1908. smartlist_free(primes);
  1909. smartlist_free(sl);
  1910. }
  1911. /** Run unit tests for smartlist-of-digests functions. */
  1912. static void
  1913. test_util_smartlist_digests(void)
  1914. {
  1915. smartlist_t *sl = smartlist_create();
  1916. /* digest_isin. */
  1917. smartlist_add(sl, tor_memdup("AAAAAAAAAAAAAAAAAAAA", DIGEST_LEN));
  1918. smartlist_add(sl, tor_memdup("\00090AAB2AAAAaasdAAAAA", DIGEST_LEN));
  1919. smartlist_add(sl, tor_memdup("\00090AAB2AAAAaasdAAAAA", DIGEST_LEN));
  1920. test_eq(0, smartlist_digest_isin(NULL, "AAAAAAAAAAAAAAAAAAAA"));
  1921. test_assert(smartlist_digest_isin(sl, "AAAAAAAAAAAAAAAAAAAA"));
  1922. test_assert(smartlist_digest_isin(sl, "\00090AAB2AAAAaasdAAAAA"));
  1923. test_eq(0, smartlist_digest_isin(sl, "\00090AAB2AAABaasdAAAAA"));
  1924. /* sort digests */
  1925. smartlist_sort_digests(sl);
  1926. test_memeq(smartlist_get(sl, 0), "\00090AAB2AAAAaasdAAAAA", DIGEST_LEN);
  1927. test_memeq(smartlist_get(sl, 1), "\00090AAB2AAAAaasdAAAAA", DIGEST_LEN);
  1928. test_memeq(smartlist_get(sl, 2), "AAAAAAAAAAAAAAAAAAAA", DIGEST_LEN);
  1929. test_eq(3, smartlist_len(sl));
  1930. /* uniq_digests */
  1931. smartlist_uniq_digests(sl);
  1932. test_eq(2, smartlist_len(sl));
  1933. test_memeq(smartlist_get(sl, 0), "\00090AAB2AAAAaasdAAAAA", DIGEST_LEN);
  1934. test_memeq(smartlist_get(sl, 1), "AAAAAAAAAAAAAAAAAAAA", DIGEST_LEN);
  1935. done:
  1936. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1937. smartlist_free(sl);
  1938. }
  1939. /** Run unit tests for concatenate-a-smartlist-of-strings functions. */
  1940. static void
  1941. test_util_smartlist_join(void)
  1942. {
  1943. smartlist_t *sl = smartlist_create();
  1944. smartlist_t *sl2 = smartlist_create(), *sl3 = smartlist_create(),
  1945. *sl4 = smartlist_create();
  1946. char *joined=NULL;
  1947. /* unique, sorted. */
  1948. smartlist_split_string(sl,
  1949. "Abashments Ambush Anchorman Bacon Banks Borscht "
  1950. "Bunks Inhumane Insurance Knish Know Manners "
  1951. "Maraschinos Stamina Sunbonnets Unicorns Wombats",
  1952. " ", 0, 0);
  1953. /* non-unique, sorted. */
  1954. smartlist_split_string(sl2,
  1955. "Ambush Anchorman Anchorman Anemias Anemias Bacon "
  1956. "Crossbowmen Inhumane Insurance Knish Know Manners "
  1957. "Manners Maraschinos Wombats Wombats Work",
  1958. " ", 0, 0);
  1959. SMARTLIST_FOREACH_JOIN(sl, char *, cp1,
  1960. sl2, char *, cp2,
  1961. strcmp(cp1,cp2),
  1962. smartlist_add(sl3, cp2)) {
  1963. test_streq(cp1, cp2);
  1964. smartlist_add(sl4, cp1);
  1965. } SMARTLIST_FOREACH_JOIN_END(cp1, cp2);
  1966. SMARTLIST_FOREACH(sl3, const char *, cp,
  1967. test_assert(smartlist_isin(sl2, cp) &&
  1968. !smartlist_string_isin(sl, cp)));
  1969. SMARTLIST_FOREACH(sl4, const char *, cp,
  1970. test_assert(smartlist_isin(sl, cp) &&
  1971. smartlist_string_isin(sl2, cp)));
  1972. joined = smartlist_join_strings(sl3, ",", 0, NULL);
  1973. test_streq(joined, "Anemias,Anemias,Crossbowmen,Work");
  1974. tor_free(joined);
  1975. joined = smartlist_join_strings(sl4, ",", 0, NULL);
  1976. test_streq(joined, "Ambush,Anchorman,Anchorman,Bacon,Inhumane,Insurance,"
  1977. "Knish,Know,Manners,Manners,Maraschinos,Wombats,Wombats");
  1978. tor_free(joined);
  1979. done:
  1980. smartlist_free(sl4);
  1981. smartlist_free(sl3);
  1982. SMARTLIST_FOREACH(sl2, char *, cp, tor_free(cp));
  1983. smartlist_free(sl2);
  1984. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  1985. smartlist_free(sl);
  1986. tor_free(joined);
  1987. }
  1988. /** Run unit tests for bitarray code */
  1989. static void
  1990. test_util_bitarray(void)
  1991. {
  1992. bitarray_t *ba = NULL;
  1993. int i, j, ok=1;
  1994. ba = bitarray_init_zero(1);
  1995. test_assert(ba);
  1996. test_assert(! bitarray_is_set(ba, 0));
  1997. bitarray_set(ba, 0);
  1998. test_assert(bitarray_is_set(ba, 0));
  1999. bitarray_clear(ba, 0);
  2000. test_assert(! bitarray_is_set(ba, 0));
  2001. bitarray_free(ba);
  2002. ba = bitarray_init_zero(1023);
  2003. for (i = 1; i < 64; ) {
  2004. for (j = 0; j < 1023; ++j) {
  2005. if (j % i)
  2006. bitarray_set(ba, j);
  2007. else
  2008. bitarray_clear(ba, j);
  2009. }
  2010. for (j = 0; j < 1023; ++j) {
  2011. if (!bool_eq(bitarray_is_set(ba, j), j%i))
  2012. ok = 0;
  2013. }
  2014. test_assert(ok);
  2015. if (i < 7)
  2016. ++i;
  2017. else if (i == 28)
  2018. i = 32;
  2019. else
  2020. i += 7;
  2021. }
  2022. done:
  2023. if (ba)
  2024. bitarray_free(ba);
  2025. }
  2026. /** Run unit tests for digest set code (implemented as a hashtable or as a
  2027. * bloom filter) */
  2028. static void
  2029. test_util_digestset(void)
  2030. {
  2031. smartlist_t *included = smartlist_create();
  2032. char d[DIGEST_LEN];
  2033. int i;
  2034. int ok = 1;
  2035. int false_positives = 0;
  2036. digestset_t *set = NULL;
  2037. for (i = 0; i < 1000; ++i) {
  2038. crypto_rand(d, DIGEST_LEN);
  2039. smartlist_add(included, tor_memdup(d, DIGEST_LEN));
  2040. }
  2041. set = digestset_new(1000);
  2042. SMARTLIST_FOREACH(included, const char *, cp,
  2043. if (digestset_isin(set, cp))
  2044. ok = 0);
  2045. test_assert(ok);
  2046. SMARTLIST_FOREACH(included, const char *, cp,
  2047. digestset_add(set, cp));
  2048. SMARTLIST_FOREACH(included, const char *, cp,
  2049. if (!digestset_isin(set, cp))
  2050. ok = 0);
  2051. test_assert(ok);
  2052. for (i = 0; i < 1000; ++i) {
  2053. crypto_rand(d, DIGEST_LEN);
  2054. if (digestset_isin(set, d))
  2055. ++false_positives;
  2056. }
  2057. test_assert(false_positives < 50); /* Should be far lower. */
  2058. done:
  2059. if (set)
  2060. digestset_free(set);
  2061. SMARTLIST_FOREACH(included, char *, cp, tor_free(cp));
  2062. smartlist_free(included);
  2063. }
  2064. /** mutex for thread test to stop the threads hitting data at the same time. */
  2065. static tor_mutex_t *_thread_test_mutex = NULL;
  2066. /** mutexes for the thread test to make sure that the threads have to
  2067. * interleave somewhat. */
  2068. static tor_mutex_t *_thread_test_start1 = NULL,
  2069. *_thread_test_start2 = NULL;
  2070. /** Shared strmap for the thread test. */
  2071. static strmap_t *_thread_test_strmap = NULL;
  2072. /** The name of thread1 for the thread test */
  2073. static char *_thread1_name = NULL;
  2074. /** The name of thread2 for the thread test */
  2075. static char *_thread2_name = NULL;
  2076. static void _thread_test_func(void* _s) ATTR_NORETURN;
  2077. /** How many iterations have the threads in the unit test run? */
  2078. static int t1_count = 0, t2_count = 0;
  2079. /** Helper function for threading unit tests: This function runs in a
  2080. * subthread. It grabs its own mutex (start1 or start2) to make sure that it
  2081. * should start, then it repeatedly alters _test_thread_strmap protected by
  2082. * _thread_test_mutex. */
  2083. static void
  2084. _thread_test_func(void* _s)
  2085. {
  2086. char *s = _s;
  2087. int i, *count;
  2088. tor_mutex_t *m;
  2089. char buf[64];
  2090. char **cp;
  2091. if (!strcmp(s, "thread 1")) {
  2092. m = _thread_test_start1;
  2093. cp = &_thread1_name;
  2094. count = &t1_count;
  2095. } else {
  2096. m = _thread_test_start2;
  2097. cp = &_thread2_name;
  2098. count = &t2_count;
  2099. }
  2100. tor_mutex_acquire(m);
  2101. tor_snprintf(buf, sizeof(buf), "%lu", tor_get_thread_id());
  2102. *cp = tor_strdup(buf);
  2103. for (i=0; i<10000; ++i) {
  2104. tor_mutex_acquire(_thread_test_mutex);
  2105. strmap_set(_thread_test_strmap, "last to run", *cp);
  2106. ++*count;
  2107. tor_mutex_release(_thread_test_mutex);
  2108. }
  2109. tor_mutex_acquire(_thread_test_mutex);
  2110. strmap_set(_thread_test_strmap, s, *cp);
  2111. tor_mutex_release(_thread_test_mutex);
  2112. tor_mutex_release(m);
  2113. spawn_exit();
  2114. }
  2115. /** Run unit tests for threading logic. */
  2116. static void
  2117. test_util_threads(void)
  2118. {
  2119. char *s1 = NULL, *s2 = NULL;
  2120. int done = 0, timedout = 0;
  2121. time_t started;
  2122. #ifndef TOR_IS_MULTITHREADED
  2123. /* Skip this test if we aren't threading. We should be threading most
  2124. * everywhere by now. */
  2125. if (1)
  2126. return;
  2127. #endif
  2128. _thread_test_mutex = tor_mutex_new();
  2129. _thread_test_start1 = tor_mutex_new();
  2130. _thread_test_start2 = tor_mutex_new();
  2131. _thread_test_strmap = strmap_new();
  2132. s1 = tor_strdup("thread 1");
  2133. s2 = tor_strdup("thread 2");
  2134. tor_mutex_acquire(_thread_test_start1);
  2135. tor_mutex_acquire(_thread_test_start2);
  2136. spawn_func(_thread_test_func, s1);
  2137. spawn_func(_thread_test_func, s2);
  2138. tor_mutex_release(_thread_test_start2);
  2139. tor_mutex_release(_thread_test_start1);
  2140. started = time(NULL);
  2141. while (!done) {
  2142. tor_mutex_acquire(_thread_test_mutex);
  2143. strmap_assert_ok(_thread_test_strmap);
  2144. if (strmap_get(_thread_test_strmap, "thread 1") &&
  2145. strmap_get(_thread_test_strmap, "thread 2")) {
  2146. done = 1;
  2147. } else if (time(NULL) > started + 25) {
  2148. timedout = done = 1;
  2149. }
  2150. tor_mutex_release(_thread_test_mutex);
  2151. }
  2152. tor_mutex_free(_thread_test_mutex);
  2153. tor_mutex_acquire(_thread_test_start1);
  2154. tor_mutex_release(_thread_test_start1);
  2155. tor_mutex_acquire(_thread_test_start2);
  2156. tor_mutex_release(_thread_test_start2);
  2157. if (timedout) {
  2158. printf("\nTimed out: %d %d", t1_count, t2_count);
  2159. test_assert(strmap_get(_thread_test_strmap, "thread 1"));
  2160. test_assert(strmap_get(_thread_test_strmap, "thread 2"));
  2161. test_assert(!timedout);
  2162. }
  2163. /* different thread IDs. */
  2164. test_assert(strcmp(strmap_get(_thread_test_strmap, "thread 1"),
  2165. strmap_get(_thread_test_strmap, "thread 2")));
  2166. test_assert(!strcmp(strmap_get(_thread_test_strmap, "thread 1"),
  2167. strmap_get(_thread_test_strmap, "last to run")) ||
  2168. !strcmp(strmap_get(_thread_test_strmap, "thread 2"),
  2169. strmap_get(_thread_test_strmap, "last to run")));
  2170. done:
  2171. tor_free(s1);
  2172. tor_free(s2);
  2173. tor_free(_thread1_name);
  2174. tor_free(_thread2_name);
  2175. if (_thread_test_strmap)
  2176. strmap_free(_thread_test_strmap, NULL);
  2177. if (_thread_test_start1)
  2178. tor_mutex_free(_thread_test_start1);
  2179. if (_thread_test_start2)
  2180. tor_mutex_free(_thread_test_start2);
  2181. }
  2182. /** Helper: return a tristate based on comparing two strings. */
  2183. static int
  2184. _compare_strings_for_pqueue(const void *s1, const void *s2)
  2185. {
  2186. return strcmp((const char*)s1, (const char*)s2);
  2187. }
  2188. /** Run unit tests for heap-based priority queue functions. */
  2189. static void
  2190. test_util_pqueue(void)
  2191. {
  2192. smartlist_t *sl = smartlist_create();
  2193. int (*cmp)(const void *, const void*);
  2194. #define OK() smartlist_pqueue_assert_ok(sl, cmp)
  2195. cmp = _compare_strings_for_pqueue;
  2196. smartlist_pqueue_add(sl, cmp, (char*)"cows");
  2197. smartlist_pqueue_add(sl, cmp, (char*)"zebras");
  2198. smartlist_pqueue_add(sl, cmp, (char*)"fish");
  2199. smartlist_pqueue_add(sl, cmp, (char*)"frogs");
  2200. smartlist_pqueue_add(sl, cmp, (char*)"apples");
  2201. smartlist_pqueue_add(sl, cmp, (char*)"squid");
  2202. smartlist_pqueue_add(sl, cmp, (char*)"daschunds");
  2203. smartlist_pqueue_add(sl, cmp, (char*)"eggplants");
  2204. smartlist_pqueue_add(sl, cmp, (char*)"weissbier");
  2205. smartlist_pqueue_add(sl, cmp, (char*)"lobsters");
  2206. smartlist_pqueue_add(sl, cmp, (char*)"roquefort");
  2207. OK();
  2208. test_eq(smartlist_len(sl), 11);
  2209. test_streq(smartlist_get(sl, 0), "apples");
  2210. test_streq(smartlist_pqueue_pop(sl, cmp), "apples");
  2211. test_eq(smartlist_len(sl), 10);
  2212. OK();
  2213. test_streq(smartlist_pqueue_pop(sl, cmp), "cows");
  2214. test_streq(smartlist_pqueue_pop(sl, cmp), "daschunds");
  2215. smartlist_pqueue_add(sl, cmp, (char*)"chinchillas");
  2216. OK();
  2217. smartlist_pqueue_add(sl, cmp, (char*)"fireflies");
  2218. OK();
  2219. test_streq(smartlist_pqueue_pop(sl, cmp), "chinchillas");
  2220. test_streq(smartlist_pqueue_pop(sl, cmp), "eggplants");
  2221. test_streq(smartlist_pqueue_pop(sl, cmp), "fireflies");
  2222. OK();
  2223. test_streq(smartlist_pqueue_pop(sl, cmp), "fish");
  2224. test_streq(smartlist_pqueue_pop(sl, cmp), "frogs");
  2225. test_streq(smartlist_pqueue_pop(sl, cmp), "lobsters");
  2226. test_streq(smartlist_pqueue_pop(sl, cmp), "roquefort");
  2227. OK();
  2228. test_eq(smartlist_len(sl), 3);
  2229. test_streq(smartlist_pqueue_pop(sl, cmp), "squid");
  2230. test_streq(smartlist_pqueue_pop(sl, cmp), "weissbier");
  2231. test_streq(smartlist_pqueue_pop(sl, cmp), "zebras");
  2232. test_eq(smartlist_len(sl), 0);
  2233. OK();
  2234. #undef OK
  2235. done:
  2236. smartlist_free(sl);
  2237. }
  2238. /** Run unit tests for compression functions */
  2239. static void
  2240. test_util_gzip(void)
  2241. {
  2242. char *buf1=NULL, *buf2=NULL, *buf3=NULL, *cp1, *cp2;
  2243. const char *ccp2;
  2244. size_t len1, len2;
  2245. tor_zlib_state_t *state = NULL;
  2246. buf1 = tor_strdup("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ");
  2247. test_assert(detect_compression_method(buf1, strlen(buf1)) == UNKNOWN_METHOD);
  2248. if (is_gzip_supported()) {
  2249. test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
  2250. GZIP_METHOD));
  2251. test_assert(buf2);
  2252. test_assert(!memcmp(buf2, "\037\213", 2)); /* Gzip magic. */
  2253. test_assert(detect_compression_method(buf2, len1) == GZIP_METHOD);
  2254. test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1,
  2255. GZIP_METHOD, 1, LOG_INFO));
  2256. test_assert(buf3);
  2257. test_streq(buf1,buf3);
  2258. tor_free(buf2);
  2259. tor_free(buf3);
  2260. }
  2261. test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
  2262. ZLIB_METHOD));
  2263. test_assert(buf2);
  2264. test_assert(!memcmp(buf2, "\x78\xDA", 2)); /* deflate magic. */
  2265. test_assert(detect_compression_method(buf2, len1) == ZLIB_METHOD);
  2266. test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1,
  2267. ZLIB_METHOD, 1, LOG_INFO));
  2268. test_assert(buf3);
  2269. test_streq(buf1,buf3);
  2270. /* Check whether we can uncompress concatenated, compressed strings. */
  2271. tor_free(buf3);
  2272. buf2 = tor_realloc(buf2, len1*2);
  2273. memcpy(buf2+len1, buf2, len1);
  2274. test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1*2,
  2275. ZLIB_METHOD, 1, LOG_INFO));
  2276. test_eq(len2, (strlen(buf1)+1)*2);
  2277. test_memeq(buf3,
  2278. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ\0"
  2279. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ\0",
  2280. (strlen(buf1)+1)*2);
  2281. tor_free(buf1);
  2282. tor_free(buf2);
  2283. tor_free(buf3);
  2284. /* Check whether we can uncompress partial strings. */
  2285. buf1 =
  2286. tor_strdup("String with low redundancy that won't be compressed much.");
  2287. test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
  2288. ZLIB_METHOD));
  2289. tor_assert(len1>16);
  2290. /* when we allow an incomplete string, we should succeed.*/
  2291. tor_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1-16,
  2292. ZLIB_METHOD, 0, LOG_INFO));
  2293. buf3[len2]='\0';
  2294. tor_assert(len2 > 5);
  2295. tor_assert(!strcmpstart(buf1, buf3));
  2296. /* when we demand a complete string, this must fail. */
  2297. tor_free(buf3);
  2298. tor_assert(tor_gzip_uncompress(&buf3, &len2, buf2, len1-16,
  2299. ZLIB_METHOD, 1, LOG_INFO));
  2300. tor_assert(!buf3);
  2301. /* Now, try streaming compression. */
  2302. tor_free(buf1);
  2303. tor_free(buf2);
  2304. tor_free(buf3);
  2305. state = tor_zlib_new(1, ZLIB_METHOD);
  2306. tor_assert(state);
  2307. cp1 = buf1 = tor_malloc(1024);
  2308. len1 = 1024;
  2309. ccp2 = "ABCDEFGHIJABCDEFGHIJ";
  2310. len2 = 21;
  2311. test_assert(tor_zlib_process(state, &cp1, &len1, &ccp2, &len2, 0)
  2312. == TOR_ZLIB_OK);
  2313. test_eq(len2, 0); /* Make sure we compressed it all. */
  2314. test_assert(cp1 > buf1);
  2315. len2 = 0;
  2316. cp2 = cp1;
  2317. test_assert(tor_zlib_process(state, &cp1, &len1, &ccp2, &len2, 1)
  2318. == TOR_ZLIB_DONE);
  2319. test_eq(len2, 0);
  2320. test_assert(cp1 > cp2); /* Make sure we really added something. */
  2321. tor_assert(!tor_gzip_uncompress(&buf3, &len2, buf1, 1024-len1,
  2322. ZLIB_METHOD, 1, LOG_WARN));
  2323. test_streq(buf3, "ABCDEFGHIJABCDEFGHIJ"); /*Make sure it compressed right.*/
  2324. done:
  2325. if (state)
  2326. tor_zlib_free(state);
  2327. tor_free(buf2);
  2328. tor_free(buf3);
  2329. tor_free(buf1);
  2330. }
  2331. /** Run unit tests for string-to-void* map functions */
  2332. static void
  2333. test_util_strmap(void)
  2334. {
  2335. strmap_t *map;
  2336. strmap_iter_t *iter;
  2337. const char *k;
  2338. void *v;
  2339. char *visited = NULL;
  2340. smartlist_t *found_keys = NULL;
  2341. map = strmap_new();
  2342. test_assert(map);
  2343. test_eq(strmap_size(map), 0);
  2344. test_assert(strmap_isempty(map));
  2345. v = strmap_set(map, "K1", (void*)99);
  2346. test_eq(v, NULL);
  2347. test_assert(!strmap_isempty(map));
  2348. v = strmap_set(map, "K2", (void*)101);
  2349. test_eq(v, NULL);
  2350. v = strmap_set(map, "K1", (void*)100);
  2351. test_eq(v, (void*)99);
  2352. test_eq_ptr(strmap_get(map,"K1"), (void*)100);
  2353. test_eq_ptr(strmap_get(map,"K2"), (void*)101);
  2354. test_eq_ptr(strmap_get(map,"K-not-there"), NULL);
  2355. strmap_assert_ok(map);
  2356. v = strmap_remove(map,"K2");
  2357. strmap_assert_ok(map);
  2358. test_eq_ptr(v, (void*)101);
  2359. test_eq_ptr(strmap_get(map,"K2"), NULL);
  2360. test_eq_ptr(strmap_remove(map,"K2"), NULL);
  2361. strmap_set(map, "K2", (void*)101);
  2362. strmap_set(map, "K3", (void*)102);
  2363. strmap_set(map, "K4", (void*)103);
  2364. test_eq(strmap_size(map), 4);
  2365. strmap_assert_ok(map);
  2366. strmap_set(map, "K5", (void*)104);
  2367. strmap_set(map, "K6", (void*)105);
  2368. strmap_assert_ok(map);
  2369. /* Test iterator. */
  2370. iter = strmap_iter_init(map);
  2371. found_keys = smartlist_create();
  2372. while (!strmap_iter_done(iter)) {
  2373. strmap_iter_get(iter,&k,&v);
  2374. smartlist_add(found_keys, tor_strdup(k));
  2375. test_eq_ptr(v, strmap_get(map, k));
  2376. if (!strcmp(k, "K2")) {
  2377. iter = strmap_iter_next_rmv(map,iter);
  2378. } else {
  2379. iter = strmap_iter_next(map,iter);
  2380. }
  2381. }
  2382. /* Make sure we removed K2, but not the others. */
  2383. test_eq_ptr(strmap_get(map, "K2"), NULL);
  2384. test_eq_ptr(strmap_get(map, "K5"), (void*)104);
  2385. /* Make sure we visited everyone once */
  2386. smartlist_sort_strings(found_keys);
  2387. visited = smartlist_join_strings(found_keys, ":", 0, NULL);
  2388. test_streq(visited, "K1:K2:K3:K4:K5:K6");
  2389. strmap_assert_ok(map);
  2390. /* Clean up after ourselves. */
  2391. strmap_free(map, NULL);
  2392. map = NULL;
  2393. /* Now try some lc functions. */
  2394. map = strmap_new();
  2395. strmap_set_lc(map,"Ab.C", (void*)1);
  2396. test_eq_ptr(strmap_get(map,"ab.c"), (void*)1);
  2397. strmap_assert_ok(map);
  2398. test_eq_ptr(strmap_get_lc(map,"AB.C"), (void*)1);
  2399. test_eq_ptr(strmap_get(map,"AB.C"), NULL);
  2400. test_eq_ptr(strmap_remove_lc(map,"aB.C"), (void*)1);
  2401. strmap_assert_ok(map);
  2402. test_eq_ptr(strmap_get_lc(map,"AB.C"), NULL);
  2403. done:
  2404. if (map)
  2405. strmap_free(map,NULL);
  2406. if (found_keys) {
  2407. SMARTLIST_FOREACH(found_keys, char *, cp, tor_free(cp));
  2408. smartlist_free(found_keys);
  2409. }
  2410. tor_free(visited);
  2411. }
  2412. /** Run unit tests for mmap() wrapper functionality. */
  2413. static void
  2414. test_util_mmap(void)
  2415. {
  2416. char *fname1 = tor_strdup(get_fname("mapped_1"));
  2417. char *fname2 = tor_strdup(get_fname("mapped_2"));
  2418. char *fname3 = tor_strdup(get_fname("mapped_3"));
  2419. const size_t buflen = 17000;
  2420. char *buf = tor_malloc(17000);
  2421. tor_mmap_t *mapping = NULL;
  2422. crypto_rand(buf, buflen);
  2423. mapping = tor_mmap_file(fname1);
  2424. test_assert(! mapping);
  2425. write_str_to_file(fname1, "Short file.", 1);
  2426. write_bytes_to_file(fname2, buf, buflen, 1);
  2427. write_bytes_to_file(fname3, buf, 16384, 1);
  2428. mapping = tor_mmap_file(fname1);
  2429. test_assert(mapping);
  2430. test_eq(mapping->size, strlen("Short file."));
  2431. test_streq(mapping->data, "Short file.");
  2432. #ifdef MS_WINDOWS
  2433. tor_munmap_file(mapping);
  2434. mapping = NULL;
  2435. test_assert(unlink(fname1) == 0);
  2436. #else
  2437. /* make sure we can unlink. */
  2438. test_assert(unlink(fname1) == 0);
  2439. test_streq(mapping->data, "Short file.");
  2440. tor_munmap_file(mapping);
  2441. mapping = NULL;
  2442. #endif
  2443. /* Now a zero-length file. */
  2444. write_str_to_file(fname1, "", 1);
  2445. mapping = tor_mmap_file(fname1);
  2446. test_eq(mapping, NULL);
  2447. test_eq(ERANGE, errno);
  2448. unlink(fname1);
  2449. /* Make sure that we fail to map a no-longer-existent file. */
  2450. mapping = tor_mmap_file(fname1);
  2451. test_assert(mapping == NULL);
  2452. /* Now try a big file that stretches across a few pages and isn't aligned */
  2453. mapping = tor_mmap_file(fname2);
  2454. test_assert(mapping);
  2455. test_eq(mapping->size, buflen);
  2456. test_memeq(mapping->data, buf, buflen);
  2457. tor_munmap_file(mapping);
  2458. mapping = NULL;
  2459. /* Now try a big aligned file. */
  2460. mapping = tor_mmap_file(fname3);
  2461. test_assert(mapping);
  2462. test_eq(mapping->size, 16384);
  2463. test_memeq(mapping->data, buf, 16384);
  2464. tor_munmap_file(mapping);
  2465. mapping = NULL;
  2466. done:
  2467. unlink(fname1);
  2468. unlink(fname2);
  2469. unlink(fname3);
  2470. tor_free(fname1);
  2471. tor_free(fname2);
  2472. tor_free(fname3);
  2473. tor_free(buf);
  2474. if (mapping)
  2475. tor_munmap_file(mapping);
  2476. }
  2477. /** Run unit tests for escaping/unescaping data for use by controllers. */
  2478. static void
  2479. test_util_control_formats(void)
  2480. {
  2481. char *out = NULL;
  2482. const char *inp =
  2483. "..This is a test\r\nof the emergency \nbroadcast\r\n..system.\r\nZ.\r\n";
  2484. size_t sz;
  2485. sz = read_escaped_data(inp, strlen(inp), &out);
  2486. test_streq(out,
  2487. ".This is a test\nof the emergency \nbroadcast\n.system.\nZ.\n");
  2488. test_eq(sz, strlen(out));
  2489. done:
  2490. tor_free(out);
  2491. }
  2492. static void
  2493. test_util_sscanf(void)
  2494. {
  2495. unsigned u1, u2, u3;
  2496. char s1[10], s2[10], s3[10], ch;
  2497. int r;
  2498. r = tor_sscanf("hello world", "hello world"); /* String match: success */
  2499. test_eq(r, 0);
  2500. r = tor_sscanf("hello world 3", "hello worlb %u", &u1); /* String fail */
  2501. test_eq(r, 0);
  2502. r = tor_sscanf("12345", "%u", &u1); /* Simple number */
  2503. test_eq(r, 1);
  2504. test_eq(u1, 12345u);
  2505. r = tor_sscanf("", "%u", &u1); /* absent number */
  2506. test_eq(r, 0);
  2507. r = tor_sscanf("A", "%u", &u1); /* bogus number */
  2508. test_eq(r, 0);
  2509. r = tor_sscanf("4294967295", "%u", &u1); /* UINT32_MAX should work. */
  2510. test_eq(r, 1);
  2511. test_eq(u1, 4294967295u);
  2512. r = tor_sscanf("4294967296", "%u", &u1); /* Always say -1 at 32 bits. */
  2513. test_eq(r, 0);
  2514. r = tor_sscanf("123456", "%2u%u", &u1, &u2); /* Width */
  2515. test_eq(r, 2);
  2516. test_eq(u1, 12u);
  2517. test_eq(u2, 3456u);
  2518. r = tor_sscanf("!12:3:456", "!%2u:%2u:%3u", &u1, &u2, &u3); /* separators */
  2519. test_eq(r, 3);
  2520. test_eq(u1, 12u);
  2521. test_eq(u2, 3u);
  2522. test_eq(u3, 456u);
  2523. r = tor_sscanf("12:3:045", "%2u:%2u:%3u", &u1, &u2, &u3); /* 0s */
  2524. test_eq(r, 3);
  2525. test_eq(u1, 12u);
  2526. test_eq(u2, 3u);
  2527. test_eq(u3, 45u);
  2528. /* %u does not match space.*/
  2529. r = tor_sscanf("12:3: 45", "%2u:%2u:%3u", &u1, &u2, &u3);
  2530. test_eq(r, 2);
  2531. /* %u does not match negative numbers. */
  2532. r = tor_sscanf("12:3:-4", "%2u:%2u:%3u", &u1, &u2, &u3);
  2533. test_eq(r, 2);
  2534. /* Arbitrary amounts of 0-padding are okay */
  2535. r = tor_sscanf("12:03:000000000000000099", "%2u:%2u:%u", &u1, &u2, &u3);
  2536. test_eq(r, 3);
  2537. test_eq(u1, 12u);
  2538. test_eq(u2, 3u);
  2539. test_eq(u3, 99u);
  2540. r = tor_sscanf("99% fresh", "%3u%% fresh", &u1); /* percents are scannable.*/
  2541. test_eq(r, 1);
  2542. test_eq(u1, 99);
  2543. r = tor_sscanf("hello", "%s", s1); /* %s needs a number. */
  2544. test_eq(r, -1);
  2545. r = tor_sscanf("hello", "%3s%7s", s1, s2); /* %s matches characters. */
  2546. test_eq(r, 2);
  2547. test_streq(s1, "hel");
  2548. test_streq(s2, "lo");
  2549. r = tor_sscanf("WD40", "%2s%u", s3, &u1); /* %s%u */
  2550. test_eq(r, 2);
  2551. test_streq(s3, "WD");
  2552. test_eq(u1, 40);
  2553. r = tor_sscanf("76trombones", "%6u%9s", &u1, s1); /* %u%s */
  2554. test_eq(r, 2);
  2555. test_eq(u1, 76);
  2556. test_streq(s1, "trombones");
  2557. r = tor_sscanf("hello world", "%9s %9s", s1, s2); /* %s doesn't eat space. */
  2558. test_eq(r, 2);
  2559. test_streq(s1, "hello");
  2560. test_streq(s2, "world");
  2561. r = tor_sscanf("hi", "%9s%9s%3s", s1, s2, s3); /* %s can be empty. */
  2562. test_eq(r, 3);
  2563. test_streq(s1, "hi");
  2564. test_streq(s2, "");
  2565. test_streq(s3, "");
  2566. r = tor_sscanf("1.2.3", "%u.%u.%u%c", &u1, &u2, &u3, &ch);
  2567. test_eq(r, 3);
  2568. r = tor_sscanf("1.2.3 foobar", "%u.%u.%u%c", &u1, &u2, &u3, &ch);
  2569. test_eq(r, 4);
  2570. done:
  2571. ;
  2572. }
  2573. /** Run unit tests for the onion handshake code. */
  2574. static void
  2575. test_onion_handshake(void)
  2576. {
  2577. /* client-side */
  2578. crypto_dh_env_t *c_dh = NULL;
  2579. char c_buf[ONIONSKIN_CHALLENGE_LEN];
  2580. char c_keys[40];
  2581. /* server-side */
  2582. char s_buf[ONIONSKIN_REPLY_LEN];
  2583. char s_keys[40];
  2584. /* shared */
  2585. crypto_pk_env_t *pk = NULL;
  2586. pk = pk_generate(0);
  2587. /* client handshake 1. */
  2588. memset(c_buf, 0, ONIONSKIN_CHALLENGE_LEN);
  2589. test_assert(! onion_skin_create(pk, &c_dh, c_buf));
  2590. /* server handshake */
  2591. memset(s_buf, 0, ONIONSKIN_REPLY_LEN);
  2592. memset(s_keys, 0, 40);
  2593. test_assert(! onion_skin_server_handshake(c_buf, pk, NULL,
  2594. s_buf, s_keys, 40));
  2595. /* client handshake 2 */
  2596. memset(c_keys, 0, 40);
  2597. test_assert(! onion_skin_client_handshake(c_dh, s_buf, c_keys, 40));
  2598. if (memcmp(c_keys, s_keys, 40)) {
  2599. puts("Aiiiie");
  2600. exit(1);
  2601. }
  2602. test_memeq(c_keys, s_keys, 40);
  2603. memset(s_buf, 0, 40);
  2604. test_memneq(c_keys, s_buf, 40);
  2605. done:
  2606. if (c_dh)
  2607. crypto_dh_free(c_dh);
  2608. if (pk)
  2609. crypto_free_pk_env(pk);
  2610. }
  2611. /** Run unit tests for router descriptor generation logic. */
  2612. static void
  2613. test_dir_format(void)
  2614. {
  2615. char buf[8192], buf2[8192];
  2616. char platform[256];
  2617. char fingerprint[FINGERPRINT_LEN+1];
  2618. char *pk1_str = NULL, *pk2_str = NULL, *pk3_str = NULL, *cp;
  2619. size_t pk1_str_len, pk2_str_len, pk3_str_len;
  2620. routerinfo_t *r1=NULL, *r2=NULL;
  2621. crypto_pk_env_t *pk1 = NULL, *pk2 = NULL, *pk3 = NULL;
  2622. routerinfo_t *rp1 = NULL;
  2623. addr_policy_t *ex1, *ex2;
  2624. routerlist_t *dir1 = NULL, *dir2 = NULL;
  2625. tor_version_t ver1;
  2626. pk1 = pk_generate(0);
  2627. pk2 = pk_generate(1);
  2628. pk3 = pk_generate(2);
  2629. test_assert( is_legal_nickname("a"));
  2630. test_assert(!is_legal_nickname(""));
  2631. test_assert(!is_legal_nickname("abcdefghijklmnopqrst")); /* 20 chars */
  2632. test_assert(!is_legal_nickname("hyphen-")); /* bad char */
  2633. test_assert( is_legal_nickname("abcdefghijklmnopqrs")); /* 19 chars */
  2634. test_assert(!is_legal_nickname("$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA"));
  2635. /* valid */
  2636. test_assert( is_legal_nickname_or_hexdigest(
  2637. "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA"));
  2638. test_assert( is_legal_nickname_or_hexdigest(
  2639. "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA=fred"));
  2640. test_assert( is_legal_nickname_or_hexdigest(
  2641. "$AAAAAAAA01234AAAAAAAAAAAAAAAAAAAAAAAAAAA~fred"));
  2642. /* too short */
  2643. test_assert(!is_legal_nickname_or_hexdigest(
  2644. "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
  2645. /* illegal char */
  2646. test_assert(!is_legal_nickname_or_hexdigest(
  2647. "$AAAAAAzAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
  2648. /* hex part too long */
  2649. test_assert(!is_legal_nickname_or_hexdigest(
  2650. "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
  2651. test_assert(!is_legal_nickname_or_hexdigest(
  2652. "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=fred"));
  2653. /* Bad nickname */
  2654. test_assert(!is_legal_nickname_or_hexdigest(
  2655. "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="));
  2656. test_assert(!is_legal_nickname_or_hexdigest(
  2657. "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~"));
  2658. test_assert(!is_legal_nickname_or_hexdigest(
  2659. "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~hyphen-"));
  2660. test_assert(!is_legal_nickname_or_hexdigest(
  2661. "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA~"
  2662. "abcdefghijklmnoppqrst"));
  2663. /* Bad extra char. */
  2664. test_assert(!is_legal_nickname_or_hexdigest(
  2665. "$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA!"));
  2666. test_assert(is_legal_nickname_or_hexdigest("xyzzy"));
  2667. test_assert(is_legal_nickname_or_hexdigest("abcdefghijklmnopqrs"));
  2668. test_assert(!is_legal_nickname_or_hexdigest("abcdefghijklmnopqrst"));
  2669. get_platform_str(platform, sizeof(platform));
  2670. r1 = tor_malloc_zero(sizeof(routerinfo_t));
  2671. r1->address = tor_strdup("18.244.0.1");
  2672. r1->addr = 0xc0a80001u; /* 192.168.0.1 */
  2673. r1->cache_info.published_on = 0;
  2674. r1->or_port = 9000;
  2675. r1->dir_port = 9003;
  2676. r1->onion_pkey = crypto_pk_dup_key(pk1);
  2677. r1->identity_pkey = crypto_pk_dup_key(pk2);
  2678. r1->bandwidthrate = 1000;
  2679. r1->bandwidthburst = 5000;
  2680. r1->bandwidthcapacity = 10000;
  2681. r1->exit_policy = NULL;
  2682. r1->nickname = tor_strdup("Magri");
  2683. r1->platform = tor_strdup(platform);
  2684. ex1 = tor_malloc_zero(sizeof(addr_policy_t));
  2685. ex2 = tor_malloc_zero(sizeof(addr_policy_t));
  2686. ex1->policy_type = ADDR_POLICY_ACCEPT;
  2687. tor_addr_from_ipv4h(&ex1->addr, 0);
  2688. ex1->maskbits = 0;
  2689. ex1->prt_min = ex1->prt_max = 80;
  2690. ex2->policy_type = ADDR_POLICY_REJECT;
  2691. tor_addr_from_ipv4h(&ex2->addr, 18<<24);
  2692. ex2->maskbits = 8;
  2693. ex2->prt_min = ex2->prt_max = 24;
  2694. r2 = tor_malloc_zero(sizeof(routerinfo_t));
  2695. r2->address = tor_strdup("1.1.1.1");
  2696. r2->addr = 0x0a030201u; /* 10.3.2.1 */
  2697. r2->platform = tor_strdup(platform);
  2698. r2->cache_info.published_on = 5;
  2699. r2->or_port = 9005;
  2700. r2->dir_port = 0;
  2701. r2->onion_pkey = crypto_pk_dup_key(pk2);
  2702. r2->identity_pkey = crypto_pk_dup_key(pk1);
  2703. r2->bandwidthrate = r2->bandwidthburst = r2->bandwidthcapacity = 3000;
  2704. r2->exit_policy = smartlist_create();
  2705. smartlist_add(r2->exit_policy, ex2);
  2706. smartlist_add(r2->exit_policy, ex1);
  2707. r2->nickname = tor_strdup("Fred");
  2708. test_assert(!crypto_pk_write_public_key_to_string(pk1, &pk1_str,
  2709. &pk1_str_len));
  2710. test_assert(!crypto_pk_write_public_key_to_string(pk2 , &pk2_str,
  2711. &pk2_str_len));
  2712. test_assert(!crypto_pk_write_public_key_to_string(pk3 , &pk3_str,
  2713. &pk3_str_len));
  2714. memset(buf, 0, 2048);
  2715. test_assert(router_dump_router_to_string(buf, 2048, r1, pk2)>0);
  2716. strlcpy(buf2, "router Magri 18.244.0.1 9000 0 9003\n"
  2717. "platform Tor "VERSION" on ", sizeof(buf2));
  2718. strlcat(buf2, get_uname(), sizeof(buf2));
  2719. strlcat(buf2, "\n"
  2720. "opt protocols Link 1 2 Circuit 1\n"
  2721. "published 1970-01-01 00:00:00\n"
  2722. "opt fingerprint ", sizeof(buf2));
  2723. test_assert(!crypto_pk_get_fingerprint(pk2, fingerprint, 1));
  2724. strlcat(buf2, fingerprint, sizeof(buf2));
  2725. strlcat(buf2, "\nuptime 0\n"
  2726. /* XXX the "0" above is hard-coded, but even if we made it reflect
  2727. * uptime, that still wouldn't make it right, because the two
  2728. * descriptors might be made on different seconds... hm. */
  2729. "bandwidth 1000 5000 10000\n"
  2730. "opt extra-info-digest 0000000000000000000000000000000000000000\n"
  2731. "onion-key\n", sizeof(buf2));
  2732. strlcat(buf2, pk1_str, sizeof(buf2));
  2733. strlcat(buf2, "signing-key\n", sizeof(buf2));
  2734. strlcat(buf2, pk2_str, sizeof(buf2));
  2735. strlcat(buf2, "opt hidden-service-dir\n", sizeof(buf2));
  2736. strlcat(buf2, "reject *:*\nrouter-signature\n", sizeof(buf2));
  2737. buf[strlen(buf2)] = '\0'; /* Don't compare the sig; it's never the same
  2738. * twice */
  2739. test_streq(buf, buf2);
  2740. test_assert(router_dump_router_to_string(buf, 2048, r1, pk2)>0);
  2741. cp = buf;
  2742. rp1 = router_parse_entry_from_string((const char*)cp,NULL,1,0,NULL);
  2743. test_assert(rp1);
  2744. test_streq(rp1->address, r1->address);
  2745. test_eq(rp1->or_port, r1->or_port);
  2746. //test_eq(rp1->dir_port, r1->dir_port);
  2747. test_eq(rp1->bandwidthrate, r1->bandwidthrate);
  2748. test_eq(rp1->bandwidthburst, r1->bandwidthburst);
  2749. test_eq(rp1->bandwidthcapacity, r1->bandwidthcapacity);
  2750. test_assert(crypto_pk_cmp_keys(rp1->onion_pkey, pk1) == 0);
  2751. test_assert(crypto_pk_cmp_keys(rp1->identity_pkey, pk2) == 0);
  2752. //test_assert(rp1->exit_policy == NULL);
  2753. #if 0
  2754. /* XXX Once we have exit policies, test this again. XXX */
  2755. strlcpy(buf2, "router tor.tor.tor 9005 0 0 3000\n", sizeof(buf2));
  2756. strlcat(buf2, pk2_str, sizeof(buf2));
  2757. strlcat(buf2, "signing-key\n", sizeof(buf2));
  2758. strlcat(buf2, pk1_str, sizeof(buf2));
  2759. strlcat(buf2, "accept *:80\nreject 18.*:24\n\n", sizeof(buf2));
  2760. test_assert(router_dump_router_to_string(buf, 2048, &r2, pk2)>0);
  2761. test_streq(buf, buf2);
  2762. cp = buf;
  2763. rp2 = router_parse_entry_from_string(&cp,1);
  2764. test_assert(rp2);
  2765. test_streq(rp2->address, r2.address);
  2766. test_eq(rp2->or_port, r2.or_port);
  2767. test_eq(rp2->dir_port, r2.dir_port);
  2768. test_eq(rp2->bandwidth, r2.bandwidth);
  2769. test_assert(crypto_pk_cmp_keys(rp2->onion_pkey, pk2) == 0);
  2770. test_assert(crypto_pk_cmp_keys(rp2->identity_pkey, pk1) == 0);
  2771. test_eq(rp2->exit_policy->policy_type, EXIT_POLICY_ACCEPT);
  2772. test_streq(rp2->exit_policy->string, "accept *:80");
  2773. test_streq(rp2->exit_policy->address, "*");
  2774. test_streq(rp2->exit_policy->port, "80");
  2775. test_eq(rp2->exit_policy->next->policy_type, EXIT_POLICY_REJECT);
  2776. test_streq(rp2->exit_policy->next->string, "reject 18.*:24");
  2777. test_streq(rp2->exit_policy->next->address, "18.*");
  2778. test_streq(rp2->exit_policy->next->port, "24");
  2779. test_assert(rp2->exit_policy->next->next == NULL);
  2780. /* Okay, now for the directories. */
  2781. {
  2782. fingerprint_list = smartlist_create();
  2783. crypto_pk_get_fingerprint(pk2, buf, 1);
  2784. add_fingerprint_to_dir("Magri", buf, fingerprint_list);
  2785. crypto_pk_get_fingerprint(pk1, buf, 1);
  2786. add_fingerprint_to_dir("Fred", buf, fingerprint_list);
  2787. }
  2788. {
  2789. char d[DIGEST_LEN];
  2790. const char *m;
  2791. /* XXXX NM re-enable. */
  2792. /* Make sure routers aren't too far in the past any more. */
  2793. r1->cache_info.published_on = time(NULL);
  2794. r2->cache_info.published_on = time(NULL)-3*60*60;
  2795. test_assert(router_dump_router_to_string(buf, 2048, r1, pk2)>0);
  2796. test_eq(dirserv_add_descriptor(buf,&m,""), ROUTER_ADDED_NOTIFY_GENERATOR);
  2797. test_assert(router_dump_router_to_string(buf, 2048, r2, pk1)>0);
  2798. test_eq(dirserv_add_descriptor(buf,&m,""), ROUTER_ADDED_NOTIFY_GENERATOR);
  2799. get_options()->Nickname = tor_strdup("DirServer");
  2800. test_assert(!dirserv_dump_directory_to_string(&cp,pk3, 0));
  2801. crypto_pk_get_digest(pk3, d);
  2802. test_assert(!router_parse_directory(cp));
  2803. test_eq(2, smartlist_len(dir1->routers));
  2804. tor_free(cp);
  2805. }
  2806. #endif
  2807. dirserv_free_fingerprint_list();
  2808. /* Try out version parsing functionality */
  2809. test_eq(0, tor_version_parse("0.3.4pre2-cvs", &ver1));
  2810. test_eq(0, ver1.major);
  2811. test_eq(3, ver1.minor);
  2812. test_eq(4, ver1.micro);
  2813. test_eq(VER_PRE, ver1.status);
  2814. test_eq(2, ver1.patchlevel);
  2815. test_eq(0, tor_version_parse("0.3.4rc1", &ver1));
  2816. test_eq(0, ver1.major);
  2817. test_eq(3, ver1.minor);
  2818. test_eq(4, ver1.micro);
  2819. test_eq(VER_RC, ver1.status);
  2820. test_eq(1, ver1.patchlevel);
  2821. test_eq(0, tor_version_parse("1.3.4", &ver1));
  2822. test_eq(1, ver1.major);
  2823. test_eq(3, ver1.minor);
  2824. test_eq(4, ver1.micro);
  2825. test_eq(VER_RELEASE, ver1.status);
  2826. test_eq(0, ver1.patchlevel);
  2827. test_eq(0, tor_version_parse("1.3.4.999", &ver1));
  2828. test_eq(1, ver1.major);
  2829. test_eq(3, ver1.minor);
  2830. test_eq(4, ver1.micro);
  2831. test_eq(VER_RELEASE, ver1.status);
  2832. test_eq(999, ver1.patchlevel);
  2833. test_eq(0, tor_version_parse("0.1.2.4-alpha", &ver1));
  2834. test_eq(0, ver1.major);
  2835. test_eq(1, ver1.minor);
  2836. test_eq(2, ver1.micro);
  2837. test_eq(4, ver1.patchlevel);
  2838. test_eq(VER_RELEASE, ver1.status);
  2839. test_streq("alpha", ver1.status_tag);
  2840. test_eq(0, tor_version_parse("0.1.2.4", &ver1));
  2841. test_eq(0, ver1.major);
  2842. test_eq(1, ver1.minor);
  2843. test_eq(2, ver1.micro);
  2844. test_eq(4, ver1.patchlevel);
  2845. test_eq(VER_RELEASE, ver1.status);
  2846. test_streq("", ver1.status_tag);
  2847. #define test_eq_vs(vs1, vs2) test_eq_type(version_status_t, "%d", (vs1), (vs2))
  2848. #define test_v_i_o(val, ver, lst) \
  2849. test_eq_vs(val, tor_version_is_obsolete(ver, lst))
  2850. /* make sure tor_version_is_obsolete() works */
  2851. test_v_i_o(VS_OLD, "0.0.1", "Tor 0.0.2");
  2852. test_v_i_o(VS_OLD, "0.0.1", "0.0.2, Tor 0.0.3");
  2853. test_v_i_o(VS_OLD, "0.0.1", "0.0.2,Tor 0.0.3");
  2854. test_v_i_o(VS_OLD, "0.0.1","0.0.3,BetterTor 0.0.1");
  2855. test_v_i_o(VS_RECOMMENDED, "0.0.2", "Tor 0.0.2,Tor 0.0.3");
  2856. test_v_i_o(VS_NEW_IN_SERIES, "0.0.2", "Tor 0.0.2pre1,Tor 0.0.3");
  2857. test_v_i_o(VS_OLD, "0.0.2", "Tor 0.0.2.1,Tor 0.0.3");
  2858. test_v_i_o(VS_NEW, "0.1.0", "Tor 0.0.2,Tor 0.0.3");
  2859. test_v_i_o(VS_RECOMMENDED, "0.0.7rc2", "0.0.7,Tor 0.0.7rc2,Tor 0.0.8");
  2860. test_v_i_o(VS_OLD, "0.0.5.0", "0.0.5.1-cvs");
  2861. test_v_i_o(VS_NEW_IN_SERIES, "0.0.5.1-cvs", "0.0.5, 0.0.6");
  2862. /* Not on list, but newer than any in same series. */
  2863. test_v_i_o(VS_NEW_IN_SERIES, "0.1.0.3",
  2864. "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
  2865. /* Series newer than any on list. */
  2866. 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");
  2867. /* Series older than any on list. */
  2868. 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");
  2869. /* Not on list, not newer than any on same series. */
  2870. test_v_i_o(VS_UNRECOMMENDED, "0.1.0.1",
  2871. "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
  2872. /* On list, not newer than any on same series. */
  2873. test_v_i_o(VS_UNRECOMMENDED,
  2874. "0.1.0.1", "Tor 0.1.0.2,Tor 0.0.9.5,Tor 0.1.1.0");
  2875. test_eq(0, tor_version_as_new_as("Tor 0.0.5", "0.0.9pre1-cvs"));
  2876. test_eq(1, tor_version_as_new_as(
  2877. "Tor 0.0.8 on Darwin 64-121-192-100.c3-0."
  2878. "sfpo-ubr1.sfrn-sfpo.ca.cable.rcn.com Power Macintosh",
  2879. "0.0.8rc2"));
  2880. test_eq(0, tor_version_as_new_as(
  2881. "Tor 0.0.8 on Darwin 64-121-192-100.c3-0."
  2882. "sfpo-ubr1.sfrn-sfpo.ca.cable.rcn.com Power Macintosh", "0.0.8.2"));
  2883. /* Now try svn revisions. */
  2884. test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100)",
  2885. "Tor 0.2.1.0-dev (r99)"));
  2886. test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100) on Banana Jr",
  2887. "Tor 0.2.1.0-dev (r99) on Hal 9000"));
  2888. test_eq(1, tor_version_as_new_as("Tor 0.2.1.0-dev (r100)",
  2889. "Tor 0.2.1.0-dev on Colossus"));
  2890. test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev (r99)",
  2891. "Tor 0.2.1.0-dev (r100)"));
  2892. test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev (r99) on MCP",
  2893. "Tor 0.2.1.0-dev (r100) on AM"));
  2894. test_eq(0, tor_version_as_new_as("Tor 0.2.1.0-dev",
  2895. "Tor 0.2.1.0-dev (r99)"));
  2896. test_eq(1, tor_version_as_new_as("Tor 0.2.1.1",
  2897. "Tor 0.2.1.0-dev (r99)"));
  2898. /* Now try git revisions */
  2899. test_eq(0, tor_version_parse("0.5.6.7 (git-ff00ff)", &ver1));
  2900. test_eq(0, ver1.major);
  2901. test_eq(5, ver1.minor);
  2902. test_eq(6, ver1.micro);
  2903. test_eq(7, ver1.patchlevel);
  2904. test_eq(3, ver1.git_tag_len);
  2905. test_memeq(ver1.git_tag, "\xff\x00\xff", 3);
  2906. test_eq(-1, tor_version_parse("0.5.6.7 (git-ff00xx)", &ver1));
  2907. test_eq(-1, tor_version_parse("0.5.6.7 (git-ff00fff)", &ver1));
  2908. test_eq(0, tor_version_parse("0.5.6.7 (git ff00fff)", &ver1));
  2909. done:
  2910. if (r1)
  2911. routerinfo_free(r1);
  2912. if (r2)
  2913. routerinfo_free(r2);
  2914. tor_free(pk1_str);
  2915. tor_free(pk2_str);
  2916. tor_free(pk3_str);
  2917. if (pk1) crypto_free_pk_env(pk1);
  2918. if (pk2) crypto_free_pk_env(pk2);
  2919. if (pk3) crypto_free_pk_env(pk3);
  2920. if (rp1) routerinfo_free(rp1);
  2921. tor_free(dir1); /* XXXX And more !*/
  2922. tor_free(dir2); /* And more !*/
  2923. }
  2924. /** Run unit tests for misc directory functions. */
  2925. static void
  2926. test_dirutil(void)
  2927. {
  2928. smartlist_t *sl = smartlist_create();
  2929. fp_pair_t *pair;
  2930. dir_split_resource_into_fingerprint_pairs(
  2931. /* Two pairs, out of order, with one duplicate. */
  2932. "73656372657420646174612E0000000000FFFFFF-"
  2933. "557365204145532d32353620696e73746561642e+"
  2934. "73656372657420646174612E0000000000FFFFFF-"
  2935. "557365204145532d32353620696e73746561642e+"
  2936. "48657861646563696d616c2069736e277420736f-"
  2937. "676f6f6420666f7220686964696e6720796f7572.z", sl);
  2938. test_eq(smartlist_len(sl), 2);
  2939. pair = smartlist_get(sl, 0);
  2940. test_memeq(pair->first, "Hexadecimal isn't so", DIGEST_LEN);
  2941. test_memeq(pair->second, "good for hiding your", DIGEST_LEN);
  2942. pair = smartlist_get(sl, 1);
  2943. test_memeq(pair->first, "secret data.\0\0\0\0\0\xff\xff\xff", DIGEST_LEN);
  2944. test_memeq(pair->second, "Use AES-256 instead.", DIGEST_LEN);
  2945. done:
  2946. SMARTLIST_FOREACH(sl, fp_pair_t *, pair, tor_free(pair));
  2947. smartlist_free(sl);
  2948. }
  2949. static void
  2950. test_dirutil_measured_bw(void)
  2951. {
  2952. measured_bw_line_t mbwl;
  2953. int i;
  2954. const char *lines_pass[] = {
  2955. "node_id=$557365204145532d32353620696e73746561642e bw=1024\n",
  2956. "node_id=$557365204145532d32353620696e73746561642e\t bw=1024 \n",
  2957. " node_id=$557365204145532d32353620696e73746561642e bw=1024\n",
  2958. "\tnoise\tnode_id=$557365204145532d32353620696e73746561642e "
  2959. "bw=1024 junk=007\n",
  2960. "misc=junk node_id=$557365204145532d32353620696e73746561642e "
  2961. "bw=1024 junk=007\n",
  2962. "end"
  2963. };
  2964. const char *lines_fail[] = {
  2965. /* Test possible python stupidity on input */
  2966. "node_id=None bw=1024\n",
  2967. "node_id=$None bw=1024\n",
  2968. "node_id=$557365204145532d32353620696e73746561642e bw=None\n",
  2969. "node_id=$557365204145532d32353620696e73746561642e bw=1024.0\n",
  2970. "node_id=$557365204145532d32353620696e73746561642e bw=.1024\n",
  2971. "node_id=$557365204145532d32353620696e73746561642e bw=1.024\n",
  2972. "node_id=$557365204145532d32353620696e73746561642e bw=1024 bw=0\n",
  2973. "node_id=$557365204145532d32353620696e73746561642e bw=1024 bw=None\n",
  2974. "node_id=$557365204145532d32353620696e73746561642e bw=-1024\n",
  2975. /* Test incomplete writes due to race conditions, partial copies, etc */
  2976. "node_i",
  2977. "node_i\n",
  2978. "node_id=",
  2979. "node_id=\n",
  2980. "node_id=$557365204145532d32353620696e73746561642e bw=",
  2981. "node_id=$557365204145532d32353620696e73746561642e bw=1024",
  2982. "node_id=$557365204145532d32353620696e73746561642e bw=\n",
  2983. "node_id=$557365204145532d32353620696e7374",
  2984. "node_id=$557365204145532d32353620696e7374\n",
  2985. "",
  2986. "\n",
  2987. " \n ",
  2988. " \n\n",
  2989. /* Test assorted noise */
  2990. " node_id= ",
  2991. "node_id==$557365204145532d32353620696e73746561642e bw==1024\n",
  2992. "node_id=$55736520414552d32353620696e73746561642e bw=1024\n",
  2993. "node_id=557365204145532d32353620696e73746561642e bw=1024\n",
  2994. "node_id= $557365204145532d32353620696e73746561642e bw=0.23\n",
  2995. "end"
  2996. };
  2997. for (i = 0; strcmp(lines_fail[i], "end"); i++) {
  2998. //fprintf(stderr, "Testing: %s\n", lines_fail[i]);
  2999. test_assert(measured_bw_line_parse(&mbwl, lines_fail[i]) == -1);
  3000. }
  3001. for (i = 0; strcmp(lines_pass[i], "end"); i++) {
  3002. //fprintf(stderr, "Testing: %s %d\n", lines_pass[i], TOR_ISSPACE('\n'));
  3003. test_assert(measured_bw_line_parse(&mbwl, lines_pass[i]) == 0);
  3004. test_assert(mbwl.bw == 1024);
  3005. test_assert(strcmp(mbwl.node_hex,
  3006. "557365204145532d32353620696e73746561642e") == 0);
  3007. }
  3008. done:
  3009. return;
  3010. }
  3011. static void
  3012. test_dirutil_param_voting(void)
  3013. {
  3014. networkstatus_t vote1, vote2, vote3, vote4;
  3015. smartlist_t *votes = smartlist_create();
  3016. char *res = NULL;
  3017. /* dirvote_compute_params only looks at the net_params field of the votes,
  3018. so that's all we need to set.
  3019. */
  3020. memset(&vote1, 0, sizeof(vote1));
  3021. memset(&vote2, 0, sizeof(vote2));
  3022. memset(&vote3, 0, sizeof(vote3));
  3023. memset(&vote4, 0, sizeof(vote4));
  3024. vote1.net_params = smartlist_create();
  3025. vote2.net_params = smartlist_create();
  3026. vote3.net_params = smartlist_create();
  3027. vote4.net_params = smartlist_create();
  3028. smartlist_split_string(vote1.net_params,
  3029. "ab=90 abcd=20 cw=50 x-yz=-99", NULL, 0, 0);
  3030. smartlist_split_string(vote2.net_params,
  3031. "ab=27 cw=5 x-yz=88", NULL, 0, 0);
  3032. smartlist_split_string(vote3.net_params,
  3033. "abcd=20 c=60 cw=500 x-yz=-9 zzzzz=101", NULL, 0, 0);
  3034. smartlist_split_string(vote4.net_params,
  3035. "ab=900 abcd=200 c=1 cw=51 x-yz=100", NULL, 0, 0);
  3036. test_eq(100, networkstatus_get_param(&vote4, "x-yz", 50));
  3037. test_eq(222, networkstatus_get_param(&vote4, "foobar", 222));
  3038. smartlist_add(votes, &vote1);
  3039. smartlist_add(votes, &vote2);
  3040. smartlist_add(votes, &vote3);
  3041. smartlist_add(votes, &vote4);
  3042. res = dirvote_compute_params(votes);
  3043. test_streq(res,
  3044. "ab=90 abcd=20 c=1 cw=50 x-yz=-9 zzzzz=101");
  3045. done:
  3046. tor_free(res);
  3047. SMARTLIST_FOREACH(vote1.net_params, char *, cp, tor_free(cp));
  3048. SMARTLIST_FOREACH(vote2.net_params, char *, cp, tor_free(cp));
  3049. SMARTLIST_FOREACH(vote3.net_params, char *, cp, tor_free(cp));
  3050. SMARTLIST_FOREACH(vote4.net_params, char *, cp, tor_free(cp));
  3051. smartlist_free(vote1.net_params);
  3052. smartlist_free(vote2.net_params);
  3053. smartlist_free(vote3.net_params);
  3054. smartlist_free(vote4.net_params);
  3055. return;
  3056. }
  3057. static void
  3058. test_circuit_timeout(void)
  3059. {
  3060. /* Plan:
  3061. * 1. Generate 1000 samples
  3062. * 2. Estimate parameters
  3063. * 3. If difference, repeat
  3064. * 4. Save state
  3065. * 5. load state
  3066. * 6. Estimate parameters
  3067. * 7. compare differences
  3068. */
  3069. circuit_build_times_t initial;
  3070. circuit_build_times_t estimate;
  3071. circuit_build_times_t final;
  3072. double timeout1, timeout2;
  3073. or_state_t state;
  3074. char *msg;
  3075. int i, runs;
  3076. circuit_build_times_init(&initial);
  3077. circuit_build_times_init(&estimate);
  3078. circuit_build_times_init(&final);
  3079. memset(&state, 0, sizeof(or_state_t));
  3080. circuitbuild_running_unit_tests();
  3081. #define timeout0 (build_time_t)(30*1000.0)
  3082. initial.Xm = 750;
  3083. circuit_build_times_initial_alpha(&initial, BUILDTIMEOUT_QUANTILE_CUTOFF,
  3084. timeout0);
  3085. do {
  3086. int n = 0;
  3087. for (i=0; i < MIN_CIRCUITS_TO_OBSERVE; i++) {
  3088. if (circuit_build_times_add_time(&estimate,
  3089. circuit_build_times_generate_sample(&initial, 0, 1)) == 0) {
  3090. n++;
  3091. }
  3092. }
  3093. circuit_build_times_update_alpha(&estimate);
  3094. timeout1 = circuit_build_times_calculate_timeout(&estimate,
  3095. BUILDTIMEOUT_QUANTILE_CUTOFF);
  3096. circuit_build_times_set_timeout(&estimate);
  3097. log_warn(LD_CIRC, "Timeout is %lf, Xm is %d", timeout1, estimate.Xm);
  3098. /* XXX: 5% distribution error may not be the right metric */
  3099. } while (fabs(circuit_build_times_cdf(&initial, timeout0) -
  3100. circuit_build_times_cdf(&initial, timeout1)) > 0.05
  3101. /* 5% error */
  3102. && estimate.total_build_times < NCIRCUITS_TO_OBSERVE);
  3103. test_assert(estimate.total_build_times < NCIRCUITS_TO_OBSERVE);
  3104. circuit_build_times_update_state(&estimate, &state);
  3105. test_assert(circuit_build_times_parse_state(&final, &state, &msg) == 0);
  3106. circuit_build_times_update_alpha(&final);
  3107. timeout2 = circuit_build_times_calculate_timeout(&final,
  3108. BUILDTIMEOUT_QUANTILE_CUTOFF);
  3109. circuit_build_times_set_timeout(&final);
  3110. log_warn(LD_CIRC, "Timeout is %lf, Xm is %d", timeout2, final.Xm);
  3111. test_assert(fabs(circuit_build_times_cdf(&initial, timeout0) -
  3112. circuit_build_times_cdf(&initial, timeout2)) < 0.05);
  3113. for (runs = 0; runs < 50; runs++) {
  3114. int build_times_idx = 0;
  3115. int total_build_times = 0;
  3116. final.timeout_ms = BUILD_TIMEOUT_INITIAL_VALUE;
  3117. estimate.timeout_ms = BUILD_TIMEOUT_INITIAL_VALUE;
  3118. for (i = 0; i < RECENT_CIRCUITS*2; i++) {
  3119. circuit_build_times_network_circ_success(&estimate);
  3120. circuit_build_times_add_time(&estimate,
  3121. circuit_build_times_generate_sample(&estimate, 0,
  3122. BUILDTIMEOUT_QUANTILE_CUTOFF));
  3123. estimate.have_computed_timeout = 1;
  3124. circuit_build_times_network_circ_success(&estimate);
  3125. circuit_build_times_add_time(&final,
  3126. circuit_build_times_generate_sample(&final, 0,
  3127. BUILDTIMEOUT_QUANTILE_CUTOFF));
  3128. final.have_computed_timeout = 1;
  3129. }
  3130. test_assert(!circuit_build_times_network_check_changed(&estimate));
  3131. test_assert(!circuit_build_times_network_check_changed(&final));
  3132. /* Reset liveness to be non-live */
  3133. final.liveness.network_last_live = 0;
  3134. estimate.liveness.network_last_live = 0;
  3135. build_times_idx = estimate.build_times_idx;
  3136. total_build_times = estimate.total_build_times;
  3137. for (i = 0; i < NETWORK_NONLIVE_TIMEOUT_COUNT; i++) {
  3138. test_assert(circuit_build_times_network_check_live(&estimate));
  3139. test_assert(circuit_build_times_network_check_live(&final));
  3140. if (circuit_build_times_add_timeout(&estimate, 0,
  3141. (time_t)(approx_time()-estimate.timeout_ms/1000.0-1)))
  3142. estimate.have_computed_timeout = 1;
  3143. if (circuit_build_times_add_timeout(&final, 0,
  3144. (time_t)(approx_time()-final.timeout_ms/1000.0-1)))
  3145. final.have_computed_timeout = 1;
  3146. }
  3147. test_assert(!circuit_build_times_network_check_live(&estimate));
  3148. test_assert(!circuit_build_times_network_check_live(&final));
  3149. for ( ; i < NETWORK_NONLIVE_DISCARD_COUNT; i++) {
  3150. if (circuit_build_times_add_timeout(&estimate, 0,
  3151. (time_t)(approx_time()-estimate.timeout_ms/1000.0-1)))
  3152. estimate.have_computed_timeout = 1;
  3153. if (i < NETWORK_NONLIVE_DISCARD_COUNT-1) {
  3154. if (circuit_build_times_add_timeout(&final, 0,
  3155. (time_t)(approx_time()-final.timeout_ms/1000.0-1)))
  3156. final.have_computed_timeout = 1;
  3157. }
  3158. }
  3159. test_assert(!circuit_build_times_network_check_live(&estimate));
  3160. test_assert(!circuit_build_times_network_check_live(&final));
  3161. log_info(LD_CIRC, "idx: %d %d, tot: %d %d",
  3162. build_times_idx, estimate.build_times_idx,
  3163. total_build_times, estimate.total_build_times);
  3164. /* Check rollback index. Should match top of loop. */
  3165. test_assert(build_times_idx == estimate.build_times_idx);
  3166. test_assert(total_build_times == estimate.total_build_times);
  3167. /* Now simulate that the network has become live and we need
  3168. * a change */
  3169. circuit_build_times_network_is_live(&estimate);
  3170. circuit_build_times_network_is_live(&final);
  3171. for (i = 0; i < MAX_RECENT_TIMEOUT_COUNT; i++) {
  3172. if (circuit_build_times_add_timeout(&estimate, 1, approx_time()-1))
  3173. estimate.have_computed_timeout = 1;
  3174. if (i < MAX_RECENT_TIMEOUT_COUNT-1) {
  3175. if (circuit_build_times_add_timeout(&final, 1, approx_time()-1))
  3176. final.have_computed_timeout = 1;
  3177. }
  3178. }
  3179. test_assert(estimate.liveness.after_firsthop_idx == 0);
  3180. test_assert(final.liveness.after_firsthop_idx ==
  3181. MAX_RECENT_TIMEOUT_COUNT-1);
  3182. test_assert(circuit_build_times_network_check_live(&estimate));
  3183. test_assert(circuit_build_times_network_check_live(&final));
  3184. if (circuit_build_times_add_timeout(&final, 1, approx_time()-1))
  3185. final.have_computed_timeout = 1;
  3186. }
  3187. done:
  3188. return;
  3189. }
  3190. extern const char AUTHORITY_CERT_1[];
  3191. extern const char AUTHORITY_SIGNKEY_1[];
  3192. extern const char AUTHORITY_CERT_2[];
  3193. extern const char AUTHORITY_SIGNKEY_2[];
  3194. extern const char AUTHORITY_CERT_3[];
  3195. extern const char AUTHORITY_SIGNKEY_3[];
  3196. /** Helper: Test that two networkstatus_voter_info_t do in fact represent the
  3197. * same voting authority, and that they do in fact have all the same
  3198. * information. */
  3199. static void
  3200. test_same_voter(networkstatus_voter_info_t *v1,
  3201. networkstatus_voter_info_t *v2)
  3202. {
  3203. test_streq(v1->nickname, v2->nickname);
  3204. test_memeq(v1->identity_digest, v2->identity_digest, DIGEST_LEN);
  3205. test_streq(v1->address, v2->address);
  3206. test_eq(v1->addr, v2->addr);
  3207. test_eq(v1->dir_port, v2->dir_port);
  3208. test_eq(v1->or_port, v2->or_port);
  3209. test_streq(v1->contact, v2->contact);
  3210. test_memeq(v1->vote_digest, v2->vote_digest, DIGEST_LEN);
  3211. done:
  3212. ;
  3213. }
  3214. /** Run unit tests for getting the median of a list. */
  3215. static void
  3216. test_util_order_functions(void)
  3217. {
  3218. int lst[25], n = 0;
  3219. // int a=12,b=24,c=25,d=60,e=77;
  3220. #define median() median_int(lst, n)
  3221. lst[n++] = 12;
  3222. test_eq(12, median()); /* 12 */
  3223. lst[n++] = 77;
  3224. //smartlist_shuffle(sl);
  3225. test_eq(12, median()); /* 12, 77 */
  3226. lst[n++] = 77;
  3227. //smartlist_shuffle(sl);
  3228. test_eq(77, median()); /* 12, 77, 77 */
  3229. lst[n++] = 24;
  3230. test_eq(24, median()); /* 12,24,77,77 */
  3231. lst[n++] = 60;
  3232. lst[n++] = 12;
  3233. lst[n++] = 25;
  3234. //smartlist_shuffle(sl);
  3235. test_eq(25, median()); /* 12,12,24,25,60,77,77 */
  3236. #undef median
  3237. done:
  3238. ;
  3239. }
  3240. /** Helper: Make a new routerinfo containing the right information for a
  3241. * given vote_routerstatus_t. */
  3242. static routerinfo_t *
  3243. generate_ri_from_rs(const vote_routerstatus_t *vrs)
  3244. {
  3245. routerinfo_t *r;
  3246. const routerstatus_t *rs = &vrs->status;
  3247. static time_t published = 0;
  3248. r = tor_malloc_zero(sizeof(routerinfo_t));
  3249. memcpy(r->cache_info.identity_digest, rs->identity_digest, DIGEST_LEN);
  3250. memcpy(r->cache_info.signed_descriptor_digest, rs->descriptor_digest,
  3251. DIGEST_LEN);
  3252. r->cache_info.do_not_cache = 1;
  3253. r->cache_info.routerlist_index = -1;
  3254. r->cache_info.signed_descriptor_body =
  3255. tor_strdup("123456789012345678901234567890123");
  3256. r->cache_info.signed_descriptor_len =
  3257. strlen(r->cache_info.signed_descriptor_body);
  3258. r->exit_policy = smartlist_create();
  3259. r->cache_info.published_on = ++published + time(NULL);
  3260. return r;
  3261. }
  3262. /** Run unit tests for generating and parsing V3 consensus networkstatus
  3263. * documents. */
  3264. static void
  3265. test_v3_networkstatus(void)
  3266. {
  3267. authority_cert_t *cert1=NULL, *cert2=NULL, *cert3=NULL;
  3268. crypto_pk_env_t *sign_skey_1=NULL, *sign_skey_2=NULL, *sign_skey_3=NULL;
  3269. crypto_pk_env_t *sign_skey_leg1=NULL;
  3270. const char *msg=NULL;
  3271. time_t now = time(NULL);
  3272. networkstatus_voter_info_t *voter;
  3273. networkstatus_t *vote=NULL, *v1=NULL, *v2=NULL, *v3=NULL, *con=NULL;
  3274. vote_routerstatus_t *vrs;
  3275. routerstatus_t *rs;
  3276. char *v1_text=NULL, *v2_text=NULL, *v3_text=NULL, *consensus_text=NULL, *cp;
  3277. smartlist_t *votes = smartlist_create();
  3278. /* For generating the two other consensuses. */
  3279. char *detached_text1=NULL, *detached_text2=NULL;
  3280. char *consensus_text2=NULL, *consensus_text3=NULL;
  3281. networkstatus_t *con2=NULL, *con3=NULL;
  3282. ns_detached_signatures_t *dsig1=NULL, *dsig2=NULL;
  3283. /* Parse certificates and keys. */
  3284. cert1 = authority_cert_parse_from_string(AUTHORITY_CERT_1, NULL);
  3285. test_assert(cert1);
  3286. test_assert(cert1->is_cross_certified);
  3287. cert2 = authority_cert_parse_from_string(AUTHORITY_CERT_2, NULL);
  3288. test_assert(cert2);
  3289. cert3 = authority_cert_parse_from_string(AUTHORITY_CERT_3, NULL);
  3290. test_assert(cert3);
  3291. sign_skey_1 = crypto_new_pk_env();
  3292. sign_skey_2 = crypto_new_pk_env();
  3293. sign_skey_3 = crypto_new_pk_env();
  3294. sign_skey_leg1 = pk_generate(4);
  3295. test_assert(!crypto_pk_read_private_key_from_string(sign_skey_1,
  3296. AUTHORITY_SIGNKEY_1));
  3297. test_assert(!crypto_pk_read_private_key_from_string(sign_skey_2,
  3298. AUTHORITY_SIGNKEY_2));
  3299. test_assert(!crypto_pk_read_private_key_from_string(sign_skey_3,
  3300. AUTHORITY_SIGNKEY_3));
  3301. test_assert(!crypto_pk_cmp_keys(sign_skey_1, cert1->signing_key));
  3302. test_assert(!crypto_pk_cmp_keys(sign_skey_2, cert2->signing_key));
  3303. /*
  3304. * Set up a vote; generate it; try to parse it.
  3305. */
  3306. vote = tor_malloc_zero(sizeof(networkstatus_t));
  3307. vote->type = NS_TYPE_VOTE;
  3308. vote->published = now;
  3309. vote->valid_after = now+1000;
  3310. vote->fresh_until = now+2000;
  3311. vote->valid_until = now+3000;
  3312. vote->vote_seconds = 100;
  3313. vote->dist_seconds = 200;
  3314. vote->supported_methods = smartlist_create();
  3315. smartlist_split_string(vote->supported_methods, "1 2 3", NULL, 0, -1);
  3316. vote->client_versions = tor_strdup("0.1.2.14,0.1.2.15");
  3317. vote->server_versions = tor_strdup("0.1.2.14,0.1.2.15,0.1.2.16");
  3318. vote->known_flags = smartlist_create();
  3319. smartlist_split_string(vote->known_flags,
  3320. "Authority Exit Fast Guard Running Stable V2Dir Valid",
  3321. 0, SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  3322. vote->voters = smartlist_create();
  3323. voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
  3324. voter->nickname = tor_strdup("Voter1");
  3325. voter->address = tor_strdup("1.2.3.4");
  3326. voter->addr = 0x01020304;
  3327. voter->dir_port = 80;
  3328. voter->or_port = 9000;
  3329. voter->contact = tor_strdup("voter@example.com");
  3330. crypto_pk_get_digest(cert1->identity_key, voter->identity_digest);
  3331. smartlist_add(vote->voters, voter);
  3332. vote->cert = authority_cert_dup(cert1);
  3333. vote->net_params = smartlist_create();
  3334. smartlist_split_string(vote->net_params, "circuitwindow=101 foo=990",
  3335. NULL, 0, 0);
  3336. vote->routerstatus_list = smartlist_create();
  3337. /* add the first routerstatus. */
  3338. vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
  3339. rs = &vrs->status;
  3340. vrs->version = tor_strdup("0.1.2.14");
  3341. rs->published_on = now-1500;
  3342. strlcpy(rs->nickname, "router2", sizeof(rs->nickname));
  3343. memset(rs->identity_digest, 3, DIGEST_LEN);
  3344. memset(rs->descriptor_digest, 78, DIGEST_LEN);
  3345. rs->addr = 0x99008801;
  3346. rs->or_port = 443;
  3347. rs->dir_port = 8000;
  3348. /* all flags but running cleared */
  3349. rs->is_running = 1;
  3350. smartlist_add(vote->routerstatus_list, vrs);
  3351. test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs), &msg,0,0)>=0);
  3352. /* add the second routerstatus. */
  3353. vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
  3354. rs = &vrs->status;
  3355. vrs->version = tor_strdup("0.2.0.5");
  3356. rs->published_on = now-1000;
  3357. strlcpy(rs->nickname, "router1", sizeof(rs->nickname));
  3358. memset(rs->identity_digest, 5, DIGEST_LEN);
  3359. memset(rs->descriptor_digest, 77, DIGEST_LEN);
  3360. rs->addr = 0x99009901;
  3361. rs->or_port = 443;
  3362. rs->dir_port = 0;
  3363. rs->is_exit = rs->is_stable = rs->is_fast = rs->is_running =
  3364. rs->is_valid = rs->is_v2_dir = rs->is_possible_guard = 1;
  3365. smartlist_add(vote->routerstatus_list, vrs);
  3366. test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs), &msg,0,0)>=0);
  3367. /* add the third routerstatus. */
  3368. vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
  3369. rs = &vrs->status;
  3370. vrs->version = tor_strdup("0.1.0.3");
  3371. rs->published_on = now-1000;
  3372. strlcpy(rs->nickname, "router3", sizeof(rs->nickname));
  3373. memset(rs->identity_digest, 33, DIGEST_LEN);
  3374. memset(rs->descriptor_digest, 79, DIGEST_LEN);
  3375. rs->addr = 0xAA009901;
  3376. rs->or_port = 400;
  3377. rs->dir_port = 9999;
  3378. rs->is_authority = rs->is_exit = rs->is_stable = rs->is_fast =
  3379. rs->is_running = rs->is_valid = rs->is_v2_dir = rs->is_possible_guard = 1;
  3380. smartlist_add(vote->routerstatus_list, vrs);
  3381. test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs), &msg,0,0)>=0);
  3382. /* add a fourth routerstatus that is not running. */
  3383. vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
  3384. rs = &vrs->status;
  3385. vrs->version = tor_strdup("0.1.6.3");
  3386. rs->published_on = now-1000;
  3387. strlcpy(rs->nickname, "router4", sizeof(rs->nickname));
  3388. memset(rs->identity_digest, 34, DIGEST_LEN);
  3389. memset(rs->descriptor_digest, 48, DIGEST_LEN);
  3390. rs->addr = 0xC0000203;
  3391. rs->or_port = 500;
  3392. rs->dir_port = 1999;
  3393. /* Running flag (and others) cleared */
  3394. smartlist_add(vote->routerstatus_list, vrs);
  3395. test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs), &msg,0,0)>=0);
  3396. /* dump the vote and try to parse it. */
  3397. v1_text = format_networkstatus_vote(sign_skey_1, vote);
  3398. test_assert(v1_text);
  3399. v1 = networkstatus_parse_vote_from_string(v1_text, NULL, NS_TYPE_VOTE);
  3400. test_assert(v1);
  3401. /* Make sure the parsed thing was right. */
  3402. test_eq(v1->type, NS_TYPE_VOTE);
  3403. test_eq(v1->published, vote->published);
  3404. test_eq(v1->valid_after, vote->valid_after);
  3405. test_eq(v1->fresh_until, vote->fresh_until);
  3406. test_eq(v1->valid_until, vote->valid_until);
  3407. test_eq(v1->vote_seconds, vote->vote_seconds);
  3408. test_eq(v1->dist_seconds, vote->dist_seconds);
  3409. test_streq(v1->client_versions, vote->client_versions);
  3410. test_streq(v1->server_versions, vote->server_versions);
  3411. test_assert(v1->voters && smartlist_len(v1->voters));
  3412. voter = smartlist_get(v1->voters, 0);
  3413. test_streq(voter->nickname, "Voter1");
  3414. test_streq(voter->address, "1.2.3.4");
  3415. test_eq(voter->addr, 0x01020304);
  3416. test_eq(voter->dir_port, 80);
  3417. test_eq(voter->or_port, 9000);
  3418. test_streq(voter->contact, "voter@example.com");
  3419. test_assert(v1->cert);
  3420. test_assert(!crypto_pk_cmp_keys(sign_skey_1, v1->cert->signing_key));
  3421. cp = smartlist_join_strings(v1->known_flags, ":", 0, NULL);
  3422. test_streq(cp, "Authority:Exit:Fast:Guard:Running:Stable:V2Dir:Valid");
  3423. tor_free(cp);
  3424. test_eq(smartlist_len(v1->routerstatus_list), 4);
  3425. /* Check the first routerstatus. */
  3426. vrs = smartlist_get(v1->routerstatus_list, 0);
  3427. rs = &vrs->status;
  3428. test_streq(vrs->version, "0.1.2.14");
  3429. test_eq(rs->published_on, now-1500);
  3430. test_streq(rs->nickname, "router2");
  3431. test_memeq(rs->identity_digest,
  3432. "\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3",
  3433. DIGEST_LEN);
  3434. test_memeq(rs->descriptor_digest, "NNNNNNNNNNNNNNNNNNNN", DIGEST_LEN);
  3435. test_eq(rs->addr, 0x99008801);
  3436. test_eq(rs->or_port, 443);
  3437. test_eq(rs->dir_port, 8000);
  3438. test_eq(vrs->flags, U64_LITERAL(16)); // no flags except "running"
  3439. /* Check the second routerstatus. */
  3440. vrs = smartlist_get(v1->routerstatus_list, 1);
  3441. rs = &vrs->status;
  3442. test_streq(vrs->version, "0.2.0.5");
  3443. test_eq(rs->published_on, now-1000);
  3444. test_streq(rs->nickname, "router1");
  3445. test_memeq(rs->identity_digest,
  3446. "\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5",
  3447. DIGEST_LEN);
  3448. test_memeq(rs->descriptor_digest, "MMMMMMMMMMMMMMMMMMMM", DIGEST_LEN);
  3449. test_eq(rs->addr, 0x99009901);
  3450. test_eq(rs->or_port, 443);
  3451. test_eq(rs->dir_port, 0);
  3452. test_eq(vrs->flags, U64_LITERAL(254)); // all flags except "authority."
  3453. {
  3454. measured_bw_line_t mbw;
  3455. memset(mbw.node_id, 33, sizeof(mbw.node_id));
  3456. mbw.bw = 1024;
  3457. test_assert(measured_bw_line_apply(&mbw,
  3458. v1->routerstatus_list) == 1);
  3459. vrs = smartlist_get(v1->routerstatus_list, 2);
  3460. test_assert(vrs->status.has_measured_bw &&
  3461. vrs->status.measured_bw == 1024);
  3462. }
  3463. /* Generate second vote. It disagrees on some of the times,
  3464. * and doesn't list versions, and knows some crazy flags */
  3465. vote->published = now+1;
  3466. vote->fresh_until = now+3005;
  3467. vote->dist_seconds = 300;
  3468. authority_cert_free(vote->cert);
  3469. vote->cert = authority_cert_dup(cert2);
  3470. vote->net_params = smartlist_create();
  3471. smartlist_split_string(vote->net_params, "bar=2000000000 circuitwindow=20",
  3472. NULL, 0, 0);
  3473. tor_free(vote->client_versions);
  3474. tor_free(vote->server_versions);
  3475. voter = smartlist_get(vote->voters, 0);
  3476. tor_free(voter->nickname);
  3477. tor_free(voter->address);
  3478. voter->nickname = tor_strdup("Voter2");
  3479. voter->address = tor_strdup("2.3.4.5");
  3480. voter->addr = 0x02030405;
  3481. crypto_pk_get_digest(cert2->identity_key, voter->identity_digest);
  3482. smartlist_add(vote->known_flags, tor_strdup("MadeOfCheese"));
  3483. smartlist_add(vote->known_flags, tor_strdup("MadeOfTin"));
  3484. smartlist_sort_strings(vote->known_flags);
  3485. vrs = smartlist_get(vote->routerstatus_list, 2);
  3486. smartlist_del_keeporder(vote->routerstatus_list, 2);
  3487. tor_free(vrs->version);
  3488. tor_free(vrs);
  3489. vrs = smartlist_get(vote->routerstatus_list, 0);
  3490. vrs->status.is_fast = 1;
  3491. /* generate and parse. */
  3492. v2_text = format_networkstatus_vote(sign_skey_2, vote);
  3493. test_assert(v2_text);
  3494. v2 = networkstatus_parse_vote_from_string(v2_text, NULL, NS_TYPE_VOTE);
  3495. test_assert(v2);
  3496. /* Check that flags come out right.*/
  3497. cp = smartlist_join_strings(v2->known_flags, ":", 0, NULL);
  3498. test_streq(cp, "Authority:Exit:Fast:Guard:MadeOfCheese:MadeOfTin:"
  3499. "Running:Stable:V2Dir:Valid");
  3500. tor_free(cp);
  3501. vrs = smartlist_get(v2->routerstatus_list, 1);
  3502. /* 1023 - authority(1) - madeofcheese(16) - madeoftin(32) */
  3503. test_eq(vrs->flags, U64_LITERAL(974));
  3504. /* Generate the third vote. */
  3505. vote->published = now;
  3506. vote->fresh_until = now+2003;
  3507. vote->dist_seconds = 250;
  3508. authority_cert_free(vote->cert);
  3509. vote->cert = authority_cert_dup(cert3);
  3510. vote->net_params = smartlist_create();
  3511. smartlist_split_string(vote->net_params, "circuitwindow=80 foo=660",
  3512. NULL, 0, 0);
  3513. smartlist_add(vote->supported_methods, tor_strdup("4"));
  3514. vote->client_versions = tor_strdup("0.1.2.14,0.1.2.17");
  3515. vote->server_versions = tor_strdup("0.1.2.10,0.1.2.15,0.1.2.16");
  3516. voter = smartlist_get(vote->voters, 0);
  3517. tor_free(voter->nickname);
  3518. tor_free(voter->address);
  3519. voter->nickname = tor_strdup("Voter3");
  3520. voter->address = tor_strdup("3.4.5.6");
  3521. voter->addr = 0x03040506;
  3522. crypto_pk_get_digest(cert3->identity_key, voter->identity_digest);
  3523. /* This one has a legacy id. */
  3524. memset(voter->legacy_id_digest, (int)'A', DIGEST_LEN);
  3525. vrs = smartlist_get(vote->routerstatus_list, 0);
  3526. smartlist_del_keeporder(vote->routerstatus_list, 0);
  3527. tor_free(vrs->version);
  3528. tor_free(vrs);
  3529. vrs = smartlist_get(vote->routerstatus_list, 0);
  3530. memset(vrs->status.descriptor_digest, (int)'Z', DIGEST_LEN);
  3531. test_assert(router_add_to_routerlist(generate_ri_from_rs(vrs), &msg,0,0)>=0);
  3532. v3_text = format_networkstatus_vote(sign_skey_3, vote);
  3533. test_assert(v3_text);
  3534. v3 = networkstatus_parse_vote_from_string(v3_text, NULL, NS_TYPE_VOTE);
  3535. test_assert(v3);
  3536. /* Compute a consensus as voter 3. */
  3537. smartlist_add(votes, v3);
  3538. smartlist_add(votes, v1);
  3539. smartlist_add(votes, v2);
  3540. consensus_text = networkstatus_compute_consensus(votes, 3,
  3541. cert3->identity_key,
  3542. sign_skey_3,
  3543. "AAAAAAAAAAAAAAAAAAAA",
  3544. sign_skey_leg1);
  3545. test_assert(consensus_text);
  3546. con = networkstatus_parse_vote_from_string(consensus_text, NULL,
  3547. NS_TYPE_CONSENSUS);
  3548. test_assert(con);
  3549. //log_notice(LD_GENERAL, "<<%s>>\n<<%s>>\n<<%s>>\n",
  3550. // v1_text, v2_text, v3_text);
  3551. /* Check consensus contents. */
  3552. test_assert(con->type == NS_TYPE_CONSENSUS);
  3553. test_eq(con->published, 0); /* this field only appears in votes. */
  3554. test_eq(con->valid_after, now+1000);
  3555. test_eq(con->fresh_until, now+2003); /* median */
  3556. test_eq(con->valid_until, now+3000);
  3557. test_eq(con->vote_seconds, 100);
  3558. test_eq(con->dist_seconds, 250); /* median */
  3559. test_streq(con->client_versions, "0.1.2.14");
  3560. test_streq(con->server_versions, "0.1.2.15,0.1.2.16");
  3561. cp = smartlist_join_strings(v2->known_flags, ":", 0, NULL);
  3562. test_streq(cp, "Authority:Exit:Fast:Guard:MadeOfCheese:MadeOfTin:"
  3563. "Running:Stable:V2Dir:Valid");
  3564. tor_free(cp);
  3565. cp = smartlist_join_strings(con->net_params, ":", 0, NULL);
  3566. test_streq(cp, "bar=2000000000:circuitwindow=80:foo=660");
  3567. tor_free(cp);
  3568. test_eq(4, smartlist_len(con->voters)); /*3 voters, 1 legacy key.*/
  3569. /* The voter id digests should be in this order. */
  3570. test_assert(memcmp(cert2->cache_info.identity_digest,
  3571. cert1->cache_info.identity_digest,DIGEST_LEN)<0);
  3572. test_assert(memcmp(cert1->cache_info.identity_digest,
  3573. cert3->cache_info.identity_digest,DIGEST_LEN)<0);
  3574. test_same_voter(smartlist_get(con->voters, 1),
  3575. smartlist_get(v2->voters, 0));
  3576. test_same_voter(smartlist_get(con->voters, 2),
  3577. smartlist_get(v1->voters, 0));
  3578. test_same_voter(smartlist_get(con->voters, 3),
  3579. smartlist_get(v3->voters, 0));
  3580. test_assert(!con->cert);
  3581. test_eq(2, smartlist_len(con->routerstatus_list));
  3582. /* There should be two listed routers: one with identity 3, one with
  3583. * identity 5. */
  3584. /* This one showed up in 2 digests. */
  3585. rs = smartlist_get(con->routerstatus_list, 0);
  3586. test_memeq(rs->identity_digest,
  3587. "\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3\x3",
  3588. DIGEST_LEN);
  3589. test_memeq(rs->descriptor_digest, "NNNNNNNNNNNNNNNNNNNN", DIGEST_LEN);
  3590. test_assert(!rs->is_authority);
  3591. test_assert(!rs->is_exit);
  3592. test_assert(!rs->is_fast);
  3593. test_assert(!rs->is_possible_guard);
  3594. test_assert(!rs->is_stable);
  3595. test_assert(rs->is_running); /* If it wasn't running it wouldn't be here */
  3596. test_assert(!rs->is_v2_dir);
  3597. test_assert(!rs->is_valid);
  3598. test_assert(!rs->is_named);
  3599. /* XXXX check version */
  3600. rs = smartlist_get(con->routerstatus_list, 1);
  3601. /* This one showed up in 3 digests. Twice with ID 'M', once with 'Z'. */
  3602. test_memeq(rs->identity_digest,
  3603. "\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5\x5",
  3604. DIGEST_LEN);
  3605. test_streq(rs->nickname, "router1");
  3606. test_memeq(rs->descriptor_digest, "MMMMMMMMMMMMMMMMMMMM", DIGEST_LEN);
  3607. test_eq(rs->published_on, now-1000);
  3608. test_eq(rs->addr, 0x99009901);
  3609. test_eq(rs->or_port, 443);
  3610. test_eq(rs->dir_port, 0);
  3611. test_assert(!rs->is_authority);
  3612. test_assert(rs->is_exit);
  3613. test_assert(rs->is_fast);
  3614. test_assert(rs->is_possible_guard);
  3615. test_assert(rs->is_stable);
  3616. test_assert(rs->is_running);
  3617. test_assert(rs->is_v2_dir);
  3618. test_assert(rs->is_valid);
  3619. test_assert(!rs->is_named);
  3620. /* XXXX check version */
  3621. // x231
  3622. // x213
  3623. /* Check signatures. the first voter is a pseudo-entry with a legacy key.
  3624. * The second one hasn't signed. The fourth one has signed: validate it. */
  3625. voter = smartlist_get(con->voters, 1);
  3626. test_assert(!voter->signature);
  3627. test_assert(!voter->good_signature);
  3628. test_assert(!voter->bad_signature);
  3629. voter = smartlist_get(con->voters, 3);
  3630. test_assert(voter->signature);
  3631. test_assert(!voter->good_signature);
  3632. test_assert(!voter->bad_signature);
  3633. test_assert(!networkstatus_check_voter_signature(con,
  3634. smartlist_get(con->voters, 3),
  3635. cert3));
  3636. test_assert(voter->signature);
  3637. test_assert(voter->good_signature);
  3638. test_assert(!voter->bad_signature);
  3639. {
  3640. const char *msg=NULL;
  3641. /* Compute the other two signed consensuses. */
  3642. smartlist_shuffle(votes);
  3643. consensus_text2 = networkstatus_compute_consensus(votes, 3,
  3644. cert2->identity_key,
  3645. sign_skey_2, NULL,NULL);
  3646. smartlist_shuffle(votes);
  3647. consensus_text3 = networkstatus_compute_consensus(votes, 3,
  3648. cert1->identity_key,
  3649. sign_skey_1, NULL,NULL);
  3650. test_assert(consensus_text2);
  3651. test_assert(consensus_text3);
  3652. con2 = networkstatus_parse_vote_from_string(consensus_text2, NULL,
  3653. NS_TYPE_CONSENSUS);
  3654. con3 = networkstatus_parse_vote_from_string(consensus_text3, NULL,
  3655. NS_TYPE_CONSENSUS);
  3656. test_assert(con2);
  3657. test_assert(con3);
  3658. /* All three should have the same digest. */
  3659. test_memeq(con->networkstatus_digest, con2->networkstatus_digest,
  3660. DIGEST_LEN);
  3661. test_memeq(con->networkstatus_digest, con3->networkstatus_digest,
  3662. DIGEST_LEN);
  3663. /* Extract a detached signature from con3. */
  3664. detached_text1 = networkstatus_get_detached_signatures(con3);
  3665. tor_assert(detached_text1);
  3666. /* Try to parse it. */
  3667. dsig1 = networkstatus_parse_detached_signatures(detached_text1, NULL);
  3668. tor_assert(dsig1);
  3669. /* Are parsed values as expected? */
  3670. test_eq(dsig1->valid_after, con3->valid_after);
  3671. test_eq(dsig1->fresh_until, con3->fresh_until);
  3672. test_eq(dsig1->valid_until, con3->valid_until);
  3673. test_memeq(dsig1->networkstatus_digest, con3->networkstatus_digest,
  3674. DIGEST_LEN);
  3675. test_eq(1, smartlist_len(dsig1->signatures));
  3676. voter = smartlist_get(dsig1->signatures, 0);
  3677. test_memeq(voter->identity_digest, cert1->cache_info.identity_digest,
  3678. DIGEST_LEN);
  3679. /* Try adding it to con2. */
  3680. detached_text2 = networkstatus_get_detached_signatures(con2);
  3681. test_eq(1, networkstatus_add_detached_signatures(con2, dsig1, &msg));
  3682. tor_free(detached_text2);
  3683. detached_text2 = networkstatus_get_detached_signatures(con2);
  3684. //printf("\n<%s>\n", detached_text2);
  3685. dsig2 = networkstatus_parse_detached_signatures(detached_text2, NULL);
  3686. test_assert(dsig2);
  3687. /*
  3688. printf("\n");
  3689. SMARTLIST_FOREACH(dsig2->signatures, networkstatus_voter_info_t *, vi, {
  3690. char hd[64];
  3691. base16_encode(hd, sizeof(hd), vi->identity_digest, DIGEST_LEN);
  3692. printf("%s\n", hd);
  3693. });
  3694. */
  3695. test_eq(2, smartlist_len(dsig2->signatures));
  3696. /* Try adding to con2 twice; verify that nothing changes. */
  3697. test_eq(0, networkstatus_add_detached_signatures(con2, dsig1, &msg));
  3698. /* Add to con. */
  3699. test_eq(2, networkstatus_add_detached_signatures(con, dsig2, &msg));
  3700. /* Check signatures */
  3701. test_assert(!networkstatus_check_voter_signature(con,
  3702. smartlist_get(con->voters, 1),
  3703. cert2));
  3704. test_assert(!networkstatus_check_voter_signature(con,
  3705. smartlist_get(con->voters, 2),
  3706. cert1));
  3707. }
  3708. done:
  3709. smartlist_free(votes);
  3710. tor_free(v1_text);
  3711. tor_free(v2_text);
  3712. tor_free(v3_text);
  3713. tor_free(consensus_text);
  3714. if (vote)
  3715. networkstatus_vote_free(vote);
  3716. if (v1)
  3717. networkstatus_vote_free(v1);
  3718. if (v2)
  3719. networkstatus_vote_free(v2);
  3720. if (v3)
  3721. networkstatus_vote_free(v3);
  3722. if (con)
  3723. networkstatus_vote_free(con);
  3724. if (sign_skey_1)
  3725. crypto_free_pk_env(sign_skey_1);
  3726. if (sign_skey_2)
  3727. crypto_free_pk_env(sign_skey_2);
  3728. if (sign_skey_3)
  3729. crypto_free_pk_env(sign_skey_3);
  3730. if (sign_skey_leg1)
  3731. crypto_free_pk_env(sign_skey_leg1);
  3732. if (cert1)
  3733. authority_cert_free(cert1);
  3734. if (cert2)
  3735. authority_cert_free(cert2);
  3736. if (cert3)
  3737. authority_cert_free(cert3);
  3738. tor_free(consensus_text2);
  3739. tor_free(consensus_text3);
  3740. tor_free(detached_text1);
  3741. tor_free(detached_text2);
  3742. if (con2)
  3743. networkstatus_vote_free(con2);
  3744. if (con3)
  3745. networkstatus_vote_free(con3);
  3746. if (dsig1)
  3747. ns_detached_signatures_free(dsig1);
  3748. if (dsig2)
  3749. ns_detached_signatures_free(dsig2);
  3750. }
  3751. /** Helper: Parse the exit policy string in <b>policy_str</b>, and make sure
  3752. * that policies_summarize() produces the string <b>expected_summary</b> from
  3753. * it. */
  3754. static void
  3755. test_policy_summary_helper(const char *policy_str,
  3756. const char *expected_summary)
  3757. {
  3758. config_line_t line;
  3759. smartlist_t *policy = smartlist_create();
  3760. char *summary = NULL;
  3761. int r;
  3762. line.key = (char*)"foo";
  3763. line.value = (char *)policy_str;
  3764. line.next = NULL;
  3765. r = policies_parse_exit_policy(&line, &policy, 0, NULL);
  3766. test_eq(r, 0);
  3767. summary = policy_summarize(policy);
  3768. test_assert(summary != NULL);
  3769. test_streq(summary, expected_summary);
  3770. done:
  3771. tor_free(summary);
  3772. if (policy)
  3773. addr_policy_list_free(policy);
  3774. }
  3775. /** Run unit tests for generating summary lines of exit policies */
  3776. static void
  3777. test_policies(void)
  3778. {
  3779. int i;
  3780. smartlist_t *policy = NULL, *policy2 = NULL;
  3781. addr_policy_t *p;
  3782. tor_addr_t tar;
  3783. config_line_t line;
  3784. smartlist_t *sm = NULL;
  3785. char *policy_str = NULL;
  3786. policy = smartlist_create();
  3787. p = router_parse_addr_policy_item_from_string("reject 192.168.0.0/16:*",-1);
  3788. test_assert(p != NULL);
  3789. test_eq(ADDR_POLICY_REJECT, p->policy_type);
  3790. tor_addr_from_ipv4h(&tar, 0xc0a80000u);
  3791. test_eq(0, tor_addr_compare(&p->addr, &tar, CMP_EXACT));
  3792. test_eq(16, p->maskbits);
  3793. test_eq(1, p->prt_min);
  3794. test_eq(65535, p->prt_max);
  3795. smartlist_add(policy, p);
  3796. test_assert(ADDR_POLICY_ACCEPTED ==
  3797. compare_addr_to_addr_policy(0x01020304u, 2, policy));
  3798. test_assert(ADDR_POLICY_PROBABLY_ACCEPTED ==
  3799. compare_addr_to_addr_policy(0, 2, policy));
  3800. test_assert(ADDR_POLICY_REJECTED ==
  3801. compare_addr_to_addr_policy(0xc0a80102, 2, policy));
  3802. policy2 = NULL;
  3803. test_assert(0 == policies_parse_exit_policy(NULL, &policy2, 1, NULL));
  3804. test_assert(policy2);
  3805. test_assert(!exit_policy_is_general_exit(policy));
  3806. test_assert(exit_policy_is_general_exit(policy2));
  3807. test_assert(!exit_policy_is_general_exit(NULL));
  3808. test_assert(cmp_addr_policies(policy, policy2));
  3809. test_assert(cmp_addr_policies(policy, NULL));
  3810. test_assert(!cmp_addr_policies(policy2, policy2));
  3811. test_assert(!cmp_addr_policies(NULL, NULL));
  3812. test_assert(!policy_is_reject_star(policy2));
  3813. test_assert(policy_is_reject_star(policy));
  3814. test_assert(policy_is_reject_star(NULL));
  3815. addr_policy_list_free(policy);
  3816. policy = NULL;
  3817. /* make sure compacting logic works. */
  3818. policy = NULL;
  3819. line.key = (char*)"foo";
  3820. line.value = (char*)"accept *:80,reject private:*,reject *:*";
  3821. line.next = NULL;
  3822. test_assert(0 == policies_parse_exit_policy(&line, &policy, 0, NULL));
  3823. test_assert(policy);
  3824. //test_streq(policy->string, "accept *:80");
  3825. //test_streq(policy->next->string, "reject *:*");
  3826. test_eq(smartlist_len(policy), 2);
  3827. /* test policy summaries */
  3828. /* check if we properly ignore private IP addresses */
  3829. test_policy_summary_helper("reject 192.168.0.0/16:*,"
  3830. "reject 0.0.0.0/8:*,"
  3831. "reject 10.0.0.0/8:*,"
  3832. "accept *:10-30,"
  3833. "accept *:90,"
  3834. "reject *:*",
  3835. "accept 10-30,90");
  3836. /* check all accept policies, and proper counting of rejects */
  3837. test_policy_summary_helper("reject 11.0.0.0/9:80,"
  3838. "reject 12.0.0.0/9:80,"
  3839. "reject 13.0.0.0/9:80,"
  3840. "reject 14.0.0.0/9:80,"
  3841. "accept *:*", "accept 1-65535");
  3842. test_policy_summary_helper("reject 11.0.0.0/9:80,"
  3843. "reject 12.0.0.0/9:80,"
  3844. "reject 13.0.0.0/9:80,"
  3845. "reject 14.0.0.0/9:80,"
  3846. "reject 15.0.0.0:81,"
  3847. "accept *:*", "accept 1-65535");
  3848. test_policy_summary_helper("reject 11.0.0.0/9:80,"
  3849. "reject 12.0.0.0/9:80,"
  3850. "reject 13.0.0.0/9:80,"
  3851. "reject 14.0.0.0/9:80,"
  3852. "reject 15.0.0.0:80,"
  3853. "accept *:*",
  3854. "reject 80");
  3855. /* no exits */
  3856. test_policy_summary_helper("accept 11.0.0.0/9:80,"
  3857. "reject *:*",
  3858. "reject 1-65535");
  3859. /* port merging */
  3860. test_policy_summary_helper("accept *:80,"
  3861. "accept *:81,"
  3862. "accept *:100-110,"
  3863. "accept *:111,"
  3864. "reject *:*",
  3865. "accept 80-81,100-111");
  3866. /* border ports */
  3867. test_policy_summary_helper("accept *:1,"
  3868. "accept *:3,"
  3869. "accept *:65535,"
  3870. "reject *:*",
  3871. "accept 1,3,65535");
  3872. /* holes */
  3873. test_policy_summary_helper("accept *:1,"
  3874. "accept *:3,"
  3875. "accept *:5,"
  3876. "accept *:7,"
  3877. "reject *:*",
  3878. "accept 1,3,5,7");
  3879. test_policy_summary_helper("reject *:1,"
  3880. "reject *:3,"
  3881. "reject *:5,"
  3882. "reject *:7,"
  3883. "accept *:*",
  3884. "reject 1,3,5,7");
  3885. /* truncation ports */
  3886. sm = smartlist_create();
  3887. for (i=1; i<2000; i+=2) {
  3888. char buf[POLICY_BUF_LEN];
  3889. tor_snprintf(buf, sizeof(buf), "reject *:%d", i);
  3890. smartlist_add(sm, tor_strdup(buf));
  3891. }
  3892. smartlist_add(sm, tor_strdup("accept *:*"));
  3893. policy_str = smartlist_join_strings(sm, ",", 0, NULL);
  3894. test_policy_summary_helper( policy_str,
  3895. "accept 2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,"
  3896. "46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,"
  3897. "92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,"
  3898. "130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,"
  3899. "166,168,170,172,174,176,178,180,182,184,186,188,190,192,194,196,198,200,"
  3900. "202,204,206,208,210,212,214,216,218,220,222,224,226,228,230,232,234,236,"
  3901. "238,240,242,244,246,248,250,252,254,256,258,260,262,264,266,268,270,272,"
  3902. "274,276,278,280,282,284,286,288,290,292,294,296,298,300,302,304,306,308,"
  3903. "310,312,314,316,318,320,322,324,326,328,330,332,334,336,338,340,342,344,"
  3904. "346,348,350,352,354,356,358,360,362,364,366,368,370,372,374,376,378,380,"
  3905. "382,384,386,388,390,392,394,396,398,400,402,404,406,408,410,412,414,416,"
  3906. "418,420,422,424,426,428,430,432,434,436,438,440,442,444,446,448,450,452,"
  3907. "454,456,458,460,462,464,466,468,470,472,474,476,478,480,482,484,486,488,"
  3908. "490,492,494,496,498,500,502,504,506,508,510,512,514,516,518,520,522");
  3909. done:
  3910. if (policy)
  3911. addr_policy_list_free(policy);
  3912. if (policy2)
  3913. addr_policy_list_free(policy2);
  3914. tor_free(policy_str);
  3915. if (sm) {
  3916. SMARTLIST_FOREACH(sm, char *, s, tor_free(s));
  3917. smartlist_free(sm);
  3918. }
  3919. }
  3920. /** Run AES performance benchmarks. */
  3921. static void
  3922. bench_aes(void)
  3923. {
  3924. int len, i;
  3925. char *b1, *b2;
  3926. crypto_cipher_env_t *c;
  3927. struct timeval start, end;
  3928. const int iters = 100000;
  3929. uint64_t nsec;
  3930. c = crypto_new_cipher_env();
  3931. crypto_cipher_generate_key(c);
  3932. crypto_cipher_encrypt_init_cipher(c);
  3933. for (len = 1; len <= 8192; len *= 2) {
  3934. b1 = tor_malloc_zero(len);
  3935. b2 = tor_malloc_zero(len);
  3936. tor_gettimeofday(&start);
  3937. for (i = 0; i < iters; ++i) {
  3938. crypto_cipher_encrypt(c, b1, b2, len);
  3939. }
  3940. tor_gettimeofday(&end);
  3941. tor_free(b1);
  3942. tor_free(b2);
  3943. nsec = (uint64_t) tv_udiff(&start,&end);
  3944. nsec *= 1000;
  3945. nsec /= (iters*len);
  3946. printf("%d bytes: "U64_FORMAT" nsec per byte\n", len,
  3947. U64_PRINTF_ARG(nsec));
  3948. }
  3949. crypto_free_cipher_env(c);
  3950. }
  3951. /** Run digestmap_t performance benchmarks. */
  3952. static void
  3953. bench_dmap(void)
  3954. {
  3955. smartlist_t *sl = smartlist_create();
  3956. smartlist_t *sl2 = smartlist_create();
  3957. struct timeval start, end, pt2, pt3, pt4;
  3958. const int iters = 10000;
  3959. const int elts = 4000;
  3960. const int fpostests = 1000000;
  3961. char d[20];
  3962. int i,n=0, fp = 0;
  3963. digestmap_t *dm = digestmap_new();
  3964. digestset_t *ds = digestset_new(elts);
  3965. for (i = 0; i < elts; ++i) {
  3966. crypto_rand(d, 20);
  3967. smartlist_add(sl, tor_memdup(d, 20));
  3968. }
  3969. for (i = 0; i < elts; ++i) {
  3970. crypto_rand(d, 20);
  3971. smartlist_add(sl2, tor_memdup(d, 20));
  3972. }
  3973. printf("nbits=%d\n", ds->mask+1);
  3974. tor_gettimeofday(&start);
  3975. for (i = 0; i < iters; ++i) {
  3976. SMARTLIST_FOREACH(sl, const char *, cp, digestmap_set(dm, cp, (void*)1));
  3977. }
  3978. tor_gettimeofday(&pt2);
  3979. for (i = 0; i < iters; ++i) {
  3980. SMARTLIST_FOREACH(sl, const char *, cp, digestmap_get(dm, cp));
  3981. SMARTLIST_FOREACH(sl2, const char *, cp, digestmap_get(dm, cp));
  3982. }
  3983. tor_gettimeofday(&pt3);
  3984. for (i = 0; i < iters; ++i) {
  3985. SMARTLIST_FOREACH(sl, const char *, cp, digestset_add(ds, cp));
  3986. }
  3987. tor_gettimeofday(&pt4);
  3988. for (i = 0; i < iters; ++i) {
  3989. SMARTLIST_FOREACH(sl, const char *, cp, n += digestset_isin(ds, cp));
  3990. SMARTLIST_FOREACH(sl2, const char *, cp, n += digestset_isin(ds, cp));
  3991. }
  3992. tor_gettimeofday(&end);
  3993. for (i = 0; i < fpostests; ++i) {
  3994. crypto_rand(d, 20);
  3995. if (digestset_isin(ds, d)) ++fp;
  3996. }
  3997. printf("%ld\n",(unsigned long)tv_udiff(&start, &pt2));
  3998. printf("%ld\n",(unsigned long)tv_udiff(&pt2, &pt3));
  3999. printf("%ld\n",(unsigned long)tv_udiff(&pt3, &pt4));
  4000. printf("%ld\n",(unsigned long)tv_udiff(&pt4, &end));
  4001. printf("-- %d\n", n);
  4002. printf("++ %f\n", fp/(double)fpostests);
  4003. digestmap_free(dm, NULL);
  4004. digestset_free(ds);
  4005. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  4006. SMARTLIST_FOREACH(sl2, char *, cp, tor_free(cp));
  4007. smartlist_free(sl);
  4008. smartlist_free(sl2);
  4009. }
  4010. /** Run unittests for memory pool allocator */
  4011. static void
  4012. test_util_mempool(void)
  4013. {
  4014. mp_pool_t *pool = NULL;
  4015. smartlist_t *allocated = NULL;
  4016. int i;
  4017. pool = mp_pool_new(1, 100);
  4018. test_assert(pool);
  4019. test_assert(pool->new_chunk_capacity >= 100);
  4020. test_assert(pool->item_alloc_size >= sizeof(void*)+1);
  4021. mp_pool_destroy(pool);
  4022. pool = NULL;
  4023. pool = mp_pool_new(241, 2500);
  4024. test_assert(pool);
  4025. test_assert(pool->new_chunk_capacity >= 10);
  4026. test_assert(pool->item_alloc_size >= sizeof(void*)+241);
  4027. test_eq(pool->item_alloc_size & 0x03, 0);
  4028. test_assert(pool->new_chunk_capacity < 60);
  4029. allocated = smartlist_create();
  4030. for (i = 0; i < 20000; ++i) {
  4031. if (smartlist_len(allocated) < 20 || crypto_rand_int(2)) {
  4032. void *m = mp_pool_get(pool);
  4033. memset(m, 0x09, 241);
  4034. smartlist_add(allocated, m);
  4035. //printf("%d: %p\n", i, m);
  4036. //mp_pool_assert_ok(pool);
  4037. } else {
  4038. int idx = crypto_rand_int(smartlist_len(allocated));
  4039. void *m = smartlist_get(allocated, idx);
  4040. //printf("%d: free %p\n", i, m);
  4041. smartlist_del(allocated, idx);
  4042. mp_pool_release(m);
  4043. //mp_pool_assert_ok(pool);
  4044. }
  4045. if (crypto_rand_int(777)==0)
  4046. mp_pool_clean(pool, 1, 1);
  4047. if (i % 777)
  4048. mp_pool_assert_ok(pool);
  4049. }
  4050. done:
  4051. if (allocated) {
  4052. SMARTLIST_FOREACH(allocated, void *, m, mp_pool_release(m));
  4053. mp_pool_assert_ok(pool);
  4054. mp_pool_clean(pool, 0, 0);
  4055. mp_pool_assert_ok(pool);
  4056. smartlist_free(allocated);
  4057. }
  4058. if (pool)
  4059. mp_pool_destroy(pool);
  4060. }
  4061. /** Run unittests for memory area allocator */
  4062. static void
  4063. test_util_memarea(void)
  4064. {
  4065. memarea_t *area = memarea_new();
  4066. char *p1, *p2, *p3, *p1_orig;
  4067. void *malloced_ptr = NULL;
  4068. int i;
  4069. test_assert(area);
  4070. p1_orig = p1 = memarea_alloc(area,64);
  4071. p2 = memarea_alloc_zero(area,52);
  4072. p3 = memarea_alloc(area,11);
  4073. test_assert(memarea_owns_ptr(area, p1));
  4074. test_assert(memarea_owns_ptr(area, p2));
  4075. test_assert(memarea_owns_ptr(area, p3));
  4076. /* Make sure we left enough space. */
  4077. test_assert(p1+64 <= p2);
  4078. test_assert(p2+52 <= p3);
  4079. /* Make sure we aligned. */
  4080. test_eq(((uintptr_t)p1) % sizeof(void*), 0);
  4081. test_eq(((uintptr_t)p2) % sizeof(void*), 0);
  4082. test_eq(((uintptr_t)p3) % sizeof(void*), 0);
  4083. test_assert(!memarea_owns_ptr(area, p3+8192));
  4084. test_assert(!memarea_owns_ptr(area, p3+30));
  4085. test_assert(tor_mem_is_zero(p2, 52));
  4086. /* Make sure we don't overalign. */
  4087. p1 = memarea_alloc(area, 1);
  4088. p2 = memarea_alloc(area, 1);
  4089. test_eq(p1+sizeof(void*), p2);
  4090. {
  4091. malloced_ptr = tor_malloc(64);
  4092. test_assert(!memarea_owns_ptr(area, malloced_ptr));
  4093. tor_free(malloced_ptr);
  4094. }
  4095. /* memarea_memdup */
  4096. {
  4097. malloced_ptr = tor_malloc(64);
  4098. crypto_rand((char*)malloced_ptr, 64);
  4099. p1 = memarea_memdup(area, malloced_ptr, 64);
  4100. test_assert(p1 != malloced_ptr);
  4101. test_memeq(p1, malloced_ptr, 64);
  4102. tor_free(malloced_ptr);
  4103. }
  4104. /* memarea_strdup. */
  4105. p1 = memarea_strdup(area,"");
  4106. p2 = memarea_strdup(area, "abcd");
  4107. test_assert(p1);
  4108. test_assert(p2);
  4109. test_streq(p1, "");
  4110. test_streq(p2, "abcd");
  4111. /* memarea_strndup. */
  4112. {
  4113. const char *s = "Ad ogni porta batte la morte e grida: il nome!";
  4114. /* (From Turandot, act 3.) */
  4115. size_t len = strlen(s);
  4116. p1 = memarea_strndup(area, s, 1000);
  4117. p2 = memarea_strndup(area, s, 10);
  4118. test_streq(p1, s);
  4119. test_assert(p2 >= p1 + len + 1);
  4120. test_memeq(s, p2, 10);
  4121. test_eq(p2[10], '\0');
  4122. p3 = memarea_strndup(area, s, len);
  4123. test_streq(p3, s);
  4124. p3 = memarea_strndup(area, s, len-1);
  4125. test_memeq(s, p3, len-1);
  4126. test_eq(p3[len-1], '\0');
  4127. }
  4128. memarea_clear(area);
  4129. p1 = memarea_alloc(area, 1);
  4130. test_eq(p1, p1_orig);
  4131. memarea_clear(area);
  4132. /* Check for running over an area's size. */
  4133. for (i = 0; i < 512; ++i) {
  4134. p1 = memarea_alloc(area, crypto_rand_int(5)+1);
  4135. test_assert(memarea_owns_ptr(area, p1));
  4136. }
  4137. memarea_assert_ok(area);
  4138. /* Make sure we can allocate a too-big object. */
  4139. p1 = memarea_alloc_zero(area, 9000);
  4140. p2 = memarea_alloc_zero(area, 16);
  4141. test_assert(memarea_owns_ptr(area, p1));
  4142. test_assert(memarea_owns_ptr(area, p2));
  4143. done:
  4144. memarea_drop_all(area);
  4145. tor_free(malloced_ptr);
  4146. }
  4147. /** Run unit tests for utility functions to get file names relative to
  4148. * the data directory. */
  4149. static void
  4150. test_util_datadir(void)
  4151. {
  4152. char buf[1024];
  4153. char *f = NULL;
  4154. f = get_datadir_fname(NULL);
  4155. test_streq(f, temp_dir);
  4156. tor_free(f);
  4157. f = get_datadir_fname("state");
  4158. tor_snprintf(buf, sizeof(buf), "%s"PATH_SEPARATOR"state", temp_dir);
  4159. test_streq(f, buf);
  4160. tor_free(f);
  4161. f = get_datadir_fname2("cache", "thingy");
  4162. tor_snprintf(buf, sizeof(buf),
  4163. "%s"PATH_SEPARATOR"cache"PATH_SEPARATOR"thingy", temp_dir);
  4164. test_streq(f, buf);
  4165. tor_free(f);
  4166. f = get_datadir_fname2_suffix("cache", "thingy", ".foo");
  4167. tor_snprintf(buf, sizeof(buf),
  4168. "%s"PATH_SEPARATOR"cache"PATH_SEPARATOR"thingy.foo", temp_dir);
  4169. test_streq(f, buf);
  4170. tor_free(f);
  4171. f = get_datadir_fname_suffix("cache", ".foo");
  4172. tor_snprintf(buf, sizeof(buf), "%s"PATH_SEPARATOR"cache.foo",
  4173. temp_dir);
  4174. test_streq(f, buf);
  4175. done:
  4176. tor_free(f);
  4177. }
  4178. static void
  4179. test_util_strtok(void)
  4180. {
  4181. char buf[128];
  4182. char buf2[128];
  4183. char *cp1, *cp2;
  4184. strlcpy(buf, "Graved on the dark in gestures of descent", sizeof(buf));
  4185. strlcpy(buf2, "they.seemed;their!own;most.perfect;monument", sizeof(buf2));
  4186. /* -- "Year's End", Richard Wilbur */
  4187. test_streq("Graved", tor_strtok_r_impl(buf, " ", &cp1));
  4188. test_streq("they", tor_strtok_r_impl(buf2, ".!..;!", &cp2));
  4189. #define S1() tor_strtok_r_impl(NULL, " ", &cp1)
  4190. #define S2() tor_strtok_r_impl(NULL, ".!..;!", &cp2)
  4191. test_streq("on", S1());
  4192. test_streq("the", S1());
  4193. test_streq("dark", S1());
  4194. test_streq("seemed", S2());
  4195. test_streq("their", S2());
  4196. test_streq("own", S2());
  4197. test_streq("in", S1());
  4198. test_streq("gestures", S1());
  4199. test_streq("of", S1());
  4200. test_streq("most", S2());
  4201. test_streq("perfect", S2());
  4202. test_streq("descent", S1());
  4203. test_streq("monument", S2());
  4204. test_assert(NULL == S1());
  4205. test_assert(NULL == S2());
  4206. done:
  4207. ;
  4208. }
  4209. /** Test AES-CTR encryption and decryption with IV. */
  4210. static void
  4211. test_crypto_aes_iv(void)
  4212. {
  4213. crypto_cipher_env_t *cipher;
  4214. char *plain, *encrypted1, *encrypted2, *decrypted1, *decrypted2;
  4215. char plain_1[1], plain_15[15], plain_16[16], plain_17[17];
  4216. char key1[16], key2[16];
  4217. ssize_t encrypted_size, decrypted_size;
  4218. plain = tor_malloc(4095);
  4219. encrypted1 = tor_malloc(4095 + 1 + 16);
  4220. encrypted2 = tor_malloc(4095 + 1 + 16);
  4221. decrypted1 = tor_malloc(4095 + 1);
  4222. decrypted2 = tor_malloc(4095 + 1);
  4223. crypto_rand(plain, 4095);
  4224. crypto_rand(key1, 16);
  4225. crypto_rand(key2, 16);
  4226. crypto_rand(plain_1, 1);
  4227. crypto_rand(plain_15, 15);
  4228. crypto_rand(plain_16, 16);
  4229. crypto_rand(plain_17, 17);
  4230. key1[0] = key2[0] + 128; /* Make sure that contents are different. */
  4231. /* Encrypt and decrypt with the same key. */
  4232. cipher = crypto_create_init_cipher(key1, 1);
  4233. encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 4095,
  4234. plain, 4095);
  4235. crypto_free_cipher_env(cipher);
  4236. cipher = NULL;
  4237. test_eq(encrypted_size, 16 + 4095);
  4238. tor_assert(encrypted_size > 0); /* This is obviously true, since 4111 is
  4239. * greater than 0, but its truth is not
  4240. * obvious to all analysis tools. */
  4241. cipher = crypto_create_init_cipher(key1, 0);
  4242. decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 4095,
  4243. encrypted1, encrypted_size);
  4244. crypto_free_cipher_env(cipher);
  4245. cipher = NULL;
  4246. test_eq(decrypted_size, 4095);
  4247. tor_assert(decrypted_size > 0);
  4248. test_memeq(plain, decrypted1, 4095);
  4249. /* Encrypt a second time (with a new random initialization vector). */
  4250. cipher = crypto_create_init_cipher(key1, 1);
  4251. encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted2, 16 + 4095,
  4252. plain, 4095);
  4253. crypto_free_cipher_env(cipher);
  4254. cipher = NULL;
  4255. test_eq(encrypted_size, 16 + 4095);
  4256. tor_assert(encrypted_size > 0);
  4257. cipher = crypto_create_init_cipher(key1, 0);
  4258. decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted2, 4095,
  4259. encrypted2, encrypted_size);
  4260. crypto_free_cipher_env(cipher);
  4261. cipher = NULL;
  4262. test_eq(decrypted_size, 4095);
  4263. tor_assert(decrypted_size > 0);
  4264. test_memeq(plain, decrypted2, 4095);
  4265. test_memneq(encrypted1, encrypted2, encrypted_size);
  4266. /* Decrypt with the wrong key. */
  4267. cipher = crypto_create_init_cipher(key2, 0);
  4268. decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted2, 4095,
  4269. encrypted1, encrypted_size);
  4270. crypto_free_cipher_env(cipher);
  4271. cipher = NULL;
  4272. test_memneq(plain, decrypted2, encrypted_size);
  4273. /* Alter the initialization vector. */
  4274. encrypted1[0] += 42;
  4275. cipher = crypto_create_init_cipher(key1, 0);
  4276. decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 4095,
  4277. encrypted1, encrypted_size);
  4278. crypto_free_cipher_env(cipher);
  4279. cipher = NULL;
  4280. test_memneq(plain, decrypted2, 4095);
  4281. /* Special length case: 1. */
  4282. cipher = crypto_create_init_cipher(key1, 1);
  4283. encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 1,
  4284. plain_1, 1);
  4285. crypto_free_cipher_env(cipher);
  4286. cipher = NULL;
  4287. test_eq(encrypted_size, 16 + 1);
  4288. tor_assert(encrypted_size > 0);
  4289. cipher = crypto_create_init_cipher(key1, 0);
  4290. decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 1,
  4291. encrypted1, encrypted_size);
  4292. crypto_free_cipher_env(cipher);
  4293. cipher = NULL;
  4294. test_eq(decrypted_size, 1);
  4295. tor_assert(decrypted_size > 0);
  4296. test_memeq(plain_1, decrypted1, 1);
  4297. /* Special length case: 15. */
  4298. cipher = crypto_create_init_cipher(key1, 1);
  4299. encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 15,
  4300. plain_15, 15);
  4301. crypto_free_cipher_env(cipher);
  4302. cipher = NULL;
  4303. test_eq(encrypted_size, 16 + 15);
  4304. tor_assert(encrypted_size > 0);
  4305. cipher = crypto_create_init_cipher(key1, 0);
  4306. decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 15,
  4307. encrypted1, encrypted_size);
  4308. crypto_free_cipher_env(cipher);
  4309. cipher = NULL;
  4310. test_eq(decrypted_size, 15);
  4311. tor_assert(decrypted_size > 0);
  4312. test_memeq(plain_15, decrypted1, 15);
  4313. /* Special length case: 16. */
  4314. cipher = crypto_create_init_cipher(key1, 1);
  4315. encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 16,
  4316. plain_16, 16);
  4317. crypto_free_cipher_env(cipher);
  4318. cipher = NULL;
  4319. test_eq(encrypted_size, 16 + 16);
  4320. tor_assert(encrypted_size > 0);
  4321. cipher = crypto_create_init_cipher(key1, 0);
  4322. decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 16,
  4323. encrypted1, encrypted_size);
  4324. crypto_free_cipher_env(cipher);
  4325. cipher = NULL;
  4326. test_eq(decrypted_size, 16);
  4327. tor_assert(decrypted_size > 0);
  4328. test_memeq(plain_16, decrypted1, 16);
  4329. /* Special length case: 17. */
  4330. cipher = crypto_create_init_cipher(key1, 1);
  4331. encrypted_size = crypto_cipher_encrypt_with_iv(cipher, encrypted1, 16 + 17,
  4332. plain_17, 17);
  4333. crypto_free_cipher_env(cipher);
  4334. cipher = NULL;
  4335. test_eq(encrypted_size, 16 + 17);
  4336. tor_assert(encrypted_size > 0);
  4337. cipher = crypto_create_init_cipher(key1, 0);
  4338. decrypted_size = crypto_cipher_decrypt_with_iv(cipher, decrypted1, 17,
  4339. encrypted1, encrypted_size);
  4340. test_eq(decrypted_size, 17);
  4341. tor_assert(decrypted_size > 0);
  4342. test_memeq(plain_17, decrypted1, 17);
  4343. done:
  4344. /* Free memory. */
  4345. tor_free(plain);
  4346. tor_free(encrypted1);
  4347. tor_free(encrypted2);
  4348. tor_free(decrypted1);
  4349. tor_free(decrypted2);
  4350. if (cipher)
  4351. crypto_free_cipher_env(cipher);
  4352. }
  4353. /** Test base32 decoding. */
  4354. static void
  4355. test_crypto_base32_decode(void)
  4356. {
  4357. char plain[60], encoded[96 + 1], decoded[60];
  4358. int res;
  4359. crypto_rand(plain, 60);
  4360. /* Encode and decode a random string. */
  4361. base32_encode(encoded, 96 + 1, plain, 60);
  4362. res = base32_decode(decoded, 60, encoded, 96);
  4363. test_eq(res, 0);
  4364. test_memeq(plain, decoded, 60);
  4365. /* Encode, uppercase, and decode a random string. */
  4366. base32_encode(encoded, 96 + 1, plain, 60);
  4367. tor_strupper(encoded);
  4368. res = base32_decode(decoded, 60, encoded, 96);
  4369. test_eq(res, 0);
  4370. test_memeq(plain, decoded, 60);
  4371. /* Change encoded string and decode. */
  4372. if (encoded[0] == 'A' || encoded[0] == 'a')
  4373. encoded[0] = 'B';
  4374. else
  4375. encoded[0] = 'A';
  4376. res = base32_decode(decoded, 60, encoded, 96);
  4377. test_eq(res, 0);
  4378. test_memneq(plain, decoded, 60);
  4379. /* Bad encodings. */
  4380. encoded[0] = '!';
  4381. res = base32_decode(decoded, 60, encoded, 96);
  4382. test_assert(res < 0);
  4383. done:
  4384. ;
  4385. }
  4386. /** Test encoding and parsing of rendezvous service descriptors. */
  4387. static void
  4388. test_rend_fns(void)
  4389. {
  4390. rend_service_descriptor_t *generated = NULL, *parsed = NULL;
  4391. char service_id[DIGEST_LEN];
  4392. char service_id_base32[REND_SERVICE_ID_LEN_BASE32+1];
  4393. const char *next_desc;
  4394. smartlist_t *descs = smartlist_create();
  4395. char computed_desc_id[DIGEST_LEN];
  4396. char parsed_desc_id[DIGEST_LEN];
  4397. crypto_pk_env_t *pk1 = NULL, *pk2 = NULL;
  4398. time_t now;
  4399. char *intro_points_encrypted = NULL;
  4400. size_t intro_points_size;
  4401. size_t encoded_size;
  4402. int i;
  4403. char address1[] = "fooaddress.onion";
  4404. char address2[] = "aaaaaaaaaaaaaaaa.onion";
  4405. char address3[] = "fooaddress.exit";
  4406. char address4[] = "www.torproject.org";
  4407. test_assert(BAD_HOSTNAME == parse_extended_hostname(address1, 1));
  4408. test_assert(ONION_HOSTNAME == parse_extended_hostname(address2, 1));
  4409. test_assert(EXIT_HOSTNAME == parse_extended_hostname(address3, 1));
  4410. test_assert(NORMAL_HOSTNAME == parse_extended_hostname(address4, 1));
  4411. pk1 = pk_generate(0);
  4412. pk2 = pk_generate(1);
  4413. generated = tor_malloc_zero(sizeof(rend_service_descriptor_t));
  4414. generated->pk = crypto_pk_dup_key(pk1);
  4415. crypto_pk_get_digest(generated->pk, service_id);
  4416. base32_encode(service_id_base32, REND_SERVICE_ID_LEN_BASE32+1,
  4417. service_id, REND_SERVICE_ID_LEN);
  4418. now = time(NULL);
  4419. generated->timestamp = now;
  4420. generated->version = 2;
  4421. generated->protocols = 42;
  4422. generated->intro_nodes = smartlist_create();
  4423. for (i = 0; i < 3; i++) {
  4424. rend_intro_point_t *intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  4425. crypto_pk_env_t *okey = pk_generate(2 + i);
  4426. intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
  4427. intro->extend_info->onion_key = okey;
  4428. crypto_pk_get_digest(intro->extend_info->onion_key,
  4429. intro->extend_info->identity_digest);
  4430. //crypto_rand(info->identity_digest, DIGEST_LEN); /* Would this work? */
  4431. intro->extend_info->nickname[0] = '$';
  4432. base16_encode(intro->extend_info->nickname + 1,
  4433. sizeof(intro->extend_info->nickname) - 1,
  4434. intro->extend_info->identity_digest, DIGEST_LEN);
  4435. /* Does not cover all IP addresses. */
  4436. tor_addr_from_ipv4h(&intro->extend_info->addr, crypto_rand_int(65536));
  4437. intro->extend_info->port = crypto_rand_int(65536);
  4438. intro->intro_key = crypto_pk_dup_key(pk2);
  4439. smartlist_add(generated->intro_nodes, intro);
  4440. }
  4441. test_assert(rend_encode_v2_descriptors(descs, generated, now, 0,
  4442. REND_NO_AUTH, NULL, NULL) > 0);
  4443. test_assert(rend_compute_v2_desc_id(computed_desc_id, service_id_base32,
  4444. NULL, now, 0) == 0);
  4445. test_memeq(((rend_encoded_v2_service_descriptor_t *)
  4446. smartlist_get(descs, 0))->desc_id, computed_desc_id, DIGEST_LEN);
  4447. test_assert(rend_parse_v2_service_descriptor(&parsed, parsed_desc_id,
  4448. &intro_points_encrypted,
  4449. &intro_points_size,
  4450. &encoded_size,
  4451. &next_desc,
  4452. ((rend_encoded_v2_service_descriptor_t *)
  4453. smartlist_get(descs, 0))->desc_str) == 0);
  4454. test_assert(parsed);
  4455. test_memeq(((rend_encoded_v2_service_descriptor_t *)
  4456. smartlist_get(descs, 0))->desc_id, parsed_desc_id, DIGEST_LEN);
  4457. test_eq(rend_parse_introduction_points(parsed, intro_points_encrypted,
  4458. intro_points_size), 3);
  4459. test_assert(!crypto_pk_cmp_keys(generated->pk, parsed->pk));
  4460. test_eq(parsed->timestamp, now);
  4461. test_eq(parsed->version, 2);
  4462. test_eq(parsed->protocols, 42);
  4463. test_eq(smartlist_len(parsed->intro_nodes), 3);
  4464. for (i = 0; i < smartlist_len(parsed->intro_nodes); i++) {
  4465. rend_intro_point_t *par_intro = smartlist_get(parsed->intro_nodes, i),
  4466. *gen_intro = smartlist_get(generated->intro_nodes, i);
  4467. extend_info_t *par_info = par_intro->extend_info;
  4468. extend_info_t *gen_info = gen_intro->extend_info;
  4469. test_assert(!crypto_pk_cmp_keys(gen_info->onion_key, par_info->onion_key));
  4470. test_memeq(gen_info->identity_digest, par_info->identity_digest,
  4471. DIGEST_LEN);
  4472. test_streq(gen_info->nickname, par_info->nickname);
  4473. test_assert(tor_addr_eq(&gen_info->addr, &par_info->addr));
  4474. test_eq(gen_info->port, par_info->port);
  4475. }
  4476. rend_service_descriptor_free(parsed);
  4477. rend_service_descriptor_free(generated);
  4478. parsed = generated = NULL;
  4479. done:
  4480. if (descs) {
  4481. for (i = 0; i < smartlist_len(descs); i++)
  4482. rend_encoded_v2_service_descriptor_free(smartlist_get(descs, i));
  4483. smartlist_free(descs);
  4484. }
  4485. if (parsed)
  4486. rend_service_descriptor_free(parsed);
  4487. if (generated)
  4488. rend_service_descriptor_free(generated);
  4489. if (pk1)
  4490. crypto_free_pk_env(pk1);
  4491. if (pk2)
  4492. crypto_free_pk_env(pk2);
  4493. tor_free(intro_points_encrypted);
  4494. }
  4495. /** Run unit tests for GeoIP code. */
  4496. static void
  4497. test_geoip(void)
  4498. {
  4499. int i, j;
  4500. time_t now = time(NULL);
  4501. char *s = NULL;
  4502. /* Populate the DB a bit. Add these in order, since we can't do the final
  4503. * 'sort' step. These aren't very good IP addresses, but they're perfectly
  4504. * fine uint32_t values. */
  4505. test_eq(0, geoip_parse_entry("10,50,AB"));
  4506. test_eq(0, geoip_parse_entry("52,90,XY"));
  4507. test_eq(0, geoip_parse_entry("95,100,AB"));
  4508. test_eq(0, geoip_parse_entry("\"105\",\"140\",\"ZZ\""));
  4509. test_eq(0, geoip_parse_entry("\"150\",\"190\",\"XY\""));
  4510. test_eq(0, geoip_parse_entry("\"200\",\"250\",\"AB\""));
  4511. /* We should have 3 countries: ab, xy, zz. */
  4512. test_eq(3, geoip_get_n_countries());
  4513. /* Make sure that country ID actually works. */
  4514. #define NAMEFOR(x) geoip_get_country_name(geoip_get_country_by_ip(x))
  4515. test_streq("ab", NAMEFOR(32));
  4516. test_streq("??", NAMEFOR(5));
  4517. test_streq("??", NAMEFOR(51));
  4518. test_streq("xy", NAMEFOR(150));
  4519. test_streq("xy", NAMEFOR(190));
  4520. test_streq("??", NAMEFOR(2000));
  4521. #undef NAMEFOR
  4522. get_options()->BridgeRelay = 1;
  4523. get_options()->BridgeRecordUsageByCountry = 1;
  4524. /* Put 9 observations in AB... */
  4525. for (i=32; i < 40; ++i)
  4526. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, i, now-7200);
  4527. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, 225, now-7200);
  4528. /* and 3 observations in XY, several times. */
  4529. for (j=0; j < 10; ++j)
  4530. for (i=52; i < 55; ++i)
  4531. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, i, now-3600);
  4532. /* and 17 observations in ZZ... */
  4533. for (i=110; i < 127; ++i)
  4534. geoip_note_client_seen(GEOIP_CLIENT_CONNECT, i, now);
  4535. s = geoip_get_client_history_bridge(now+5*24*60*60,
  4536. GEOIP_CLIENT_CONNECT);
  4537. test_assert(s);
  4538. test_streq("zz=24,ab=16,xy=8", s);
  4539. tor_free(s);
  4540. /* Now clear out all the AB observations. */
  4541. geoip_remove_old_clients(now-6000);
  4542. s = geoip_get_client_history_bridge(now+5*24*60*60,
  4543. GEOIP_CLIENT_CONNECT);
  4544. test_assert(s);
  4545. test_streq("zz=24,xy=8", s);
  4546. done:
  4547. tor_free(s);
  4548. }
  4549. /** For test_array. Declare an CLI-invocable off-by-default function in the
  4550. * unit tests, with function name and user-visible name <b>x</b>*/
  4551. #define DISABLED(x) { #x, x, 0, 0, 0 }
  4552. /** For test_array. Declare an CLI-invocable unit test function, with function
  4553. * name test_<b>x</b>(), and user-visible name <b>x</b> */
  4554. #define ENT(x) { #x, test_ ## x, 0, 0, 1 }
  4555. /** For test_array. Declare an CLI-invocable unit test function, with function
  4556. * name test_<b>x</b>_<b>y</b>(), and user-visible name
  4557. * <b>x</b>/<b>y</b>. This function will be treated as a subentry of <b>x</b>,
  4558. * so that invoking <b>x</b> from the CLI invokes this test too. */
  4559. #define SUBENT(x,y) { #x "/" #y, test_ ## x ## _ ## y, 1, 0, 1 }
  4560. /** An array of functions and information for all the unit tests we can run. */
  4561. static struct {
  4562. const char *test_name; /**< How does the user refer to this test from the
  4563. * command line? */
  4564. void (*test_fn)(void); /**< What function is called to run this test? */
  4565. int is_subent; /**< Is this a subentry of a bigger set of related tests? */
  4566. int selected; /**< Are we planning to run this one? */
  4567. int is_default; /**< If the user doesn't say what tests they want, do they
  4568. * get this function by default? */
  4569. } test_array[] = {
  4570. ENT(buffers),
  4571. ENT(crypto),
  4572. SUBENT(crypto, rng),
  4573. SUBENT(crypto, aes),
  4574. SUBENT(crypto, sha),
  4575. SUBENT(crypto, pk),
  4576. SUBENT(crypto, dh),
  4577. SUBENT(crypto, s2k),
  4578. SUBENT(crypto, aes_iv),
  4579. SUBENT(crypto, base32_decode),
  4580. ENT(util),
  4581. SUBENT(util, ip6_helpers),
  4582. SUBENT(util, gzip),
  4583. SUBENT(util, datadir),
  4584. SUBENT(util, smartlist_basic),
  4585. SUBENT(util, smartlist_strings),
  4586. SUBENT(util, smartlist_overlap),
  4587. SUBENT(util, smartlist_digests),
  4588. SUBENT(util, smartlist_join),
  4589. SUBENT(util, bitarray),
  4590. SUBENT(util, digestset),
  4591. SUBENT(util, mempool),
  4592. SUBENT(util, memarea),
  4593. SUBENT(util, strmap),
  4594. SUBENT(util, control_formats),
  4595. SUBENT(util, pqueue),
  4596. SUBENT(util, mmap),
  4597. SUBENT(util, threads),
  4598. SUBENT(util, order_functions),
  4599. SUBENT(util, sscanf),
  4600. SUBENT(util, strtok),
  4601. ENT(onion_handshake),
  4602. ENT(dir_format),
  4603. ENT(dirutil),
  4604. SUBENT(dirutil, measured_bw),
  4605. SUBENT(dirutil, param_voting),
  4606. ENT(circuit_timeout),
  4607. ENT(v3_networkstatus),
  4608. ENT(policies),
  4609. ENT(rend_fns),
  4610. ENT(geoip),
  4611. DISABLED(bench_aes),
  4612. DISABLED(bench_dmap),
  4613. { NULL, NULL, 0, 0, 0 },
  4614. };
  4615. static void syntax(void) ATTR_NORETURN;
  4616. /** Print a syntax usage message, and exit.*/
  4617. static void
  4618. syntax(void)
  4619. {
  4620. int i;
  4621. printf("Syntax:\n"
  4622. " test [-v|--verbose] [--warn|--notice|--info|--debug]\n"
  4623. " [testname...]\n"
  4624. "Recognized tests are:\n");
  4625. for (i = 0; test_array[i].test_name; ++i) {
  4626. printf(" %s\n", test_array[i].test_name);
  4627. }
  4628. exit(0);
  4629. }
  4630. /** Main entry point for unit test code: parse the command line, and run
  4631. * some unit tests. */
  4632. int
  4633. main(int c, char**v)
  4634. {
  4635. or_options_t *options;
  4636. char *errmsg = NULL;
  4637. int i;
  4638. int verbose = 0, any_selected = 0;
  4639. int loglevel = LOG_ERR;
  4640. #ifdef USE_DMALLOC
  4641. {
  4642. int r = CRYPTO_set_mem_ex_functions(_tor_malloc, _tor_realloc, _tor_free);
  4643. tor_assert(r);
  4644. }
  4645. #endif
  4646. update_approx_time(time(NULL));
  4647. options = options_new();
  4648. tor_threads_init();
  4649. init_logging();
  4650. for (i = 1; i < c; ++i) {
  4651. if (!strcmp(v[i], "-v") || !strcmp(v[i], "--verbose"))
  4652. verbose++;
  4653. else if (!strcmp(v[i], "--warn"))
  4654. loglevel = LOG_WARN;
  4655. else if (!strcmp(v[i], "--notice"))
  4656. loglevel = LOG_NOTICE;
  4657. else if (!strcmp(v[i], "--info"))
  4658. loglevel = LOG_INFO;
  4659. else if (!strcmp(v[i], "--debug"))
  4660. loglevel = LOG_DEBUG;
  4661. else if (!strcmp(v[i], "--help") || !strcmp(v[i], "-h") || v[i][0] == '-')
  4662. syntax();
  4663. else {
  4664. int j, found=0;
  4665. for (j = 0; test_array[j].test_name; ++j) {
  4666. if (!strcmp(v[i], test_array[j].test_name) ||
  4667. (test_array[j].is_subent &&
  4668. !strcmpstart(test_array[j].test_name, v[i]) &&
  4669. test_array[j].test_name[strlen(v[i])] == '/') ||
  4670. (v[i][0] == '=' && !strcmp(v[i]+1, test_array[j].test_name))) {
  4671. test_array[j].selected = 1;
  4672. any_selected = 1;
  4673. found = 1;
  4674. }
  4675. }
  4676. if (!found) {
  4677. printf("Unknown test: %s\n", v[i]);
  4678. syntax();
  4679. }
  4680. }
  4681. }
  4682. if (!any_selected) {
  4683. for (i = 0; test_array[i].test_name; ++i) {
  4684. test_array[i].selected = test_array[i].is_default;
  4685. }
  4686. }
  4687. {
  4688. log_severity_list_t s;
  4689. memset(&s, 0, sizeof(s));
  4690. set_log_severity_config(loglevel, LOG_ERR, &s);
  4691. add_stream_log(&s, "", fileno(stdout));
  4692. }
  4693. options->command = CMD_RUN_UNITTESTS;
  4694. crypto_global_init(0, NULL, NULL);
  4695. rep_hist_init();
  4696. network_init();
  4697. setup_directory();
  4698. options_init(options);
  4699. options->DataDirectory = tor_strdup(temp_dir);
  4700. options->EntryStatistics = 1;
  4701. if (set_options(options, &errmsg) < 0) {
  4702. printf("Failed to set initial options: %s\n", errmsg);
  4703. tor_free(errmsg);
  4704. return 1;
  4705. }
  4706. crypto_seed_rng(1);
  4707. atexit(remove_directory);
  4708. printf("Running Tor unit tests on %s\n", get_uname());
  4709. for (i = 0; test_array[i].test_name; ++i) {
  4710. if (!test_array[i].selected)
  4711. continue;
  4712. if (!test_array[i].is_subent) {
  4713. printf("\n============================== %s\n",test_array[i].test_name);
  4714. } else if (test_array[i].is_subent && verbose) {
  4715. printf("\n%s", test_array[i].test_name);
  4716. }
  4717. test_array[i].test_fn();
  4718. }
  4719. puts("");
  4720. free_pregenerated_keys();
  4721. #ifdef USE_DMALLOC
  4722. tor_free_all(0);
  4723. dmalloc_log_unfreed();
  4724. #endif
  4725. if (have_failed)
  4726. return 1;
  4727. else
  4728. return 0;
  4729. }