test_util.c 195 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315
  1. /* Copyright (c) 2001-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2018, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. #include "orconfig.h"
  6. #define COMPAT_PRIVATE
  7. #define COMPAT_TIME_PRIVATE
  8. #define CONTROL_PRIVATE
  9. #define UTIL_PRIVATE
  10. #define UTIL_MALLOC_PRIVATE
  11. #define SOCKET_PRIVATE
  12. #define SUBPROCESS_PRIVATE
  13. #include "lib/testsupport/testsupport.h"
  14. #include "or/or.h"
  15. #include "lib/container/buffers.h"
  16. #include "or/config.h"
  17. #include "or/control.h"
  18. #include "or/transports.h"
  19. #include "lib/crypt_ops/crypto_rand.h"
  20. #include "test/test.h"
  21. #include "lib/memarea/memarea.h"
  22. #include "lib/process/waitpid.h"
  23. #include "test/log_test_helpers.h"
  24. #include "lib/compress/compress_zstd.h"
  25. #include "lib/encoding/keyval.h"
  26. #include "lib/fdio/fdio.h"
  27. #include "lib/process/env.h"
  28. #include "lib/process/pidfile.h"
  29. #include "lib/process/subprocess.h"
  30. #include "lib/intmath/weakrng.h"
  31. #include "lib/thread/numcpus.h"
  32. #include "lib/math/fp.h"
  33. #include "lib/math/laplace.h"
  34. #include "lib/meminfo/meminfo.h"
  35. #include "lib/time/tvdiff.h"
  36. #ifdef HAVE_PWD_H
  37. #include <pwd.h>
  38. #endif
  39. #ifdef HAVE_SYS_UTIME_H
  40. #include <sys/utime.h>
  41. #endif
  42. #ifdef HAVE_UTIME_H
  43. #include <utime.h>
  44. #endif
  45. #ifdef _WIN32
  46. #include <tchar.h>
  47. #endif
  48. #include <math.h>
  49. #include <ctype.h>
  50. #include <float.h>
  51. #define INFINITY_DBL ((double)INFINITY)
  52. #define NAN_DBL ((double)NAN)
  53. /* XXXX this is a minimal wrapper to make the unit tests compile with the
  54. * changed tor_timegm interface. */
  55. static time_t
  56. tor_timegm_wrapper(const struct tm *tm)
  57. {
  58. time_t t;
  59. if (tor_timegm(tm, &t) < 0)
  60. return -1;
  61. return t;
  62. }
  63. #define tor_timegm tor_timegm_wrapper
  64. static void
  65. test_util_read_until_eof_impl(const char *fname, size_t file_len,
  66. size_t read_limit)
  67. {
  68. char *fifo_name = NULL;
  69. char *test_str = NULL;
  70. char *str = NULL;
  71. size_t sz = 9999999;
  72. int fd = -1;
  73. int r;
  74. fifo_name = tor_strdup(get_fname(fname));
  75. test_str = tor_malloc(file_len);
  76. crypto_rand(test_str, file_len);
  77. r = write_bytes_to_file(fifo_name, test_str, file_len, 1);
  78. tt_int_op(r, OP_EQ, 0);
  79. fd = open(fifo_name, O_RDONLY|O_BINARY);
  80. tt_int_op(fd, OP_GE, 0);
  81. str = read_file_to_str_until_eof(fd, read_limit, &sz);
  82. tt_ptr_op(str, OP_NE, NULL);
  83. if (read_limit < file_len)
  84. tt_int_op(sz, OP_EQ, read_limit);
  85. else
  86. tt_int_op(sz, OP_EQ, file_len);
  87. tt_mem_op(test_str, OP_EQ, str, sz);
  88. tt_int_op(str[sz], OP_EQ, '\0');
  89. done:
  90. unlink(fifo_name);
  91. tor_free(fifo_name);
  92. tor_free(test_str);
  93. tor_free(str);
  94. if (fd >= 0)
  95. close(fd);
  96. }
  97. static void
  98. test_util_read_file_eof_tiny_limit(void *arg)
  99. {
  100. (void)arg;
  101. // purposely set limit shorter than what we wrote to the FIFO to
  102. // test the maximum, and that it puts the NUL in the right spot
  103. test_util_read_until_eof_impl("tor_test_fifo_tiny", 5, 4);
  104. }
  105. static void
  106. test_util_read_file_eof_one_loop_a(void *arg)
  107. {
  108. (void)arg;
  109. test_util_read_until_eof_impl("tor_test_fifo_1ka", 1024, 1023);
  110. }
  111. static void
  112. test_util_read_file_eof_one_loop_b(void *arg)
  113. {
  114. (void)arg;
  115. test_util_read_until_eof_impl("tor_test_fifo_1kb", 1024, 1024);
  116. }
  117. static void
  118. test_util_read_file_eof_two_loops(void *arg)
  119. {
  120. (void)arg;
  121. // write more than 1024 bytes to the FIFO to test two passes through
  122. // the loop in the method; if the re-alloc size is changed this
  123. // should be updated as well.
  124. test_util_read_until_eof_impl("tor_test_fifo_2k", 2048, 10000);
  125. }
  126. static void
  127. test_util_read_file_eof_two_loops_b(void *arg)
  128. {
  129. (void)arg;
  130. test_util_read_until_eof_impl("tor_test_fifo_2kb", 2048, 2048);
  131. }
  132. static void
  133. test_util_read_file_eof_zero_bytes(void *arg)
  134. {
  135. (void)arg;
  136. // zero-byte fifo
  137. test_util_read_until_eof_impl("tor_test_fifo_empty", 0, 10000);
  138. }
  139. /* Test the basic expected behaviour for write_chunks_to_file.
  140. * NOTE: This will need to be updated if we ever change the tempfile location
  141. * or extension */
  142. static void
  143. test_util_write_chunks_to_file(void *arg)
  144. {
  145. char *fname = NULL;
  146. char *tempname = NULL;
  147. char *str = NULL;
  148. int r;
  149. struct stat st;
  150. /* These should be two different sizes to ensure the data is different
  151. * between the data file and the temp file's 'known string' */
  152. int temp_str_len = 1024;
  153. int data_str_len = 512;
  154. char *data_str = tor_malloc(data_str_len);
  155. char *temp_str = tor_malloc(temp_str_len);
  156. smartlist_t *chunks = smartlist_new();
  157. sized_chunk_t c = {data_str, data_str_len/2};
  158. sized_chunk_t c2 = {data_str + data_str_len/2, data_str_len/2};
  159. (void)arg;
  160. crypto_rand(temp_str, temp_str_len);
  161. crypto_rand(data_str, data_str_len);
  162. // Ensure it can write multiple chunks
  163. smartlist_add(chunks, &c);
  164. smartlist_add(chunks, &c2);
  165. /*
  166. * Check if it writes using a tempfile
  167. */
  168. fname = tor_strdup(get_fname("write_chunks_with_tempfile"));
  169. tor_asprintf(&tempname, "%s.tmp", fname);
  170. // write a known string to a file where the tempfile will be
  171. r = write_bytes_to_file(tempname, temp_str, temp_str_len, 1);
  172. tt_int_op(r, OP_EQ, 0);
  173. // call write_chunks_to_file
  174. r = write_chunks_to_file(fname, chunks, 1, 0);
  175. tt_int_op(r, OP_EQ, 0);
  176. // assert the file has been written (expected size)
  177. str = read_file_to_str(fname, RFTS_BIN, &st);
  178. tt_assert(str != NULL);
  179. tt_u64_op((uint64_t)st.st_size, OP_EQ, data_str_len);
  180. tt_mem_op(data_str, OP_EQ, str, data_str_len);
  181. tor_free(str);
  182. // assert that the tempfile is removed (should not leave artifacts)
  183. str = read_file_to_str(tempname, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
  184. tt_assert(str == NULL);
  185. // Remove old testfile for second test
  186. r = unlink(fname);
  187. tt_int_op(r, OP_EQ, 0);
  188. tor_free(fname);
  189. tor_free(tempname);
  190. /*
  191. * Check if it skips using a tempfile with flags
  192. */
  193. fname = tor_strdup(get_fname("write_chunks_with_no_tempfile"));
  194. tor_asprintf(&tempname, "%s.tmp", fname);
  195. // write a known string to a file where the tempfile will be
  196. r = write_bytes_to_file(tempname, temp_str, temp_str_len, 1);
  197. tt_int_op(r, OP_EQ, 0);
  198. // call write_chunks_to_file with no_tempfile = true
  199. r = write_chunks_to_file(fname, chunks, 1, 1);
  200. tt_int_op(r, OP_EQ, 0);
  201. // assert the file has been written (expected size)
  202. str = read_file_to_str(fname, RFTS_BIN, &st);
  203. tt_assert(str != NULL);
  204. tt_u64_op((uint64_t)st.st_size, OP_EQ, data_str_len);
  205. tt_mem_op(data_str, OP_EQ, str, data_str_len);
  206. tor_free(str);
  207. // assert the tempfile still contains the known string
  208. str = read_file_to_str(tempname, RFTS_BIN, &st);
  209. tt_assert(str != NULL);
  210. tt_u64_op((uint64_t)st.st_size, OP_EQ, temp_str_len);
  211. tt_mem_op(temp_str, OP_EQ, str, temp_str_len);
  212. done:
  213. unlink(fname);
  214. unlink(tempname);
  215. smartlist_free(chunks);
  216. tor_free(fname);
  217. tor_free(tempname);
  218. tor_free(str);
  219. tor_free(data_str);
  220. tor_free(temp_str);
  221. }
  222. #define _TFE(a, b, f) tt_int_op((a).f, OP_EQ, (b).f)
  223. /** test the minimum set of struct tm fields needed for a unique epoch value
  224. * this is also the set we use to test tor_timegm */
  225. #define TM_EQUAL(a, b) \
  226. TT_STMT_BEGIN \
  227. _TFE(a, b, tm_year); \
  228. _TFE(a, b, tm_mon ); \
  229. _TFE(a, b, tm_mday); \
  230. _TFE(a, b, tm_hour); \
  231. _TFE(a, b, tm_min ); \
  232. _TFE(a, b, tm_sec ); \
  233. TT_STMT_END
  234. static void
  235. test_util_time(void *arg)
  236. {
  237. struct timeval start, end;
  238. struct tm a_time, b_time;
  239. char timestr[128];
  240. time_t t_res;
  241. int i;
  242. struct timeval tv;
  243. /* Test tv_udiff and tv_mdiff */
  244. (void)arg;
  245. start.tv_sec = 5;
  246. start.tv_usec = 5000;
  247. end.tv_sec = 5;
  248. end.tv_usec = 5000;
  249. tt_int_op(0L,OP_EQ, tv_udiff(&start, &end));
  250. tt_int_op(0L,OP_EQ, tv_mdiff(&start, &end));
  251. tt_int_op(0L,OP_EQ, tv_udiff(&end, &start));
  252. tt_int_op(0L,OP_EQ, tv_mdiff(&end, &start));
  253. end.tv_usec = 7000;
  254. tt_int_op(2000L,OP_EQ, tv_udiff(&start, &end));
  255. tt_int_op(2L,OP_EQ, tv_mdiff(&start, &end));
  256. tt_int_op(-2000L,OP_EQ, tv_udiff(&end, &start));
  257. tt_int_op(-2L,OP_EQ, tv_mdiff(&end, &start));
  258. end.tv_sec = 6;
  259. tt_int_op(1002000L,OP_EQ, tv_udiff(&start, &end));
  260. tt_int_op(1002L,OP_EQ, tv_mdiff(&start, &end));
  261. tt_int_op(-1002000L,OP_EQ, tv_udiff(&end, &start));
  262. tt_int_op(-1002L,OP_EQ, tv_mdiff(&end, &start));
  263. end.tv_usec = 0;
  264. tt_int_op(995000L,OP_EQ, tv_udiff(&start, &end));
  265. tt_int_op(995L,OP_EQ, tv_mdiff(&start, &end));
  266. tt_int_op(-995000L,OP_EQ, tv_udiff(&end, &start));
  267. tt_int_op(-995L,OP_EQ, tv_mdiff(&end, &start));
  268. end.tv_sec = 4;
  269. tt_int_op(-1005000L,OP_EQ, tv_udiff(&start, &end));
  270. tt_int_op(-1005L,OP_EQ, tv_mdiff(&start, &end));
  271. tt_int_op(1005000L,OP_EQ, tv_udiff(&end, &start));
  272. tt_int_op(1005L,OP_EQ, tv_mdiff(&end, &start));
  273. /* Negative tv_sec values, these will break on platforms where tv_sec is
  274. * unsigned */
  275. end.tv_sec = -10;
  276. tt_int_op(-15005000L,OP_EQ, tv_udiff(&start, &end));
  277. tt_int_op(-15005L,OP_EQ, tv_mdiff(&start, &end));
  278. tt_int_op(15005000L,OP_EQ, tv_udiff(&end, &start));
  279. tt_int_op(15005L,OP_EQ, tv_mdiff(&end, &start));
  280. start.tv_sec = -100;
  281. tt_int_op(89995000L,OP_EQ, tv_udiff(&start, &end));
  282. tt_int_op(89995L,OP_EQ, tv_mdiff(&start, &end));
  283. tt_int_op(-89995000L,OP_EQ, tv_udiff(&end, &start));
  284. tt_int_op(-89995L,OP_EQ, tv_mdiff(&end, &start));
  285. /* Test that tv_usec values round away from zero when converted to msec */
  286. start.tv_sec = 0;
  287. start.tv_usec = 0;
  288. end.tv_sec = 10;
  289. end.tv_usec = 499;
  290. tt_int_op(10000499L, OP_EQ, tv_udiff(&start, &end));
  291. tt_int_op(10000L, OP_EQ, tv_mdiff(&start, &end));
  292. tt_int_op(-10000499L, OP_EQ, tv_udiff(&end, &start));
  293. tt_int_op(-10000L, OP_EQ, tv_mdiff(&end, &start));
  294. start.tv_sec = 0;
  295. start.tv_usec = 0;
  296. end.tv_sec = 10;
  297. end.tv_usec = 500;
  298. tt_int_op(10000500L, OP_EQ, tv_udiff(&start, &end));
  299. tt_int_op(10001L, OP_EQ, tv_mdiff(&start, &end));
  300. tt_int_op(-10000500L, OP_EQ, tv_udiff(&end, &start));
  301. tt_int_op(-10000L, OP_EQ, tv_mdiff(&end, &start));
  302. start.tv_sec = 0;
  303. start.tv_usec = 0;
  304. end.tv_sec = 10;
  305. end.tv_usec = 501;
  306. tt_int_op(10000501L, OP_EQ, tv_udiff(&start, &end));
  307. tt_int_op(10001L, OP_EQ, tv_mdiff(&start, &end));
  308. tt_int_op(-10000501L, OP_EQ, tv_udiff(&end, &start));
  309. tt_int_op(-10001L, OP_EQ, tv_mdiff(&end, &start));
  310. /* Overflow conditions */
  311. #ifdef _WIN32
  312. /* Would you believe that tv_sec is a long on windows? Of course you would.*/
  313. #define TV_SEC_MAX LONG_MAX
  314. #define TV_SEC_MIN LONG_MIN
  315. #else
  316. /* Some BSDs have struct timeval.tv_sec 64-bit, but time_t (and long) 32-bit
  317. * Which means TIME_MAX is not actually the maximum value of tv_sec.
  318. * But that's ok for the moment, because the code correctly performs 64-bit
  319. * calculations internally, then catches the overflow. */
  320. #define TV_SEC_MAX TIME_MAX
  321. #define TV_SEC_MIN TIME_MIN
  322. #endif /* defined(_WIN32) */
  323. /* Assume tv_usec is an unsigned integer until proven otherwise */
  324. #define TV_USEC_MAX UINT_MAX
  325. #define TOR_USEC_PER_SEC 1000000
  326. /* Overflows in the result type */
  327. /* All comparisons work */
  328. start.tv_sec = 0;
  329. start.tv_usec = 0;
  330. end.tv_sec = LONG_MAX/1000 - 2;
  331. end.tv_usec = 0;
  332. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&start, &end));
  333. tt_int_op(end.tv_sec*1000L, OP_EQ, tv_mdiff(&start, &end));
  334. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&end, &start));
  335. tt_int_op(-end.tv_sec*1000L, OP_EQ, tv_mdiff(&end, &start));
  336. start.tv_sec = 0;
  337. start.tv_usec = 0;
  338. end.tv_sec = LONG_MAX/1000000 - 1;
  339. end.tv_usec = 0;
  340. tt_int_op(end.tv_sec*1000000L, OP_EQ, tv_udiff(&start, &end));
  341. tt_int_op(end.tv_sec*1000L, OP_EQ, tv_mdiff(&start, &end));
  342. tt_int_op(-end.tv_sec*1000000L, OP_EQ, tv_udiff(&end, &start));
  343. tt_int_op(-end.tv_sec*1000L, OP_EQ, tv_mdiff(&end, &start));
  344. /* No comparisons work */
  345. start.tv_sec = 0;
  346. start.tv_usec = 0;
  347. end.tv_sec = LONG_MAX/1000 + 1;
  348. end.tv_usec = 0;
  349. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&start, &end));
  350. tt_int_op(LONG_MAX, OP_EQ, tv_mdiff(&start, &end));
  351. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&end, &start));
  352. tt_int_op(LONG_MAX, OP_EQ, tv_mdiff(&end, &start));
  353. start.tv_sec = 0;
  354. start.tv_usec = 0;
  355. end.tv_sec = LONG_MAX/1000000 + 1;
  356. end.tv_usec = 0;
  357. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&start, &end));
  358. tt_int_op(end.tv_sec*1000L, OP_EQ, tv_mdiff(&start, &end));
  359. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&end, &start));
  360. tt_int_op(-end.tv_sec*1000L, OP_EQ, tv_mdiff(&end, &start));
  361. start.tv_sec = 0;
  362. start.tv_usec = 0;
  363. end.tv_sec = LONG_MAX/1000;
  364. end.tv_usec = TOR_USEC_PER_SEC;
  365. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&start, &end));
  366. tt_int_op(LONG_MAX, OP_EQ, tv_mdiff(&start, &end));
  367. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&end, &start));
  368. tt_int_op(LONG_MAX, OP_EQ, tv_mdiff(&end, &start));
  369. start.tv_sec = 0;
  370. start.tv_usec = 0;
  371. end.tv_sec = LONG_MAX/1000000;
  372. end.tv_usec = TOR_USEC_PER_SEC;
  373. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&start, &end));
  374. tt_int_op((end.tv_sec + 1)*1000L, OP_EQ, tv_mdiff(&start, &end));
  375. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&end, &start));
  376. tt_int_op(-(end.tv_sec + 1)*1000L, OP_EQ, tv_mdiff(&end, &start));
  377. /* Overflows on comparison to zero */
  378. start.tv_sec = 0;
  379. start.tv_usec = 0;
  380. end.tv_sec = TV_SEC_MAX;
  381. end.tv_usec = 0;
  382. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&start, &end));
  383. tt_int_op(LONG_MAX, OP_EQ, tv_mdiff(&start, &end));
  384. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&end, &start));
  385. tt_int_op(LONG_MAX, OP_EQ, tv_mdiff(&end, &start));
  386. end.tv_sec = TV_SEC_MAX;
  387. end.tv_usec = TOR_USEC_PER_SEC;
  388. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&start, &end));
  389. tt_int_op(LONG_MAX, OP_EQ, tv_mdiff(&start, &end));
  390. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&end, &start));
  391. tt_int_op(LONG_MAX, OP_EQ, tv_mdiff(&end, &start));
  392. end.tv_sec = 0;
  393. end.tv_usec = TV_USEC_MAX;
  394. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&start, &end));
  395. tt_int_op(LONG_MAX, OP_EQ, tv_mdiff(&start, &end));
  396. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&end, &start));
  397. tt_int_op(LONG_MAX, OP_EQ, tv_mdiff(&end, &start));
  398. end.tv_sec = TV_SEC_MAX;
  399. end.tv_usec = TV_USEC_MAX;
  400. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&start, &end));
  401. tt_int_op(LONG_MAX, OP_EQ, tv_mdiff(&start, &end));
  402. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&end, &start));
  403. tt_int_op(LONG_MAX, OP_EQ, tv_mdiff(&end, &start));
  404. end.tv_sec = 0;
  405. end.tv_usec = 0;
  406. start.tv_sec = TV_SEC_MIN;
  407. start.tv_usec = 0;
  408. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&start, &end));
  409. tt_int_op(LONG_MAX, OP_EQ, tv_mdiff(&start, &end));
  410. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&end, &start));
  411. tt_int_op(LONG_MAX, OP_EQ, tv_mdiff(&end, &start));
  412. start.tv_sec = TV_SEC_MIN;
  413. start.tv_usec = TOR_USEC_PER_SEC;
  414. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&start, &end));
  415. tt_int_op(LONG_MAX, OP_EQ, tv_mdiff(&start, &end));
  416. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&end, &start));
  417. tt_int_op(LONG_MAX, OP_EQ, tv_mdiff(&end, &start));
  418. start.tv_sec = TV_SEC_MIN;
  419. start.tv_usec = TV_USEC_MAX;
  420. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&start, &end));
  421. tt_int_op(LONG_MAX, OP_EQ, tv_mdiff(&start, &end));
  422. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&end, &start));
  423. tt_int_op(LONG_MAX, OP_EQ, tv_mdiff(&end, &start));
  424. /* overflows on comparison to maxima / minima */
  425. start.tv_sec = TV_SEC_MIN;
  426. start.tv_usec = 0;
  427. end.tv_sec = TV_SEC_MAX;
  428. end.tv_usec = 0;
  429. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&start, &end));
  430. tt_int_op(LONG_MAX, OP_EQ, tv_mdiff(&start, &end));
  431. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&end, &start));
  432. tt_int_op(LONG_MAX, OP_EQ, tv_mdiff(&end, &start));
  433. end.tv_sec = TV_SEC_MAX;
  434. end.tv_usec = TOR_USEC_PER_SEC;
  435. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&start, &end));
  436. tt_int_op(LONG_MAX, OP_EQ, tv_mdiff(&start, &end));
  437. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&end, &start));
  438. tt_int_op(LONG_MAX, OP_EQ, tv_mdiff(&end, &start));
  439. end.tv_sec = TV_SEC_MAX;
  440. end.tv_usec = 0;
  441. start.tv_sec = TV_SEC_MIN;
  442. start.tv_usec = 0;
  443. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&start, &end));
  444. tt_int_op(LONG_MAX, OP_EQ, tv_mdiff(&start, &end));
  445. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&end, &start));
  446. tt_int_op(LONG_MAX, OP_EQ, tv_mdiff(&end, &start));
  447. start.tv_sec = TV_SEC_MIN;
  448. start.tv_usec = TOR_USEC_PER_SEC;
  449. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&start, &end));
  450. tt_int_op(LONG_MAX, OP_EQ, tv_mdiff(&start, &end));
  451. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&end, &start));
  452. tt_int_op(LONG_MAX, OP_EQ, tv_mdiff(&end, &start));
  453. /* overflows on comparison to maxima / minima with extra usec */
  454. start.tv_sec = TV_SEC_MIN;
  455. start.tv_usec = TOR_USEC_PER_SEC;
  456. end.tv_sec = TV_SEC_MAX;
  457. end.tv_usec = 0;
  458. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&start, &end));
  459. tt_int_op(LONG_MAX, OP_EQ, tv_mdiff(&start, &end));
  460. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&end, &start));
  461. tt_int_op(LONG_MAX, OP_EQ, tv_mdiff(&end, &start));
  462. end.tv_sec = TV_SEC_MAX;
  463. end.tv_usec = TOR_USEC_PER_SEC;
  464. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&start, &end));
  465. tt_int_op(LONG_MAX, OP_EQ, tv_mdiff(&start, &end));
  466. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&end, &start));
  467. tt_int_op(LONG_MAX, OP_EQ, tv_mdiff(&end, &start));
  468. end.tv_sec = TV_SEC_MAX;
  469. end.tv_usec = TOR_USEC_PER_SEC;
  470. start.tv_sec = TV_SEC_MIN;
  471. start.tv_usec = 0;
  472. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&start, &end));
  473. tt_int_op(LONG_MAX, OP_EQ, tv_mdiff(&start, &end));
  474. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&end, &start));
  475. tt_int_op(LONG_MAX, OP_EQ, tv_mdiff(&end, &start));
  476. start.tv_sec = TV_SEC_MIN;
  477. start.tv_usec = TOR_USEC_PER_SEC;
  478. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&start, &end));
  479. tt_int_op(LONG_MAX, OP_EQ, tv_mdiff(&start, &end));
  480. tt_int_op(LONG_MAX, OP_EQ, tv_udiff(&end, &start));
  481. tt_int_op(LONG_MAX, OP_EQ, tv_mdiff(&end, &start));
  482. /* Test tor_timegm & tor_gmtime_r */
  483. /* The test values here are confirmed to be correct on a platform
  484. * with a working timegm & gmtime_r. */
  485. /* Start with known-zero a_time and b_time.
  486. * This avoids passing uninitialised values to TM_EQUAL in a_time.
  487. * Zeroing may not be needed for b_time, as long as tor_gmtime_r
  488. * never reads the existing values in the structure.
  489. * But we really don't want intermittently failing tests. */
  490. memset(&a_time, 0, sizeof(struct tm));
  491. memset(&b_time, 0, sizeof(struct tm));
  492. a_time.tm_year = 2003-1900;
  493. a_time.tm_mon = 7;
  494. a_time.tm_mday = 30;
  495. a_time.tm_hour = 6;
  496. a_time.tm_min = 14;
  497. a_time.tm_sec = 55;
  498. t_res = 1062224095UL;
  499. tt_int_op(t_res, OP_EQ, tor_timegm(&a_time));
  500. tor_gmtime_r(&t_res, &b_time);
  501. TM_EQUAL(a_time, b_time);
  502. a_time.tm_year = 2004-1900; /* Try a leap year, after feb. */
  503. t_res = 1093846495UL;
  504. tt_int_op(t_res, OP_EQ, tor_timegm(&a_time));
  505. tor_gmtime_r(&t_res, &b_time);
  506. TM_EQUAL(a_time, b_time);
  507. a_time.tm_mon = 1; /* Try a leap year, in feb. */
  508. a_time.tm_mday = 10;
  509. t_res = 1076393695UL;
  510. tt_int_op(t_res, OP_EQ, tor_timegm(&a_time));
  511. tor_gmtime_r(&t_res, &b_time);
  512. TM_EQUAL(a_time, b_time);
  513. a_time.tm_mon = 0;
  514. t_res = 1073715295UL;
  515. tt_int_op(t_res, OP_EQ, tor_timegm(&a_time));
  516. tor_gmtime_r(&t_res, &b_time);
  517. TM_EQUAL(a_time, b_time);
  518. /* This value is in range with 32 bit and 64 bit time_t */
  519. a_time.tm_year = 2037-1900;
  520. t_res = 2115180895UL;
  521. tt_int_op(t_res, OP_EQ, tor_timegm(&a_time));
  522. tor_gmtime_r(&t_res, &b_time);
  523. TM_EQUAL(a_time, b_time);
  524. /* This value is out of range with 32 bit time_t, but in range for 64 bit
  525. * time_t */
  526. a_time.tm_year = 2039-1900;
  527. #if SIZEOF_TIME_T == 4
  528. setup_full_capture_of_logs(LOG_WARN);
  529. tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
  530. expect_single_log_msg_containing("Result does not fit in tor_timegm");
  531. teardown_capture_of_logs();
  532. #elif SIZEOF_TIME_T == 8
  533. t_res = 2178252895UL;
  534. tt_int_op(t_res, OP_EQ, tor_timegm(&a_time));
  535. tor_gmtime_r(&t_res, &b_time);
  536. TM_EQUAL(a_time, b_time);
  537. #endif /* SIZEOF_TIME_T == 4 || ... */
  538. /* Test tor_timegm out of range */
  539. /* The below tests will all cause a BUG message, so we capture, suppress,
  540. * and detect. */
  541. #define CAPTURE() do { \
  542. setup_full_capture_of_logs(LOG_WARN); \
  543. } while (0)
  544. #define CHECK_TIMEGM_WARNING(msg) do { \
  545. expect_single_log_msg_containing(msg); \
  546. teardown_capture_of_logs(); \
  547. } while (0)
  548. #define CHECK_TIMEGM_ARG_OUT_OF_RANGE(msg) \
  549. CHECK_TIMEGM_WARNING("Out-of-range argument to tor_timegm")
  550. /* year */
  551. /* Wrong year < 1970 */
  552. a_time.tm_year = 1969-1900;
  553. CAPTURE();
  554. tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
  555. CHECK_TIMEGM_ARG_OUT_OF_RANGE();
  556. a_time.tm_year = -1-1900;
  557. CAPTURE();
  558. tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
  559. CHECK_TIMEGM_ARG_OUT_OF_RANGE();
  560. #if SIZEOF_INT == 4 || SIZEOF_INT == 8
  561. a_time.tm_year = -1*(1 << 16);
  562. CAPTURE();
  563. tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
  564. CHECK_TIMEGM_ARG_OUT_OF_RANGE();
  565. /* one of the smallest tm_year values my 64 bit system supports:
  566. * t_res = -9223372036854775LL without clamping */
  567. a_time.tm_year = -292275055-1900;
  568. CAPTURE();
  569. tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
  570. CHECK_TIMEGM_ARG_OUT_OF_RANGE();
  571. a_time.tm_year = INT32_MIN;
  572. CAPTURE();
  573. tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
  574. CHECK_TIMEGM_ARG_OUT_OF_RANGE();
  575. #endif /* SIZEOF_INT == 4 || SIZEOF_INT == 8 */
  576. #if SIZEOF_INT == 8
  577. a_time.tm_year = -1*(1 << 48);
  578. CAPTURE();
  579. tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
  580. CHECK_TIMEGM_ARG_OUT_OF_RANGE();
  581. /* while unlikely, the system's gmtime(_r) could return
  582. * a "correct" retrospective gregorian negative year value,
  583. * which I'm pretty sure is:
  584. * -1*(2^63)/60/60/24*2000/730485 + 1970 = -292277022657
  585. * 730485 is the number of days in two millennia, including leap days */
  586. a_time.tm_year = -292277022657-1900;
  587. CAPTURE();
  588. tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
  589. CHECK_TIMEGM_ARG_OUT_OF_RANGE();
  590. a_time.tm_year = INT64_MIN;
  591. CAPTURE();
  592. tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
  593. CHECK_TIMEGM_ARG_OUT_OF_RANGE();
  594. #endif /* SIZEOF_INT == 8 */
  595. /* Wrong year >= INT32_MAX - 1900 */
  596. #if SIZEOF_INT == 4 || SIZEOF_INT == 8
  597. a_time.tm_year = INT32_MAX-1900;
  598. CAPTURE();
  599. tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
  600. CHECK_TIMEGM_ARG_OUT_OF_RANGE();
  601. a_time.tm_year = INT32_MAX;
  602. CAPTURE();
  603. tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
  604. CHECK_TIMEGM_ARG_OUT_OF_RANGE();
  605. #endif /* SIZEOF_INT == 4 || SIZEOF_INT == 8 */
  606. #if SIZEOF_INT == 8
  607. /* one of the largest tm_year values my 64 bit system supports */
  608. a_time.tm_year = 292278994-1900;
  609. CAPTURE();
  610. tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
  611. CHECK_TIMEGM_ARG_OUT_OF_RANGE();
  612. /* while unlikely, the system's gmtime(_r) could return
  613. * a "correct" proleptic gregorian year value,
  614. * which I'm pretty sure is:
  615. * (2^63-1)/60/60/24*2000/730485 + 1970 = 292277026596
  616. * 730485 is the number of days in two millennia, including leap days */
  617. a_time.tm_year = 292277026596-1900;
  618. CAPTURE();
  619. tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
  620. CHECK_TIMEGM_ARG_OUT_OF_RANGE();
  621. a_time.tm_year = INT64_MAX-1900;
  622. CAPTURE();
  623. tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
  624. CHECK_TIMEGM_ARG_OUT_OF_RANGE();
  625. a_time.tm_year = INT64_MAX;
  626. CAPTURE();
  627. tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
  628. CHECK_TIMEGM_ARG_OUT_OF_RANGE();
  629. #endif /* SIZEOF_INT == 8 */
  630. /* month */
  631. a_time.tm_year = 2007-1900; /* restore valid year */
  632. a_time.tm_mon = 12; /* Wrong month, it's 0-based */
  633. CAPTURE();
  634. tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
  635. CHECK_TIMEGM_ARG_OUT_OF_RANGE();
  636. a_time.tm_mon = -1; /* Wrong month */
  637. CAPTURE();
  638. tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
  639. CHECK_TIMEGM_ARG_OUT_OF_RANGE();
  640. /* day */
  641. a_time.tm_mon = 6; /* Try July */
  642. a_time.tm_mday = 32; /* Wrong day */
  643. CAPTURE();
  644. tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
  645. CHECK_TIMEGM_ARG_OUT_OF_RANGE();
  646. a_time.tm_mon = 5; /* Try June */
  647. a_time.tm_mday = 31; /* Wrong day */
  648. CAPTURE();
  649. tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
  650. CHECK_TIMEGM_ARG_OUT_OF_RANGE();
  651. a_time.tm_year = 2008-1900; /* Try a leap year */
  652. a_time.tm_mon = 1; /* in feb. */
  653. a_time.tm_mday = 30; /* Wrong day */
  654. CAPTURE();
  655. tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
  656. CHECK_TIMEGM_ARG_OUT_OF_RANGE();
  657. a_time.tm_year = 2011-1900; /* Try a non-leap year */
  658. a_time.tm_mon = 1; /* in feb. */
  659. a_time.tm_mday = 29; /* Wrong day */
  660. CAPTURE();
  661. tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
  662. CHECK_TIMEGM_ARG_OUT_OF_RANGE();
  663. a_time.tm_mday = 0; /* Wrong day, it's 1-based (to be different) */
  664. CAPTURE();
  665. tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
  666. CHECK_TIMEGM_ARG_OUT_OF_RANGE();
  667. /* hour */
  668. a_time.tm_mday = 3; /* restore valid month day */
  669. a_time.tm_hour = 24; /* Wrong hour, it's 0-based */
  670. CAPTURE();
  671. tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
  672. CHECK_TIMEGM_ARG_OUT_OF_RANGE();
  673. a_time.tm_hour = -1; /* Wrong hour */
  674. CAPTURE();
  675. tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
  676. CHECK_TIMEGM_ARG_OUT_OF_RANGE();
  677. /* minute */
  678. a_time.tm_hour = 22; /* restore valid hour */
  679. a_time.tm_min = 60; /* Wrong minute, it's 0-based */
  680. CAPTURE();
  681. tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
  682. CHECK_TIMEGM_ARG_OUT_OF_RANGE();
  683. a_time.tm_min = -1; /* Wrong minute */
  684. CAPTURE();
  685. tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
  686. CHECK_TIMEGM_ARG_OUT_OF_RANGE();
  687. /* second */
  688. a_time.tm_min = 37; /* restore valid minute */
  689. a_time.tm_sec = 61; /* Wrong second: 0-based with leap seconds */
  690. CAPTURE();
  691. tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
  692. CHECK_TIMEGM_ARG_OUT_OF_RANGE();
  693. a_time.tm_sec = -1; /* Wrong second */
  694. CAPTURE();
  695. tt_int_op((time_t) -1,OP_EQ, tor_timegm(&a_time));
  696. CHECK_TIMEGM_ARG_OUT_OF_RANGE();
  697. /* Test tor_gmtime_r out of range */
  698. /* time_t < 0 yields a year clamped to 1 or 1970,
  699. * depending on whether the implementation of the system gmtime(_r)
  700. * sets struct tm (1) or not (1970) */
  701. t_res = -1;
  702. tor_gmtime_r(&t_res, &b_time);
  703. tt_assert(b_time.tm_year == (1970-1900) ||
  704. b_time.tm_year == (1969-1900));
  705. if (sizeof(time_t) == 4 || sizeof(time_t) == 8) {
  706. t_res = -1*(1 << 30);
  707. tor_gmtime_r(&t_res, &b_time);
  708. tt_assert(b_time.tm_year == (1970-1900) ||
  709. b_time.tm_year == (1935-1900));
  710. t_res = INT32_MIN;
  711. tor_gmtime_r(&t_res, &b_time);
  712. tt_assert(b_time.tm_year == (1970-1900) ||
  713. b_time.tm_year == (1901-1900));
  714. }
  715. #if SIZEOF_TIME_T == 8
  716. {
  717. /* one of the smallest tm_year values my 64 bit system supports:
  718. * b_time.tm_year == (-292275055LL-1900LL) without clamping */
  719. t_res = -9223372036854775LL;
  720. tor_gmtime_r(&t_res, &b_time);
  721. tt_assert(b_time.tm_year == (1970-1900) ||
  722. b_time.tm_year == (1-1900));
  723. /* while unlikely, the system's gmtime(_r) could return
  724. * a "correct" retrospective gregorian negative year value,
  725. * which I'm pretty sure is:
  726. * -1*(2^63)/60/60/24*2000/730485 + 1970 = -292277022657
  727. * 730485 is the number of days in two millennia, including leap days
  728. * (int64_t)b_time.tm_year == (-292277022657LL-1900LL) without clamping */
  729. t_res = INT64_MIN;
  730. CAPTURE();
  731. tor_gmtime_r(&t_res, &b_time);
  732. if (! (b_time.tm_year == (1970-1900) ||
  733. b_time.tm_year == (1-1900))) {
  734. tt_int_op(b_time.tm_year, OP_EQ, 1970-1900);
  735. }
  736. if (b_time.tm_year != 1970-1900) {
  737. CHECK_TIMEGM_WARNING("Rounding up to ");
  738. } else {
  739. teardown_capture_of_logs();
  740. }
  741. }
  742. #endif /* SIZEOF_TIME_T == 8 */
  743. /* time_t >= INT_MAX yields a year clamped to 2037 or 9999,
  744. * depending on whether the implementation of the system gmtime(_r)
  745. * sets struct tm (9999) or not (2037) */
  746. #if SIZEOF_TIME_T == 4 || SIZEOF_TIME_T == 8
  747. {
  748. t_res = 3*(1 << 29);
  749. tor_gmtime_r(&t_res, &b_time);
  750. tt_assert(b_time.tm_year == (2021-1900));
  751. t_res = INT32_MAX;
  752. tor_gmtime_r(&t_res, &b_time);
  753. tt_assert(b_time.tm_year == (2037-1900) ||
  754. b_time.tm_year == (2038-1900));
  755. }
  756. #endif /* SIZEOF_TIME_T == 4 || SIZEOF_TIME_T == 8 */
  757. #if SIZEOF_TIME_T == 8
  758. {
  759. /* one of the largest tm_year values my 64 bit system supports:
  760. * b_time.tm_year == (292278994L-1900L) without clamping */
  761. t_res = 9223372036854775LL;
  762. tor_gmtime_r(&t_res, &b_time);
  763. tt_assert(b_time.tm_year == (2037-1900) ||
  764. b_time.tm_year == (9999-1900));
  765. /* while unlikely, the system's gmtime(_r) could return
  766. * a "correct" proleptic gregorian year value,
  767. * which I'm pretty sure is:
  768. * (2^63-1)/60/60/24*2000/730485 + 1970 = 292277026596
  769. * 730485 is the number of days in two millennia, including leap days
  770. * (int64_t)b_time.tm_year == (292277026596L-1900L) without clamping */
  771. t_res = INT64_MAX;
  772. CAPTURE();
  773. tor_gmtime_r(&t_res, &b_time);
  774. CHECK_TIMEGM_WARNING("Rounding down to ");
  775. tt_assert(b_time.tm_year == (2037-1900) ||
  776. b_time.tm_year == (9999-1900));
  777. }
  778. #endif /* SIZEOF_TIME_T == 8 */
  779. /* Test {format,parse}_rfc1123_time */
  780. format_rfc1123_time(timestr, 0);
  781. tt_str_op("Thu, 01 Jan 1970 00:00:00 GMT",OP_EQ, timestr);
  782. format_rfc1123_time(timestr, (time_t)1091580502UL);
  783. tt_str_op("Wed, 04 Aug 2004 00:48:22 GMT",OP_EQ, timestr);
  784. t_res = 0;
  785. i = parse_rfc1123_time(timestr, &t_res);
  786. tt_int_op(0,OP_EQ, i);
  787. tt_int_op(t_res,OP_EQ, (time_t)1091580502UL);
  788. /* This value is in range with 32 bit and 64 bit time_t */
  789. format_rfc1123_time(timestr, (time_t)2080000000UL);
  790. tt_str_op("Fri, 30 Nov 2035 01:46:40 GMT",OP_EQ, timestr);
  791. t_res = 0;
  792. i = parse_rfc1123_time(timestr, &t_res);
  793. tt_int_op(0,OP_EQ, i);
  794. tt_int_op(t_res,OP_EQ, (time_t)2080000000UL);
  795. /* This value is out of range with 32 bit time_t, but in range for 64 bit
  796. * time_t */
  797. format_rfc1123_time(timestr, (time_t)2150000000UL);
  798. #if SIZEOF_TIME_T == 4
  799. #if 0
  800. /* Wrapping around will have made it this. */
  801. /* On windows, at least, this is clipped to 1 Jan 1970. ??? */
  802. tt_str_op("Sat, 11 Jan 1902 23:45:04 GMT",OP_EQ, timestr);
  803. #endif
  804. /* Make sure that the right date doesn't parse. */
  805. strlcpy(timestr, "Wed, 17 Feb 2038 06:13:20 GMT", sizeof(timestr));
  806. t_res = 0;
  807. CAPTURE();
  808. i = parse_rfc1123_time(timestr, &t_res);
  809. CHECK_TIMEGM_WARNING("does not fit in tor_timegm");
  810. tt_int_op(-1,OP_EQ, i);
  811. #elif SIZEOF_TIME_T == 8
  812. tt_str_op("Wed, 17 Feb 2038 06:13:20 GMT",OP_EQ, timestr);
  813. t_res = 0;
  814. i = parse_rfc1123_time(timestr, &t_res);
  815. tt_int_op(0,OP_EQ, i);
  816. tt_int_op(t_res,OP_EQ, (time_t)2150000000UL);
  817. #endif /* SIZEOF_TIME_T == 4 || ... */
  818. /* The timezone doesn't matter */
  819. t_res = 0;
  820. tt_int_op(0,OP_EQ,
  821. parse_rfc1123_time("Wed, 04 Aug 2004 00:48:22 ZUL", &t_res));
  822. tt_int_op(t_res,OP_EQ, (time_t)1091580502UL);
  823. tt_int_op(-1,OP_EQ,
  824. parse_rfc1123_time("Wed, zz Aug 2004 99-99x99 GMT", &t_res));
  825. tt_int_op(-1,OP_EQ,
  826. parse_rfc1123_time("Wed, 32 Mar 2011 00:00:00 GMT", &t_res));
  827. tt_int_op(-1,OP_EQ,
  828. parse_rfc1123_time("Wed, 30 Mar 2011 24:00:00 GMT", &t_res));
  829. tt_int_op(-1,OP_EQ,
  830. parse_rfc1123_time("Wed, 30 Mar 2011 23:60:00 GMT", &t_res));
  831. tt_int_op(-1,OP_EQ,
  832. parse_rfc1123_time("Wed, 30 Mar 2011 23:59:62 GMT", &t_res));
  833. tt_int_op(-1,OP_EQ,
  834. parse_rfc1123_time("Wed, 30 Mar 1969 23:59:59 GMT", &t_res));
  835. tt_int_op(-1,OP_EQ,
  836. parse_rfc1123_time("Wed, 30 Ene 2011 23:59:59 GMT", &t_res));
  837. tt_int_op(-1,OP_EQ,
  838. parse_rfc1123_time("Wed, 30 Mar 2011 23:59:59 GM", &t_res));
  839. tt_int_op(-1,OP_EQ,
  840. parse_rfc1123_time("Wed, 30 Mar 1900 23:59:59 GMT", &t_res));
  841. /* Leap year. */
  842. tt_int_op(-1,OP_EQ,
  843. parse_rfc1123_time("Wed, 29 Feb 2011 16:00:00 GMT", &t_res));
  844. tt_int_op(0,OP_EQ,
  845. parse_rfc1123_time("Wed, 29 Feb 2012 16:00:00 GMT", &t_res));
  846. /* Leap second plus one */
  847. tt_int_op(-1,OP_EQ,
  848. parse_rfc1123_time("Wed, 30 Mar 2011 23:59:61 GMT", &t_res));
  849. /* Test parse_iso_time */
  850. t_res = 0;
  851. i = parse_iso_time("", &t_res);
  852. tt_int_op(-1,OP_EQ, i);
  853. t_res = 0;
  854. i = parse_iso_time("2004-08-32 00:48:22", &t_res);
  855. tt_int_op(-1,OP_EQ, i);
  856. t_res = 0;
  857. i = parse_iso_time("1969-08-03 00:48:22", &t_res);
  858. tt_int_op(-1,OP_EQ, i);
  859. t_res = 0;
  860. i = parse_iso_time("2004-08-04 00:48:22", &t_res);
  861. tt_int_op(0,OP_EQ, i);
  862. tt_int_op(t_res,OP_EQ, (time_t)1091580502UL);
  863. t_res = 0;
  864. i = parse_iso_time("2004-8-4 0:48:22", &t_res);
  865. tt_int_op(0,OP_EQ, i);
  866. tt_int_op(t_res,OP_EQ, (time_t)1091580502UL);
  867. /* This value is in range with 32 bit and 64 bit time_t */
  868. t_res = 0;
  869. i = parse_iso_time("2035-11-30 01:46:40", &t_res);
  870. tt_int_op(0,OP_EQ, i);
  871. tt_int_op(t_res,OP_EQ, (time_t)2080000000UL);
  872. /* This value is out of range with 32 bit time_t, but in range for 64 bit
  873. * time_t */
  874. t_res = 0;
  875. #if SIZEOF_TIME_T == 4
  876. CAPTURE();
  877. i = parse_iso_time("2038-02-17 06:13:20", &t_res);
  878. tt_int_op(-1,OP_EQ, i);
  879. CHECK_TIMEGM_WARNING("does not fit in tor_timegm");
  880. #elif SIZEOF_TIME_T == 8
  881. i = parse_iso_time("2038-02-17 06:13:20", &t_res);
  882. tt_int_op(0,OP_EQ, i);
  883. tt_int_op(t_res,OP_EQ, (time_t)2150000000UL);
  884. #endif /* SIZEOF_TIME_T == 4 || ... */
  885. tt_int_op(-1,OP_EQ, parse_iso_time("2004-08-zz 99-99x99", &t_res));
  886. tt_int_op(-1,OP_EQ, parse_iso_time("2011-03-32 00:00:00", &t_res));
  887. tt_int_op(-1,OP_EQ, parse_iso_time("2011-03-30 24:00:00", &t_res));
  888. tt_int_op(-1,OP_EQ, parse_iso_time("2011-03-30 23:60:00", &t_res));
  889. tt_int_op(-1,OP_EQ, parse_iso_time("2011-03-30 23:59:62", &t_res));
  890. tt_int_op(-1,OP_EQ, parse_iso_time("1969-03-30 23:59:59", &t_res));
  891. tt_int_op(-1,OP_EQ, parse_iso_time("2011-00-30 23:59:59", &t_res));
  892. tt_int_op(-1,OP_EQ, parse_iso_time("2147483647-08-29 14:00:00", &t_res));
  893. tt_int_op(-1,OP_EQ, parse_iso_time("2011-03-30 23:59", &t_res));
  894. tt_int_op(-1,OP_EQ, parse_iso_time("2004-08-04 00:48:22.100", &t_res));
  895. tt_int_op(-1,OP_EQ, parse_iso_time("2004-08-04 00:48:22XYZ", &t_res));
  896. /* but... that _is_ acceptable if we aren't being strict. */
  897. t_res = 0;
  898. i = parse_iso_time_("2004-08-04 00:48:22XYZ", &t_res, 0, 0);
  899. tt_int_op(0,OP_EQ, i);
  900. tt_int_op(t_res,OP_EQ, (time_t)1091580502UL);
  901. /* try nospace variant. */
  902. t_res = 0;
  903. i = parse_iso_time_nospace("2004-08-04T00:48:22", &t_res);
  904. tt_int_op(0,OP_EQ, i);
  905. tt_int_op(t_res,OP_EQ, (time_t)1091580502UL);
  906. tt_int_op(-1,OP_EQ, parse_iso_time("2004-08-04T00:48:22", &t_res));
  907. tt_int_op(-1,OP_EQ, parse_iso_time_nospace("2004-08-04 00:48:22", &t_res));
  908. tt_int_op(-1,OP_EQ, parse_iso_time("2004-08-04x00:48:22", &t_res));
  909. tt_int_op(-1,OP_EQ, parse_iso_time_nospace("2004-08-04x00:48:22", &t_res));
  910. /* Test tor_gettimeofday */
  911. end.tv_sec = 4;
  912. end.tv_usec = 999990;
  913. start.tv_sec = 1;
  914. start.tv_usec = 500;
  915. tor_gettimeofday(&start);
  916. /* now make sure time works. */
  917. tor_gettimeofday(&end);
  918. /* We might've timewarped a little. */
  919. tt_int_op(tv_udiff(&start, &end), OP_GE, -5000);
  920. /* Test format_iso_time */
  921. tv.tv_sec = (time_t)1326296338UL;
  922. tv.tv_usec = 3060;
  923. format_iso_time(timestr, (time_t)tv.tv_sec);
  924. tt_str_op("2012-01-11 15:38:58",OP_EQ, timestr);
  925. /* The output of format_local_iso_time will vary by timezone, and setting
  926. our timezone for testing purposes would be a nontrivial flaky pain.
  927. Skip this test for now.
  928. format_local_iso_time(timestr, tv.tv_sec);
  929. test_streq("2012-01-11 10:38:58", timestr);
  930. */
  931. format_iso_time_nospace(timestr, (time_t)tv.tv_sec);
  932. tt_str_op("2012-01-11T15:38:58",OP_EQ, timestr);
  933. tt_int_op(strlen(timestr),OP_EQ, ISO_TIME_LEN);
  934. format_iso_time_nospace_usec(timestr, &tv);
  935. tt_str_op("2012-01-11T15:38:58.003060",OP_EQ, timestr);
  936. tt_int_op(strlen(timestr),OP_EQ, ISO_TIME_USEC_LEN);
  937. tv.tv_usec = 0;
  938. /* This value is in range with 32 bit and 64 bit time_t */
  939. tv.tv_sec = (time_t)2080000000UL;
  940. format_iso_time(timestr, (time_t)tv.tv_sec);
  941. tt_str_op("2035-11-30 01:46:40",OP_EQ, timestr);
  942. /* This value is out of range with 32 bit time_t, but in range for 64 bit
  943. * time_t */
  944. tv.tv_sec = (time_t)2150000000UL;
  945. format_iso_time(timestr, (time_t)tv.tv_sec);
  946. #if SIZEOF_TIME_T == 4
  947. /* format_iso_time should indicate failure on overflow, but it doesn't yet.
  948. * Hopefully #18480 will improve the failure semantics in this case.
  949. tt_str_op("2038-02-17 06:13:20",OP_EQ, timestr);
  950. */
  951. #elif SIZEOF_TIME_T == 8
  952. #ifndef _WIN32
  953. /* This SHOULD work on windows too; see bug #18665 */
  954. tt_str_op("2038-02-17 06:13:20",OP_EQ, timestr);
  955. #endif
  956. #endif /* SIZEOF_TIME_T == 4 || ... */
  957. #undef CAPTURE
  958. #undef CHECK_TIMEGM_ARG_OUT_OF_RANGE
  959. done:
  960. teardown_capture_of_logs();
  961. }
  962. static void
  963. test_util_parse_http_time(void *arg)
  964. {
  965. struct tm a_time;
  966. char b[ISO_TIME_LEN+1];
  967. (void)arg;
  968. #define T(s) do { \
  969. format_iso_time(b, tor_timegm(&a_time)); \
  970. tt_str_op(b, OP_EQ, (s)); \
  971. b[0]='\0'; \
  972. } while (0)
  973. /* Test parse_http_time */
  974. tt_int_op(-1,OP_EQ,
  975. parse_http_time("", &a_time));
  976. tt_int_op(-1,OP_EQ,
  977. parse_http_time("Sunday, 32 Aug 2004 00:48:22 GMT", &a_time));
  978. tt_int_op(-1,OP_EQ,
  979. parse_http_time("Sunday, 3 Aug 1869 00:48:22 GMT", &a_time));
  980. tt_int_op(-1,OP_EQ,
  981. parse_http_time("Sunday, 32-Aug-94 00:48:22 GMT", &a_time));
  982. tt_int_op(-1,OP_EQ,
  983. parse_http_time("Sunday, 3-Ago-04 00:48:22", &a_time));
  984. tt_int_op(-1,OP_EQ,
  985. parse_http_time("Sunday, August the third", &a_time));
  986. tt_int_op(-1,OP_EQ,
  987. parse_http_time("Wednesday,,04 Aug 1994 00:48:22 GMT", &a_time));
  988. tt_int_op(0,OP_EQ,
  989. parse_http_time("Wednesday, 04 Aug 1994 00:48:22 GMT", &a_time));
  990. tt_int_op((time_t)775961302UL,OP_EQ, tor_timegm(&a_time));
  991. T("1994-08-04 00:48:22");
  992. tt_int_op(0,OP_EQ,
  993. parse_http_time("Wednesday, 4 Aug 1994 0:48:22 GMT", &a_time));
  994. tt_int_op((time_t)775961302UL,OP_EQ, tor_timegm(&a_time));
  995. T("1994-08-04 00:48:22");
  996. tt_int_op(0,OP_EQ,
  997. parse_http_time("Miercoles, 4 Aug 1994 0:48:22 GMT", &a_time));
  998. tt_int_op((time_t)775961302UL,OP_EQ, tor_timegm(&a_time));
  999. T("1994-08-04 00:48:22");
  1000. tt_int_op(0,OP_EQ,
  1001. parse_http_time("Wednesday, 04-Aug-94 00:48:22 GMT", &a_time));
  1002. tt_int_op((time_t)775961302UL,OP_EQ, tor_timegm(&a_time));
  1003. T("1994-08-04 00:48:22");
  1004. tt_int_op(0,OP_EQ,
  1005. parse_http_time("Wednesday, 4-Aug-94 0:48:22 GMT", &a_time));
  1006. tt_int_op((time_t)775961302UL,OP_EQ, tor_timegm(&a_time));
  1007. T("1994-08-04 00:48:22");
  1008. tt_int_op(0,OP_EQ,
  1009. parse_http_time("Miercoles, 4-Aug-94 0:48:22 GMT", &a_time));
  1010. tt_int_op((time_t)775961302UL,OP_EQ, tor_timegm(&a_time));
  1011. T("1994-08-04 00:48:22");
  1012. tt_int_op(0,OP_EQ, parse_http_time("Wed Aug 04 00:48:22 1994", &a_time));
  1013. tt_int_op((time_t)775961302UL,OP_EQ, tor_timegm(&a_time));
  1014. T("1994-08-04 00:48:22");
  1015. tt_int_op(0,OP_EQ, parse_http_time("Wed Aug 4 0:48:22 1994", &a_time));
  1016. tt_int_op((time_t)775961302UL,OP_EQ, tor_timegm(&a_time));
  1017. T("1994-08-04 00:48:22");
  1018. tt_int_op(0,OP_EQ, parse_http_time("Mie Aug 4 0:48:22 1994", &a_time));
  1019. tt_int_op((time_t)775961302UL,OP_EQ, tor_timegm(&a_time));
  1020. T("1994-08-04 00:48:22");
  1021. tt_int_op(0,OP_EQ,parse_http_time("Sun, 1 Jan 2012 00:00:00 GMT", &a_time));
  1022. tt_int_op((time_t)1325376000UL,OP_EQ, tor_timegm(&a_time));
  1023. T("2012-01-01 00:00:00");
  1024. tt_int_op(0,OP_EQ,parse_http_time("Mon, 31 Dec 2012 00:00:00 GMT", &a_time));
  1025. tt_int_op((time_t)1356912000UL,OP_EQ, tor_timegm(&a_time));
  1026. T("2012-12-31 00:00:00");
  1027. /* This value is in range with 32 bit and 64 bit time_t */
  1028. tt_int_op(0,OP_EQ,parse_http_time("Fri, 30 Nov 2035 01:46:40 GMT", &a_time));
  1029. tt_int_op((time_t)2080000000UL,OP_EQ, tor_timegm(&a_time));
  1030. T("2035-11-30 01:46:40");
  1031. /* This value is out of range with 32 bit time_t, but in range for 64 bit
  1032. * time_t */
  1033. #if SIZEOF_TIME_T == 4
  1034. /* parse_http_time should indicate failure on overflow, but it doesn't yet.
  1035. * Hopefully #18480 will improve the failure semantics in this case. */
  1036. setup_full_capture_of_logs(LOG_WARN);
  1037. tt_int_op(0,OP_EQ,parse_http_time("Wed, 17 Feb 2038 06:13:20 GMT", &a_time));
  1038. tt_int_op((time_t)-1,OP_EQ, tor_timegm(&a_time));
  1039. expect_single_log_msg_containing("does not fit in tor_timegm");
  1040. teardown_capture_of_logs();
  1041. #elif SIZEOF_TIME_T == 8
  1042. tt_int_op(0,OP_EQ,parse_http_time("Wed, 17 Feb 2038 06:13:20 GMT", &a_time));
  1043. tt_int_op((time_t)2150000000UL,OP_EQ, tor_timegm(&a_time));
  1044. T("2038-02-17 06:13:20");
  1045. #endif /* SIZEOF_TIME_T == 4 || ... */
  1046. tt_int_op(-1,OP_EQ, parse_http_time("2004-08-zz 99-99x99 GMT", &a_time));
  1047. tt_int_op(-1,OP_EQ, parse_http_time("2011-03-32 00:00:00 GMT", &a_time));
  1048. tt_int_op(-1,OP_EQ, parse_http_time("2011-03-30 24:00:00 GMT", &a_time));
  1049. tt_int_op(-1,OP_EQ, parse_http_time("2011-03-30 23:60:00 GMT", &a_time));
  1050. tt_int_op(-1,OP_EQ, parse_http_time("2011-03-30 23:59:62 GMT", &a_time));
  1051. tt_int_op(-1,OP_EQ, parse_http_time("1969-03-30 23:59:59 GMT", &a_time));
  1052. tt_int_op(-1,OP_EQ, parse_http_time("2011-00-30 23:59:59 GMT", &a_time));
  1053. tt_int_op(-1,OP_EQ, parse_http_time("2011-03-30 23:59", &a_time));
  1054. #undef T
  1055. done:
  1056. teardown_capture_of_logs();
  1057. }
  1058. static void
  1059. test_util_config_line(void *arg)
  1060. {
  1061. char buf[1024];
  1062. char *k=NULL, *v=NULL;
  1063. const char *str;
  1064. /* Test parse_config_line_from_str */
  1065. (void)arg;
  1066. strlcpy(buf, "k v\n" " key value with spaces \n" "keykey val\n"
  1067. "k2\n"
  1068. "k3 \n" "\n" " \n" "#comment\n"
  1069. "k4#a\n" "k5#abc\n" "k6 val #with comment\n"
  1070. "kseven \"a quoted 'string\"\n"
  1071. "k8 \"a \\x71uoted\\n\\\"str\\\\ing\\t\\001\\01\\1\\\"\"\n"
  1072. "k9 a line that\\\n spans two lines.\n\n"
  1073. "k10 more than\\\n one contin\\\nuation\n"
  1074. "k11 \\\ncontinuation at the start\n"
  1075. "k12 line with a\\\n#comment\n embedded\n"
  1076. "k13\\\ncontinuation at the very start\n"
  1077. "k14 a line that has a comment and # ends with a slash \\\n"
  1078. "k15 this should be the next new line\n"
  1079. "k16 a line that has a comment and # ends without a slash \n"
  1080. "k17 this should be the next new line\n"
  1081. , sizeof(buf));
  1082. str = buf;
  1083. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1084. tt_str_op(k,OP_EQ, "k");
  1085. tt_str_op(v,OP_EQ, "v");
  1086. tor_free(k); tor_free(v);
  1087. tt_assert(!strcmpstart(str, "key value with"));
  1088. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1089. tt_str_op(k,OP_EQ, "key");
  1090. tt_str_op(v,OP_EQ, "value with spaces");
  1091. tor_free(k); tor_free(v);
  1092. tt_assert(!strcmpstart(str, "keykey"));
  1093. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1094. tt_str_op(k,OP_EQ, "keykey");
  1095. tt_str_op(v,OP_EQ, "val");
  1096. tor_free(k); tor_free(v);
  1097. tt_assert(!strcmpstart(str, "k2\n"));
  1098. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1099. tt_str_op(k,OP_EQ, "k2");
  1100. tt_str_op(v,OP_EQ, "");
  1101. tor_free(k); tor_free(v);
  1102. tt_assert(!strcmpstart(str, "k3 \n"));
  1103. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1104. tt_str_op(k,OP_EQ, "k3");
  1105. tt_str_op(v,OP_EQ, "");
  1106. tor_free(k); tor_free(v);
  1107. tt_assert(!strcmpstart(str, "#comment"));
  1108. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1109. tt_str_op(k,OP_EQ, "k4");
  1110. tt_str_op(v,OP_EQ, "");
  1111. tor_free(k); tor_free(v);
  1112. tt_assert(!strcmpstart(str, "k5#abc"));
  1113. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1114. tt_str_op(k,OP_EQ, "k5");
  1115. tt_str_op(v,OP_EQ, "");
  1116. tor_free(k); tor_free(v);
  1117. tt_assert(!strcmpstart(str, "k6"));
  1118. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1119. tt_str_op(k,OP_EQ, "k6");
  1120. tt_str_op(v,OP_EQ, "val");
  1121. tor_free(k); tor_free(v);
  1122. tt_assert(!strcmpstart(str, "kseven"));
  1123. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1124. tt_str_op(k,OP_EQ, "kseven");
  1125. tt_str_op(v,OP_EQ, "a quoted \'string");
  1126. tor_free(k); tor_free(v);
  1127. tt_assert(!strcmpstart(str, "k8 "));
  1128. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1129. tt_str_op(k,OP_EQ, "k8");
  1130. tt_str_op(v,OP_EQ, "a quoted\n\"str\\ing\t\x01\x01\x01\"");
  1131. tor_free(k); tor_free(v);
  1132. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1133. tt_str_op(k,OP_EQ, "k9");
  1134. tt_str_op(v,OP_EQ, "a line that spans two lines.");
  1135. tor_free(k); tor_free(v);
  1136. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1137. tt_str_op(k,OP_EQ, "k10");
  1138. tt_str_op(v,OP_EQ, "more than one continuation");
  1139. tor_free(k); tor_free(v);
  1140. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1141. tt_str_op(k,OP_EQ, "k11");
  1142. tt_str_op(v,OP_EQ, "continuation at the start");
  1143. tor_free(k); tor_free(v);
  1144. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1145. tt_str_op(k,OP_EQ, "k12");
  1146. tt_str_op(v,OP_EQ, "line with a embedded");
  1147. tor_free(k); tor_free(v);
  1148. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1149. tt_str_op(k,OP_EQ, "k13");
  1150. tt_str_op(v,OP_EQ, "continuation at the very start");
  1151. tor_free(k); tor_free(v);
  1152. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1153. tt_str_op(k,OP_EQ, "k14");
  1154. tt_str_op(v,OP_EQ, "a line that has a comment and" );
  1155. tor_free(k); tor_free(v);
  1156. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1157. tt_str_op(k,OP_EQ, "k15");
  1158. tt_str_op(v,OP_EQ, "this should be the next new line");
  1159. tor_free(k); tor_free(v);
  1160. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1161. tt_str_op(k,OP_EQ, "k16");
  1162. tt_str_op(v,OP_EQ, "a line that has a comment and" );
  1163. tor_free(k); tor_free(v);
  1164. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1165. tt_str_op(k,OP_EQ, "k17");
  1166. tt_str_op(v,OP_EQ, "this should be the next new line");
  1167. tor_free(k); tor_free(v);
  1168. tt_str_op(str,OP_EQ, "");
  1169. done:
  1170. tor_free(k);
  1171. tor_free(v);
  1172. }
  1173. static void
  1174. test_util_config_line_quotes(void *arg)
  1175. {
  1176. char buf1[1024];
  1177. char buf2[128];
  1178. char buf3[128];
  1179. char buf4[128];
  1180. char *k=NULL, *v=NULL;
  1181. const char *str;
  1182. /* Test parse_config_line_from_str */
  1183. (void)arg;
  1184. strlcpy(buf1, "kTrailingSpace \"quoted value\" \n"
  1185. "kTrailingGarbage \"quoted value\"trailing garbage\n"
  1186. , sizeof(buf1));
  1187. strlcpy(buf2, "kTrailingSpaceAndGarbage \"quoted value\" trailing space+g\n"
  1188. , sizeof(buf2));
  1189. strlcpy(buf3, "kMultilineTrailingSpace \"mline\\ \nvalue w/ trailing sp\"\n"
  1190. , sizeof(buf3));
  1191. strlcpy(buf4, "kMultilineNoTrailingBackslash \"naked multiline\nvalue\"\n"
  1192. , sizeof(buf4));
  1193. str = buf1;
  1194. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1195. tt_str_op(k,OP_EQ, "kTrailingSpace");
  1196. tt_str_op(v,OP_EQ, "quoted value");
  1197. tor_free(k); tor_free(v);
  1198. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1199. tt_ptr_op(str,OP_EQ, NULL);
  1200. tor_free(k); tor_free(v);
  1201. str = buf2;
  1202. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1203. tt_ptr_op(str,OP_EQ, NULL);
  1204. tor_free(k); tor_free(v);
  1205. str = buf3;
  1206. const char *err = NULL;
  1207. str = parse_config_line_from_str_verbose(str, &k, &v, &err);
  1208. tt_ptr_op(str,OP_EQ, NULL);
  1209. tor_free(k); tor_free(v);
  1210. tt_str_op(err, OP_EQ, "Invalid escape sequence in quoted string");
  1211. str = buf4;
  1212. err = NULL;
  1213. str = parse_config_line_from_str_verbose(str, &k, &v, &err);
  1214. tt_ptr_op(str,OP_EQ, NULL);
  1215. tor_free(k); tor_free(v);
  1216. tt_str_op(err, OP_EQ, "Invalid escape sequence in quoted string");
  1217. done:
  1218. tor_free(k);
  1219. tor_free(v);
  1220. }
  1221. static void
  1222. test_util_config_line_comment_character(void *arg)
  1223. {
  1224. char buf[1024];
  1225. char *k=NULL, *v=NULL;
  1226. const char *str;
  1227. /* Test parse_config_line_from_str */
  1228. (void)arg;
  1229. strlcpy(buf, "k1 \"# in quotes\"\n"
  1230. "k2 some value # some comment\n"
  1231. "k3 /home/user/myTorNetwork#2\n" /* Testcase for #1323 */
  1232. , sizeof(buf));
  1233. str = buf;
  1234. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1235. tt_str_op(k,OP_EQ, "k1");
  1236. tt_str_op(v,OP_EQ, "# in quotes");
  1237. tor_free(k); tor_free(v);
  1238. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1239. tt_str_op(k,OP_EQ, "k2");
  1240. tt_str_op(v,OP_EQ, "some value");
  1241. tor_free(k); tor_free(v);
  1242. tt_str_op(str,OP_EQ, "k3 /home/user/myTorNetwork#2\n");
  1243. #if 0
  1244. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1245. test_streq(k, "k3");
  1246. test_streq(v, "/home/user/myTorNetwork#2");
  1247. tor_free(k); tor_free(v);
  1248. test_streq(str, "");
  1249. #endif /* 0 */
  1250. done:
  1251. tor_free(k);
  1252. tor_free(v);
  1253. }
  1254. static void
  1255. test_util_config_line_escaped_content(void *arg)
  1256. {
  1257. char buf1[1024];
  1258. char buf2[128];
  1259. char buf3[128];
  1260. char buf4[128];
  1261. char buf5[128];
  1262. char buf6[128];
  1263. char *k=NULL, *v=NULL;
  1264. const char *str;
  1265. /* Test parse_config_line_from_str */
  1266. (void)arg;
  1267. strlcpy(buf1, "HexadecimalLower \"\\x2a\"\n"
  1268. "HexadecimalUpper \"\\x2A\"\n"
  1269. "HexadecimalUpperX \"\\X2A\"\n"
  1270. "Octal \"\\52\"\n"
  1271. "Newline \"\\n\"\n"
  1272. "Tab \"\\t\"\n"
  1273. "CarriageReturn \"\\r\"\n"
  1274. "DoubleQuote \"\\\"\"\n"
  1275. "SimpleQuote \"\\'\"\n"
  1276. "Backslash \"\\\\\"\n"
  1277. "Mix \"This is a \\\"star\\\":\\t\\'\\x2a\\'\\nAnd second line\"\n"
  1278. , sizeof(buf1));
  1279. strlcpy(buf2, "BrokenEscapedContent \"\\a\"\n"
  1280. , sizeof(buf2));
  1281. strlcpy(buf3, "BrokenEscapedContent \"\\x\"\n"
  1282. , sizeof(buf3));
  1283. strlcpy(buf4, "BrokenOctal \"\\8\"\n"
  1284. , sizeof(buf4));
  1285. strlcpy(buf5, "BrokenHex \"\\xg4\"\n"
  1286. , sizeof(buf5));
  1287. strlcpy(buf6, "BrokenEscape \"\\"
  1288. , sizeof(buf6));
  1289. str = buf1;
  1290. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1291. tt_str_op(k,OP_EQ, "HexadecimalLower");
  1292. tt_str_op(v,OP_EQ, "*");
  1293. tor_free(k); tor_free(v);
  1294. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1295. tt_str_op(k,OP_EQ, "HexadecimalUpper");
  1296. tt_str_op(v,OP_EQ, "*");
  1297. tor_free(k); tor_free(v);
  1298. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1299. tt_str_op(k,OP_EQ, "HexadecimalUpperX");
  1300. tt_str_op(v,OP_EQ, "*");
  1301. tor_free(k); tor_free(v);
  1302. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1303. tt_str_op(k,OP_EQ, "Octal");
  1304. tt_str_op(v,OP_EQ, "*");
  1305. tor_free(k); tor_free(v);
  1306. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1307. tt_str_op(k,OP_EQ, "Newline");
  1308. tt_str_op(v,OP_EQ, "\n");
  1309. tor_free(k); tor_free(v);
  1310. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1311. tt_str_op(k,OP_EQ, "Tab");
  1312. tt_str_op(v,OP_EQ, "\t");
  1313. tor_free(k); tor_free(v);
  1314. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1315. tt_str_op(k,OP_EQ, "CarriageReturn");
  1316. tt_str_op(v,OP_EQ, "\r");
  1317. tor_free(k); tor_free(v);
  1318. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1319. tt_str_op(k,OP_EQ, "DoubleQuote");
  1320. tt_str_op(v,OP_EQ, "\"");
  1321. tor_free(k); tor_free(v);
  1322. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1323. tt_str_op(k,OP_EQ, "SimpleQuote");
  1324. tt_str_op(v,OP_EQ, "'");
  1325. tor_free(k); tor_free(v);
  1326. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1327. tt_str_op(k,OP_EQ, "Backslash");
  1328. tt_str_op(v,OP_EQ, "\\");
  1329. tor_free(k); tor_free(v);
  1330. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1331. tt_str_op(k,OP_EQ, "Mix");
  1332. tt_str_op(v,OP_EQ, "This is a \"star\":\t'*'\nAnd second line");
  1333. tor_free(k); tor_free(v);
  1334. tt_str_op(str,OP_EQ, "");
  1335. str = buf2;
  1336. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1337. tt_ptr_op(str,OP_EQ, NULL);
  1338. tor_free(k); tor_free(v);
  1339. str = buf3;
  1340. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1341. tt_ptr_op(str,OP_EQ, NULL);
  1342. tor_free(k); tor_free(v);
  1343. str = buf4;
  1344. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1345. tt_ptr_op(str,OP_EQ, NULL);
  1346. tor_free(k); tor_free(v);
  1347. #if 0
  1348. str = buf5;
  1349. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1350. tt_ptr_op(str, OP_EQ, NULL);
  1351. tor_free(k); tor_free(v);
  1352. #endif /* 0 */
  1353. str = buf6;
  1354. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1355. tt_ptr_op(str,OP_EQ, NULL);
  1356. tor_free(k); tor_free(v);
  1357. /* more things to try. */
  1358. /* Bad hex: */
  1359. strlcpy(buf1, "Foo \"\\x9g\"\n", sizeof(buf1));
  1360. strlcpy(buf2, "Foo \"\\xg0\"\n", sizeof(buf2));
  1361. strlcpy(buf3, "Foo \"\\xf\"\n", sizeof(buf3));
  1362. /* bad escape */
  1363. strlcpy(buf4, "Foo \"\\q\"\n", sizeof(buf4));
  1364. /* missing endquote */
  1365. strlcpy(buf5, "Foo \"hello\n", sizeof(buf5));
  1366. /* extra stuff */
  1367. strlcpy(buf6, "Foo \"hello\" world\n", sizeof(buf6));
  1368. str=buf1;
  1369. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1370. tt_ptr_op(str,OP_EQ, NULL);
  1371. tor_free(k); tor_free(v);
  1372. str=buf2;
  1373. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1374. tt_ptr_op(str,OP_EQ, NULL);
  1375. tor_free(k); tor_free(v);
  1376. str=buf3;
  1377. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1378. tt_ptr_op(str,OP_EQ, NULL);
  1379. tor_free(k); tor_free(v);
  1380. str=buf4;
  1381. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1382. tt_ptr_op(str,OP_EQ, NULL);
  1383. tor_free(k); tor_free(v);
  1384. str=buf5;
  1385. str = parse_config_line_from_str_verbose(str, &k, &v, NULL);
  1386. tt_ptr_op(str,OP_EQ, NULL);
  1387. tor_free(k); tor_free(v);
  1388. str=buf6;
  1389. const char *err = NULL;
  1390. str = parse_config_line_from_str_verbose(str, &k, &v, &err);
  1391. tt_ptr_op(str,OP_EQ, NULL);
  1392. tor_free(k); tor_free(v);
  1393. tt_str_op(err,OP_EQ, "Excess data after quoted string");
  1394. done:
  1395. tor_free(k);
  1396. tor_free(v);
  1397. }
  1398. static void
  1399. test_util_config_line_crlf(void *arg)
  1400. {
  1401. char *k=NULL, *v=NULL;
  1402. const char *err = NULL;
  1403. (void)arg;
  1404. const char *str =
  1405. "Hello world\r\n"
  1406. "Hello \"nice big world\"\r\n";
  1407. str = parse_config_line_from_str_verbose(str, &k, &v, &err);
  1408. tt_assert(str);
  1409. tt_str_op(k,OP_EQ,"Hello");
  1410. tt_str_op(v,OP_EQ,"world");
  1411. tt_ptr_op(err, OP_EQ, NULL);
  1412. tor_free(k); tor_free(v);
  1413. str = parse_config_line_from_str_verbose(str, &k, &v, &err);
  1414. tt_assert(str);
  1415. tt_str_op(k,OP_EQ,"Hello");
  1416. tt_str_op(v,OP_EQ,"nice big world");
  1417. tt_ptr_op(err, OP_EQ, NULL);
  1418. tor_free(k); tor_free(v);
  1419. tt_str_op(str,OP_EQ, "");
  1420. done:
  1421. tor_free(k); tor_free(v);
  1422. }
  1423. #ifndef _WIN32
  1424. static void
  1425. test_util_expand_filename(void *arg)
  1426. {
  1427. char *str;
  1428. (void)arg;
  1429. setenv("HOME", "/home/itv", 1); /* For "internal test value" */
  1430. str = expand_filename("");
  1431. tt_str_op("",OP_EQ, str);
  1432. tor_free(str);
  1433. str = expand_filename("/normal/path");
  1434. tt_str_op("/normal/path",OP_EQ, str);
  1435. tor_free(str);
  1436. str = expand_filename("/normal/trailing/path/");
  1437. tt_str_op("/normal/trailing/path/",OP_EQ, str);
  1438. tor_free(str);
  1439. str = expand_filename("~");
  1440. tt_str_op("/home/itv/",OP_EQ, str);
  1441. tor_free(str);
  1442. str = expand_filename("$HOME/nodice");
  1443. tt_str_op("$HOME/nodice",OP_EQ, str);
  1444. tor_free(str);
  1445. str = expand_filename("~/");
  1446. tt_str_op("/home/itv/",OP_EQ, str);
  1447. tor_free(str);
  1448. str = expand_filename("~/foobarqux");
  1449. tt_str_op("/home/itv/foobarqux",OP_EQ, str);
  1450. tor_free(str);
  1451. str = expand_filename("~/../../etc/passwd");
  1452. tt_str_op("/home/itv/../../etc/passwd",OP_EQ, str);
  1453. tor_free(str);
  1454. str = expand_filename("~/trailing/");
  1455. tt_str_op("/home/itv/trailing/",OP_EQ, str);
  1456. tor_free(str);
  1457. /* Ideally we'd test ~anotheruser, but that's shady to test (we'd
  1458. have to somehow inject/fake the get_user_homedir call) */
  1459. /* $HOME ending in a trailing slash */
  1460. setenv("HOME", "/home/itv/", 1);
  1461. str = expand_filename("~");
  1462. tt_str_op("/home/itv/",OP_EQ, str);
  1463. tor_free(str);
  1464. str = expand_filename("~/");
  1465. tt_str_op("/home/itv/",OP_EQ, str);
  1466. tor_free(str);
  1467. str = expand_filename("~/foo");
  1468. tt_str_op("/home/itv/foo",OP_EQ, str);
  1469. tor_free(str);
  1470. /* Try with empty $HOME */
  1471. setenv("HOME", "", 1);
  1472. str = expand_filename("~");
  1473. tt_str_op("/",OP_EQ, str);
  1474. tor_free(str);
  1475. str = expand_filename("~/");
  1476. tt_str_op("/",OP_EQ, str);
  1477. tor_free(str);
  1478. str = expand_filename("~/foobar");
  1479. tt_str_op("/foobar",OP_EQ, str);
  1480. tor_free(str);
  1481. /* Try with $HOME unset */
  1482. unsetenv("HOME");
  1483. str = expand_filename("~");
  1484. tt_str_op("/",OP_EQ, str);
  1485. tor_free(str);
  1486. str = expand_filename("~/");
  1487. tt_str_op("/",OP_EQ, str);
  1488. tor_free(str);
  1489. str = expand_filename("~/foobar");
  1490. tt_str_op("/foobar",OP_EQ, str);
  1491. tor_free(str);
  1492. done:
  1493. tor_free(str);
  1494. }
  1495. #endif /* !defined(_WIN32) */
  1496. /** Test tor_escape_str_for_pt_args(). */
  1497. static void
  1498. test_util_escape_string_socks(void *arg)
  1499. {
  1500. char *escaped_string = NULL;
  1501. /** Simple backslash escape. */
  1502. (void)arg;
  1503. escaped_string = tor_escape_str_for_pt_args("This is a backslash: \\",";\\");
  1504. tt_assert(escaped_string);
  1505. tt_str_op(escaped_string,OP_EQ, "This is a backslash: \\\\");
  1506. tor_free(escaped_string);
  1507. /** Simple semicolon escape. */
  1508. escaped_string = tor_escape_str_for_pt_args("First rule:Do not use ;",";\\");
  1509. tt_assert(escaped_string);
  1510. tt_str_op(escaped_string,OP_EQ, "First rule:Do not use \\;");
  1511. tor_free(escaped_string);
  1512. /** Empty string. */
  1513. escaped_string = tor_escape_str_for_pt_args("", ";\\");
  1514. tt_assert(escaped_string);
  1515. tt_str_op(escaped_string,OP_EQ, "");
  1516. tor_free(escaped_string);
  1517. /** Escape all characters. */
  1518. escaped_string = tor_escape_str_for_pt_args(";\\;\\", ";\\");
  1519. tt_assert(escaped_string);
  1520. tt_str_op(escaped_string,OP_EQ, "\\;\\\\\\;\\\\");
  1521. tor_free(escaped_string);
  1522. escaped_string = tor_escape_str_for_pt_args(";", ";\\");
  1523. tt_assert(escaped_string);
  1524. tt_str_op(escaped_string,OP_EQ, "\\;");
  1525. tor_free(escaped_string);
  1526. done:
  1527. tor_free(escaped_string);
  1528. }
  1529. static void
  1530. test_util_string_is_key_value(void *ptr)
  1531. {
  1532. (void)ptr;
  1533. tt_assert(string_is_key_value(LOG_WARN, "key=value"));
  1534. tt_assert(string_is_key_value(LOG_WARN, "k=v"));
  1535. tt_assert(string_is_key_value(LOG_WARN, "key="));
  1536. tt_assert(string_is_key_value(LOG_WARN, "x="));
  1537. tt_assert(string_is_key_value(LOG_WARN, "xx="));
  1538. tt_assert(!string_is_key_value(LOG_WARN, "=value"));
  1539. tt_assert(!string_is_key_value(LOG_WARN, "=x"));
  1540. tt_assert(!string_is_key_value(LOG_WARN, "="));
  1541. /* ??? */
  1542. /* tt_assert(!string_is_key_value(LOG_WARN, "===")); */
  1543. done:
  1544. ;
  1545. }
  1546. /** Test basic string functionality. */
  1547. static void
  1548. test_util_strmisc(void *arg)
  1549. {
  1550. char buf[1024];
  1551. char *cp_tmp = NULL;
  1552. /* Test strl operations */
  1553. (void)arg;
  1554. tt_int_op(5,OP_EQ, strlcpy(buf, "Hello", 0));
  1555. tt_int_op(5,OP_EQ, strlcpy(buf, "Hello", 10));
  1556. tt_str_op(buf,OP_EQ, "Hello");
  1557. tt_int_op(5,OP_EQ, strlcpy(buf, "Hello", 6));
  1558. tt_str_op(buf,OP_EQ, "Hello");
  1559. tt_int_op(5,OP_EQ, strlcpy(buf, "Hello", 5));
  1560. tt_str_op(buf,OP_EQ, "Hell");
  1561. strlcpy(buf, "Hello", sizeof(buf));
  1562. tt_int_op(10,OP_EQ, strlcat(buf, "Hello", 5));
  1563. /* Test strstrip() */
  1564. strlcpy(buf, "Testing 1 2 3", sizeof(buf));
  1565. tor_strstrip(buf, ",!");
  1566. tt_str_op(buf,OP_EQ, "Testing 1 2 3");
  1567. strlcpy(buf, "!Testing 1 2 3?", sizeof(buf));
  1568. tor_strstrip(buf, "!? ");
  1569. tt_str_op(buf,OP_EQ, "Testing123");
  1570. strlcpy(buf, "!!!Testing 1 2 3??", sizeof(buf));
  1571. tor_strstrip(buf, "!? ");
  1572. tt_str_op(buf,OP_EQ, "Testing123");
  1573. /* Test snprintf */
  1574. /* Returning -1 when there's not enough room in the output buffer */
  1575. tt_int_op(-1,OP_EQ, tor_snprintf(buf, 0, "Foo"));
  1576. tt_int_op(-1,OP_EQ, tor_snprintf(buf, 2, "Foo"));
  1577. tt_int_op(-1,OP_EQ, tor_snprintf(buf, 3, "Foo"));
  1578. tt_int_op(-1,OP_NE, tor_snprintf(buf, 4, "Foo"));
  1579. /* Always NUL-terminate the output */
  1580. tor_snprintf(buf, 5, "abcdef");
  1581. tt_int_op(0,OP_EQ, buf[4]);
  1582. tor_snprintf(buf, 10, "abcdef");
  1583. tt_int_op(0,OP_EQ, buf[6]);
  1584. /* uint64 */
  1585. tor_snprintf(buf, sizeof(buf), "x!"U64_FORMAT"!x",
  1586. U64_PRINTF_ARG(U64_LITERAL(12345678901)));
  1587. tt_str_op("x!12345678901!x",OP_EQ, buf);
  1588. /* Test str{,case}cmpstart */
  1589. tt_assert(strcmpstart("abcdef", "abcdef")==0);
  1590. tt_assert(strcmpstart("abcdef", "abc")==0);
  1591. tt_assert(strcmpstart("abcdef", "abd")<0);
  1592. tt_assert(strcmpstart("abcdef", "abb")>0);
  1593. tt_assert(strcmpstart("ab", "abb")<0);
  1594. tt_assert(strcmpstart("ab", "")==0);
  1595. tt_assert(strcmpstart("ab", "ab ")<0);
  1596. tt_assert(strcasecmpstart("abcdef", "abCdEF")==0);
  1597. tt_assert(strcasecmpstart("abcDeF", "abc")==0);
  1598. tt_assert(strcasecmpstart("abcdef", "Abd")<0);
  1599. tt_assert(strcasecmpstart("Abcdef", "abb")>0);
  1600. tt_assert(strcasecmpstart("ab", "Abb")<0);
  1601. tt_assert(strcasecmpstart("ab", "")==0);
  1602. tt_assert(strcasecmpstart("ab", "ab ")<0);
  1603. /* Test str{,case}cmpend */
  1604. tt_assert(strcmpend("abcdef", "abcdef")==0);
  1605. tt_assert(strcmpend("abcdef", "def")==0);
  1606. tt_assert(strcmpend("abcdef", "deg")<0);
  1607. tt_assert(strcmpend("abcdef", "dee")>0);
  1608. tt_assert(strcmpend("ab", "aab")>0);
  1609. tt_assert(strcasecmpend("AbcDEF", "abcdef")==0);
  1610. tt_assert(strcasecmpend("abcdef", "dEF")==0);
  1611. tt_assert(strcasecmpend("abcdef", "Deg")<0);
  1612. tt_assert(strcasecmpend("abcDef", "dee")>0);
  1613. tt_assert(strcasecmpend("AB", "abb")<0);
  1614. /* Test digest_is_zero */
  1615. memset(buf,0,20);
  1616. buf[20] = 'x';
  1617. tt_assert(tor_digest_is_zero(buf));
  1618. buf[19] = 'x';
  1619. tt_assert(!tor_digest_is_zero(buf));
  1620. /* Test mem_is_zero */
  1621. memset(buf,0,128);
  1622. buf[128] = 'x';
  1623. tt_assert(tor_mem_is_zero(buf, 10));
  1624. tt_assert(tor_mem_is_zero(buf, 20));
  1625. tt_assert(tor_mem_is_zero(buf, 128));
  1626. tt_assert(!tor_mem_is_zero(buf, 129));
  1627. buf[60] = (char)255;
  1628. tt_assert(!tor_mem_is_zero(buf, 128));
  1629. buf[0] = (char)1;
  1630. tt_assert(!tor_mem_is_zero(buf, 10));
  1631. /* Test 'escaped' */
  1632. tt_ptr_op(escaped(NULL), OP_EQ, NULL);
  1633. tt_str_op("\"\"",OP_EQ, escaped(""));
  1634. tt_str_op("\"abcd\"",OP_EQ, escaped("abcd"));
  1635. tt_str_op("\"\\\\ \\n\\r\\t\\\"\\'\"",OP_EQ, escaped("\\ \n\r\t\"'"));
  1636. tt_str_op("\"unnecessary \\'backslashes\\'\"",OP_EQ,
  1637. escaped("unnecessary \'backslashes\'"));
  1638. /* Non-printable characters appear as octal */
  1639. tt_str_op("\"z\\001abc\\277d\"",OP_EQ, escaped("z\001abc\277d"));
  1640. tt_str_op("\"z\\336\\255 ;foo\"",OP_EQ, escaped("z\xde\xad\x20;foo"));
  1641. /* Other cases of esc_for_log{,_len} */
  1642. cp_tmp = esc_for_log(NULL);
  1643. tt_str_op(cp_tmp, OP_EQ, "(null)");
  1644. tor_free(cp_tmp);
  1645. cp_tmp = esc_for_log_len("abcdefg", 3);
  1646. tt_str_op(cp_tmp, OP_EQ, "\"abc\"");
  1647. tor_free(cp_tmp);
  1648. cp_tmp = esc_for_log_len("abcdefg", 100);
  1649. tt_str_op(cp_tmp, OP_EQ, "\"abcdefg\"");
  1650. tor_free(cp_tmp);
  1651. /* Test strndup and memdup */
  1652. {
  1653. const char *s = "abcdefghijklmnopqrstuvwxyz";
  1654. cp_tmp = tor_strndup(s, 30);
  1655. tt_str_op(cp_tmp,OP_EQ, s); /* same string, */
  1656. tt_ptr_op(cp_tmp,OP_NE,s); /* but different pointers. */
  1657. tor_free(cp_tmp);
  1658. cp_tmp = tor_strndup(s, 5);
  1659. tt_str_op(cp_tmp,OP_EQ, "abcde");
  1660. tor_free(cp_tmp);
  1661. s = "a\0b\0c\0d\0e\0";
  1662. cp_tmp = tor_memdup(s,10);
  1663. tt_mem_op(cp_tmp,OP_EQ, s, 10); /* same ram, */
  1664. tt_ptr_op(cp_tmp,OP_NE,s); /* but different pointers. */
  1665. tor_free(cp_tmp);
  1666. }
  1667. /* Test str-foo functions */
  1668. cp_tmp = tor_strdup("abcdef");
  1669. tt_assert(tor_strisnonupper(cp_tmp));
  1670. cp_tmp[3] = 'D';
  1671. tt_assert(!tor_strisnonupper(cp_tmp));
  1672. tor_strupper(cp_tmp);
  1673. tt_str_op(cp_tmp,OP_EQ, "ABCDEF");
  1674. tor_strlower(cp_tmp);
  1675. tt_str_op(cp_tmp,OP_EQ, "abcdef");
  1676. tt_assert(tor_strisnonupper(cp_tmp));
  1677. tt_assert(tor_strisprint(cp_tmp));
  1678. cp_tmp[3] = 3;
  1679. tt_assert(!tor_strisprint(cp_tmp));
  1680. tor_free(cp_tmp);
  1681. /* Test memmem and memstr */
  1682. {
  1683. const char *haystack = "abcde";
  1684. tt_ptr_op(tor_memmem(haystack, 5, "ef", 2), OP_EQ, NULL);
  1685. tt_ptr_op(tor_memmem(haystack, 5, "cd", 2),OP_EQ, haystack + 2);
  1686. tt_ptr_op(tor_memmem(haystack, 5, "cde", 3),OP_EQ, haystack + 2);
  1687. tt_ptr_op(tor_memmem(haystack, 4, "cde", 3), OP_EQ, NULL);
  1688. haystack = "ababcad";
  1689. tt_ptr_op(tor_memmem(haystack, 7, "abc", 3),OP_EQ, haystack + 2);
  1690. tt_ptr_op(tor_memmem(haystack, 7, "ad", 2),OP_EQ, haystack + 5);
  1691. tt_ptr_op(tor_memmem(haystack, 7, "cad", 3),OP_EQ, haystack + 4);
  1692. tt_ptr_op(tor_memmem(haystack, 7, "dadad", 5), OP_EQ, NULL);
  1693. tt_ptr_op(tor_memmem(haystack, 7, "abcdefghij", 10), OP_EQ, NULL);
  1694. /* memstr */
  1695. tt_ptr_op(tor_memstr(haystack, 7, "abc"),OP_EQ, haystack + 2);
  1696. tt_ptr_op(tor_memstr(haystack, 7, "cad"),OP_EQ, haystack + 4);
  1697. tt_ptr_op(tor_memstr(haystack, 6, "cad"), OP_EQ, NULL);
  1698. tt_ptr_op(tor_memstr(haystack, 7, "cadd"), OP_EQ, NULL);
  1699. tt_ptr_op(tor_memstr(haystack, 7, "fe"), OP_EQ, NULL);
  1700. tt_ptr_op(tor_memstr(haystack, 7, "ababcade"), OP_EQ, NULL);
  1701. }
  1702. /* Test hex_str */
  1703. {
  1704. char binary_data[68];
  1705. size_t idx;
  1706. for (idx = 0; idx < sizeof(binary_data); ++idx)
  1707. binary_data[idx] = idx;
  1708. tt_str_op(hex_str(binary_data, 0),OP_EQ, "");
  1709. tt_str_op(hex_str(binary_data, 1),OP_EQ, "00");
  1710. tt_str_op(hex_str(binary_data, 17),OP_EQ,
  1711. "000102030405060708090A0B0C0D0E0F10");
  1712. tt_str_op(hex_str(binary_data, 32),OP_EQ,
  1713. "000102030405060708090A0B0C0D0E0F"
  1714. "101112131415161718191A1B1C1D1E1F");
  1715. tt_str_op(hex_str(binary_data, 34),OP_EQ,
  1716. "000102030405060708090A0B0C0D0E0F"
  1717. "101112131415161718191A1B1C1D1E1F");
  1718. /* Repeat these tests for shorter strings after longer strings
  1719. have been tried, to make sure we're correctly terminating strings */
  1720. tt_str_op(hex_str(binary_data, 1),OP_EQ, "00");
  1721. tt_str_op(hex_str(binary_data, 0),OP_EQ, "");
  1722. }
  1723. /* Test strcmp_opt */
  1724. tt_int_op(strcmp_opt("", "foo"), OP_LT, 0);
  1725. tt_int_op(strcmp_opt("", ""), OP_EQ, 0);
  1726. tt_int_op(strcmp_opt("foo", ""), OP_GT, 0);
  1727. tt_int_op(strcmp_opt(NULL, ""), OP_LT, 0);
  1728. tt_int_op(strcmp_opt(NULL, NULL), OP_EQ, 0);
  1729. tt_int_op(strcmp_opt("", NULL), OP_GT, 0);
  1730. tt_int_op(strcmp_opt(NULL, "foo"), OP_LT, 0);
  1731. tt_int_op(strcmp_opt("foo", NULL), OP_GT, 0);
  1732. /* Test strcmp_len */
  1733. tt_int_op(strcmp_len("foo", "bar", 3), OP_GT, 0);
  1734. tt_int_op(strcmp_len("foo", "bar", 2), OP_LT, 0);
  1735. tt_int_op(strcmp_len("foo2", "foo1", 4), OP_GT, 0);
  1736. tt_int_op(strcmp_len("foo2", "foo1", 3), OP_LT, 0); /* Really stop at len */
  1737. tt_int_op(strcmp_len("foo2", "foo", 3), OP_EQ, 0); /* Really stop at len */
  1738. tt_int_op(strcmp_len("blah", "", 4), OP_GT, 0);
  1739. tt_int_op(strcmp_len("blah", "", 0), OP_EQ, 0);
  1740. done:
  1741. tor_free(cp_tmp);
  1742. }
  1743. static void
  1744. test_util_parse_integer(void *arg)
  1745. {
  1746. (void)arg;
  1747. int i;
  1748. char *cp;
  1749. /* Test parse_long */
  1750. /* Empty/zero input */
  1751. tt_int_op(0L,OP_EQ, tor_parse_long("",10,0,100,&i,NULL));
  1752. tt_int_op(0,OP_EQ, i);
  1753. tt_int_op(0L,OP_EQ, tor_parse_long("0",10,0,100,&i,NULL));
  1754. tt_int_op(1,OP_EQ, i);
  1755. /* Normal cases */
  1756. tt_int_op(10L,OP_EQ, tor_parse_long("10",10,0,100,&i,NULL));
  1757. tt_int_op(1,OP_EQ, i);
  1758. tt_int_op(10L,OP_EQ, tor_parse_long("10",10,0,10,&i,NULL));
  1759. tt_int_op(1,OP_EQ, i);
  1760. tt_int_op(10L,OP_EQ, tor_parse_long("10",10,10,100,&i,NULL));
  1761. tt_int_op(1,OP_EQ, i);
  1762. tt_int_op(-50L,OP_EQ, tor_parse_long("-50",10,-100,100,&i,NULL));
  1763. tt_int_op(1,OP_EQ, i);
  1764. tt_int_op(-50L,OP_EQ, tor_parse_long("-50",10,-100,0,&i,NULL));
  1765. tt_int_op(1,OP_EQ, i);
  1766. tt_int_op(-50L,OP_EQ, tor_parse_long("-50",10,-50,0,&i,NULL));
  1767. tt_int_op(1,OP_EQ, i);
  1768. /* Extra garbage */
  1769. tt_int_op(0L,OP_EQ, tor_parse_long("10m",10,0,100,&i,NULL));
  1770. tt_int_op(0,OP_EQ, i);
  1771. tt_int_op(0L,OP_EQ, tor_parse_long("-50 plus garbage",10,-100,100,&i,NULL));
  1772. tt_int_op(0,OP_EQ, i);
  1773. tt_int_op(10L,OP_EQ, tor_parse_long("10m",10,0,100,&i,&cp));
  1774. tt_int_op(1,OP_EQ, i);
  1775. tt_str_op(cp,OP_EQ, "m");
  1776. tt_int_op(-50L,OP_EQ, tor_parse_long("-50 plus garbage",10,-100,100,&i,&cp));
  1777. tt_int_op(1,OP_EQ, i);
  1778. tt_str_op(cp,OP_EQ, " plus garbage");
  1779. /* Illogical min max */
  1780. tt_int_op(0L,OP_EQ, tor_parse_long("10",10,50,4,&i,NULL));
  1781. tt_int_op(0,OP_EQ, i);
  1782. tt_int_op(0L,OP_EQ, tor_parse_long("-50",10,100,-100,&i,NULL));
  1783. tt_int_op(0,OP_EQ, i);
  1784. /* Out of bounds */
  1785. tt_int_op(0L,OP_EQ, tor_parse_long("10",10,50,100,&i,NULL));
  1786. tt_int_op(0,OP_EQ, i);
  1787. tt_int_op(0L,OP_EQ, tor_parse_long("-50",10,0,100,&i,NULL));
  1788. tt_int_op(0,OP_EQ, i);
  1789. /* Base different than 10 */
  1790. tt_int_op(2L,OP_EQ, tor_parse_long("10",2,0,100,NULL,NULL));
  1791. tt_int_op(0L,OP_EQ, tor_parse_long("2",2,0,100,NULL,NULL));
  1792. tt_int_op(68284L,OP_EQ, tor_parse_long("10abc",16,0,70000,NULL,NULL));
  1793. tt_int_op(68284L,OP_EQ, tor_parse_long("10ABC",16,0,70000,NULL,NULL));
  1794. tt_int_op(0L,OP_EQ, tor_parse_long("10",-2,0,100,NULL,NULL));
  1795. tt_int_op(0,OP_EQ, tor_parse_long("10ABC",-1,0,70000,&i,NULL));
  1796. tt_int_op(i,OP_EQ, 0);
  1797. /* Test parse_ulong */
  1798. tt_int_op(0UL,OP_EQ, tor_parse_ulong("",10,0,100,NULL,NULL));
  1799. tt_int_op(0UL,OP_EQ, tor_parse_ulong("0",10,0,100,NULL,NULL));
  1800. tt_int_op(10UL,OP_EQ, tor_parse_ulong("10",10,0,100,NULL,NULL));
  1801. tt_int_op(0UL,OP_EQ, tor_parse_ulong("10",10,50,100,NULL,NULL));
  1802. tt_int_op(10UL,OP_EQ, tor_parse_ulong("10",10,0,10,NULL,NULL));
  1803. tt_int_op(10UL,OP_EQ, tor_parse_ulong("10",10,10,100,NULL,NULL));
  1804. tt_int_op(0UL,OP_EQ, tor_parse_ulong("8",8,0,100,NULL,NULL));
  1805. tt_int_op(50UL,OP_EQ, tor_parse_ulong("50",10,50,100,NULL,NULL));
  1806. tt_int_op(0UL,OP_EQ, tor_parse_ulong("-50",10,0,100,NULL,NULL));
  1807. tt_int_op(0UL,OP_EQ, tor_parse_ulong("50",-1,50,100,&i,NULL));
  1808. tt_int_op(0,OP_EQ, i);
  1809. tt_int_op(0UL,OP_EQ, tor_parse_ulong("-50",10,0,100,&i,NULL));
  1810. tt_int_op(0,OP_EQ, i);
  1811. /* Test parse_uint64 */
  1812. tt_assert(U64_LITERAL(10) == tor_parse_uint64("10 x",10,0,100, &i, &cp));
  1813. tt_int_op(1,OP_EQ, i);
  1814. tt_str_op(cp,OP_EQ, " x");
  1815. tt_assert(U64_LITERAL(12345678901) ==
  1816. tor_parse_uint64("12345678901",10,0,UINT64_MAX, &i, &cp));
  1817. tt_int_op(1,OP_EQ, i);
  1818. tt_str_op(cp,OP_EQ, "");
  1819. tt_assert(U64_LITERAL(0) ==
  1820. tor_parse_uint64("12345678901",10,500,INT32_MAX, &i, &cp));
  1821. tt_int_op(0,OP_EQ, i);
  1822. tt_assert(U64_LITERAL(0) ==
  1823. tor_parse_uint64("123",-1,0,INT32_MAX, &i, &cp));
  1824. tt_int_op(0,OP_EQ, i);
  1825. {
  1826. /* Test parse_double */
  1827. double d = tor_parse_double("10", 0, (double)UINT64_MAX,&i,NULL);
  1828. tt_int_op(1,OP_EQ, i);
  1829. tt_assert(DBL_TO_U64(d) == 10);
  1830. d = tor_parse_double("0", 0, (double)UINT64_MAX,&i,NULL);
  1831. tt_int_op(1,OP_EQ, i);
  1832. tt_assert(DBL_TO_U64(d) == 0);
  1833. d = tor_parse_double(" ", 0, (double)UINT64_MAX,&i,NULL);
  1834. tt_double_op(fabs(d), OP_LT, 1e-10);
  1835. tt_int_op(0,OP_EQ, i);
  1836. d = tor_parse_double(".0a", 0, (double)UINT64_MAX,&i,NULL);
  1837. tt_double_op(fabs(d), OP_LT, 1e-10);
  1838. tt_int_op(0,OP_EQ, i);
  1839. d = tor_parse_double(".0a", 0, (double)UINT64_MAX,&i,&cp);
  1840. tt_double_op(fabs(d), OP_LT, 1e-10);
  1841. tt_int_op(1,OP_EQ, i);
  1842. d = tor_parse_double("-.0", 0, (double)UINT64_MAX,&i,NULL);
  1843. tt_int_op(1,OP_EQ, i);
  1844. tt_assert(DBL_TO_U64(d) == 0);
  1845. d = tor_parse_double("-10", -100.0, 100.0,&i,NULL);
  1846. tt_int_op(1,OP_EQ, i);
  1847. tt_double_op(fabs(d - -10.0),OP_LT, 1E-12);
  1848. }
  1849. {
  1850. /* Test tor_parse_* where we overflow/underflow the underlying type. */
  1851. /* This string should overflow 64-bit ints. */
  1852. #define TOOBIG "100000000000000000000000000"
  1853. tt_int_op(0L, OP_EQ,
  1854. tor_parse_long(TOOBIG, 10, LONG_MIN, LONG_MAX, &i, NULL));
  1855. tt_int_op(i,OP_EQ, 0);
  1856. tt_int_op(0L,OP_EQ,
  1857. tor_parse_long("-"TOOBIG, 10, LONG_MIN, LONG_MAX, &i, NULL));
  1858. tt_int_op(i,OP_EQ, 0);
  1859. tt_int_op(0UL,OP_EQ, tor_parse_ulong(TOOBIG, 10, 0, ULONG_MAX, &i, NULL));
  1860. tt_int_op(i,OP_EQ, 0);
  1861. tt_u64_op(U64_LITERAL(0), OP_EQ, tor_parse_uint64(TOOBIG, 10,
  1862. 0, UINT64_MAX, &i, NULL));
  1863. tt_int_op(i,OP_EQ, 0);
  1864. }
  1865. done:
  1866. ;
  1867. }
  1868. static void
  1869. test_util_pow2(void *arg)
  1870. {
  1871. /* Test tor_log2(). */
  1872. (void)arg;
  1873. tt_int_op(tor_log2(64),OP_EQ, 6);
  1874. tt_int_op(tor_log2(65),OP_EQ, 6);
  1875. tt_int_op(tor_log2(63),OP_EQ, 5);
  1876. /* incorrect mathematically, but as specified: */
  1877. tt_int_op(tor_log2(0),OP_EQ, 0);
  1878. tt_int_op(tor_log2(1),OP_EQ, 0);
  1879. tt_int_op(tor_log2(2),OP_EQ, 1);
  1880. tt_int_op(tor_log2(3),OP_EQ, 1);
  1881. tt_int_op(tor_log2(4),OP_EQ, 2);
  1882. tt_int_op(tor_log2(5),OP_EQ, 2);
  1883. tt_int_op(tor_log2(U64_LITERAL(40000000000000000)),OP_EQ, 55);
  1884. tt_int_op(tor_log2(UINT64_MAX),OP_EQ, 63);
  1885. /* Test round_to_power_of_2 */
  1886. tt_u64_op(round_to_power_of_2(120), OP_EQ, 128);
  1887. tt_u64_op(round_to_power_of_2(128), OP_EQ, 128);
  1888. tt_u64_op(round_to_power_of_2(130), OP_EQ, 128);
  1889. tt_u64_op(round_to_power_of_2(U64_LITERAL(40000000000000000)), OP_EQ,
  1890. U64_LITERAL(1)<<55);
  1891. tt_u64_op(round_to_power_of_2(U64_LITERAL(0xffffffffffffffff)), OP_EQ,
  1892. U64_LITERAL(1)<<63);
  1893. tt_u64_op(round_to_power_of_2(0), OP_EQ, 1);
  1894. tt_u64_op(round_to_power_of_2(1), OP_EQ, 1);
  1895. tt_u64_op(round_to_power_of_2(2), OP_EQ, 2);
  1896. tt_u64_op(round_to_power_of_2(3), OP_EQ, 2);
  1897. tt_u64_op(round_to_power_of_2(4), OP_EQ, 4);
  1898. tt_u64_op(round_to_power_of_2(5), OP_EQ, 4);
  1899. tt_u64_op(round_to_power_of_2(6), OP_EQ, 4);
  1900. tt_u64_op(round_to_power_of_2(7), OP_EQ, 8);
  1901. done:
  1902. ;
  1903. }
  1904. static void
  1905. test_util_compress_impl(compress_method_t method)
  1906. {
  1907. char *buf1=NULL, *buf2=NULL, *buf3=NULL;
  1908. size_t len1, len2;
  1909. tt_assert(tor_compress_supports_method(method));
  1910. if (method != NO_METHOD) {
  1911. tt_ptr_op(tor_compress_version_str(method), OP_NE, NULL);
  1912. tt_ptr_op(tor_compress_header_version_str(method), OP_NE, NULL);
  1913. }
  1914. buf1 = tor_strdup("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ");
  1915. tt_assert(detect_compression_method(buf1, strlen(buf1)) == UNKNOWN_METHOD);
  1916. tt_assert(!tor_compress(&buf2, &len1, buf1, strlen(buf1)+1, method));
  1917. tt_ptr_op(buf2, OP_NE, NULL);
  1918. if (method == NO_METHOD) {
  1919. // The identity transform doesn't actually compress, and it isn't
  1920. // detectable as "the identity transform."
  1921. tt_int_op(len1, OP_EQ, strlen(buf1)+1);
  1922. tt_int_op(detect_compression_method(buf2, len1), OP_EQ, UNKNOWN_METHOD);
  1923. } else {
  1924. tt_int_op(len1, OP_LT, strlen(buf1));
  1925. tt_int_op(detect_compression_method(buf2, len1), OP_EQ, method);
  1926. }
  1927. tt_assert(!tor_uncompress(&buf3, &len2, buf2, len1, method, 1, LOG_INFO));
  1928. tt_ptr_op(buf3, OP_NE, NULL);
  1929. tt_int_op(strlen(buf1) + 1, OP_EQ, len2);
  1930. tt_str_op(buf1, OP_EQ, buf3);
  1931. tt_int_op(buf3[len2], OP_EQ, 0);
  1932. /* Check whether we can uncompress concatenated, compressed strings. */
  1933. tor_free(buf3);
  1934. buf2 = tor_reallocarray(buf2, len1, 2);
  1935. memcpy(buf2+len1, buf2, len1);
  1936. tt_assert(!tor_uncompress(&buf3, &len2, buf2, len1*2, method, 1, LOG_INFO));
  1937. tt_int_op((strlen(buf1)+1)*2, OP_EQ, len2);
  1938. tt_mem_op(buf3, OP_EQ,
  1939. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ\0"
  1940. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ\0",
  1941. (strlen(buf1)+1)*2);
  1942. tt_int_op(buf3[len2], OP_EQ, 0);
  1943. /* Check whether we can uncompress partial strings */
  1944. tor_free(buf1);
  1945. tor_free(buf2);
  1946. tor_free(buf3);
  1947. size_t b1len = 1<<10;
  1948. if (method == ZSTD_METHOD) {
  1949. // zstd needs a big input before it starts generating output that it
  1950. // can partially decompress.
  1951. b1len = 1<<18;
  1952. }
  1953. buf1 = tor_malloc(b1len);
  1954. crypto_rand(buf1, b1len);
  1955. tt_assert(!tor_compress(&buf2, &len1, buf1, b1len, method));
  1956. tt_int_op(len1, OP_GT, 16);
  1957. /* when we allow an incomplete output we should succeed.*/
  1958. tt_assert(!tor_uncompress(&buf3, &len2, buf2, len1-16,
  1959. method, 0, LOG_INFO));
  1960. tt_int_op(len2, OP_GT, 5);
  1961. tt_int_op(len2, OP_LE, len1);
  1962. tt_assert(fast_memeq(buf1, buf3, len2));
  1963. tt_int_op(buf3[len2], OP_EQ, 0);
  1964. /* when we demand a complete output from a real compression method, this
  1965. * must fail. */
  1966. tor_free(buf3);
  1967. if (method != NO_METHOD) {
  1968. tt_assert(tor_uncompress(&buf3, &len2, buf2, len1-16,
  1969. method, 1, LOG_INFO));
  1970. tt_ptr_op(buf3, OP_EQ, NULL);
  1971. }
  1972. done:
  1973. tor_free(buf1);
  1974. tor_free(buf2);
  1975. tor_free(buf3);
  1976. }
  1977. static void
  1978. test_util_compress_stream_impl(compress_method_t method,
  1979. compression_level_t level)
  1980. {
  1981. char *buf1=NULL, *buf2=NULL, *buf3=NULL, *cp1, *cp2;
  1982. const char *ccp2;
  1983. size_t len1, len2;
  1984. tor_compress_state_t *state = NULL;
  1985. state = tor_compress_new(1, method, level);
  1986. tt_assert(state);
  1987. cp1 = buf1 = tor_malloc(1024);
  1988. len1 = 1024;
  1989. ccp2 = "ABCDEFGHIJABCDEFGHIJ";
  1990. len2 = 21;
  1991. tt_int_op(tor_compress_process(state, &cp1, &len1, &ccp2, &len2, 0),
  1992. OP_EQ, TOR_COMPRESS_OK);
  1993. tt_int_op(0, OP_EQ, len2); /* Make sure we compressed it all. */
  1994. tt_assert(cp1 > buf1);
  1995. len2 = 0;
  1996. cp2 = cp1;
  1997. tt_int_op(tor_compress_process(state, &cp1, &len1, &ccp2, &len2, 1),
  1998. OP_EQ, TOR_COMPRESS_DONE);
  1999. tt_int_op(0, OP_EQ, len2);
  2000. if (method == NO_METHOD) {
  2001. tt_ptr_op(cp1, OP_EQ, cp2);
  2002. } else {
  2003. tt_assert(cp1 > cp2); /* Make sure we really added something. */
  2004. }
  2005. tt_int_op(tor_compress_state_size(state), OP_GT, 0);
  2006. tt_assert(!tor_uncompress(&buf3, &len2, buf1, 1024-len1,
  2007. method, 1, LOG_WARN));
  2008. /* Make sure it compressed right. */
  2009. tt_str_op(buf3, OP_EQ, "ABCDEFGHIJABCDEFGHIJ");
  2010. tt_int_op(21, OP_EQ, len2);
  2011. done:
  2012. if (state)
  2013. tor_compress_free(state);
  2014. tor_free(buf1);
  2015. tor_free(buf2);
  2016. tor_free(buf3);
  2017. }
  2018. /** Setup function for compression tests: handles x-zstd:nostatic
  2019. */
  2020. static void *
  2021. compression_test_setup(const struct testcase_t *testcase)
  2022. {
  2023. tor_assert(testcase->setup_data);
  2024. tor_assert(testcase->setup_data != (void*)TT_SKIP);
  2025. const char *methodname = testcase->setup_data;
  2026. if (!strcmp(methodname, "x-zstd:nostatic")) {
  2027. methodname = "x-zstd";
  2028. tor_zstd_set_static_apis_disabled_for_testing(1);
  2029. }
  2030. return (void *)methodname;
  2031. }
  2032. /** Cleanup for compression tests: disables nostatic */
  2033. static int
  2034. compression_test_cleanup(const struct testcase_t *testcase, void *ptr)
  2035. {
  2036. (void)testcase;
  2037. (void)ptr;
  2038. tor_zstd_set_static_apis_disabled_for_testing(0);
  2039. return 1;
  2040. }
  2041. static const struct testcase_setup_t compress_setup = {
  2042. compression_test_setup, compression_test_cleanup
  2043. };
  2044. /** Run unit tests for compression functions */
  2045. static void
  2046. test_util_compress(void *arg)
  2047. {
  2048. const char *methodname = arg;
  2049. tt_assert(methodname);
  2050. compress_method_t method = compression_method_get_by_name(methodname);
  2051. tt_int_op(method, OP_NE, UNKNOWN_METHOD);
  2052. if (! tor_compress_supports_method(method)) {
  2053. tt_skip();
  2054. }
  2055. compression_level_t levels[] = {
  2056. BEST_COMPRESSION,
  2057. HIGH_COMPRESSION,
  2058. MEDIUM_COMPRESSION,
  2059. LOW_COMPRESSION
  2060. };
  2061. test_util_compress_impl(method);
  2062. for (unsigned l = 0; l < ARRAY_LENGTH(levels); ++l) {
  2063. compression_level_t level = levels[l];
  2064. test_util_compress_stream_impl(method, level);
  2065. }
  2066. done:
  2067. ;
  2068. }
  2069. static void
  2070. test_util_decompress_concatenated_impl(compress_method_t method)
  2071. {
  2072. char input[4096];
  2073. char *c1 = NULL, *c2 = NULL, *c3 = NULL;
  2074. char *result = NULL;
  2075. size_t sz1, sz2, sz3, szr;
  2076. int r;
  2077. crypto_rand(input, sizeof(input));
  2078. /* Compress the input in two chunks. */
  2079. r = tor_compress(&c1, &sz1, input, 2048, method);
  2080. tt_int_op(r, OP_EQ, 0);
  2081. r = tor_compress(&c2, &sz2, input+2048, 2048, method);
  2082. tt_int_op(r, OP_EQ, 0);
  2083. /* concatenate the chunks. */
  2084. sz3 = sz1 + sz2;
  2085. c3 = tor_malloc(sz3);
  2086. memcpy(c3, c1, sz1);
  2087. memcpy(c3+sz1, c2, sz2);
  2088. /* decompress the concatenated result */
  2089. r = tor_uncompress(&result, &szr, c3, sz3, method, 0, LOG_WARN);
  2090. tt_int_op(r, OP_EQ, 0);
  2091. tt_int_op(szr, OP_EQ, sizeof(input));
  2092. tt_mem_op(result, OP_EQ, input, sizeof(input));
  2093. done:
  2094. tor_free(c1);
  2095. tor_free(c2);
  2096. tor_free(c3);
  2097. tor_free(result);
  2098. }
  2099. static void
  2100. test_util_decompress_concatenated(void *arg)
  2101. {
  2102. const char *methodname = arg;
  2103. tt_assert(methodname);
  2104. compress_method_t method = compression_method_get_by_name(methodname);
  2105. tt_int_op(method, OP_NE, UNKNOWN_METHOD);
  2106. if (! tor_compress_supports_method(method)) {
  2107. tt_skip();
  2108. }
  2109. test_util_decompress_concatenated_impl(method);
  2110. done:
  2111. ;
  2112. }
  2113. static void
  2114. test_util_decompress_junk_impl(compress_method_t method)
  2115. {
  2116. char input[4096];
  2117. char *result = NULL, *result2 = NULL;
  2118. size_t szr, szr2, sz;
  2119. int r;
  2120. /* This shouldn't be a compressed string according to any method. */
  2121. strlcpy(input, "This shouldn't be a compressed string by any means.",
  2122. sizeof(input));
  2123. sz = strlen(input);
  2124. setup_capture_of_logs(LOG_WARN);
  2125. r = tor_uncompress(&result, &szr, input, sz, method, 0, LOG_WARN);
  2126. tt_int_op(r, OP_EQ, -1);
  2127. tt_ptr_op(result, OP_EQ, NULL);
  2128. expect_log_msg_containing("Error while uncompressing data: bad input?");
  2129. mock_clean_saved_logs();
  2130. /* Now try again, with a compressed object that starts out good and turns to
  2131. junk. */
  2132. crypto_rand(input, sizeof(input));
  2133. r = tor_compress(&result, &szr, input, sizeof(input), method);
  2134. tt_int_op(r, OP_EQ, 0);
  2135. crypto_rand(result+szr/2, szr-(szr/2)); // trash the 2nd half of the result
  2136. r = tor_uncompress(&result2, &szr2, result, szr, method, 0, LOG_WARN);
  2137. tt_int_op(r, OP_EQ, -1);
  2138. expect_log_msg_containing("Error while uncompressing data: bad input?");
  2139. done:
  2140. teardown_capture_of_logs();
  2141. tor_free(result);
  2142. tor_free(result2);
  2143. }
  2144. static void
  2145. test_util_decompress_junk(void *arg)
  2146. {
  2147. const char *methodname = arg;
  2148. tt_assert(methodname);
  2149. compress_method_t method = compression_method_get_by_name(methodname);
  2150. tt_int_op(method, OP_NE, UNKNOWN_METHOD);
  2151. if (! tor_compress_supports_method(method)) {
  2152. tt_skip();
  2153. }
  2154. test_util_decompress_junk_impl(method);
  2155. done:
  2156. ;
  2157. }
  2158. /* mock replacement for tor_compress_is_compression_bomb that doesn't
  2159. * believe in compression bombs. */
  2160. static int
  2161. mock_is_never_compression_bomb(size_t in, size_t out)
  2162. {
  2163. (void)in;
  2164. (void) out;
  2165. return 0;
  2166. }
  2167. static void
  2168. test_util_decompress_dos_impl(compress_method_t method)
  2169. {
  2170. char *input;
  2171. char *result = NULL, *result2 = NULL;
  2172. size_t szr, szr2;
  2173. int r;
  2174. const size_t big = 1024*1024;
  2175. /* one megabyte of 0s. */
  2176. input = tor_malloc_zero(big);
  2177. /* Compress it into "result": it should fail. */
  2178. setup_full_capture_of_logs(LOG_WARN);
  2179. r = tor_compress(&result, &szr, input, big, method);
  2180. tt_int_op(r, OP_EQ, -1);
  2181. expect_log_msg_containing(
  2182. "other Tors would think this was a compression bomb");
  2183. teardown_capture_of_logs();
  2184. /* Try again, but this time suppress compression-bomb detection */
  2185. MOCK(tor_compress_is_compression_bomb, mock_is_never_compression_bomb);
  2186. r = tor_compress(&result, &szr, input, big, method);
  2187. UNMOCK(tor_compress_is_compression_bomb);
  2188. tt_int_op(r, OP_EQ, 0);
  2189. tt_ptr_op(result, OP_NE, NULL);
  2190. /* We should refuse to uncomrpess it again, since it looks like a
  2191. * compression bomb. */
  2192. setup_capture_of_logs(LOG_WARN);
  2193. r = tor_uncompress(&result2, &szr2, result, szr, method, 0, LOG_WARN);
  2194. tt_int_op(r, OP_EQ, -1);
  2195. expect_log_msg_containing("bomb; abandoning stream");
  2196. done:
  2197. teardown_capture_of_logs();
  2198. tor_free(input);
  2199. tor_free(result);
  2200. tor_free(result2);
  2201. }
  2202. static void
  2203. test_util_decompress_dos(void *arg)
  2204. {
  2205. const char *methodname = arg;
  2206. tt_assert(methodname);
  2207. compress_method_t method = compression_method_get_by_name(methodname);
  2208. tt_int_op(method, OP_NE, UNKNOWN_METHOD);
  2209. if (! tor_compress_supports_method(method)) {
  2210. tt_skip();
  2211. }
  2212. test_util_decompress_dos_impl(method);
  2213. done:
  2214. ;
  2215. }
  2216. static void
  2217. test_util_gzip_compression_bomb(void *arg)
  2218. {
  2219. /* A 'compression bomb' is a very small object that uncompresses to a huge
  2220. * one. Most compression formats support them, but they can be a DOS vector.
  2221. * In Tor we try not to generate them, and we don't accept them.
  2222. */
  2223. (void) arg;
  2224. size_t one_million = 1<<20;
  2225. char *one_mb = tor_malloc_zero(one_million);
  2226. char *result = NULL;
  2227. size_t result_len = 0;
  2228. tor_compress_state_t *state = NULL;
  2229. /* Make sure we can't produce a compression bomb */
  2230. setup_full_capture_of_logs(LOG_WARN);
  2231. tt_int_op(-1, OP_EQ, tor_compress(&result, &result_len,
  2232. one_mb, one_million,
  2233. ZLIB_METHOD));
  2234. expect_single_log_msg_containing(
  2235. "We compressed something and got an insanely high "
  2236. "compression factor; other Tors would think this "
  2237. "was a compression bomb.");
  2238. teardown_capture_of_logs();
  2239. /* Here's a compression bomb that we made manually. */
  2240. const char compression_bomb[1039] =
  2241. { 0x78, 0xDA, 0xED, 0xC1, 0x31, 0x01, 0x00, 0x00, 0x00, 0xC2,
  2242. 0xA0, 0xF5, 0x4F, 0x6D, 0x08, 0x5F, 0xA0 /* .... */ };
  2243. tt_int_op(-1, OP_EQ, tor_uncompress(&result, &result_len,
  2244. compression_bomb, 1039,
  2245. ZLIB_METHOD, 0, LOG_WARN));
  2246. /* Now try streaming that. */
  2247. state = tor_compress_new(0, ZLIB_METHOD, HIGH_COMPRESSION);
  2248. tor_compress_output_t r;
  2249. const char *inp = compression_bomb;
  2250. size_t inlen = 1039;
  2251. do {
  2252. char *outp = one_mb;
  2253. size_t outleft = 4096; /* small on purpose */
  2254. r = tor_compress_process(state, &outp, &outleft, &inp, &inlen, 0);
  2255. tt_int_op(inlen, OP_NE, 0);
  2256. } while (r == TOR_COMPRESS_BUFFER_FULL);
  2257. tt_int_op(r, OP_EQ, TOR_COMPRESS_ERROR);
  2258. done:
  2259. tor_free(one_mb);
  2260. tor_compress_free(state);
  2261. }
  2262. /** Run unit tests for mmap() wrapper functionality. */
  2263. static void
  2264. test_util_mmap(void *arg)
  2265. {
  2266. char *fname1 = tor_strdup(get_fname("mapped_1"));
  2267. char *fname2 = tor_strdup(get_fname("mapped_2"));
  2268. char *fname3 = tor_strdup(get_fname("mapped_3"));
  2269. const size_t buflen = 17000;
  2270. char *buf = tor_malloc(17000);
  2271. tor_mmap_t *mapping = NULL;
  2272. (void)arg;
  2273. crypto_rand(buf, buflen);
  2274. mapping = tor_mmap_file(fname1);
  2275. tt_ptr_op(mapping, OP_EQ, NULL);
  2276. write_str_to_file(fname1, "Short file.", 1);
  2277. mapping = tor_mmap_file(fname1);
  2278. tt_assert(mapping);
  2279. tt_int_op(mapping->size,OP_EQ, strlen("Short file."));
  2280. tt_str_op(mapping->data,OP_EQ, "Short file.");
  2281. #ifdef _WIN32
  2282. tt_int_op(0, OP_EQ, tor_munmap_file(mapping));
  2283. mapping = NULL;
  2284. tt_assert(unlink(fname1) == 0);
  2285. #else
  2286. /* make sure we can unlink. */
  2287. tt_assert(unlink(fname1) == 0);
  2288. tt_str_op(mapping->data,OP_EQ, "Short file.");
  2289. tt_int_op(0, OP_EQ, tor_munmap_file(mapping));
  2290. mapping = NULL;
  2291. #endif /* defined(_WIN32) */
  2292. /* Now a zero-length file. */
  2293. write_str_to_file(fname1, "", 1);
  2294. mapping = tor_mmap_file(fname1);
  2295. tt_ptr_op(mapping,OP_EQ, NULL);
  2296. tt_int_op(ERANGE,OP_EQ, errno);
  2297. unlink(fname1);
  2298. /* Make sure that we fail to map a no-longer-existent file. */
  2299. mapping = tor_mmap_file(fname1);
  2300. tt_ptr_op(mapping, OP_EQ, NULL);
  2301. /* Now try a big file that stretches across a few pages and isn't aligned */
  2302. write_bytes_to_file(fname2, buf, buflen, 1);
  2303. mapping = tor_mmap_file(fname2);
  2304. tt_assert(mapping);
  2305. tt_int_op(mapping->size,OP_EQ, buflen);
  2306. tt_mem_op(mapping->data,OP_EQ, buf, buflen);
  2307. tt_int_op(0, OP_EQ, tor_munmap_file(mapping));
  2308. mapping = NULL;
  2309. /* Now try a big aligned file. */
  2310. write_bytes_to_file(fname3, buf, 16384, 1);
  2311. mapping = tor_mmap_file(fname3);
  2312. tt_assert(mapping);
  2313. tt_int_op(mapping->size,OP_EQ, 16384);
  2314. tt_mem_op(mapping->data,OP_EQ, buf, 16384);
  2315. tt_int_op(0, OP_EQ, tor_munmap_file(mapping));
  2316. mapping = NULL;
  2317. done:
  2318. unlink(fname1);
  2319. unlink(fname2);
  2320. unlink(fname3);
  2321. tor_free(fname1);
  2322. tor_free(fname2);
  2323. tor_free(fname3);
  2324. tor_free(buf);
  2325. tor_munmap_file(mapping);
  2326. }
  2327. /** Run unit tests for escaping/unescaping data for use by controllers. */
  2328. static void
  2329. test_util_control_formats(void *arg)
  2330. {
  2331. char *out = NULL;
  2332. const char *inp =
  2333. "..This is a test\r\n.of the emergency \n..system.\r\n\rZ.\r\n";
  2334. size_t sz;
  2335. (void)arg;
  2336. sz = read_escaped_data(inp, strlen(inp), &out);
  2337. tt_str_op(out,OP_EQ,
  2338. ".This is a test\nof the emergency \n.system.\n\rZ.\n");
  2339. tt_int_op(sz,OP_EQ, strlen(out));
  2340. done:
  2341. tor_free(out);
  2342. }
  2343. #define test_feq(value1,value2) do { \
  2344. double v1 = (value1), v2=(value2); \
  2345. double tf_diff = v1-v2; \
  2346. double tf_tolerance = ((v1+v2)/2.0)/1e8; \
  2347. if (tf_diff<0) tf_diff=-tf_diff; \
  2348. if (tf_tolerance<0) tf_tolerance=-tf_tolerance; \
  2349. if (tf_diff<tf_tolerance) { \
  2350. TT_BLATHER(("%s ~~ %s: %f ~~ %f",#value1,#value2,v1,v2)); \
  2351. } else { \
  2352. TT_FAIL(("%s ~~ %s: %f != %f",#value1,#value2,v1,v2)); \
  2353. } \
  2354. } while (0)
  2355. static void
  2356. test_util_sscanf(void *arg)
  2357. {
  2358. unsigned u1, u2, u3;
  2359. unsigned long ulng;
  2360. char s1[20], s2[10], s3[10], ch, *huge = NULL;
  2361. int r;
  2362. long lng1,lng2;
  2363. int int1, int2;
  2364. double d1,d2,d3,d4;
  2365. /* Simple tests (malformed patterns, literal matching, ...) */
  2366. (void)arg;
  2367. tt_int_op(-1,OP_EQ, tor_sscanf("123", "%i", &r)); /* %i is not supported */
  2368. tt_int_op(-1,OP_EQ,
  2369. tor_sscanf("wrong", "%5c", s1)); /* %c cannot have a number. */
  2370. tt_int_op(-1,OP_EQ, tor_sscanf("hello", "%s", s1)); /* %s needs a number. */
  2371. /* this will fail because we don't allow widths longer than 9999 */
  2372. {
  2373. huge = tor_malloc(1000000);
  2374. r = tor_sscanf("prettylongstring", "%99999s", huge);
  2375. tor_free(huge);
  2376. tt_int_op(-1,OP_EQ, r);
  2377. }
  2378. #if 0
  2379. /* GCC thinks these two are illegal. */
  2380. test_eq(-1, tor_sscanf("prettylongstring", "%0s", s1));
  2381. test_eq(0, tor_sscanf("prettylongstring", "%10s", NULL));
  2382. #endif
  2383. /* No '%'-strings: always "success" */
  2384. tt_int_op(0,OP_EQ, tor_sscanf("hello world", "hello world"));
  2385. tt_int_op(0,OP_EQ, tor_sscanf("hello world", "good bye"));
  2386. /* Excess data */
  2387. tt_int_op(0,OP_EQ,
  2388. tor_sscanf("hello 3", "%u", &u1)); /* have to match the start */
  2389. tt_int_op(0,OP_EQ, tor_sscanf(" 3 hello", "%u", &u1));
  2390. tt_int_op(0,OP_EQ,
  2391. tor_sscanf(" 3 hello", "%2u", &u1)); /* not even in this case */
  2392. tt_int_op(1,OP_EQ,
  2393. tor_sscanf("3 hello", "%u", &u1)); /* but trailing is alright */
  2394. /* Numbers (ie. %u) */
  2395. tt_int_op(0,OP_EQ,
  2396. tor_sscanf("hello world 3", "hello worlb %u", &u1)); /* d vs b */
  2397. tt_int_op(1,OP_EQ, tor_sscanf("12345", "%u", &u1));
  2398. tt_int_op(12345u,OP_EQ, u1);
  2399. tt_int_op(1,OP_EQ, tor_sscanf("12346 ", "%u", &u1));
  2400. tt_int_op(12346u,OP_EQ, u1);
  2401. tt_int_op(0,OP_EQ, tor_sscanf(" 12347", "%u", &u1));
  2402. tt_int_op(1,OP_EQ, tor_sscanf(" 12348", " %u", &u1));
  2403. tt_int_op(12348u,OP_EQ, u1);
  2404. tt_int_op(1,OP_EQ, tor_sscanf("0", "%u", &u1));
  2405. tt_int_op(0u,OP_EQ, u1);
  2406. tt_int_op(1,OP_EQ, tor_sscanf("0000", "%u", &u2));
  2407. tt_int_op(0u,OP_EQ, u2);
  2408. tt_int_op(0,OP_EQ, tor_sscanf("", "%u", &u1)); /* absent number */
  2409. tt_int_op(0,OP_EQ, tor_sscanf("A", "%u", &u1)); /* bogus number */
  2410. tt_int_op(0,OP_EQ, tor_sscanf("-1", "%u", &u1)); /* negative number */
  2411. /* Numbers with size (eg. %2u) */
  2412. tt_int_op(0,OP_EQ, tor_sscanf("-1", "%2u", &u1));
  2413. tt_int_op(2,OP_EQ, tor_sscanf("123456", "%2u%u", &u1, &u2));
  2414. tt_int_op(12u,OP_EQ, u1);
  2415. tt_int_op(3456u,OP_EQ, u2);
  2416. tt_int_op(1,OP_EQ, tor_sscanf("123456", "%8u", &u1));
  2417. tt_int_op(123456u,OP_EQ, u1);
  2418. tt_int_op(1,OP_EQ, tor_sscanf("123457 ", "%8u", &u1));
  2419. tt_int_op(123457u,OP_EQ, u1);
  2420. tt_int_op(0,OP_EQ, tor_sscanf(" 123456", "%8u", &u1));
  2421. tt_int_op(3,OP_EQ, tor_sscanf("!12:3:456", "!%2u:%2u:%3u", &u1, &u2, &u3));
  2422. tt_int_op(12u,OP_EQ, u1);
  2423. tt_int_op(3u,OP_EQ, u2);
  2424. tt_int_op(456u,OP_EQ, u3);
  2425. tt_int_op(3,OP_EQ,
  2426. tor_sscanf("67:8:099", "%2u:%2u:%3u", &u1, &u2, &u3)); /* 0s */
  2427. tt_int_op(67u,OP_EQ, u1);
  2428. tt_int_op(8u,OP_EQ, u2);
  2429. tt_int_op(99u,OP_EQ, u3);
  2430. /* %u does not match space.*/
  2431. tt_int_op(2,OP_EQ, tor_sscanf("12:3: 45", "%2u:%2u:%3u", &u1, &u2, &u3));
  2432. tt_int_op(12u,OP_EQ, u1);
  2433. tt_int_op(3u,OP_EQ, u2);
  2434. /* %u does not match negative numbers. */
  2435. tt_int_op(2,OP_EQ, tor_sscanf("67:8:-9", "%2u:%2u:%3u", &u1, &u2, &u3));
  2436. tt_int_op(67u,OP_EQ, u1);
  2437. tt_int_op(8u,OP_EQ, u2);
  2438. /* Arbitrary amounts of 0-padding are okay */
  2439. tt_int_op(3,OP_EQ, tor_sscanf("12:03:000000000000000099", "%2u:%2u:%u",
  2440. &u1, &u2, &u3));
  2441. tt_int_op(12u,OP_EQ, u1);
  2442. tt_int_op(3u,OP_EQ, u2);
  2443. tt_int_op(99u,OP_EQ, u3);
  2444. /* Hex (ie. %x) */
  2445. tt_int_op(3,OP_EQ,
  2446. tor_sscanf("1234 02aBcdEf ff", "%x %x %x", &u1, &u2, &u3));
  2447. tt_int_op(0x1234,OP_EQ, u1);
  2448. tt_int_op(0x2ABCDEF,OP_EQ, u2);
  2449. tt_int_op(0xFF,OP_EQ, u3);
  2450. /* Width works on %x */
  2451. tt_int_op(3,OP_EQ, tor_sscanf("f00dcafe444", "%4x%4x%u", &u1, &u2, &u3));
  2452. tt_int_op(0xf00d,OP_EQ, u1);
  2453. tt_int_op(0xcafe,OP_EQ, u2);
  2454. tt_int_op(444,OP_EQ, u3);
  2455. /* Literal '%' (ie. '%%') */
  2456. tt_int_op(1,OP_EQ, tor_sscanf("99% fresh", "%3u%% fresh", &u1));
  2457. tt_int_op(99,OP_EQ, u1);
  2458. tt_int_op(0,OP_EQ, tor_sscanf("99 fresh", "%% %3u %s", &u1, s1));
  2459. tt_int_op(1,OP_EQ, tor_sscanf("99 fresh", "%3u%% %s", &u1, s1));
  2460. tt_int_op(2,OP_EQ, tor_sscanf("99 fresh", "%3u %5s %%", &u1, s1));
  2461. tt_int_op(99,OP_EQ, u1);
  2462. tt_str_op(s1,OP_EQ, "fresh");
  2463. tt_int_op(1,OP_EQ, tor_sscanf("% boo", "%% %3s", s1));
  2464. tt_str_op("boo",OP_EQ, s1);
  2465. /* Strings (ie. %s) */
  2466. tt_int_op(2,OP_EQ, tor_sscanf("hello", "%3s%7s", s1, s2));
  2467. tt_str_op(s1,OP_EQ, "hel");
  2468. tt_str_op(s2,OP_EQ, "lo");
  2469. tt_int_op(2,OP_EQ, tor_sscanf("WD40", "%2s%u", s3, &u1)); /* %s%u */
  2470. tt_str_op(s3,OP_EQ, "WD");
  2471. tt_int_op(40,OP_EQ, u1);
  2472. tt_int_op(2,OP_EQ, tor_sscanf("WD40", "%3s%u", s3, &u1)); /* %s%u */
  2473. tt_str_op(s3,OP_EQ, "WD4");
  2474. tt_int_op(0,OP_EQ, u1);
  2475. tt_int_op(2,OP_EQ, tor_sscanf("76trombones", "%6u%9s", &u1, s1)); /* %u%s */
  2476. tt_int_op(76,OP_EQ, u1);
  2477. tt_str_op(s1,OP_EQ, "trombones");
  2478. {
  2479. huge = tor_malloc(1000);
  2480. r = tor_sscanf("prettylongstring", "%999s", huge);
  2481. tt_int_op(1,OP_EQ, r);
  2482. tt_str_op(huge,OP_EQ, "prettylongstring");
  2483. tor_free(huge);
  2484. }
  2485. /* %s doesn't eat spaces */
  2486. tt_int_op(2,OP_EQ, tor_sscanf("hello world", "%9s %9s", s1, s2));
  2487. tt_str_op(s1,OP_EQ, "hello");
  2488. tt_str_op(s2,OP_EQ, "world");
  2489. tt_int_op(2,OP_EQ, tor_sscanf("bye world?", "%9s %9s", s1, s2));
  2490. tt_str_op(s1,OP_EQ, "bye");
  2491. tt_str_op(s2,OP_EQ, "");
  2492. tt_int_op(3,OP_EQ,
  2493. tor_sscanf("hi", "%9s%9s%3s", s1, s2, s3)); /* %s can be empty. */
  2494. tt_str_op(s1,OP_EQ, "hi");
  2495. tt_str_op(s2,OP_EQ, "");
  2496. tt_str_op(s3,OP_EQ, "");
  2497. tt_int_op(3,OP_EQ, tor_sscanf("1.2.3", "%u.%u.%u%c", &u1, &u2, &u3, &ch));
  2498. tt_int_op(4,OP_EQ,
  2499. tor_sscanf("1.2.3 foobar", "%u.%u.%u%c", &u1, &u2, &u3, &ch));
  2500. tt_int_op(' ',OP_EQ, ch);
  2501. r = tor_sscanf("12345 -67890 -1", "%d %ld %d", &int1, &lng1, &int2);
  2502. tt_int_op(r,OP_EQ, 3);
  2503. tt_int_op(int1,OP_EQ, 12345);
  2504. tt_int_op(lng1,OP_EQ, -67890);
  2505. tt_int_op(int2,OP_EQ, -1);
  2506. #if SIZEOF_INT == 4
  2507. /* %u */
  2508. /* UINT32_MAX should work */
  2509. tt_int_op(1,OP_EQ, tor_sscanf("4294967295", "%u", &u1));
  2510. tt_int_op(4294967295U,OP_EQ, u1);
  2511. /* But UINT32_MAX + 1 shouldn't work */
  2512. tt_int_op(0,OP_EQ, tor_sscanf("4294967296", "%u", &u1));
  2513. /* but parsing only 9... */
  2514. tt_int_op(1,OP_EQ, tor_sscanf("4294967296", "%9u", &u1));
  2515. tt_int_op(429496729U,OP_EQ, u1);
  2516. /* %x */
  2517. /* UINT32_MAX should work */
  2518. tt_int_op(1,OP_EQ, tor_sscanf("FFFFFFFF", "%x", &u1));
  2519. tt_int_op(0xFFFFFFFF,OP_EQ, u1);
  2520. /* But UINT32_MAX + 1 shouldn't work */
  2521. tt_int_op(0,OP_EQ, tor_sscanf("100000000", "%x", &u1));
  2522. /* %d */
  2523. /* INT32_MIN and INT32_MAX should work */
  2524. r = tor_sscanf("-2147483648. 2147483647.", "%d. %d.", &int1, &int2);
  2525. tt_int_op(r,OP_EQ, 2);
  2526. tt_int_op(int1,OP_EQ, -2147483647 - 1);
  2527. tt_int_op(int2,OP_EQ, 2147483647);
  2528. /* But INT32_MIN - 1 and INT32_MAX + 1 shouldn't work */
  2529. r = tor_sscanf("-2147483649.", "%d.", &int1);
  2530. tt_int_op(r,OP_EQ, 0);
  2531. r = tor_sscanf("2147483648.", "%d.", &int1);
  2532. tt_int_op(r,OP_EQ, 0);
  2533. /* and the first failure stops further processing */
  2534. r = tor_sscanf("-2147483648. 2147483648.",
  2535. "%d. %d.", &int1, &int2);
  2536. tt_int_op(r,OP_EQ, 1);
  2537. r = tor_sscanf("-2147483649. 2147483647.",
  2538. "%d. %d.", &int1, &int2);
  2539. tt_int_op(r,OP_EQ, 0);
  2540. r = tor_sscanf("2147483648. -2147483649.",
  2541. "%d. %d.", &int1, &int2);
  2542. tt_int_op(r,OP_EQ, 0);
  2543. #elif SIZEOF_INT == 8
  2544. /* %u */
  2545. /* UINT64_MAX should work */
  2546. tt_int_op(1,OP_EQ, tor_sscanf("18446744073709551615", "%u", &u1));
  2547. tt_int_op(18446744073709551615U,OP_EQ, u1);
  2548. /* But UINT64_MAX + 1 shouldn't work */
  2549. tt_int_op(0,OP_EQ, tor_sscanf("18446744073709551616", "%u", &u1));
  2550. /* but parsing only 19... */
  2551. tt_int_op(1,OP_EQ, tor_sscanf("18446744073709551616", "%19u", &u1));
  2552. tt_int_op(1844674407370955161U,OP_EQ, u1);
  2553. /* %x */
  2554. /* UINT64_MAX should work */
  2555. tt_int_op(1,OP_EQ, tor_sscanf("FFFFFFFFFFFFFFFF", "%x", &u1));
  2556. tt_int_op(0xFFFFFFFFFFFFFFFF,OP_EQ, u1);
  2557. /* But UINT64_MAX + 1 shouldn't work */
  2558. tt_int_op(0,OP_EQ, tor_sscanf("10000000000000000", "%x", &u1));
  2559. /* %d */
  2560. /* INT64_MIN and INT64_MAX should work */
  2561. r = tor_sscanf("-9223372036854775808. 9223372036854775807.",
  2562. "%d. %d.", &int1, &int2);
  2563. tt_int_op(r,OP_EQ, 2);
  2564. tt_int_op(int1,OP_EQ, -9223372036854775807 - 1);
  2565. tt_int_op(int2,OP_EQ, 9223372036854775807);
  2566. /* But INT64_MIN - 1 and INT64_MAX + 1 shouldn't work */
  2567. r = tor_sscanf("-9223372036854775809.", "%d.", &int1);
  2568. tt_int_op(r,OP_EQ, 0);
  2569. r = tor_sscanf("9223372036854775808.", "%d.", &int1);
  2570. tt_int_op(r,OP_EQ, 0);
  2571. /* and the first failure stops further processing */
  2572. r = tor_sscanf("-9223372036854775808. 9223372036854775808.",
  2573. "%d. %d.", &int1, &int2);
  2574. tt_int_op(r,OP_EQ, 1);
  2575. r = tor_sscanf("-9223372036854775809. 9223372036854775807.",
  2576. "%d. %d.", &int1, &int2);
  2577. tt_int_op(r,OP_EQ, 0);
  2578. r = tor_sscanf("9223372036854775808. -9223372036854775809.",
  2579. "%d. %d.", &int1, &int2);
  2580. tt_int_op(r,OP_EQ, 0);
  2581. #endif /* SIZEOF_INT == 4 || ... */
  2582. #if SIZEOF_LONG == 4
  2583. /* %lu */
  2584. /* UINT32_MAX should work */
  2585. tt_int_op(1,OP_EQ, tor_sscanf("4294967295", "%lu", &ulng));
  2586. tt_int_op(4294967295UL,OP_EQ, ulng);
  2587. /* But UINT32_MAX + 1 shouldn't work */
  2588. tt_int_op(0,OP_EQ, tor_sscanf("4294967296", "%lu", &ulng));
  2589. /* but parsing only 9... */
  2590. tt_int_op(1,OP_EQ, tor_sscanf("4294967296", "%9lu", &ulng));
  2591. tt_int_op(429496729UL,OP_EQ, ulng);
  2592. /* %lx */
  2593. /* UINT32_MAX should work */
  2594. tt_int_op(1,OP_EQ, tor_sscanf("FFFFFFFF", "%lx", &ulng));
  2595. tt_int_op(0xFFFFFFFFUL,OP_EQ, ulng);
  2596. /* But UINT32_MAX + 1 shouldn't work */
  2597. tt_int_op(0,OP_EQ, tor_sscanf("100000000", "%lx", &ulng));
  2598. /* %ld */
  2599. /* INT32_MIN and INT32_MAX should work */
  2600. r = tor_sscanf("-2147483648. 2147483647.", "%ld. %ld.", &lng1, &lng2);
  2601. tt_int_op(r,OP_EQ, 2);
  2602. tt_int_op(lng1,OP_EQ, -2147483647L - 1L);
  2603. tt_int_op(lng2,OP_EQ, 2147483647L);
  2604. /* But INT32_MIN - 1 and INT32_MAX + 1 shouldn't work */
  2605. r = tor_sscanf("-2147483649.", "%ld.", &lng1);
  2606. tt_int_op(r,OP_EQ, 0);
  2607. r = tor_sscanf("2147483648.", "%ld.", &lng1);
  2608. tt_int_op(r,OP_EQ, 0);
  2609. /* and the first failure stops further processing */
  2610. r = tor_sscanf("-2147483648. 2147483648.",
  2611. "%ld. %ld.", &lng1, &lng2);
  2612. tt_int_op(r,OP_EQ, 1);
  2613. r = tor_sscanf("-2147483649. 2147483647.",
  2614. "%ld. %ld.", &lng1, &lng2);
  2615. tt_int_op(r,OP_EQ, 0);
  2616. r = tor_sscanf("2147483648. -2147483649.",
  2617. "%ld. %ld.", &lng1, &lng2);
  2618. tt_int_op(r,OP_EQ, 0);
  2619. #elif SIZEOF_LONG == 8
  2620. /* %lu */
  2621. /* UINT64_MAX should work */
  2622. tt_int_op(1,OP_EQ, tor_sscanf("18446744073709551615", "%lu", &ulng));
  2623. tt_int_op(18446744073709551615UL,OP_EQ, ulng);
  2624. /* But UINT64_MAX + 1 shouldn't work */
  2625. tt_int_op(0,OP_EQ, tor_sscanf("18446744073709551616", "%lu", &ulng));
  2626. /* but parsing only 19... */
  2627. tt_int_op(1,OP_EQ, tor_sscanf("18446744073709551616", "%19lu", &ulng));
  2628. tt_int_op(1844674407370955161UL,OP_EQ, ulng);
  2629. /* %lx */
  2630. /* UINT64_MAX should work */
  2631. tt_int_op(1,OP_EQ, tor_sscanf("FFFFFFFFFFFFFFFF", "%lx", &ulng));
  2632. tt_int_op(0xFFFFFFFFFFFFFFFFUL,OP_EQ, ulng);
  2633. /* But UINT64_MAX + 1 shouldn't work */
  2634. tt_int_op(0,OP_EQ, tor_sscanf("10000000000000000", "%lx", &ulng));
  2635. /* %ld */
  2636. /* INT64_MIN and INT64_MAX should work */
  2637. r = tor_sscanf("-9223372036854775808. 9223372036854775807.",
  2638. "%ld. %ld.", &lng1, &lng2);
  2639. tt_int_op(r,OP_EQ, 2);
  2640. tt_int_op(lng1,OP_EQ, -9223372036854775807L - 1L);
  2641. tt_int_op(lng2,OP_EQ, 9223372036854775807L);
  2642. /* But INT64_MIN - 1 and INT64_MAX + 1 shouldn't work */
  2643. r = tor_sscanf("-9223372036854775809.", "%ld.", &lng1);
  2644. tt_int_op(r,OP_EQ, 0);
  2645. r = tor_sscanf("9223372036854775808.", "%ld.", &lng1);
  2646. tt_int_op(r,OP_EQ, 0);
  2647. /* and the first failure stops further processing */
  2648. r = tor_sscanf("-9223372036854775808. 9223372036854775808.",
  2649. "%ld. %ld.", &lng1, &lng2);
  2650. tt_int_op(r,OP_EQ, 1);
  2651. r = tor_sscanf("-9223372036854775809. 9223372036854775807.",
  2652. "%ld. %ld.", &lng1, &lng2);
  2653. tt_int_op(r,OP_EQ, 0);
  2654. r = tor_sscanf("9223372036854775808. -9223372036854775809.",
  2655. "%ld. %ld.", &lng1, &lng2);
  2656. tt_int_op(r,OP_EQ, 0);
  2657. #endif /* SIZEOF_LONG == 4 || ... */
  2658. r = tor_sscanf("123.456 .000007 -900123123.2000787 00003.2",
  2659. "%lf %lf %lf %lf", &d1,&d2,&d3,&d4);
  2660. tt_int_op(r,OP_EQ, 4);
  2661. test_feq(d1, 123.456);
  2662. test_feq(d2, .000007);
  2663. test_feq(d3, -900123123.2000787);
  2664. test_feq(d4, 3.2);
  2665. done:
  2666. tor_free(huge);
  2667. }
  2668. #define tt_char_op(a,op,b) tt_assert_op_type(a,op,b,char,"%c")
  2669. #define tt_ci_char_op(a,op,b) \
  2670. tt_char_op(TOR_TOLOWER((int)a),op,TOR_TOLOWER((int)b))
  2671. #ifndef HAVE_STRNLEN
  2672. static size_t
  2673. strnlen(const char *s, size_t len)
  2674. {
  2675. const char *p = memchr(s, 0, len);
  2676. if (!p)
  2677. return len;
  2678. return p - s;
  2679. }
  2680. #endif /* !defined(HAVE_STRNLEN) */
  2681. static void
  2682. test_util_format_time_interval(void *arg)
  2683. {
  2684. /* use the same sized buffer and integers as tor uses */
  2685. #define DBUF_SIZE 64
  2686. char dbuf[DBUF_SIZE];
  2687. #define T_ "%ld"
  2688. long sec, min, hour, day;
  2689. /* we don't care about the exact spelling of the
  2690. * second(s), minute(s), hour(s), day(s) labels */
  2691. #define LABEL_SIZE 21
  2692. #define L_ "%20s"
  2693. char label_s[LABEL_SIZE];
  2694. char label_m[LABEL_SIZE];
  2695. char label_h[LABEL_SIZE];
  2696. char label_d[LABEL_SIZE];
  2697. #define TL_ T_ " " L_
  2698. int r;
  2699. (void)arg;
  2700. /* In these tests, we're not picky about
  2701. * spelling or abbreviations */
  2702. /* seconds: 0, 1, 9, 10, 59 */
  2703. /* ignore exact spelling of "second(s)"*/
  2704. format_time_interval(dbuf, sizeof(dbuf), 0);
  2705. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2706. r = tor_sscanf(dbuf, TL_, &sec, label_s);
  2707. tt_int_op(r,OP_EQ, 2);
  2708. tt_ci_char_op(label_s[0],OP_EQ, 's');
  2709. tt_int_op(sec,OP_EQ, 0);
  2710. format_time_interval(dbuf, sizeof(dbuf), 1);
  2711. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2712. r = tor_sscanf(dbuf, TL_, &sec, label_s);
  2713. tt_int_op(r,OP_EQ, 2);
  2714. tt_ci_char_op(label_s[0],OP_EQ, 's');
  2715. tt_int_op(sec,OP_EQ, 1);
  2716. format_time_interval(dbuf, sizeof(dbuf), 10);
  2717. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2718. r = tor_sscanf(dbuf, TL_, &sec, label_s);
  2719. tt_int_op(r,OP_EQ, 2);
  2720. tt_ci_char_op(label_s[0],OP_EQ, 's');
  2721. tt_int_op(sec,OP_EQ, 10);
  2722. format_time_interval(dbuf, sizeof(dbuf), 59);
  2723. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2724. r = tor_sscanf(dbuf, TL_, &sec, label_s);
  2725. tt_int_op(r,OP_EQ, 2);
  2726. tt_ci_char_op(label_s[0],OP_EQ, 's');
  2727. tt_int_op(sec,OP_EQ, 59);
  2728. /* negative seconds are reported as their absolute value */
  2729. format_time_interval(dbuf, sizeof(dbuf), -4);
  2730. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2731. r = tor_sscanf(dbuf, TL_, &sec, label_s);
  2732. tt_int_op(r,OP_EQ, 2);
  2733. tt_ci_char_op(label_s[0],OP_EQ, 's');
  2734. tt_int_op(sec,OP_EQ, 4);
  2735. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2736. format_time_interval(dbuf, sizeof(dbuf), -32);
  2737. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2738. r = tor_sscanf(dbuf, TL_, &sec, label_s);
  2739. tt_int_op(r,OP_EQ, 2);
  2740. tt_ci_char_op(label_s[0],OP_EQ, 's');
  2741. tt_int_op(sec,OP_EQ, 32);
  2742. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2743. /* minutes: 1:00, 1:01, 1:59, 2:00, 2:01, 59:59 */
  2744. /* ignore trailing "0 second(s)", if present */
  2745. format_time_interval(dbuf, sizeof(dbuf), 60);
  2746. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2747. r = tor_sscanf(dbuf, TL_, &min, label_m);
  2748. tt_int_op(r,OP_EQ, 2);
  2749. tt_ci_char_op(label_m[0],OP_EQ, 'm');
  2750. tt_int_op(min,OP_EQ, 1);
  2751. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2752. /* ignore exact spelling of "minute(s)," and "second(s)" */
  2753. format_time_interval(dbuf, sizeof(dbuf), 60 + 1);
  2754. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2755. r = tor_sscanf(dbuf, TL_ " " TL_,
  2756. &min, label_m, &sec, label_s);
  2757. tt_int_op(r,OP_EQ, 4);
  2758. tt_int_op(min,OP_EQ, 1);
  2759. tt_ci_char_op(label_m[0],OP_EQ, 'm');
  2760. tt_int_op(sec,OP_EQ, 1);
  2761. tt_ci_char_op(label_s[0],OP_EQ, 's');
  2762. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2763. format_time_interval(dbuf, sizeof(dbuf), 60*2 - 1);
  2764. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2765. r = tor_sscanf(dbuf, TL_ " " TL_,
  2766. &min, label_m, &sec, label_s);
  2767. tt_int_op(r,OP_EQ, 4);
  2768. tt_int_op(min,OP_EQ, 1);
  2769. tt_ci_char_op(label_m[0],OP_EQ, 'm');
  2770. tt_int_op(sec,OP_EQ, 59);
  2771. tt_ci_char_op(label_s[0],OP_EQ, 's');
  2772. /* ignore trailing "0 second(s)", if present */
  2773. format_time_interval(dbuf, sizeof(dbuf), 60*2);
  2774. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2775. r = tor_sscanf(dbuf, TL_, &min, label_m);
  2776. tt_int_op(r,OP_EQ, 2);
  2777. tt_int_op(min,OP_EQ, 2);
  2778. tt_ci_char_op(label_m[0],OP_EQ, 'm');
  2779. /* ignore exact spelling of "minute(s)," and "second(s)" */
  2780. format_time_interval(dbuf, sizeof(dbuf), 60*2 + 1);
  2781. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2782. r = tor_sscanf(dbuf, TL_ " " TL_,
  2783. &min, label_m, &sec, label_s);
  2784. tt_int_op(r,OP_EQ, 4);
  2785. tt_int_op(min,OP_EQ, 2);
  2786. tt_ci_char_op(label_m[0],OP_EQ, 'm');
  2787. tt_int_op(sec,OP_EQ, 1);
  2788. tt_ci_char_op(label_s[0],OP_EQ, 's');
  2789. format_time_interval(dbuf, sizeof(dbuf), 60*60 - 1);
  2790. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2791. r = tor_sscanf(dbuf, TL_ " " TL_,
  2792. &min, label_m, &sec, label_s);
  2793. tt_int_op(r,OP_EQ, 4);
  2794. tt_int_op(min,OP_EQ, 59);
  2795. tt_ci_char_op(label_m[0],OP_EQ, 'm');
  2796. tt_int_op(sec,OP_EQ, 59);
  2797. tt_ci_char_op(label_s[0],OP_EQ, 's');
  2798. /* negative minutes are reported as their absolute value */
  2799. /* ignore trailing "0 second(s)", if present */
  2800. format_time_interval(dbuf, sizeof(dbuf), -3*60);
  2801. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2802. r = tor_sscanf(dbuf, TL_, &min, label_m);
  2803. tt_int_op(r,OP_EQ, 2);
  2804. tt_int_op(min,OP_EQ, 3);
  2805. tt_ci_char_op(label_m[0],OP_EQ, 'm');
  2806. /* ignore exact spelling of "minute(s)," and "second(s)" */
  2807. format_time_interval(dbuf, sizeof(dbuf), -96);
  2808. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2809. r = tor_sscanf(dbuf, TL_ " " TL_,
  2810. &min, label_m, &sec, label_s);
  2811. tt_int_op(r,OP_EQ, 4);
  2812. tt_int_op(min,OP_EQ, 1);
  2813. tt_ci_char_op(label_m[0],OP_EQ, 'm');
  2814. tt_int_op(sec,OP_EQ, 36);
  2815. tt_ci_char_op(label_s[0],OP_EQ, 's');
  2816. format_time_interval(dbuf, sizeof(dbuf), -2815);
  2817. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2818. r = tor_sscanf(dbuf, TL_ " " TL_,
  2819. &min, label_m, &sec, label_s);
  2820. tt_int_op(r,OP_EQ, 4);
  2821. tt_int_op(min,OP_EQ, 46);
  2822. tt_ci_char_op(label_m[0],OP_EQ, 'm');
  2823. tt_int_op(sec,OP_EQ, 55);
  2824. tt_ci_char_op(label_s[0],OP_EQ, 's');
  2825. /* hours: 1:00, 1:00:01, 1:01, 23:59, 23:59:59 */
  2826. /* always ignore trailing seconds, if present */
  2827. /* ignore trailing "0 minute(s)" etc., if present */
  2828. format_time_interval(dbuf, sizeof(dbuf), 60*60);
  2829. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2830. r = tor_sscanf(dbuf, TL_, &hour, label_h);
  2831. tt_int_op(r,OP_EQ, 2);
  2832. tt_int_op(hour,OP_EQ, 1);
  2833. tt_ci_char_op(label_h[0],OP_EQ, 'h');
  2834. format_time_interval(dbuf, sizeof(dbuf), 60*60 + 1);
  2835. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2836. r = tor_sscanf(dbuf, TL_, &hour, label_h);
  2837. tt_int_op(r,OP_EQ, 2);
  2838. tt_int_op(hour,OP_EQ, 1);
  2839. tt_ci_char_op(label_h[0],OP_EQ, 'h');
  2840. /* ignore exact spelling of "hour(s)," etc. */
  2841. format_time_interval(dbuf, sizeof(dbuf), 60*60 + 60);
  2842. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2843. r = tor_sscanf(dbuf, TL_ " " TL_,
  2844. &hour, label_h, &min, label_m);
  2845. tt_int_op(r,OP_EQ, 4);
  2846. tt_int_op(hour,OP_EQ, 1);
  2847. tt_ci_char_op(label_h[0],OP_EQ, 'h');
  2848. tt_int_op(min,OP_EQ, 1);
  2849. tt_ci_char_op(label_m[0],OP_EQ, 'm');
  2850. format_time_interval(dbuf, sizeof(dbuf), 24*60*60 - 60);
  2851. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2852. r = tor_sscanf(dbuf, TL_ " " TL_,
  2853. &hour, label_h, &min, label_m);
  2854. tt_int_op(r,OP_EQ, 4);
  2855. tt_int_op(hour,OP_EQ, 23);
  2856. tt_ci_char_op(label_h[0],OP_EQ, 'h');
  2857. tt_int_op(min,OP_EQ, 59);
  2858. tt_ci_char_op(label_m[0],OP_EQ, 'm');
  2859. format_time_interval(dbuf, sizeof(dbuf), 24*60*60 - 1);
  2860. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2861. r = tor_sscanf(dbuf, TL_ " " TL_,
  2862. &hour, label_h, &min, label_m);
  2863. tt_int_op(r,OP_EQ, 4);
  2864. tt_int_op(hour,OP_EQ, 23);
  2865. tt_ci_char_op(label_h[0],OP_EQ, 'h');
  2866. tt_int_op(min,OP_EQ, 59);
  2867. tt_ci_char_op(label_m[0],OP_EQ, 'm');
  2868. /* negative hours are reported as their absolute value */
  2869. /* ignore exact spelling of "hour(s)," etc., if present */
  2870. format_time_interval(dbuf, sizeof(dbuf), -2*60*60);
  2871. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2872. r = tor_sscanf(dbuf, TL_, &hour, label_h);
  2873. tt_int_op(r,OP_EQ, 2);
  2874. tt_int_op(hour,OP_EQ, 2);
  2875. tt_ci_char_op(label_h[0],OP_EQ, 'h');
  2876. format_time_interval(dbuf, sizeof(dbuf), -75804);
  2877. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2878. r = tor_sscanf(dbuf, TL_ " " TL_,
  2879. &hour, label_h, &min, label_m);
  2880. tt_int_op(r,OP_EQ, 4);
  2881. tt_int_op(hour,OP_EQ, 21);
  2882. tt_ci_char_op(label_h[0],OP_EQ, 'h');
  2883. tt_int_op(min,OP_EQ, 3);
  2884. tt_ci_char_op(label_m[0],OP_EQ, 'm');
  2885. /* days: 1:00, 1:00:00:01, 1:00:01, 1:01 */
  2886. /* always ignore trailing seconds, if present */
  2887. /* ignore trailing "0 hours(s)" etc., if present */
  2888. format_time_interval(dbuf, sizeof(dbuf), 24*60*60);
  2889. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2890. r = tor_sscanf(dbuf, TL_, &day, label_d);
  2891. tt_int_op(r,OP_EQ, 2);
  2892. tt_int_op(day,OP_EQ, 1);
  2893. tt_ci_char_op(label_d[0],OP_EQ, 'd');
  2894. format_time_interval(dbuf, sizeof(dbuf), 24*60*60 + 1);
  2895. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2896. r = tor_sscanf(dbuf, TL_, &day, label_d);
  2897. tt_int_op(r,OP_EQ, 2);
  2898. tt_int_op(day,OP_EQ, 1);
  2899. tt_ci_char_op(label_d[0],OP_EQ, 'd');
  2900. /* ignore exact spelling of "days(s)," etc. */
  2901. format_time_interval(dbuf, sizeof(dbuf), 24*60*60 + 60);
  2902. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2903. r = tor_sscanf(dbuf, TL_ " " TL_ " " TL_,
  2904. &day, label_d, &hour, label_h, &min, label_m);
  2905. if (r == -1) {
  2906. /* ignore 0 hours(s), if present */
  2907. r = tor_sscanf(dbuf, TL_ " " TL_,
  2908. &day, label_d, &min, label_m);
  2909. }
  2910. tt_assert(r == 4 || r == 6);
  2911. tt_int_op(day,OP_EQ, 1);
  2912. tt_ci_char_op(label_d[0],OP_EQ, 'd');
  2913. if (r == 6) {
  2914. tt_int_op(hour,OP_EQ, 0);
  2915. tt_ci_char_op(label_h[0],OP_EQ, 'h');
  2916. }
  2917. tt_int_op(min,OP_EQ, 1);
  2918. tt_ci_char_op(label_m[0],OP_EQ, 'm');
  2919. /* ignore trailing "0 minutes(s)" etc., if present */
  2920. format_time_interval(dbuf, sizeof(dbuf), 24*60*60 + 60*60);
  2921. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2922. r = tor_sscanf(dbuf, TL_ " " TL_,
  2923. &day, label_d, &hour, label_h);
  2924. tt_int_op(r,OP_EQ, 4);
  2925. tt_int_op(day,OP_EQ, 1);
  2926. tt_ci_char_op(label_d[0],OP_EQ, 'd');
  2927. tt_int_op(hour,OP_EQ, 1);
  2928. tt_ci_char_op(label_h[0],OP_EQ, 'h');
  2929. /* negative days are reported as their absolute value */
  2930. format_time_interval(dbuf, sizeof(dbuf), -21936184);
  2931. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2932. r = tor_sscanf(dbuf, TL_ " " TL_ " " TL_,
  2933. &day, label_d, &hour, label_h, &min, label_m);
  2934. tt_int_op(r,OP_EQ, 6);
  2935. tt_int_op(day,OP_EQ, 253);
  2936. tt_ci_char_op(label_d[0],OP_EQ, 'd');
  2937. tt_int_op(hour,OP_EQ, 21);
  2938. tt_ci_char_op(label_h[0],OP_EQ, 'h');
  2939. tt_int_op(min,OP_EQ, 23);
  2940. tt_ci_char_op(label_m[0],OP_EQ, 'm');
  2941. /* periods > 1 year are reported in days (warn?) */
  2942. /* ignore exact spelling of "days(s)," etc., if present */
  2943. format_time_interval(dbuf, sizeof(dbuf), 758635154);
  2944. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2945. r = tor_sscanf(dbuf, TL_ " " TL_ " " TL_,
  2946. &day, label_d, &hour, label_h, &min, label_m);
  2947. tt_int_op(r,OP_EQ, 6);
  2948. tt_int_op(day,OP_EQ, 8780);
  2949. tt_ci_char_op(label_d[0],OP_EQ, 'd');
  2950. tt_int_op(hour,OP_EQ, 11);
  2951. tt_ci_char_op(label_h[0],OP_EQ, 'h');
  2952. tt_int_op(min,OP_EQ, 59);
  2953. tt_ci_char_op(label_m[0],OP_EQ, 'm');
  2954. /* negative periods > 1 year are reported in days (warn?) */
  2955. format_time_interval(dbuf, sizeof(dbuf), -1427014922);
  2956. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2957. r = tor_sscanf(dbuf, TL_ " " TL_ " " TL_,
  2958. &day, label_d, &hour, label_h, &min, label_m);
  2959. tt_int_op(r,OP_EQ, 6);
  2960. tt_int_op(day,OP_EQ, 16516);
  2961. tt_ci_char_op(label_d[0],OP_EQ, 'd');
  2962. tt_int_op(hour,OP_EQ, 9);
  2963. tt_ci_char_op(label_h[0],OP_EQ, 'h');
  2964. tt_int_op(min,OP_EQ, 2);
  2965. tt_ci_char_op(label_m[0],OP_EQ, 'm');
  2966. #if SIZEOF_LONG == 4 || SIZEOF_LONG == 8
  2967. /* We can try INT32_MIN/MAX */
  2968. /* Always ignore second(s) */
  2969. /* INT32_MAX */
  2970. format_time_interval(dbuf, sizeof(dbuf), 2147483647);
  2971. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2972. r = tor_sscanf(dbuf, TL_ " " TL_ " " TL_,
  2973. &day, label_d, &hour, label_h, &min, label_m);
  2974. tt_int_op(r,OP_EQ, 6);
  2975. tt_int_op(day,OP_EQ, 24855);
  2976. tt_ci_char_op(label_d[0],OP_EQ, 'd');
  2977. tt_int_op(hour,OP_EQ, 3);
  2978. tt_ci_char_op(label_h[0],OP_EQ, 'h');
  2979. tt_int_op(min,OP_EQ, 14);
  2980. tt_ci_char_op(label_m[0],OP_EQ, 'm');
  2981. /* and 7 seconds - ignored */
  2982. /* INT32_MIN: check that we get the absolute value of interval,
  2983. * which doesn't actually fit in int32_t.
  2984. * We expect INT32_MAX or INT32_MAX + 1 with 64 bit longs */
  2985. format_time_interval(dbuf, sizeof(dbuf), -2147483647L - 1L);
  2986. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  2987. r = tor_sscanf(dbuf, TL_ " " TL_ " " TL_,
  2988. &day, label_d, &hour, label_h, &min, label_m);
  2989. tt_int_op(r,OP_EQ, 6);
  2990. tt_int_op(day,OP_EQ, 24855);
  2991. tt_ci_char_op(label_d[0],OP_EQ, 'd');
  2992. tt_int_op(hour,OP_EQ, 3);
  2993. tt_ci_char_op(label_h[0],OP_EQ, 'h');
  2994. tt_int_op(min,OP_EQ, 14);
  2995. tt_ci_char_op(label_m[0],OP_EQ, 'm');
  2996. /* and 7 or 8 seconds - ignored */
  2997. #endif /* SIZEOF_LONG == 4 || SIZEOF_LONG == 8 */
  2998. #if SIZEOF_LONG == 8
  2999. /* We can try INT64_MIN/MAX */
  3000. /* Always ignore second(s) */
  3001. /* INT64_MAX */
  3002. format_time_interval(dbuf, sizeof(dbuf), 9223372036854775807L);
  3003. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  3004. r = tor_sscanf(dbuf, TL_ " " TL_ " " TL_,
  3005. &day, label_d, &hour, label_h, &min, label_m);
  3006. tt_int_op(r,OP_EQ, 6);
  3007. tt_int_op(day,OP_EQ, 106751991167300L);
  3008. tt_ci_char_op(label_d[0],OP_EQ, 'd');
  3009. tt_int_op(hour,OP_EQ, 15);
  3010. tt_ci_char_op(label_h[0],OP_EQ, 'h');
  3011. tt_int_op(min,OP_EQ, 30);
  3012. tt_ci_char_op(label_m[0],OP_EQ, 'm');
  3013. /* and 7 seconds - ignored */
  3014. /* INT64_MIN: check that we get the absolute value of interval,
  3015. * which doesn't actually fit in int64_t.
  3016. * We expect INT64_MAX */
  3017. format_time_interval(dbuf, sizeof(dbuf),
  3018. -9223372036854775807L - 1L);
  3019. tt_int_op(strnlen(dbuf, DBUF_SIZE),OP_LE, DBUF_SIZE - 1);
  3020. r = tor_sscanf(dbuf, TL_ " " TL_ " " TL_,
  3021. &day, label_d, &hour, label_h, &min, label_m);
  3022. tt_int_op(r,OP_EQ, 6);
  3023. tt_int_op(day,OP_EQ, 106751991167300L);
  3024. tt_ci_char_op(label_d[0],OP_EQ, 'd');
  3025. tt_int_op(hour,OP_EQ, 15);
  3026. tt_ci_char_op(label_h[0],OP_EQ, 'h');
  3027. tt_int_op(min,OP_EQ, 30);
  3028. tt_ci_char_op(label_m[0],OP_EQ, 'm');
  3029. /* and 7 or 8 seconds - ignored */
  3030. #endif /* SIZEOF_LONG == 8 */
  3031. done:
  3032. ;
  3033. }
  3034. #undef tt_char_op
  3035. #undef tt_ci_char_op
  3036. #undef DBUF_SIZE
  3037. #undef T_
  3038. #undef LABEL_SIZE
  3039. #undef L_
  3040. #undef TL_
  3041. static void
  3042. test_util_path_is_relative(void *arg)
  3043. {
  3044. /* OS-independent tests */
  3045. (void)arg;
  3046. tt_int_op(1,OP_EQ, path_is_relative(""));
  3047. tt_int_op(1,OP_EQ, path_is_relative("dir"));
  3048. tt_int_op(1,OP_EQ, path_is_relative("dir/"));
  3049. tt_int_op(1,OP_EQ, path_is_relative("./dir"));
  3050. tt_int_op(1,OP_EQ, path_is_relative("../dir"));
  3051. tt_int_op(0,OP_EQ, path_is_relative("/"));
  3052. tt_int_op(0,OP_EQ, path_is_relative("/dir"));
  3053. tt_int_op(0,OP_EQ, path_is_relative("/dir/"));
  3054. /* Windows */
  3055. #ifdef _WIN32
  3056. /* I don't have Windows so I can't test this, hence the "#ifdef
  3057. 0". These are tests that look useful, so please try to get them
  3058. running and uncomment if it all works as it should */
  3059. tt_int_op(1,OP_EQ, path_is_relative("dir"));
  3060. tt_int_op(1,OP_EQ, path_is_relative("dir\\"));
  3061. tt_int_op(1,OP_EQ, path_is_relative("dir\\a:"));
  3062. tt_int_op(1,OP_EQ, path_is_relative("dir\\a:\\"));
  3063. tt_int_op(1,OP_EQ, path_is_relative("http:\\dir"));
  3064. tt_int_op(0,OP_EQ, path_is_relative("\\dir"));
  3065. tt_int_op(0,OP_EQ, path_is_relative("a:\\dir"));
  3066. tt_int_op(0,OP_EQ, path_is_relative("z:\\dir"));
  3067. #endif /* defined(_WIN32) */
  3068. done:
  3069. ;
  3070. }
  3071. /** Run unittests for memory area allocator */
  3072. static void
  3073. test_util_memarea(void *arg)
  3074. {
  3075. memarea_t *area = memarea_new();
  3076. char *p1, *p2, *p3, *p1_orig;
  3077. void *malloced_ptr = NULL;
  3078. int i;
  3079. #ifdef DISABLE_MEMORY_SENTINELS
  3080. /* If memory sentinels are disabled, this whole module is just an alias for
  3081. malloc(), which is free to lay out memory most any way it wants. */
  3082. if (1)
  3083. tt_skip();
  3084. #endif /* defined(DISABLE_MEMORY_SENTINELS) */
  3085. (void)arg;
  3086. tt_assert(area);
  3087. p1_orig = p1 = memarea_alloc(area,64);
  3088. p2 = memarea_alloc_zero(area,52);
  3089. p3 = memarea_alloc(area,11);
  3090. tt_assert(memarea_owns_ptr(area, p1));
  3091. tt_assert(memarea_owns_ptr(area, p2));
  3092. tt_assert(memarea_owns_ptr(area, p3));
  3093. /* Make sure we left enough space. */
  3094. tt_assert(p1+64 <= p2);
  3095. tt_assert(p2+52 <= p3);
  3096. /* Make sure we aligned. */
  3097. tt_int_op(((uintptr_t)p1) % sizeof(void*),OP_EQ, 0);
  3098. tt_int_op(((uintptr_t)p2) % sizeof(void*),OP_EQ, 0);
  3099. tt_int_op(((uintptr_t)p3) % sizeof(void*),OP_EQ, 0);
  3100. tt_assert(!memarea_owns_ptr(area, p3+8192));
  3101. tt_assert(!memarea_owns_ptr(area, p3+30));
  3102. tt_assert(tor_mem_is_zero(p2, 52));
  3103. /* Make sure we don't overalign. */
  3104. p1 = memarea_alloc(area, 1);
  3105. p2 = memarea_alloc(area, 1);
  3106. tt_ptr_op(p1+sizeof(void*),OP_EQ, p2);
  3107. {
  3108. malloced_ptr = tor_malloc(64);
  3109. tt_assert(!memarea_owns_ptr(area, malloced_ptr));
  3110. tor_free(malloced_ptr);
  3111. }
  3112. /* memarea_memdup */
  3113. {
  3114. malloced_ptr = tor_malloc(64);
  3115. crypto_rand((char*)malloced_ptr, 64);
  3116. p1 = memarea_memdup(area, malloced_ptr, 64);
  3117. tt_assert(p1 != malloced_ptr);
  3118. tt_mem_op(p1,OP_EQ, malloced_ptr, 64);
  3119. tor_free(malloced_ptr);
  3120. }
  3121. /* memarea_strdup. */
  3122. p1 = memarea_strdup(area,"");
  3123. p2 = memarea_strdup(area, "abcd");
  3124. tt_assert(p1);
  3125. tt_assert(p2);
  3126. tt_str_op(p1,OP_EQ, "");
  3127. tt_str_op(p2,OP_EQ, "abcd");
  3128. /* memarea_strndup. */
  3129. {
  3130. const char *s = "Ad ogni porta batte la morte e grida: il nome!";
  3131. /* (From Turandot, act 3.) */
  3132. size_t len = strlen(s);
  3133. p1 = memarea_strndup(area, s, 1000);
  3134. p2 = memarea_strndup(area, s, 10);
  3135. tt_str_op(p1,OP_EQ, s);
  3136. tt_assert(p2 >= p1 + len + 1);
  3137. tt_mem_op(s,OP_EQ, p2, 10);
  3138. tt_int_op(p2[10],OP_EQ, '\0');
  3139. p3 = memarea_strndup(area, s, len);
  3140. tt_str_op(p3,OP_EQ, s);
  3141. p3 = memarea_strndup(area, s, len-1);
  3142. tt_mem_op(s,OP_EQ, p3, len-1);
  3143. tt_int_op(p3[len-1],OP_EQ, '\0');
  3144. }
  3145. memarea_clear(area);
  3146. p1 = memarea_alloc(area, 1);
  3147. tt_ptr_op(p1,OP_EQ, p1_orig);
  3148. memarea_clear(area);
  3149. size_t total = 0, initial_allocation, allocation2, dummy;
  3150. memarea_get_stats(area, &initial_allocation, &dummy);
  3151. /* Check for running over an area's size. */
  3152. for (i = 0; i < 4096; ++i) {
  3153. size_t n = crypto_rand_int(6);
  3154. p1 = memarea_alloc(area, n);
  3155. total += n;
  3156. tt_assert(memarea_owns_ptr(area, p1));
  3157. }
  3158. memarea_assert_ok(area);
  3159. memarea_get_stats(area, &allocation2, &dummy);
  3160. /* Make sure we can allocate a too-big object. */
  3161. p1 = memarea_alloc_zero(area, 9000);
  3162. p2 = memarea_alloc_zero(area, 16);
  3163. total += 9000;
  3164. total += 16;
  3165. tt_assert(memarea_owns_ptr(area, p1));
  3166. tt_assert(memarea_owns_ptr(area, p2));
  3167. /* Now test stats... */
  3168. size_t allocated = 0, used = 0;
  3169. memarea_get_stats(area, &allocated, &used);
  3170. tt_int_op(used, OP_LE, allocated);
  3171. tt_int_op(used, OP_GE, total); /* not EQ, because of alignment and headers*/
  3172. tt_int_op(allocated, OP_GT, allocation2);
  3173. tt_int_op(allocation2, OP_GT, initial_allocation);
  3174. memarea_clear(area);
  3175. memarea_get_stats(area, &allocated, &used);
  3176. tt_int_op(used, OP_LT, 128); /* Not 0, because of header */
  3177. tt_int_op(allocated, OP_EQ, initial_allocation);
  3178. done:
  3179. memarea_drop_all(area);
  3180. tor_free(malloced_ptr);
  3181. }
  3182. /** Run unit tests for utility functions to get file names relative to
  3183. * the data directory. */
  3184. static void
  3185. test_util_datadir(void *arg)
  3186. {
  3187. char buf[1024];
  3188. char *f = NULL;
  3189. char *temp_dir = NULL;
  3190. (void)arg;
  3191. temp_dir = get_datadir_fname(NULL);
  3192. f = get_datadir_fname("state");
  3193. tor_snprintf(buf, sizeof(buf), "%s"PATH_SEPARATOR"state", temp_dir);
  3194. tt_str_op(f,OP_EQ, buf);
  3195. tor_free(f);
  3196. f = get_datadir_fname2("cache", "thingy");
  3197. tor_snprintf(buf, sizeof(buf),
  3198. "%s"PATH_SEPARATOR"cache"PATH_SEPARATOR"thingy", temp_dir);
  3199. tt_str_op(f,OP_EQ, buf);
  3200. tor_free(f);
  3201. f = get_datadir_fname2_suffix("cache", "thingy", ".foo");
  3202. tor_snprintf(buf, sizeof(buf),
  3203. "%s"PATH_SEPARATOR"cache"PATH_SEPARATOR"thingy.foo", temp_dir);
  3204. tt_str_op(f,OP_EQ, buf);
  3205. tor_free(f);
  3206. f = get_datadir_fname_suffix("cache", ".foo");
  3207. tor_snprintf(buf, sizeof(buf), "%s"PATH_SEPARATOR"cache.foo",
  3208. temp_dir);
  3209. tt_str_op(f,OP_EQ, buf);
  3210. done:
  3211. tor_free(f);
  3212. tor_free(temp_dir);
  3213. }
  3214. static void
  3215. test_util_strtok(void *arg)
  3216. {
  3217. char buf[128];
  3218. char buf2[128];
  3219. int i;
  3220. char *cp1, *cp2;
  3221. (void)arg;
  3222. for (i = 0; i < 3; i++) {
  3223. const char *pad1="", *pad2="";
  3224. switch (i) {
  3225. case 0:
  3226. break;
  3227. case 1:
  3228. pad1 = " ";
  3229. pad2 = "!";
  3230. break;
  3231. case 2:
  3232. pad1 = " ";
  3233. pad2 = ";!";
  3234. break;
  3235. }
  3236. tor_snprintf(buf, sizeof(buf), "%s", pad1);
  3237. tor_snprintf(buf2, sizeof(buf2), "%s", pad2);
  3238. tt_ptr_op(tor_strtok_r_impl(buf, " ", &cp1), OP_EQ, NULL);
  3239. tt_ptr_op(tor_strtok_r_impl(buf2, ".!..;!", &cp2), OP_EQ, NULL);
  3240. tor_snprintf(buf, sizeof(buf),
  3241. "%sGraved on the dark in gestures of descent%s", pad1, pad1);
  3242. tor_snprintf(buf2, sizeof(buf2),
  3243. "%sthey.seemed;;their!.own;most.perfect;monument%s",pad2,pad2);
  3244. /* -- "Year's End", Richard Wilbur */
  3245. tt_str_op("Graved",OP_EQ, tor_strtok_r_impl(buf, " ", &cp1));
  3246. tt_str_op("they",OP_EQ, tor_strtok_r_impl(buf2, ".!..;!", &cp2));
  3247. #define S1() tor_strtok_r_impl(NULL, " ", &cp1)
  3248. #define S2() tor_strtok_r_impl(NULL, ".!..;!", &cp2)
  3249. tt_str_op("on",OP_EQ, S1());
  3250. tt_str_op("the",OP_EQ, S1());
  3251. tt_str_op("dark",OP_EQ, S1());
  3252. tt_str_op("seemed",OP_EQ, S2());
  3253. tt_str_op("their",OP_EQ, S2());
  3254. tt_str_op("own",OP_EQ, S2());
  3255. tt_str_op("in",OP_EQ, S1());
  3256. tt_str_op("gestures",OP_EQ, S1());
  3257. tt_str_op("of",OP_EQ, S1());
  3258. tt_str_op("most",OP_EQ, S2());
  3259. tt_str_op("perfect",OP_EQ, S2());
  3260. tt_str_op("descent",OP_EQ, S1());
  3261. tt_str_op("monument",OP_EQ, S2());
  3262. tt_ptr_op(NULL,OP_EQ, S1());
  3263. tt_ptr_op(NULL,OP_EQ, S2());
  3264. }
  3265. buf[0] = 0;
  3266. tt_ptr_op(NULL,OP_EQ, tor_strtok_r_impl(buf, " ", &cp1));
  3267. tt_ptr_op(NULL,OP_EQ, tor_strtok_r_impl(buf, "!", &cp1));
  3268. strlcpy(buf, "Howdy!", sizeof(buf));
  3269. tt_str_op("Howdy",OP_EQ, tor_strtok_r_impl(buf, "!", &cp1));
  3270. tt_ptr_op(NULL,OP_EQ, tor_strtok_r_impl(NULL, "!", &cp1));
  3271. strlcpy(buf, " ", sizeof(buf));
  3272. tt_ptr_op(NULL,OP_EQ, tor_strtok_r_impl(buf, " ", &cp1));
  3273. strlcpy(buf, " ", sizeof(buf));
  3274. tt_ptr_op(NULL,OP_EQ, tor_strtok_r_impl(buf, " ", &cp1));
  3275. strlcpy(buf, "something ", sizeof(buf));
  3276. tt_str_op("something",OP_EQ, tor_strtok_r_impl(buf, " ", &cp1));
  3277. tt_ptr_op(NULL,OP_EQ, tor_strtok_r_impl(NULL, ";", &cp1));
  3278. done:
  3279. ;
  3280. }
  3281. static void
  3282. test_util_find_str_at_start_of_line(void *ptr)
  3283. {
  3284. const char *long_string =
  3285. "howdy world. how are you? i hope it's fine.\n"
  3286. "hello kitty\n"
  3287. "third line";
  3288. char *line2 = strchr(long_string,'\n')+1;
  3289. char *line3 = strchr(line2,'\n')+1;
  3290. const char *short_string = "hello kitty\n"
  3291. "second line\n";
  3292. char *short_line2 = strchr(short_string,'\n')+1;
  3293. (void)ptr;
  3294. tt_ptr_op(long_string,OP_EQ, find_str_at_start_of_line(long_string, ""));
  3295. tt_ptr_op(NULL,OP_EQ, find_str_at_start_of_line(short_string, "nonsense"));
  3296. tt_ptr_op(NULL,OP_EQ, find_str_at_start_of_line(long_string, "nonsense"));
  3297. tt_ptr_op(NULL,OP_EQ, find_str_at_start_of_line(long_string, "\n"));
  3298. tt_ptr_op(NULL,OP_EQ, find_str_at_start_of_line(long_string, "how "));
  3299. tt_ptr_op(NULL,OP_EQ, find_str_at_start_of_line(long_string, "kitty"));
  3300. tt_ptr_op(long_string,OP_EQ, find_str_at_start_of_line(long_string, "h"));
  3301. tt_ptr_op(long_string,OP_EQ, find_str_at_start_of_line(long_string, "how"));
  3302. tt_ptr_op(line2,OP_EQ, find_str_at_start_of_line(long_string, "he"));
  3303. tt_ptr_op(line2,OP_EQ, find_str_at_start_of_line(long_string, "hell"));
  3304. tt_ptr_op(line2,OP_EQ, find_str_at_start_of_line(long_string, "hello k"));
  3305. tt_ptr_op(line2,OP_EQ,
  3306. find_str_at_start_of_line(long_string, "hello kitty\n"));
  3307. tt_ptr_op(line2,OP_EQ,
  3308. find_str_at_start_of_line(long_string, "hello kitty\nt"));
  3309. tt_ptr_op(line3,OP_EQ, find_str_at_start_of_line(long_string, "third"));
  3310. tt_ptr_op(line3,OP_EQ, find_str_at_start_of_line(long_string, "third line"));
  3311. tt_ptr_op(NULL, OP_EQ,
  3312. find_str_at_start_of_line(long_string, "third line\n"));
  3313. tt_ptr_op(short_line2,OP_EQ, find_str_at_start_of_line(short_string,
  3314. "second line\n"));
  3315. done:
  3316. ;
  3317. }
  3318. static void
  3319. test_util_string_is_C_identifier(void *ptr)
  3320. {
  3321. (void)ptr;
  3322. tt_int_op(1,OP_EQ, string_is_C_identifier("string_is_C_identifier"));
  3323. tt_int_op(1,OP_EQ, string_is_C_identifier("_string_is_C_identifier"));
  3324. tt_int_op(1,OP_EQ, string_is_C_identifier("_"));
  3325. tt_int_op(1,OP_EQ, string_is_C_identifier("i"));
  3326. tt_int_op(1,OP_EQ, string_is_C_identifier("_____"));
  3327. tt_int_op(1,OP_EQ, string_is_C_identifier("__00__"));
  3328. tt_int_op(1,OP_EQ, string_is_C_identifier("__init__"));
  3329. tt_int_op(1,OP_EQ, string_is_C_identifier("_0"));
  3330. tt_int_op(1,OP_EQ, string_is_C_identifier("_0string_is_C_identifier"));
  3331. tt_int_op(1,OP_EQ, string_is_C_identifier("_0"));
  3332. tt_int_op(0,OP_EQ, string_is_C_identifier("0_string_is_C_identifier"));
  3333. tt_int_op(0,OP_EQ, string_is_C_identifier("0"));
  3334. tt_int_op(0,OP_EQ, string_is_C_identifier(""));
  3335. tt_int_op(0,OP_EQ, string_is_C_identifier(";"));
  3336. tt_int_op(0,OP_EQ, string_is_C_identifier("i;"));
  3337. tt_int_op(0,OP_EQ, string_is_C_identifier("_;"));
  3338. tt_int_op(0,OP_EQ, string_is_C_identifier("í"));
  3339. tt_int_op(0,OP_EQ, string_is_C_identifier("ñ"));
  3340. done:
  3341. ;
  3342. }
  3343. static void
  3344. test_util_asprintf(void *ptr)
  3345. {
  3346. #define LOREMIPSUM \
  3347. "Lorem ipsum dolor sit amet, consectetur adipisicing elit"
  3348. char *cp=NULL, *cp2=NULL;
  3349. int r;
  3350. (void)ptr;
  3351. /* simple string */
  3352. r = tor_asprintf(&cp, "simple string 100%% safe");
  3353. tt_assert(cp);
  3354. tt_str_op("simple string 100% safe",OP_EQ, cp);
  3355. tt_int_op(strlen(cp),OP_EQ, r);
  3356. tor_free(cp);
  3357. /* empty string */
  3358. r = tor_asprintf(&cp, "%s", "");
  3359. tt_assert(cp);
  3360. tt_str_op("",OP_EQ, cp);
  3361. tt_int_op(strlen(cp),OP_EQ, r);
  3362. tor_free(cp);
  3363. /* numbers (%i) */
  3364. r = tor_asprintf(&cp, "I like numbers-%2i, %i, etc.", -1, 2);
  3365. tt_assert(cp);
  3366. tt_str_op("I like numbers--1, 2, etc.",OP_EQ, cp);
  3367. tt_int_op(strlen(cp),OP_EQ, r);
  3368. /* don't free cp; next test uses it. */
  3369. /* numbers (%d) */
  3370. r = tor_asprintf(&cp2, "First=%d, Second=%d", 101, 202);
  3371. tt_assert(cp2);
  3372. tt_int_op(strlen(cp2),OP_EQ, r);
  3373. tt_str_op("First=101, Second=202",OP_EQ, cp2);
  3374. tt_assert(cp != cp2);
  3375. tor_free(cp);
  3376. tor_free(cp2);
  3377. /* Glass-box test: a string exactly 128 characters long. */
  3378. r = tor_asprintf(&cp, "Lorem1: %sLorem2: %s", LOREMIPSUM, LOREMIPSUM);
  3379. tt_assert(cp);
  3380. tt_int_op(128,OP_EQ, r);
  3381. tt_int_op(cp[128], OP_EQ, '\0');
  3382. tt_str_op("Lorem1: "LOREMIPSUM"Lorem2: "LOREMIPSUM,OP_EQ, cp);
  3383. tor_free(cp);
  3384. /* String longer than 128 characters */
  3385. r = tor_asprintf(&cp, "1: %s 2: %s 3: %s",
  3386. LOREMIPSUM, LOREMIPSUM, LOREMIPSUM);
  3387. tt_assert(cp);
  3388. tt_int_op(strlen(cp),OP_EQ, r);
  3389. tt_str_op("1: "LOREMIPSUM" 2: "LOREMIPSUM" 3: "LOREMIPSUM,OP_EQ, cp);
  3390. done:
  3391. tor_free(cp);
  3392. tor_free(cp2);
  3393. }
  3394. static void
  3395. test_util_listdir(void *ptr)
  3396. {
  3397. smartlist_t *dir_contents = NULL;
  3398. char *fname1=NULL, *fname2=NULL, *fname3=NULL, *dir1=NULL, *dirname=NULL;
  3399. int r;
  3400. (void)ptr;
  3401. fname1 = tor_strdup(get_fname("hopscotch"));
  3402. fname2 = tor_strdup(get_fname("mumblety-peg"));
  3403. fname3 = tor_strdup(get_fname(".hidden-file"));
  3404. dir1 = tor_strdup(get_fname("some-directory"));
  3405. dirname = tor_strdup(get_fname(NULL));
  3406. tt_int_op(0,OP_EQ, write_str_to_file(fname1, "X\n", 0));
  3407. tt_int_op(0,OP_EQ, write_str_to_file(fname2, "Y\n", 0));
  3408. tt_int_op(0,OP_EQ, write_str_to_file(fname3, "Z\n", 0));
  3409. #ifdef _WIN32
  3410. r = mkdir(dir1);
  3411. #else
  3412. r = mkdir(dir1, 0700);
  3413. #endif
  3414. if (r) {
  3415. fprintf(stderr, "Can't create directory %s:", dir1);
  3416. perror("");
  3417. exit(1);
  3418. }
  3419. dir_contents = tor_listdir(dirname);
  3420. tt_assert(dir_contents);
  3421. /* make sure that each filename is listed. */
  3422. tt_assert(smartlist_contains_string_case(dir_contents, "hopscotch"));
  3423. tt_assert(smartlist_contains_string_case(dir_contents, "mumblety-peg"));
  3424. tt_assert(smartlist_contains_string_case(dir_contents, ".hidden-file"));
  3425. tt_assert(smartlist_contains_string_case(dir_contents, "some-directory"));
  3426. tt_assert(!smartlist_contains_string(dir_contents, "."));
  3427. tt_assert(!smartlist_contains_string(dir_contents, ".."));
  3428. done:
  3429. tor_free(fname1);
  3430. tor_free(fname2);
  3431. tor_free(fname3);
  3432. tor_free(dir1);
  3433. tor_free(dirname);
  3434. if (dir_contents) {
  3435. SMARTLIST_FOREACH(dir_contents, char *, cp, tor_free(cp));
  3436. smartlist_free(dir_contents);
  3437. }
  3438. }
  3439. static void
  3440. test_util_parent_dir(void *ptr)
  3441. {
  3442. char *cp;
  3443. (void)ptr;
  3444. #define T(output,expect_ok,input) \
  3445. do { \
  3446. int ok; \
  3447. cp = tor_strdup(input); \
  3448. ok = get_parent_directory(cp); \
  3449. tt_int_op(expect_ok, OP_EQ, ok); \
  3450. if (ok==0) \
  3451. tt_str_op(output, OP_EQ, cp); \
  3452. tor_free(cp); \
  3453. } while (0);
  3454. T("/home/wombat", 0, "/home/wombat/knish");
  3455. T("/home/wombat", 0, "/home/wombat/knish/");
  3456. T("/home/wombat", 0, "/home/wombat/knish///");
  3457. T("./home/wombat", 0, "./home/wombat/knish/");
  3458. T("/", 0, "/home");
  3459. T("/", 0, "/home//");
  3460. T(".", 0, "./wombat");
  3461. T(".", 0, "./wombat/");
  3462. T(".", 0, "./wombat//");
  3463. T("wombat", 0, "wombat/foo");
  3464. T("wombat/..", 0, "wombat/../foo");
  3465. T("wombat/../", 0, "wombat/..//foo"); /* Is this correct? */
  3466. T("wombat/.", 0, "wombat/./foo");
  3467. T("wombat/./", 0, "wombat/.//foo"); /* Is this correct? */
  3468. T("wombat", 0, "wombat/..//");
  3469. T("wombat", 0, "wombat/foo/");
  3470. T("wombat", 0, "wombat/.foo");
  3471. T("wombat", 0, "wombat/.foo/");
  3472. T("wombat", -1, "");
  3473. T("w", -1, "");
  3474. T("wombat", 0, "wombat/knish");
  3475. T("/", 0, "/");
  3476. T("/", 0, "////");
  3477. done:
  3478. tor_free(cp);
  3479. }
  3480. static void
  3481. test_util_ftruncate(void *ptr)
  3482. {
  3483. char *buf = NULL;
  3484. const char *fname;
  3485. int fd = -1;
  3486. const char *message = "Hello world";
  3487. const char *message2 = "Hola mundo";
  3488. struct stat st;
  3489. (void) ptr;
  3490. fname = get_fname("ftruncate");
  3491. fd = tor_open_cloexec(fname, O_WRONLY|O_CREAT, 0600);
  3492. tt_int_op(fd, OP_GE, 0);
  3493. /* Make the file be there. */
  3494. tt_int_op(strlen(message), OP_EQ, write_all(fd, message, strlen(message),0));
  3495. tt_int_op((int)tor_fd_getpos(fd), OP_EQ, strlen(message));
  3496. tt_int_op(0, OP_EQ, fstat(fd, &st));
  3497. tt_int_op((int)st.st_size, OP_EQ, strlen(message));
  3498. /* Truncate and see if it got truncated */
  3499. tt_int_op(0, OP_EQ, tor_ftruncate(fd));
  3500. tt_int_op((int)tor_fd_getpos(fd), OP_EQ, 0);
  3501. tt_int_op(0, OP_EQ, fstat(fd, &st));
  3502. tt_int_op((int)st.st_size, OP_EQ, 0);
  3503. /* Replace, and see if it got replaced */
  3504. tt_int_op(strlen(message2), OP_EQ,
  3505. write_all(fd, message2, strlen(message2), 0));
  3506. tt_int_op((int)tor_fd_getpos(fd), OP_EQ, strlen(message2));
  3507. tt_int_op(0, OP_EQ, fstat(fd, &st));
  3508. tt_int_op((int)st.st_size, OP_EQ, strlen(message2));
  3509. close(fd);
  3510. fd = -1;
  3511. buf = read_file_to_str(fname, 0, NULL);
  3512. tt_str_op(message2, OP_EQ, buf);
  3513. done:
  3514. if (fd >= 0)
  3515. close(fd);
  3516. tor_free(buf);
  3517. }
  3518. static void
  3519. test_util_num_cpus(void *arg)
  3520. {
  3521. (void)arg;
  3522. int num = compute_num_cpus();
  3523. if (num < 0)
  3524. tt_skip();
  3525. tt_int_op(num, OP_GE, 1);
  3526. tt_int_op(num, OP_LE, 16);
  3527. done:
  3528. ;
  3529. }
  3530. #ifdef _WIN32
  3531. static void
  3532. test_util_load_win_lib(void *ptr)
  3533. {
  3534. HANDLE h = load_windows_system_library(_T("advapi32.dll"));
  3535. (void) ptr;
  3536. tt_assert(h);
  3537. done:
  3538. if (h)
  3539. FreeLibrary(h);
  3540. }
  3541. #endif /* defined(_WIN32) */
  3542. #ifndef _WIN32
  3543. static void
  3544. clear_hex_errno(char *hex_errno)
  3545. {
  3546. memset(hex_errno, '\0', HEX_ERRNO_SIZE + 1);
  3547. }
  3548. static void
  3549. test_util_exit_status(void *ptr)
  3550. {
  3551. /* Leave an extra byte for a \0 so we can do string comparison */
  3552. char hex_errno[HEX_ERRNO_SIZE + 1];
  3553. int n;
  3554. (void)ptr;
  3555. clear_hex_errno(hex_errno);
  3556. tt_str_op("",OP_EQ, hex_errno);
  3557. clear_hex_errno(hex_errno);
  3558. n = format_helper_exit_status(0, 0, hex_errno);
  3559. tt_str_op("0/0\n",OP_EQ, hex_errno);
  3560. tt_int_op(n,OP_EQ, strlen(hex_errno));
  3561. #if SIZEOF_INT == 4
  3562. clear_hex_errno(hex_errno);
  3563. n = format_helper_exit_status(0, 0x7FFFFFFF, hex_errno);
  3564. tt_str_op("0/7FFFFFFF\n",OP_EQ, hex_errno);
  3565. tt_int_op(n,OP_EQ, strlen(hex_errno));
  3566. clear_hex_errno(hex_errno);
  3567. n = format_helper_exit_status(0xFF, -0x80000000, hex_errno);
  3568. tt_str_op("FF/-80000000\n",OP_EQ, hex_errno);
  3569. tt_int_op(n,OP_EQ, strlen(hex_errno));
  3570. tt_int_op(n,OP_EQ, HEX_ERRNO_SIZE);
  3571. #elif SIZEOF_INT == 8
  3572. clear_hex_errno(hex_errno);
  3573. n = format_helper_exit_status(0, 0x7FFFFFFFFFFFFFFF, hex_errno);
  3574. tt_str_op("0/7FFFFFFFFFFFFFFF\n",OP_EQ, hex_errno);
  3575. tt_int_op(n,OP_EQ, strlen(hex_errno));
  3576. clear_hex_errno(hex_errno);
  3577. n = format_helper_exit_status(0xFF, -0x8000000000000000, hex_errno);
  3578. tt_str_op("FF/-8000000000000000\n",OP_EQ, hex_errno);
  3579. tt_int_op(n,OP_EQ, strlen(hex_errno));
  3580. tt_int_op(n,OP_EQ, HEX_ERRNO_SIZE);
  3581. #endif /* SIZEOF_INT == 4 || ... */
  3582. clear_hex_errno(hex_errno);
  3583. n = format_helper_exit_status(0x7F, 0, hex_errno);
  3584. tt_str_op("7F/0\n",OP_EQ, hex_errno);
  3585. tt_int_op(n,OP_EQ, strlen(hex_errno));
  3586. clear_hex_errno(hex_errno);
  3587. n = format_helper_exit_status(0x08, -0x242, hex_errno);
  3588. tt_str_op("8/-242\n",OP_EQ, hex_errno);
  3589. tt_int_op(n,OP_EQ, strlen(hex_errno));
  3590. clear_hex_errno(hex_errno);
  3591. tt_str_op("",OP_EQ, hex_errno);
  3592. done:
  3593. ;
  3594. }
  3595. #endif /* !defined(_WIN32) */
  3596. #ifndef _WIN32
  3597. static void
  3598. test_util_string_from_pipe(void *ptr)
  3599. {
  3600. int test_pipe[2] = {-1, -1};
  3601. int retval = 0;
  3602. enum stream_status status = IO_STREAM_TERM;
  3603. ssize_t retlen;
  3604. char buf[4] = { 0 };
  3605. (void)ptr;
  3606. errno = 0;
  3607. /* Set up a pipe to test on */
  3608. retval = pipe(test_pipe);
  3609. tt_int_op(retval, OP_EQ, 0);
  3610. /* Send in a string. */
  3611. retlen = write(test_pipe[1], "ABC", 3);
  3612. tt_int_op(retlen, OP_EQ, 3);
  3613. status = get_string_from_pipe(test_pipe[0], buf, sizeof(buf)-1);
  3614. tt_int_op(errno, OP_EQ, 0);
  3615. tt_int_op(status, OP_EQ, IO_STREAM_OKAY);
  3616. tt_str_op(buf, OP_EQ, "ABC");
  3617. errno = 0;
  3618. /* Send in a string that contains a nul. */
  3619. retlen = write(test_pipe[1], "AB\0", 3);
  3620. tt_int_op(retlen, OP_EQ, 3);
  3621. status = get_string_from_pipe(test_pipe[0], buf, sizeof(buf)-1);
  3622. tt_int_op(errno, OP_EQ, 0);
  3623. tt_int_op(status, OP_EQ, IO_STREAM_OKAY);
  3624. tt_str_op(buf, OP_EQ, "AB");
  3625. errno = 0;
  3626. /* Send in a string that contains a nul only. */
  3627. retlen = write(test_pipe[1], "\0", 1);
  3628. tt_int_op(retlen, OP_EQ, 1);
  3629. status = get_string_from_pipe(test_pipe[0], buf, sizeof(buf)-1);
  3630. tt_int_op(errno, OP_EQ, 0);
  3631. tt_int_op(status, OP_EQ, IO_STREAM_OKAY);
  3632. tt_str_op(buf, OP_EQ, "");
  3633. errno = 0;
  3634. /* Send in a string that contains a trailing newline. */
  3635. retlen = write(test_pipe[1], "AB\n", 3);
  3636. tt_int_op(retlen, OP_EQ, 3);
  3637. status = get_string_from_pipe(test_pipe[0], buf, sizeof(buf)-1);
  3638. tt_int_op(errno, OP_EQ, 0);
  3639. tt_int_op(status, OP_EQ, IO_STREAM_OKAY);
  3640. tt_str_op(buf, OP_EQ, "AB");
  3641. errno = 0;
  3642. /* Send in a string that contains a newline only. */
  3643. retlen = write(test_pipe[1], "\n", 1);
  3644. tt_int_op(retlen, OP_EQ, 1);
  3645. status = get_string_from_pipe(test_pipe[0], buf, sizeof(buf)-1);
  3646. tt_int_op(errno, OP_EQ, 0);
  3647. tt_int_op(status, OP_EQ, IO_STREAM_OKAY);
  3648. tt_str_op(buf, OP_EQ, "");
  3649. errno = 0;
  3650. /* Send in a string and check that we nul terminate return values. */
  3651. retlen = write(test_pipe[1], "AAA", 3);
  3652. tt_int_op(retlen, OP_EQ, 3);
  3653. status = get_string_from_pipe(test_pipe[0], buf, sizeof(buf)-1);
  3654. tt_int_op(errno, OP_EQ, 0);
  3655. tt_int_op(status, OP_EQ, IO_STREAM_OKAY);
  3656. tt_str_op(buf, OP_EQ, "AAA");
  3657. tt_mem_op(buf, OP_EQ, "AAA\0", sizeof(buf));
  3658. errno = 0;
  3659. retlen = write(test_pipe[1], "B", 1);
  3660. tt_int_op(retlen, OP_EQ, 1);
  3661. memset(buf, '\xff', sizeof(buf));
  3662. status = get_string_from_pipe(test_pipe[0], buf, sizeof(buf)-1);
  3663. tt_int_op(errno, OP_EQ, 0);
  3664. tt_int_op(status, OP_EQ, IO_STREAM_OKAY);
  3665. tt_str_op(buf, OP_EQ, "B");
  3666. tt_mem_op(buf, OP_EQ, "B\0\xff\xff", sizeof(buf));
  3667. errno = 0;
  3668. /* Send in multiple lines. */
  3669. retlen = write(test_pipe[1], "A\nB", 3);
  3670. tt_int_op(retlen, OP_EQ, 3);
  3671. status = get_string_from_pipe(test_pipe[0], buf, sizeof(buf)-1);
  3672. tt_int_op(errno, OP_EQ, 0);
  3673. tt_int_op(status, OP_EQ, IO_STREAM_OKAY);
  3674. tt_str_op(buf, OP_EQ, "A\nB");
  3675. errno = 0;
  3676. /* Send in a line and close */
  3677. retlen = write(test_pipe[1], "AB", 2);
  3678. tt_int_op(retlen, OP_EQ, 2);
  3679. retval = close(test_pipe[1]);
  3680. tt_int_op(retval, OP_EQ, 0);
  3681. test_pipe[1] = -1;
  3682. status = get_string_from_pipe(test_pipe[0], buf, sizeof(buf)-1);
  3683. tt_int_op(errno, OP_EQ, 0);
  3684. tt_int_op(status, OP_EQ, IO_STREAM_OKAY);
  3685. tt_str_op(buf, OP_EQ, "AB");
  3686. errno = 0;
  3687. /* Check for EOF */
  3688. status = get_string_from_pipe(test_pipe[0], buf, sizeof(buf)-1);
  3689. tt_int_op(errno, OP_EQ, 0);
  3690. tt_int_op(status, OP_EQ, IO_STREAM_CLOSED);
  3691. errno = 0;
  3692. done:
  3693. if (test_pipe[0] != -1)
  3694. close(test_pipe[0]);
  3695. if (test_pipe[1] != -1)
  3696. close(test_pipe[1]);
  3697. }
  3698. #endif /* !defined(_WIN32) */
  3699. /**
  3700. * Test for format_hex_number_sigsafe()
  3701. */
  3702. static void
  3703. test_util_format_hex_number(void *ptr)
  3704. {
  3705. int i, len;
  3706. char buf[33];
  3707. const struct {
  3708. const char *str;
  3709. unsigned int x;
  3710. } test_data[] = {
  3711. {"0", 0},
  3712. {"1", 1},
  3713. {"273A", 0x273a},
  3714. {"FFFF", 0xffff},
  3715. {"7FFFFFFF", 0x7fffffff},
  3716. {"FFFFFFFF", 0xffffffff},
  3717. #if UINT_MAX >= 0xffffffff
  3718. {"31BC421D", 0x31bc421d},
  3719. {"FFFFFFFF", 0xffffffff},
  3720. #endif
  3721. {NULL, 0}
  3722. };
  3723. (void)ptr;
  3724. for (i = 0; test_data[i].str != NULL; ++i) {
  3725. len = format_hex_number_sigsafe(test_data[i].x, buf, sizeof(buf));
  3726. tt_int_op(len,OP_NE, 0);
  3727. tt_int_op(len,OP_EQ, strlen(buf));
  3728. tt_str_op(buf,OP_EQ, test_data[i].str);
  3729. }
  3730. tt_int_op(4,OP_EQ, format_hex_number_sigsafe(0xffff, buf, 5));
  3731. tt_str_op(buf,OP_EQ, "FFFF");
  3732. tt_int_op(0,OP_EQ, format_hex_number_sigsafe(0xffff, buf, 4));
  3733. tt_int_op(0,OP_EQ, format_hex_number_sigsafe(0, buf, 1));
  3734. done:
  3735. return;
  3736. }
  3737. /**
  3738. * Test for format_hex_number_sigsafe()
  3739. */
  3740. static void
  3741. test_util_format_dec_number(void *ptr)
  3742. {
  3743. int i, len;
  3744. char buf[33];
  3745. const struct {
  3746. const char *str;
  3747. unsigned int x;
  3748. } test_data[] = {
  3749. {"0", 0},
  3750. {"1", 1},
  3751. {"1234", 1234},
  3752. {"12345678", 12345678},
  3753. {"99999999", 99999999},
  3754. {"100000000", 100000000},
  3755. {"4294967295", 4294967295u},
  3756. #if UINT_MAX > 0xffffffff
  3757. {"18446744073709551615", 18446744073709551615u },
  3758. #endif
  3759. {NULL, 0}
  3760. };
  3761. (void)ptr;
  3762. for (i = 0; test_data[i].str != NULL; ++i) {
  3763. len = format_dec_number_sigsafe(test_data[i].x, buf, sizeof(buf));
  3764. tt_int_op(len,OP_NE, 0);
  3765. tt_int_op(len,OP_EQ, strlen(buf));
  3766. tt_str_op(buf,OP_EQ, test_data[i].str);
  3767. len = format_dec_number_sigsafe(test_data[i].x, buf,
  3768. (int)(strlen(test_data[i].str) + 1));
  3769. tt_int_op(len,OP_EQ, strlen(buf));
  3770. tt_str_op(buf,OP_EQ, test_data[i].str);
  3771. }
  3772. tt_int_op(4,OP_EQ, format_dec_number_sigsafe(7331, buf, 5));
  3773. tt_str_op(buf,OP_EQ, "7331");
  3774. tt_int_op(0,OP_EQ, format_dec_number_sigsafe(7331, buf, 4));
  3775. tt_int_op(1,OP_EQ, format_dec_number_sigsafe(0, buf, 2));
  3776. tt_int_op(0,OP_EQ, format_dec_number_sigsafe(0, buf, 1));
  3777. done:
  3778. return;
  3779. }
  3780. /**
  3781. * Test that we can properly format a Windows command line
  3782. */
  3783. static void
  3784. test_util_join_win_cmdline(void *ptr)
  3785. {
  3786. /* Based on some test cases from "Parsing C++ Command-Line Arguments" in
  3787. * MSDN but we don't exercise all quoting rules because tor_join_win_cmdline
  3788. * will try to only generate simple cases for the child process to parse;
  3789. * i.e. we never embed quoted strings in arguments. */
  3790. const char *argvs[][4] = {
  3791. {"a", "bb", "CCC", NULL}, // Normal
  3792. {NULL, NULL, NULL, NULL}, // Empty argument list
  3793. {"", NULL, NULL, NULL}, // Empty argument
  3794. {"\"a", "b\"b", "CCC\"", NULL}, // Quotes
  3795. {"a\tbc", "dd dd", "E", NULL}, // Whitespace
  3796. {"a\\\\\\b", "de fg", "H", NULL}, // Backslashes
  3797. {"a\\\"b", "\\c", "D\\", NULL}, // Backslashes before quote
  3798. {"a\\\\b c", "d", "E", NULL}, // Backslashes not before quote
  3799. { NULL } // Terminator
  3800. };
  3801. const char *cmdlines[] = {
  3802. "a bb CCC",
  3803. "",
  3804. "\"\"",
  3805. "\\\"a b\\\"b CCC\\\"",
  3806. "\"a\tbc\" \"dd dd\" E",
  3807. "a\\\\\\b \"de fg\" H",
  3808. "a\\\\\\\"b \\c D\\",
  3809. "\"a\\\\b c\" d E",
  3810. NULL // Terminator
  3811. };
  3812. int i;
  3813. char *joined_argv = NULL;
  3814. (void)ptr;
  3815. for (i=0; cmdlines[i]!=NULL; i++) {
  3816. log_info(LD_GENERAL, "Joining argvs[%d], expecting <%s>", i, cmdlines[i]);
  3817. joined_argv = tor_join_win_cmdline(argvs[i]);
  3818. tt_str_op(cmdlines[i],OP_EQ, joined_argv);
  3819. tor_free(joined_argv);
  3820. }
  3821. done:
  3822. tor_free(joined_argv);
  3823. }
  3824. #define MAX_SPLIT_LINE_COUNT 4
  3825. struct split_lines_test_t {
  3826. const char *orig_line; // Line to be split (may contain \0's)
  3827. int orig_length; // Length of orig_line
  3828. const char *split_line[MAX_SPLIT_LINE_COUNT]; // Split lines
  3829. };
  3830. /**
  3831. * Test that we properly split a buffer into lines
  3832. */
  3833. static void
  3834. test_util_split_lines(void *ptr)
  3835. {
  3836. /* Test cases. orig_line of last test case must be NULL.
  3837. * The last element of split_line[i] must be NULL. */
  3838. struct split_lines_test_t tests[] = {
  3839. {"", 0, {NULL}},
  3840. {"foo", 3, {"foo", NULL}},
  3841. {"\n\rfoo\n\rbar\r\n", 12, {"foo", "bar", NULL}},
  3842. {"fo o\r\nb\tar", 10, {"fo o", "b.ar", NULL}},
  3843. {"\x0f""f\0o\0\n\x01""b\0r\0\r", 12, {".f.o.", ".b.r.", NULL}},
  3844. {"line 1\r\nline 2", 14, {"line 1", "line 2", NULL}},
  3845. {"line 1\r\n\r\nline 2", 16, {"line 1", "line 2", NULL}},
  3846. {"line 1\r\n\r\r\r\nline 2", 18, {"line 1", "line 2", NULL}},
  3847. {"line 1\r\n\n\n\n\rline 2", 18, {"line 1", "line 2", NULL}},
  3848. {"line 1\r\n\r\t\r\nline 3", 18, {"line 1", ".", "line 3", NULL}},
  3849. {"\n\t\r\t\nline 3", 11, {".", ".", "line 3", NULL}},
  3850. {NULL, 0, { NULL }}
  3851. };
  3852. int i, j;
  3853. char *orig_line=NULL;
  3854. smartlist_t *sl=NULL;
  3855. (void)ptr;
  3856. for (i=0; tests[i].orig_line; i++) {
  3857. sl = smartlist_new();
  3858. /* Allocate space for string and trailing NULL */
  3859. orig_line = tor_memdup(tests[i].orig_line, tests[i].orig_length + 1);
  3860. tor_split_lines(sl, orig_line, tests[i].orig_length);
  3861. j = 0;
  3862. log_info(LD_GENERAL, "Splitting test %d of length %d",
  3863. i, tests[i].orig_length);
  3864. SMARTLIST_FOREACH_BEGIN(sl, const char *, line) {
  3865. /* Check we have not got too many lines */
  3866. tt_int_op(MAX_SPLIT_LINE_COUNT, OP_GT, j);
  3867. /* Check that there actually should be a line here */
  3868. tt_ptr_op(tests[i].split_line[j], OP_NE, NULL);
  3869. log_info(LD_GENERAL, "Line %d of test %d, should be <%s>",
  3870. j, i, tests[i].split_line[j]);
  3871. /* Check that the line is as expected */
  3872. tt_str_op(line,OP_EQ, tests[i].split_line[j]);
  3873. j++;
  3874. } SMARTLIST_FOREACH_END(line);
  3875. /* Check that we didn't miss some lines */
  3876. tt_ptr_op(NULL,OP_EQ, tests[i].split_line[j]);
  3877. tor_free(orig_line);
  3878. smartlist_free(sl);
  3879. sl = NULL;
  3880. }
  3881. done:
  3882. tor_free(orig_line);
  3883. smartlist_free(sl);
  3884. }
  3885. static void
  3886. test_util_di_ops(void *arg)
  3887. {
  3888. #define LT -1
  3889. #define GT 1
  3890. #define EQ 0
  3891. const struct {
  3892. const char *a; int want_sign; const char *b;
  3893. } examples[] = {
  3894. { "Foo", EQ, "Foo" },
  3895. { "foo", GT, "bar", },
  3896. { "foobar", EQ ,"foobar" },
  3897. { "foobar", LT, "foobaw" },
  3898. { "foobar", GT, "f00bar" },
  3899. { "foobar", GT, "boobar" },
  3900. { "", EQ, "" },
  3901. { NULL, 0, NULL },
  3902. };
  3903. int i;
  3904. (void)arg;
  3905. for (i = 0; examples[i].a; ++i) {
  3906. size_t len = strlen(examples[i].a);
  3907. int eq1, eq2, neq1, neq2, cmp1, cmp2;
  3908. tt_int_op(len,OP_EQ, strlen(examples[i].b));
  3909. /* We do all of the operations, with operands in both orders. */
  3910. eq1 = tor_memeq(examples[i].a, examples[i].b, len);
  3911. eq2 = tor_memeq(examples[i].b, examples[i].a, len);
  3912. neq1 = tor_memneq(examples[i].a, examples[i].b, len);
  3913. neq2 = tor_memneq(examples[i].b, examples[i].a, len);
  3914. cmp1 = tor_memcmp(examples[i].a, examples[i].b, len);
  3915. cmp2 = tor_memcmp(examples[i].b, examples[i].a, len);
  3916. /* Check for correctness of cmp1 */
  3917. if (cmp1 < 0 && examples[i].want_sign != LT)
  3918. TT_DIE(("Assertion failed."));
  3919. else if (cmp1 > 0 && examples[i].want_sign != GT)
  3920. TT_DIE(("Assertion failed."));
  3921. else if (cmp1 == 0 && examples[i].want_sign != EQ)
  3922. TT_DIE(("Assertion failed."));
  3923. /* Check for consistency of everything else with cmp1 */
  3924. tt_int_op(eq1,OP_EQ, eq2);
  3925. tt_int_op(neq1,OP_EQ, neq2);
  3926. tt_int_op(cmp1,OP_EQ, -cmp2);
  3927. tt_int_op(eq1,OP_EQ, cmp1 == 0);
  3928. tt_int_op(neq1,OP_EQ, !eq1);
  3929. }
  3930. {
  3931. uint8_t zz = 0;
  3932. uint8_t ii = 0;
  3933. int z;
  3934. /* exhaustively test tor_memeq and tor_memcmp
  3935. * against each possible single-byte numeric difference
  3936. * some arithmetic bugs only appear with certain bit patterns */
  3937. for (z = 0; z < 256; z++) {
  3938. for (i = 0; i < 256; i++) {
  3939. ii = (uint8_t)i;
  3940. zz = (uint8_t)z;
  3941. tt_int_op(tor_memeq(&zz, &ii, 1),OP_EQ, zz == ii);
  3942. tt_int_op(tor_memcmp(&zz, &ii, 1) > 0 ? GT : EQ,OP_EQ,
  3943. zz > ii ? GT : EQ);
  3944. tt_int_op(tor_memcmp(&ii, &zz, 1) < 0 ? LT : EQ,OP_EQ,
  3945. ii < zz ? LT : EQ);
  3946. }
  3947. }
  3948. }
  3949. tt_int_op(1, OP_EQ, safe_mem_is_zero("", 0));
  3950. tt_int_op(1, OP_EQ, safe_mem_is_zero("", 1));
  3951. tt_int_op(0, OP_EQ, safe_mem_is_zero("a", 1));
  3952. tt_int_op(0, OP_EQ, safe_mem_is_zero("a", 2));
  3953. tt_int_op(0, OP_EQ, safe_mem_is_zero("\0a", 2));
  3954. tt_int_op(1, OP_EQ, safe_mem_is_zero("\0\0a", 2));
  3955. tt_int_op(1, OP_EQ, safe_mem_is_zero("\0\0\0\0\0\0\0\0", 8));
  3956. tt_int_op(1, OP_EQ, safe_mem_is_zero("\0\0\0\0\0\0\0\0a", 8));
  3957. tt_int_op(0, OP_EQ, safe_mem_is_zero("\0\0\0\0\0\0\0\0a", 9));
  3958. done:
  3959. ;
  3960. }
  3961. static void
  3962. test_util_di_map(void *arg)
  3963. {
  3964. (void)arg;
  3965. di_digest256_map_t *dimap = NULL;
  3966. uint8_t key1[] = "Robert Anton Wilson ";
  3967. uint8_t key2[] = "Martin Gardner, _Fads&fallacies";
  3968. uint8_t key3[] = "Tom Lehrer, _Be Prepared_. ";
  3969. uint8_t key4[] = "Ursula Le Guin,_A Wizard of... ";
  3970. char dflt_entry[] = "'You have made a good beginning', but no more";
  3971. tt_int_op(32, OP_EQ, sizeof(key1));
  3972. tt_int_op(32, OP_EQ, sizeof(key2));
  3973. tt_int_op(32, OP_EQ, sizeof(key3));
  3974. tt_ptr_op(dflt_entry, OP_EQ, dimap_search(dimap, key1, dflt_entry));
  3975. char *str1 = tor_strdup("You are precisely as big as what you love"
  3976. " and precisely as small as what you allow"
  3977. " to annoy you.");
  3978. char *str2 = tor_strdup("Let us hope that Lysenko's success in Russia will"
  3979. " serve for many generations to come as another"
  3980. " reminder to the world of how quickly and easily"
  3981. " a science can be corrupted when ignorant"
  3982. " political leaders deem themselves competent"
  3983. " to arbitrate scientific disputes");
  3984. char *str3 = tor_strdup("Don't write naughty words on walls "
  3985. "if you can't spell.");
  3986. dimap_add_entry(&dimap, key1, str1);
  3987. dimap_add_entry(&dimap, key2, str2);
  3988. dimap_add_entry(&dimap, key3, str3);
  3989. tt_ptr_op(str1, OP_EQ, dimap_search(dimap, key1, dflt_entry));
  3990. tt_ptr_op(str3, OP_EQ, dimap_search(dimap, key3, dflt_entry));
  3991. tt_ptr_op(str2, OP_EQ, dimap_search(dimap, key2, dflt_entry));
  3992. tt_ptr_op(dflt_entry, OP_EQ, dimap_search(dimap, key4, dflt_entry));
  3993. done:
  3994. dimap_free(dimap, tor_free_);
  3995. }
  3996. /**
  3997. * Test counting high bits
  3998. */
  3999. static void
  4000. test_util_n_bits_set(void *ptr)
  4001. {
  4002. (void)ptr;
  4003. tt_int_op(0,OP_EQ, n_bits_set_u8(0));
  4004. tt_int_op(1,OP_EQ, n_bits_set_u8(1));
  4005. tt_int_op(3,OP_EQ, n_bits_set_u8(7));
  4006. tt_int_op(1,OP_EQ, n_bits_set_u8(8));
  4007. tt_int_op(2,OP_EQ, n_bits_set_u8(129));
  4008. tt_int_op(8,OP_EQ, n_bits_set_u8(255));
  4009. done:
  4010. ;
  4011. }
  4012. /**
  4013. * Test LHS whitespace (and comment) eater
  4014. */
  4015. static void
  4016. test_util_eat_whitespace(void *ptr)
  4017. {
  4018. const char ws[] = { ' ', '\t', '\r' }; /* Except NL */
  4019. char str[80];
  4020. size_t i;
  4021. (void)ptr;
  4022. /* Try one leading ws */
  4023. strlcpy(str, "fuubaar", sizeof(str));
  4024. for (i = 0; i < sizeof(ws); ++i) {
  4025. str[0] = ws[i];
  4026. tt_ptr_op(str + 1,OP_EQ, eat_whitespace(str));
  4027. tt_ptr_op(str + 1,OP_EQ, eat_whitespace_eos(str, str + strlen(str)));
  4028. tt_ptr_op(str + 1,OP_EQ, eat_whitespace_no_nl(str));
  4029. tt_ptr_op(str + 1,OP_EQ, eat_whitespace_eos_no_nl(str, str + strlen(str)));
  4030. }
  4031. str[0] = '\n';
  4032. tt_ptr_op(str + 1,OP_EQ, eat_whitespace(str));
  4033. tt_ptr_op(str + 1,OP_EQ, eat_whitespace_eos(str, str + strlen(str)));
  4034. tt_ptr_op(str,OP_EQ, eat_whitespace_no_nl(str));
  4035. tt_ptr_op(str,OP_EQ, eat_whitespace_eos_no_nl(str, str + strlen(str)));
  4036. /* Empty string */
  4037. strlcpy(str, "", sizeof(str));
  4038. tt_ptr_op(str,OP_EQ, eat_whitespace(str));
  4039. tt_ptr_op(str,OP_EQ, eat_whitespace_eos(str, str));
  4040. tt_ptr_op(str,OP_EQ, eat_whitespace_no_nl(str));
  4041. tt_ptr_op(str,OP_EQ, eat_whitespace_eos_no_nl(str, str));
  4042. /* Only ws */
  4043. strlcpy(str, " \t\r\n", sizeof(str));
  4044. tt_ptr_op(str + strlen(str),OP_EQ, eat_whitespace(str));
  4045. tt_ptr_op(str + strlen(str),OP_EQ,
  4046. eat_whitespace_eos(str, str + strlen(str)));
  4047. tt_ptr_op(str + strlen(str) - 1,OP_EQ,
  4048. eat_whitespace_no_nl(str));
  4049. tt_ptr_op(str + strlen(str) - 1,OP_EQ,
  4050. eat_whitespace_eos_no_nl(str, str + strlen(str)));
  4051. strlcpy(str, " \t\r ", sizeof(str));
  4052. tt_ptr_op(str + strlen(str),OP_EQ, eat_whitespace(str));
  4053. tt_ptr_op(str + strlen(str),OP_EQ,
  4054. eat_whitespace_eos(str, str + strlen(str)));
  4055. tt_ptr_op(str + strlen(str),OP_EQ, eat_whitespace_no_nl(str));
  4056. tt_ptr_op(str + strlen(str),OP_EQ,
  4057. eat_whitespace_eos_no_nl(str, str + strlen(str)));
  4058. /* Multiple ws */
  4059. strlcpy(str, "fuubaar", sizeof(str));
  4060. for (i = 0; i < sizeof(ws); ++i)
  4061. str[i] = ws[i];
  4062. tt_ptr_op(str + sizeof(ws),OP_EQ, eat_whitespace(str));
  4063. tt_ptr_op(str + sizeof(ws),OP_EQ,
  4064. eat_whitespace_eos(str, str + strlen(str)));
  4065. tt_ptr_op(str + sizeof(ws),OP_EQ, eat_whitespace_no_nl(str));
  4066. tt_ptr_op(str + sizeof(ws),OP_EQ,
  4067. eat_whitespace_eos_no_nl(str, str + strlen(str)));
  4068. /* Eat comment */
  4069. strlcpy(str, "# Comment \n No Comment", sizeof(str));
  4070. tt_str_op("No Comment",OP_EQ, eat_whitespace(str));
  4071. tt_str_op("No Comment",OP_EQ, eat_whitespace_eos(str, str + strlen(str)));
  4072. tt_ptr_op(str,OP_EQ, eat_whitespace_no_nl(str));
  4073. tt_ptr_op(str,OP_EQ, eat_whitespace_eos_no_nl(str, str + strlen(str)));
  4074. /* Eat comment & ws mix */
  4075. strlcpy(str, " # \t Comment \n\t\nNo Comment", sizeof(str));
  4076. tt_str_op("No Comment",OP_EQ, eat_whitespace(str));
  4077. tt_str_op("No Comment",OP_EQ, eat_whitespace_eos(str, str + strlen(str)));
  4078. tt_ptr_op(str + 1,OP_EQ, eat_whitespace_no_nl(str));
  4079. tt_ptr_op(str + 1,OP_EQ, eat_whitespace_eos_no_nl(str, str + strlen(str)));
  4080. /* Eat entire comment */
  4081. strlcpy(str, "#Comment", sizeof(str));
  4082. tt_ptr_op(str + strlen(str),OP_EQ, eat_whitespace(str));
  4083. tt_ptr_op(str + strlen(str),OP_EQ,
  4084. eat_whitespace_eos(str, str + strlen(str)));
  4085. tt_ptr_op(str,OP_EQ, eat_whitespace_no_nl(str));
  4086. tt_ptr_op(str,OP_EQ, eat_whitespace_eos_no_nl(str, str + strlen(str)));
  4087. /* Blank line, then comment */
  4088. strlcpy(str, " \t\n # Comment", sizeof(str));
  4089. tt_ptr_op(str + strlen(str),OP_EQ, eat_whitespace(str));
  4090. tt_ptr_op(str + strlen(str),OP_EQ,
  4091. eat_whitespace_eos(str, str + strlen(str)));
  4092. tt_ptr_op(str + 2,OP_EQ, eat_whitespace_no_nl(str));
  4093. tt_ptr_op(str + 2,OP_EQ, eat_whitespace_eos_no_nl(str, str + strlen(str)));
  4094. done:
  4095. ;
  4096. }
  4097. /** Return a newly allocated smartlist containing the lines of text in
  4098. * <b>lines</b>. The returned strings are heap-allocated, and must be
  4099. * freed by the caller.
  4100. *
  4101. * XXXX? Move to container.[hc] ? */
  4102. static smartlist_t *
  4103. smartlist_new_from_text_lines(const char *lines)
  4104. {
  4105. smartlist_t *sl = smartlist_new();
  4106. char *last_line;
  4107. smartlist_split_string(sl, lines, "\n", 0, 0);
  4108. last_line = smartlist_pop_last(sl);
  4109. if (last_line != NULL && *last_line != '\0') {
  4110. smartlist_add(sl, last_line);
  4111. } else {
  4112. tor_free(last_line);
  4113. }
  4114. return sl;
  4115. }
  4116. /** Test smartlist_new_from_text_lines */
  4117. static void
  4118. test_util_sl_new_from_text_lines(void *ptr)
  4119. {
  4120. (void)ptr;
  4121. { /* Normal usage */
  4122. smartlist_t *sl = smartlist_new_from_text_lines("foo\nbar\nbaz\n");
  4123. int sl_len = smartlist_len(sl);
  4124. tt_want_int_op(sl_len, OP_EQ, 3);
  4125. if (sl_len > 0) tt_want_str_op(smartlist_get(sl, 0), OP_EQ, "foo");
  4126. if (sl_len > 1) tt_want_str_op(smartlist_get(sl, 1), OP_EQ, "bar");
  4127. if (sl_len > 2) tt_want_str_op(smartlist_get(sl, 2), OP_EQ, "baz");
  4128. SMARTLIST_FOREACH(sl, void *, x, tor_free(x));
  4129. smartlist_free(sl);
  4130. }
  4131. { /* No final newline */
  4132. smartlist_t *sl = smartlist_new_from_text_lines("foo\nbar\nbaz");
  4133. int sl_len = smartlist_len(sl);
  4134. tt_want_int_op(sl_len, OP_EQ, 3);
  4135. if (sl_len > 0) tt_want_str_op(smartlist_get(sl, 0), OP_EQ, "foo");
  4136. if (sl_len > 1) tt_want_str_op(smartlist_get(sl, 1), OP_EQ, "bar");
  4137. if (sl_len > 2) tt_want_str_op(smartlist_get(sl, 2), OP_EQ, "baz");
  4138. SMARTLIST_FOREACH(sl, void *, x, tor_free(x));
  4139. smartlist_free(sl);
  4140. }
  4141. { /* No newlines */
  4142. smartlist_t *sl = smartlist_new_from_text_lines("foo");
  4143. int sl_len = smartlist_len(sl);
  4144. tt_want_int_op(sl_len, OP_EQ, 1);
  4145. if (sl_len > 0) tt_want_str_op(smartlist_get(sl, 0), OP_EQ, "foo");
  4146. SMARTLIST_FOREACH(sl, void *, x, tor_free(x));
  4147. smartlist_free(sl);
  4148. }
  4149. { /* No text at all */
  4150. smartlist_t *sl = smartlist_new_from_text_lines("");
  4151. int sl_len = smartlist_len(sl);
  4152. tt_want_int_op(sl_len, OP_EQ, 0);
  4153. SMARTLIST_FOREACH(sl, void *, x, tor_free(x));
  4154. smartlist_free(sl);
  4155. }
  4156. }
  4157. static void
  4158. test_util_envnames(void *ptr)
  4159. {
  4160. (void) ptr;
  4161. tt_assert(environment_variable_names_equal("abc", "abc"));
  4162. tt_assert(environment_variable_names_equal("abc", "abc="));
  4163. tt_assert(environment_variable_names_equal("abc", "abc=def"));
  4164. tt_assert(environment_variable_names_equal("abc=def", "abc"));
  4165. tt_assert(environment_variable_names_equal("abc=def", "abc=ghi"));
  4166. tt_assert(environment_variable_names_equal("abc", "abc"));
  4167. tt_assert(environment_variable_names_equal("abc", "abc="));
  4168. tt_assert(environment_variable_names_equal("abc", "abc=def"));
  4169. tt_assert(environment_variable_names_equal("abc=def", "abc"));
  4170. tt_assert(environment_variable_names_equal("abc=def", "abc=ghi"));
  4171. tt_assert(!environment_variable_names_equal("abc", "abcd"));
  4172. tt_assert(!environment_variable_names_equal("abc=", "abcd"));
  4173. tt_assert(!environment_variable_names_equal("abc=", "abcd"));
  4174. tt_assert(!environment_variable_names_equal("abc=", "def"));
  4175. tt_assert(!environment_variable_names_equal("abc=", "def="));
  4176. tt_assert(!environment_variable_names_equal("abc=x", "def=x"));
  4177. tt_assert(!environment_variable_names_equal("", "a=def"));
  4178. /* A bit surprising. */
  4179. tt_assert(environment_variable_names_equal("", "=def"));
  4180. tt_assert(environment_variable_names_equal("=y", "=x"));
  4181. done:
  4182. ;
  4183. }
  4184. /** Test process_environment_make */
  4185. static void
  4186. test_util_make_environment(void *ptr)
  4187. {
  4188. const char *env_vars_string =
  4189. "PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/bin\n"
  4190. "HOME=/home/foozer\n";
  4191. const char expected_windows_env_block[] =
  4192. "HOME=/home/foozer\000"
  4193. "PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/bin\000"
  4194. "\000";
  4195. size_t expected_windows_env_block_len =
  4196. sizeof(expected_windows_env_block) - 1;
  4197. smartlist_t *env_vars = smartlist_new_from_text_lines(env_vars_string);
  4198. smartlist_t *env_vars_sorted = smartlist_new();
  4199. smartlist_t *env_vars_in_unixoid_env_block_sorted = smartlist_new();
  4200. process_environment_t *env;
  4201. (void)ptr;
  4202. env = process_environment_make(env_vars);
  4203. /* Check that the Windows environment block is correct. */
  4204. tt_want(tor_memeq(expected_windows_env_block, env->windows_environment_block,
  4205. expected_windows_env_block_len));
  4206. /* Now for the Unixoid environment block. We don't care which order
  4207. * these environment variables are in, so we sort both lists first. */
  4208. smartlist_add_all(env_vars_sorted, env_vars);
  4209. {
  4210. char **v;
  4211. for (v = env->unixoid_environment_block; *v; ++v) {
  4212. smartlist_add(env_vars_in_unixoid_env_block_sorted, *v);
  4213. }
  4214. }
  4215. smartlist_sort_strings(env_vars_sorted);
  4216. smartlist_sort_strings(env_vars_in_unixoid_env_block_sorted);
  4217. tt_want_int_op(smartlist_len(env_vars_sorted), OP_EQ,
  4218. smartlist_len(env_vars_in_unixoid_env_block_sorted));
  4219. {
  4220. int len = smartlist_len(env_vars_sorted);
  4221. int i;
  4222. if (smartlist_len(env_vars_in_unixoid_env_block_sorted) < len) {
  4223. len = smartlist_len(env_vars_in_unixoid_env_block_sorted);
  4224. }
  4225. for (i = 0; i < len; ++i) {
  4226. tt_want_str_op(smartlist_get(env_vars_sorted, i), OP_EQ,
  4227. smartlist_get(env_vars_in_unixoid_env_block_sorted, i));
  4228. }
  4229. }
  4230. /* Clean up. */
  4231. smartlist_free(env_vars_in_unixoid_env_block_sorted);
  4232. smartlist_free(env_vars_sorted);
  4233. SMARTLIST_FOREACH(env_vars, char *, x, tor_free(x));
  4234. smartlist_free(env_vars);
  4235. process_environment_free(env);
  4236. }
  4237. /** Test set_environment_variable_in_smartlist */
  4238. static void
  4239. test_util_set_env_var_in_sl(void *ptr)
  4240. {
  4241. /* The environment variables in these strings are in arbitrary
  4242. * order; we sort the resulting lists before comparing them.
  4243. *
  4244. * (They *will not* end up in the order shown in
  4245. * expected_resulting_env_vars_string.) */
  4246. const char *base_env_vars_string =
  4247. "PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/bin\n"
  4248. "HOME=/home/foozer\n"
  4249. "TERM=xterm\n"
  4250. "SHELL=/bin/ksh\n"
  4251. "USER=foozer\n"
  4252. "LOGNAME=foozer\n"
  4253. "USERNAME=foozer\n"
  4254. "LANG=en_US.utf8\n"
  4255. ;
  4256. const char *new_env_vars_string =
  4257. "TERM=putty\n"
  4258. "DISPLAY=:18.0\n"
  4259. ;
  4260. const char *expected_resulting_env_vars_string =
  4261. "PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/bin\n"
  4262. "HOME=/home/foozer\n"
  4263. "TERM=putty\n"
  4264. "SHELL=/bin/ksh\n"
  4265. "USER=foozer\n"
  4266. "LOGNAME=foozer\n"
  4267. "USERNAME=foozer\n"
  4268. "LANG=en_US.utf8\n"
  4269. "DISPLAY=:18.0\n"
  4270. ;
  4271. smartlist_t *merged_env_vars =
  4272. smartlist_new_from_text_lines(base_env_vars_string);
  4273. smartlist_t *new_env_vars =
  4274. smartlist_new_from_text_lines(new_env_vars_string);
  4275. smartlist_t *expected_resulting_env_vars =
  4276. smartlist_new_from_text_lines(expected_resulting_env_vars_string);
  4277. /* Elements of merged_env_vars are heap-allocated, and must be
  4278. * freed. Some of them are (or should) be freed by
  4279. * set_environment_variable_in_smartlist.
  4280. *
  4281. * Elements of new_env_vars are heap-allocated, but are copied into
  4282. * merged_env_vars, so they are not freed separately at the end of
  4283. * the function.
  4284. *
  4285. * Elements of expected_resulting_env_vars are heap-allocated, and
  4286. * must be freed. */
  4287. (void)ptr;
  4288. SMARTLIST_FOREACH(new_env_vars, char *, env_var,
  4289. set_environment_variable_in_smartlist(merged_env_vars,
  4290. env_var,
  4291. tor_free_,
  4292. 1));
  4293. smartlist_sort_strings(merged_env_vars);
  4294. smartlist_sort_strings(expected_resulting_env_vars);
  4295. tt_want_int_op(smartlist_len(merged_env_vars), OP_EQ,
  4296. smartlist_len(expected_resulting_env_vars));
  4297. {
  4298. int len = smartlist_len(merged_env_vars);
  4299. int i;
  4300. if (smartlist_len(expected_resulting_env_vars) < len) {
  4301. len = smartlist_len(expected_resulting_env_vars);
  4302. }
  4303. for (i = 0; i < len; ++i) {
  4304. tt_want_str_op(smartlist_get(merged_env_vars, i), OP_EQ,
  4305. smartlist_get(expected_resulting_env_vars, i));
  4306. }
  4307. }
  4308. /* Clean up. */
  4309. SMARTLIST_FOREACH(merged_env_vars, char *, x, tor_free(x));
  4310. smartlist_free(merged_env_vars);
  4311. smartlist_free(new_env_vars);
  4312. SMARTLIST_FOREACH(expected_resulting_env_vars, char *, x, tor_free(x));
  4313. smartlist_free(expected_resulting_env_vars);
  4314. }
  4315. static void
  4316. test_util_weak_random(void *arg)
  4317. {
  4318. int i, j, n[16];
  4319. tor_weak_rng_t rng;
  4320. (void) arg;
  4321. tor_init_weak_random(&rng, (unsigned)time(NULL));
  4322. for (i = 1; i <= 256; ++i) {
  4323. for (j=0;j<100;++j) {
  4324. int r = tor_weak_random_range(&rng, i);
  4325. tt_int_op(0, OP_LE, r);
  4326. tt_int_op(r, OP_LT, i);
  4327. }
  4328. }
  4329. memset(n,0,sizeof(n));
  4330. for (j=0;j<8192;++j) {
  4331. n[tor_weak_random_range(&rng, 16)]++;
  4332. }
  4333. for (i=0;i<16;++i)
  4334. tt_int_op(n[i], OP_GT, 0);
  4335. done:
  4336. ;
  4337. }
  4338. static void
  4339. test_util_mathlog(void *arg)
  4340. {
  4341. double d;
  4342. (void) arg;
  4343. d = tor_mathlog(2.718281828);
  4344. tt_double_op(fabs(d - 1.0), OP_LT, .000001);
  4345. d = tor_mathlog(10);
  4346. tt_double_op(fabs(d - 2.30258509), OP_LT, .000001);
  4347. done:
  4348. ;
  4349. }
  4350. static void
  4351. test_util_fraction(void *arg)
  4352. {
  4353. uint64_t a,b;
  4354. (void)arg;
  4355. a = 99; b = 30;
  4356. simplify_fraction64(&a,&b);
  4357. tt_u64_op(a, OP_EQ, 33);
  4358. tt_u64_op(b, OP_EQ, 10);
  4359. a = 3000000; b = 10000000;
  4360. simplify_fraction64(&a,&b);
  4361. tt_u64_op(a, OP_EQ, 3);
  4362. tt_u64_op(b, OP_EQ, 10);
  4363. a = 0; b = 15;
  4364. simplify_fraction64(&a,&b);
  4365. tt_u64_op(a, OP_EQ, 0);
  4366. tt_u64_op(b, OP_EQ, 1);
  4367. done:
  4368. ;
  4369. }
  4370. static void
  4371. test_util_round_to_next_multiple_of(void *arg)
  4372. {
  4373. (void)arg;
  4374. tt_u64_op(round_uint64_to_next_multiple_of(0,1), OP_EQ, 0);
  4375. tt_u64_op(round_uint64_to_next_multiple_of(0,7), OP_EQ, 0);
  4376. tt_u64_op(round_uint64_to_next_multiple_of(99,1), OP_EQ, 99);
  4377. tt_u64_op(round_uint64_to_next_multiple_of(99,7), OP_EQ, 105);
  4378. tt_u64_op(round_uint64_to_next_multiple_of(99,9), OP_EQ, 99);
  4379. tt_u64_op(round_uint64_to_next_multiple_of(UINT64_MAX,2), OP_EQ,
  4380. UINT64_MAX);
  4381. tt_int_op(round_uint32_to_next_multiple_of(0,1), OP_EQ, 0);
  4382. tt_int_op(round_uint32_to_next_multiple_of(0,7), OP_EQ, 0);
  4383. tt_int_op(round_uint32_to_next_multiple_of(99,1), OP_EQ, 99);
  4384. tt_int_op(round_uint32_to_next_multiple_of(99,7), OP_EQ, 105);
  4385. tt_int_op(round_uint32_to_next_multiple_of(99,9), OP_EQ, 99);
  4386. tt_int_op(round_uint32_to_next_multiple_of(UINT32_MAX,2), OP_EQ,
  4387. UINT32_MAX);
  4388. tt_uint_op(round_to_next_multiple_of(0,1), OP_EQ, 0);
  4389. tt_uint_op(round_to_next_multiple_of(0,7), OP_EQ, 0);
  4390. tt_uint_op(round_to_next_multiple_of(99,1), OP_EQ, 99);
  4391. tt_uint_op(round_to_next_multiple_of(99,7), OP_EQ, 105);
  4392. tt_uint_op(round_to_next_multiple_of(99,9), OP_EQ, 99);
  4393. tt_uint_op(round_to_next_multiple_of(UINT_MAX,2), OP_EQ,
  4394. UINT_MAX);
  4395. done:
  4396. ;
  4397. }
  4398. static void
  4399. test_util_laplace(void *arg)
  4400. {
  4401. /* Sample values produced using Python's SciPy:
  4402. *
  4403. * >>> from scipy.stats import laplace
  4404. * >>> laplace.ppf([-0.01, 0.0, 0.01, 0.5, 0.51, 0.99, 1.0, 1.01],
  4405. ... loc = 24, scale = 24)
  4406. * array([ nan, -inf, -69.88855213, 24. ,
  4407. * 24.48486498, 117.88855213, inf, nan])
  4408. */
  4409. const double mu = 24.0, b = 24.0;
  4410. const double delta_f = 15.0, epsilon = 0.3; /* b = 15.0 / 0.3 = 50.0 */
  4411. (void)arg;
  4412. tt_i64_op(INT64_MIN, OP_EQ, sample_laplace_distribution(mu, b, 0.0));
  4413. tt_i64_op(-69, OP_EQ, sample_laplace_distribution(mu, b, 0.01));
  4414. tt_i64_op(24, OP_EQ, sample_laplace_distribution(mu, b, 0.5));
  4415. tt_i64_op(24, OP_EQ, sample_laplace_distribution(mu, b, 0.51));
  4416. tt_i64_op(117, OP_EQ, sample_laplace_distribution(mu, b, 0.99));
  4417. /* >>> laplace.ppf([0.0, 0.1, 0.25, 0.5, 0.75, 0.9, 0.99],
  4418. * ... loc = 0, scale = 50)
  4419. * array([ -inf, -80.47189562, -34.65735903, 0. ,
  4420. * 34.65735903, 80.47189562, 195.60115027])
  4421. */
  4422. tt_i64_op(INT64_MIN + 20, OP_EQ,
  4423. add_laplace_noise(20, 0.0, delta_f, epsilon));
  4424. tt_i64_op(-60, OP_EQ, add_laplace_noise(20, 0.1, delta_f, epsilon));
  4425. tt_i64_op(-14, OP_EQ, add_laplace_noise(20, 0.25, delta_f, epsilon));
  4426. tt_i64_op(20, OP_EQ, add_laplace_noise(20, 0.5, delta_f, epsilon));
  4427. tt_i64_op(54, OP_EQ, add_laplace_noise(20, 0.75, delta_f, epsilon));
  4428. tt_i64_op(100, OP_EQ, add_laplace_noise(20, 0.9, delta_f, epsilon));
  4429. tt_i64_op(215, OP_EQ, add_laplace_noise(20, 0.99, delta_f, epsilon));
  4430. /* Test extreme values of signal with maximally negative values of noise
  4431. * 1.0000000000000002 is the smallest number > 1
  4432. * 0.0000000000000002 is the double epsilon (error when calculating near 1)
  4433. * this is approximately 1/(2^52)
  4434. * per https://en.wikipedia.org/wiki/Double_precision
  4435. * (let's not descend into the world of subnormals)
  4436. * >>> laplace.ppf([0, 0.0000000000000002], loc = 0, scale = 1)
  4437. * array([ -inf, -35.45506713])
  4438. */
  4439. const double noscale_df = 1.0, noscale_eps = 1.0;
  4440. tt_i64_op(INT64_MIN, OP_EQ,
  4441. add_laplace_noise(0, 0.0, noscale_df, noscale_eps));
  4442. /* is it clipped to INT64_MIN? */
  4443. tt_i64_op(INT64_MIN, OP_EQ,
  4444. add_laplace_noise(-1, 0.0, noscale_df, noscale_eps));
  4445. tt_i64_op(INT64_MIN, OP_EQ,
  4446. add_laplace_noise(INT64_MIN, 0.0,
  4447. noscale_df, noscale_eps));
  4448. /* ... even when scaled? */
  4449. tt_i64_op(INT64_MIN, OP_EQ,
  4450. add_laplace_noise(0, 0.0, delta_f, epsilon));
  4451. tt_i64_op(INT64_MIN, OP_EQ,
  4452. add_laplace_noise(0, 0.0,
  4453. DBL_MAX, 1));
  4454. tt_i64_op(INT64_MIN, OP_EQ,
  4455. add_laplace_noise(INT64_MIN, 0.0,
  4456. DBL_MAX, 1));
  4457. /* does it play nice with INT64_MAX? */
  4458. tt_i64_op((INT64_MIN + INT64_MAX), OP_EQ,
  4459. add_laplace_noise(INT64_MAX, 0.0,
  4460. noscale_df, noscale_eps));
  4461. /* do near-zero fractional values work? */
  4462. const double min_dbl_error = 0.0000000000000002;
  4463. tt_i64_op(-35, OP_EQ,
  4464. add_laplace_noise(0, min_dbl_error,
  4465. noscale_df, noscale_eps));
  4466. tt_i64_op(INT64_MIN, OP_EQ,
  4467. add_laplace_noise(INT64_MIN, min_dbl_error,
  4468. noscale_df, noscale_eps));
  4469. tt_i64_op((-35 + INT64_MAX), OP_EQ,
  4470. add_laplace_noise(INT64_MAX, min_dbl_error,
  4471. noscale_df, noscale_eps));
  4472. tt_i64_op(INT64_MIN, OP_EQ,
  4473. add_laplace_noise(0, min_dbl_error,
  4474. DBL_MAX, 1));
  4475. tt_i64_op((INT64_MAX + INT64_MIN), OP_EQ,
  4476. add_laplace_noise(INT64_MAX, min_dbl_error,
  4477. DBL_MAX, 1));
  4478. tt_i64_op(INT64_MIN, OP_EQ,
  4479. add_laplace_noise(INT64_MIN, min_dbl_error,
  4480. DBL_MAX, 1));
  4481. /* does it play nice with INT64_MAX? */
  4482. tt_i64_op((INT64_MAX - 35), OP_EQ,
  4483. add_laplace_noise(INT64_MAX, min_dbl_error,
  4484. noscale_df, noscale_eps));
  4485. /* Test extreme values of signal with maximally positive values of noise
  4486. * 1.0000000000000002 is the smallest number > 1
  4487. * 0.9999999999999998 is the greatest number < 1 by calculation
  4488. * per https://en.wikipedia.org/wiki/Double_precision
  4489. * >>> laplace.ppf([1.0, 0.9999999999999998], loc = 0, scale = 1)
  4490. * array([inf, 35.35050621])
  4491. * but the function rejects p == 1.0, so we just use max_dbl_lt_one
  4492. */
  4493. const double max_dbl_lt_one = 0.9999999999999998;
  4494. /* do near-one fractional values work? */
  4495. tt_i64_op(35, OP_EQ,
  4496. add_laplace_noise(0, max_dbl_lt_one, noscale_df, noscale_eps));
  4497. /* is it clipped to INT64_MAX? */
  4498. tt_i64_op(INT64_MAX, OP_EQ,
  4499. add_laplace_noise(INT64_MAX - 35, max_dbl_lt_one,
  4500. noscale_df, noscale_eps));
  4501. tt_i64_op(INT64_MAX, OP_EQ,
  4502. add_laplace_noise(INT64_MAX - 34, max_dbl_lt_one,
  4503. noscale_df, noscale_eps));
  4504. tt_i64_op(INT64_MAX, OP_EQ,
  4505. add_laplace_noise(INT64_MAX, max_dbl_lt_one,
  4506. noscale_df, noscale_eps));
  4507. /* ... even when scaled? */
  4508. tt_i64_op(INT64_MAX, OP_EQ,
  4509. add_laplace_noise(INT64_MAX, max_dbl_lt_one,
  4510. delta_f, epsilon));
  4511. tt_i64_op((INT64_MIN + INT64_MAX), OP_EQ,
  4512. add_laplace_noise(INT64_MIN, max_dbl_lt_one,
  4513. DBL_MAX, 1));
  4514. tt_i64_op(INT64_MAX, OP_EQ,
  4515. add_laplace_noise(INT64_MAX, max_dbl_lt_one,
  4516. DBL_MAX, 1));
  4517. /* does it play nice with INT64_MIN? */
  4518. tt_i64_op((INT64_MIN + 35), OP_EQ,
  4519. add_laplace_noise(INT64_MIN, max_dbl_lt_one,
  4520. noscale_df, noscale_eps));
  4521. done:
  4522. ;
  4523. }
  4524. static void
  4525. test_util_clamp_double_to_int64(void *arg)
  4526. {
  4527. (void)arg;
  4528. tt_i64_op(INT64_MIN, OP_EQ, clamp_double_to_int64(-INFINITY_DBL));
  4529. tt_i64_op(INT64_MIN, OP_EQ,
  4530. clamp_double_to_int64(-1.0 * pow(2.0, 64.0) - 1.0));
  4531. tt_i64_op(INT64_MIN, OP_EQ,
  4532. clamp_double_to_int64(-1.0 * pow(2.0, 63.0) - 1.0));
  4533. tt_i64_op(((uint64_t) -1) << 53, OP_EQ,
  4534. clamp_double_to_int64(-1.0 * pow(2.0, 53.0)));
  4535. tt_i64_op((((uint64_t) -1) << 53) + 1, OP_EQ,
  4536. clamp_double_to_int64(-1.0 * pow(2.0, 53.0) + 1.0));
  4537. tt_i64_op(-1, OP_EQ, clamp_double_to_int64(-1.0));
  4538. tt_i64_op(0, OP_EQ, clamp_double_to_int64(-0.9));
  4539. tt_i64_op(0, OP_EQ, clamp_double_to_int64(-0.1));
  4540. tt_i64_op(0, OP_EQ, clamp_double_to_int64(0.0));
  4541. tt_i64_op(0, OP_EQ, clamp_double_to_int64(NAN_DBL));
  4542. tt_i64_op(0, OP_EQ, clamp_double_to_int64(0.1));
  4543. tt_i64_op(0, OP_EQ, clamp_double_to_int64(0.9));
  4544. tt_i64_op(1, OP_EQ, clamp_double_to_int64(1.0));
  4545. tt_i64_op((((int64_t) 1) << 53) - 1, OP_EQ,
  4546. clamp_double_to_int64(pow(2.0, 53.0) - 1.0));
  4547. tt_i64_op(((int64_t) 1) << 53, OP_EQ,
  4548. clamp_double_to_int64(pow(2.0, 53.0)));
  4549. tt_i64_op(INT64_MAX, OP_EQ,
  4550. clamp_double_to_int64(pow(2.0, 63.0)));
  4551. tt_i64_op(INT64_MAX, OP_EQ,
  4552. clamp_double_to_int64(pow(2.0, 64.0)));
  4553. tt_i64_op(INT64_MAX, OP_EQ, clamp_double_to_int64(INFINITY_DBL));
  4554. done:
  4555. ;
  4556. }
  4557. #ifdef FD_CLOEXEC
  4558. #define CAN_CHECK_CLOEXEC
  4559. static int
  4560. fd_is_cloexec(tor_socket_t fd)
  4561. {
  4562. int flags = fcntl(fd, F_GETFD, 0);
  4563. return (flags & FD_CLOEXEC) == FD_CLOEXEC;
  4564. }
  4565. #endif /* defined(FD_CLOEXEC) */
  4566. #ifndef _WIN32
  4567. #define CAN_CHECK_NONBLOCK
  4568. static int
  4569. fd_is_nonblocking(tor_socket_t fd)
  4570. {
  4571. int flags = fcntl(fd, F_GETFL, 0);
  4572. return (flags & O_NONBLOCK) == O_NONBLOCK;
  4573. }
  4574. #endif /* !defined(_WIN32) */
  4575. #define ERRNO_IS_EPROTO(e) (e == SOCK_ERRNO(EPROTONOSUPPORT))
  4576. #define SOCK_ERR_IS_EPROTO(s) ERRNO_IS_EPROTO(tor_socket_errno(s))
  4577. /* Test for tor_open_socket*, using IPv4 or IPv6 depending on arg. */
  4578. static void
  4579. test_util_socket(void *arg)
  4580. {
  4581. const int domain = !strcmp(arg, "4") ? AF_INET : AF_INET6;
  4582. tor_socket_t fd1 = TOR_INVALID_SOCKET;
  4583. tor_socket_t fd2 = TOR_INVALID_SOCKET;
  4584. tor_socket_t fd3 = TOR_INVALID_SOCKET;
  4585. tor_socket_t fd4 = TOR_INVALID_SOCKET;
  4586. int n = get_n_open_sockets();
  4587. TT_BLATHER(("Starting with %d open sockets.", n));
  4588. (void)arg;
  4589. fd1 = tor_open_socket_with_extensions(domain, SOCK_STREAM, 0, 0, 0);
  4590. int err = tor_socket_errno(fd1);
  4591. if (fd1 < 0 && (err == SOCK_ERRNO(EPROTONOSUPPORT) ||
  4592. err == SOCK_ERRNO(EAFNOSUPPORT))) {
  4593. /* Assume we're on an IPv4-only or IPv6-only system, and give up now. */
  4594. goto done;
  4595. }
  4596. fd2 = tor_open_socket_with_extensions(domain, SOCK_STREAM, 0, 0, 1);
  4597. tt_assert(SOCKET_OK(fd1));
  4598. tt_assert(SOCKET_OK(fd2));
  4599. tt_int_op(get_n_open_sockets(), OP_EQ, n + 2);
  4600. //fd3 = tor_open_socket_with_extensions(domain, SOCK_STREAM, 0, 1, 0);
  4601. //fd4 = tor_open_socket_with_extensions(domain, SOCK_STREAM, 0, 1, 1);
  4602. fd3 = tor_open_socket(domain, SOCK_STREAM, 0);
  4603. fd4 = tor_open_socket_nonblocking(domain, SOCK_STREAM, 0);
  4604. tt_assert(SOCKET_OK(fd3));
  4605. tt_assert(SOCKET_OK(fd4));
  4606. tt_int_op(get_n_open_sockets(), OP_EQ, n + 4);
  4607. #ifdef CAN_CHECK_CLOEXEC
  4608. tt_int_op(fd_is_cloexec(fd1), OP_EQ, 0);
  4609. tt_int_op(fd_is_cloexec(fd2), OP_EQ, 0);
  4610. tt_int_op(fd_is_cloexec(fd3), OP_EQ, 1);
  4611. tt_int_op(fd_is_cloexec(fd4), OP_EQ, 1);
  4612. #endif /* defined(CAN_CHECK_CLOEXEC) */
  4613. #ifdef CAN_CHECK_NONBLOCK
  4614. tt_int_op(fd_is_nonblocking(fd1), OP_EQ, 0);
  4615. tt_int_op(fd_is_nonblocking(fd2), OP_EQ, 1);
  4616. tt_int_op(fd_is_nonblocking(fd3), OP_EQ, 0);
  4617. tt_int_op(fd_is_nonblocking(fd4), OP_EQ, 1);
  4618. #endif /* defined(CAN_CHECK_NONBLOCK) */
  4619. tor_assert(tor_close_socket == tor_close_socket__real);
  4620. /* we use close_socket__real here so that coverity can tell that we are
  4621. * really closing these sockets. */
  4622. tor_close_socket__real(fd1);
  4623. tor_close_socket__real(fd2);
  4624. fd1 = fd2 = TOR_INVALID_SOCKET;
  4625. tt_int_op(get_n_open_sockets(), OP_EQ, n + 2);
  4626. tor_close_socket__real(fd3);
  4627. tor_close_socket__real(fd4);
  4628. fd3 = fd4 = TOR_INVALID_SOCKET;
  4629. tt_int_op(get_n_open_sockets(), OP_EQ, n);
  4630. done:
  4631. if (SOCKET_OK(fd1))
  4632. tor_close_socket__real(fd1);
  4633. if (SOCKET_OK(fd2))
  4634. tor_close_socket__real(fd2);
  4635. if (SOCKET_OK(fd3))
  4636. tor_close_socket__real(fd3);
  4637. if (SOCKET_OK(fd4))
  4638. tor_close_socket__real(fd4);
  4639. }
  4640. #if 0
  4641. static int
  4642. is_there_a_localhost(int family)
  4643. {
  4644. tor_socket_t s;
  4645. s = tor_open_socket(family, SOCK_STREAM, IPPROTO_TCP);
  4646. tor_assert(SOCKET_OK(s));
  4647. int result = 0;
  4648. if (family == AF_INET) {
  4649. struct sockaddr_in s_in;
  4650. memset(&s_in, 0, sizeof(s_in));
  4651. s_in.sin_family = AF_INET;
  4652. s_in.sin_addr.s_addr = htonl(0x7f000001);
  4653. s_in.sin_port = 0;
  4654. if (bind(s, (void*)&s_in, sizeof(s_in)) == 0) {
  4655. result = 1;
  4656. }
  4657. } else if (family == AF_INET6) {
  4658. struct sockaddr_in6 sin6;
  4659. memset(&sin6, 0, sizeof(sin6));
  4660. sin6.sin6_family = AF_INET6;
  4661. sin6.sin6_addr.s6_addr[15] = 1;
  4662. sin6.sin6_port = 0;
  4663. }
  4664. tor_close_socket(s);
  4665. return result;
  4666. }
  4667. #endif /* 0 */
  4668. /* Test for socketpair and ersatz_socketpair(). We test them both, since
  4669. * the latter is a tolerably good way to exercise tor_accept_socket(). */
  4670. static void
  4671. test_util_socketpair(void *arg)
  4672. {
  4673. const int ersatz = !strcmp(arg, "1");
  4674. int (*const tor_socketpair_fn)(int, int, int, tor_socket_t[2]) =
  4675. ersatz ? tor_ersatz_socketpair : tor_socketpair;
  4676. int n = get_n_open_sockets();
  4677. tor_socket_t fds[2] = {TOR_INVALID_SOCKET, TOR_INVALID_SOCKET};
  4678. const int family = AF_UNIX;
  4679. int socketpair_result = 0;
  4680. socketpair_result = tor_socketpair_fn(family, SOCK_STREAM, 0, fds);
  4681. #ifdef __FreeBSD__
  4682. /* If there is no 127.0.0.1, tor_ersatz_socketpair will and must fail.
  4683. * Otherwise, we risk exposing a socketpair on a routable IP address. (Some
  4684. * BSD jails use a routable address for localhost. Fortunately, they have
  4685. * the real AF_UNIX socketpair.) */
  4686. if (ersatz && socketpair_result < 0) {
  4687. /* In my testing, an IPv6-only FreeBSD jail without ::1 returned EINVAL.
  4688. * Assume we're on a machine without 127.0.0.1 or ::1 and give up now. */
  4689. tt_skip();
  4690. }
  4691. #endif /* defined(__FreeBSD__) */
  4692. tt_int_op(0, OP_EQ, socketpair_result);
  4693. tt_assert(SOCKET_OK(fds[0]));
  4694. tt_assert(SOCKET_OK(fds[1]));
  4695. tt_int_op(get_n_open_sockets(), OP_EQ, n + 2);
  4696. #ifdef CAN_CHECK_CLOEXEC
  4697. tt_int_op(fd_is_cloexec(fds[0]), OP_EQ, 1);
  4698. tt_int_op(fd_is_cloexec(fds[1]), OP_EQ, 1);
  4699. #endif
  4700. #ifdef CAN_CHECK_NONBLOCK
  4701. tt_int_op(fd_is_nonblocking(fds[0]), OP_EQ, 0);
  4702. tt_int_op(fd_is_nonblocking(fds[1]), OP_EQ, 0);
  4703. #endif
  4704. done:
  4705. if (SOCKET_OK(fds[0]))
  4706. tor_close_socket(fds[0]);
  4707. if (SOCKET_OK(fds[1]))
  4708. tor_close_socket(fds[1]);
  4709. }
  4710. #undef SOCKET_EPROTO
  4711. static void
  4712. test_util_max_mem(void *arg)
  4713. {
  4714. size_t memory1, memory2;
  4715. int r, r2;
  4716. (void) arg;
  4717. r = get_total_system_memory(&memory1);
  4718. r2 = get_total_system_memory(&memory2);
  4719. tt_int_op(r, OP_EQ, r2);
  4720. tt_uint_op(memory2, OP_EQ, memory1);
  4721. TT_BLATHER(("System memory: "U64_FORMAT, U64_PRINTF_ARG(memory1)));
  4722. if (r==0) {
  4723. /* You have at least a megabyte. */
  4724. tt_uint_op(memory1, OP_GT, (1<<20));
  4725. } else {
  4726. /* You do not have a petabyte. */
  4727. #if SIZEOF_SIZE_T == SIZEOF_UINT64_T
  4728. tt_u64_op(memory1, OP_LT, (U64_LITERAL(1)<<50));
  4729. #endif
  4730. }
  4731. done:
  4732. ;
  4733. }
  4734. static void
  4735. test_util_dest_validation_edgecase(void *arg)
  4736. {
  4737. (void)arg;
  4738. tt_assert(!string_is_valid_dest(NULL));
  4739. tt_assert(!string_is_valid_dest(""));
  4740. done:
  4741. return;
  4742. }
  4743. static void
  4744. test_util_hostname_validation(void *arg)
  4745. {
  4746. (void)arg;
  4747. // Lets try valid hostnames first.
  4748. tt_assert(string_is_valid_nonrfc_hostname("torproject.org"));
  4749. tt_assert(string_is_valid_nonrfc_hostname("ocw.mit.edu"));
  4750. tt_assert(string_is_valid_nonrfc_hostname("i.4cdn.org"));
  4751. tt_assert(string_is_valid_nonrfc_hostname("stanford.edu"));
  4752. tt_assert(string_is_valid_nonrfc_hostname("multiple-words-with-hypens.jp"));
  4753. // Subdomain name cannot start with '-' or '_'.
  4754. tt_assert(!string_is_valid_nonrfc_hostname("-torproject.org"));
  4755. tt_assert(!string_is_valid_nonrfc_hostname("subdomain.-domain.org"));
  4756. tt_assert(!string_is_valid_nonrfc_hostname("-subdomain.domain.org"));
  4757. tt_assert(!string_is_valid_nonrfc_hostname("___abc.org"));
  4758. // Hostnames cannot contain non-alphanumeric characters.
  4759. tt_assert(!string_is_valid_nonrfc_hostname("%%domain.\\org."));
  4760. tt_assert(!string_is_valid_nonrfc_hostname("***x.net"));
  4761. tt_assert(!string_is_valid_nonrfc_hostname("\xff\xffxyz.org"));
  4762. tt_assert(!string_is_valid_nonrfc_hostname("word1 word2.net"));
  4763. // Test workaround for nytimes.com stupidity, technically invalid,
  4764. // but we allow it since they are big, even though they are failing to
  4765. // comply with a ~30 year old standard.
  4766. tt_assert(string_is_valid_nonrfc_hostname("core3_euw1.fabrik.nytimes.com"));
  4767. // Firefox passes FQDNs with trailing '.'s directly to the SOCKS proxy,
  4768. // which is redundant since the spec states DOMAINNAME addresses are fully
  4769. // qualified. While unusual, this should be tollerated.
  4770. tt_assert(string_is_valid_nonrfc_hostname("core9_euw1.fabrik.nytimes.com."));
  4771. tt_assert(!string_is_valid_nonrfc_hostname(
  4772. "..washingtonpost.is.better.com"));
  4773. tt_assert(!string_is_valid_nonrfc_hostname("so.is..ft.com"));
  4774. tt_assert(!string_is_valid_nonrfc_hostname("..."));
  4775. // XXX: do we allow single-label DNS names?
  4776. // We shouldn't for SOCKS (spec says "contains a fully-qualified domain name"
  4777. // but only test pathologically malformed traling '.' cases for now.
  4778. tt_assert(!string_is_valid_nonrfc_hostname("."));
  4779. tt_assert(!string_is_valid_nonrfc_hostname(".."));
  4780. // IP address strings are not hostnames.
  4781. tt_assert(!string_is_valid_nonrfc_hostname("8.8.8.8"));
  4782. tt_assert(!string_is_valid_nonrfc_hostname("[2a00:1450:401b:800::200e]"));
  4783. tt_assert(!string_is_valid_nonrfc_hostname("2a00:1450:401b:800::200e"));
  4784. // We allow alphanumeric TLDs. For discussion, see ticket #25055.
  4785. tt_assert(string_is_valid_nonrfc_hostname("lucky.13"));
  4786. tt_assert(string_is_valid_nonrfc_hostname("luck.y13"));
  4787. tt_assert(string_is_valid_nonrfc_hostname("luck.y13."));
  4788. // We allow punycode TLDs. For examples, see
  4789. // http://data.iana.org/TLD/tlds-alpha-by-domain.txt
  4790. tt_assert(string_is_valid_nonrfc_hostname("example.xn--l1acc"));
  4791. done:
  4792. return;
  4793. }
  4794. static void
  4795. test_util_ipv4_validation(void *arg)
  4796. {
  4797. (void)arg;
  4798. tt_assert(string_is_valid_ipv4_address("192.168.0.1"));
  4799. tt_assert(string_is_valid_ipv4_address("8.8.8.8"));
  4800. tt_assert(!string_is_valid_ipv4_address("abcd"));
  4801. tt_assert(!string_is_valid_ipv4_address("300.300.300.300"));
  4802. tt_assert(!string_is_valid_ipv4_address("8.8."));
  4803. done:
  4804. return;
  4805. }
  4806. static void
  4807. test_util_writepid(void *arg)
  4808. {
  4809. (void) arg;
  4810. char *contents = NULL;
  4811. const char *fname = get_fname("tmp_pid");
  4812. unsigned long pid;
  4813. char c;
  4814. write_pidfile(fname);
  4815. contents = read_file_to_str(fname, 0, NULL);
  4816. tt_assert(contents);
  4817. int n = tor_sscanf(contents, "%lu\n%c", &pid, &c);
  4818. tt_int_op(n, OP_EQ, 1);
  4819. #ifdef _WIN32
  4820. tt_uint_op(pid, OP_EQ, _getpid());
  4821. #else
  4822. tt_uint_op(pid, OP_EQ, getpid());
  4823. #endif
  4824. done:
  4825. tor_free(contents);
  4826. }
  4827. static void
  4828. test_util_get_avail_disk_space(void *arg)
  4829. {
  4830. (void) arg;
  4831. int64_t val;
  4832. /* No answer for nonexistent directory */
  4833. val = tor_get_avail_disk_space("/akljasdfklsajdklasjkldjsa");
  4834. tt_i64_op(val, OP_EQ, -1);
  4835. /* Try the current directory */
  4836. val = tor_get_avail_disk_space(".");
  4837. #if !defined(HAVE_STATVFS) && !defined(_WIN32)
  4838. tt_i64_op(val, OP_EQ, -1); /* You don't have an implementation for this */
  4839. #else
  4840. tt_i64_op(val, OP_GT, 0); /* You have some space. */
  4841. tt_i64_op(val, OP_LT, ((int64_t)1)<<56); /* You don't have a zebibyte */
  4842. #endif /* !defined(HAVE_STATVFS) && !defined(_WIN32) */
  4843. done:
  4844. ;
  4845. }
  4846. static void
  4847. test_util_touch_file(void *arg)
  4848. {
  4849. (void) arg;
  4850. const char *fname = get_fname("touch");
  4851. const time_t now = time(NULL);
  4852. struct stat st;
  4853. write_bytes_to_file(fname, "abc", 3, 1);
  4854. tt_int_op(0, OP_EQ, stat(fname, &st));
  4855. /* A subtle point: the filesystem time is not necessarily equal to the
  4856. * system clock time, since one can be using a monotonic clock, or coarse
  4857. * monotonic clock, or whatever. So we might wind up with an mtime a few
  4858. * microseconds ago. Let's just give it a lot of wiggle room. */
  4859. tt_i64_op(st.st_mtime, OP_GE, now - 1);
  4860. const time_t five_sec_ago = now - 5;
  4861. struct utimbuf u = { five_sec_ago, five_sec_ago };
  4862. tt_int_op(0, OP_EQ, utime(fname, &u));
  4863. tt_int_op(0, OP_EQ, stat(fname, &st));
  4864. /* Let's hope that utime/stat give the same second as a round-trip? */
  4865. tt_i64_op(st.st_mtime, OP_EQ, five_sec_ago);
  4866. /* Finally we can touch the file */
  4867. tt_int_op(0, OP_EQ, touch_file(fname));
  4868. tt_int_op(0, OP_EQ, stat(fname, &st));
  4869. tt_i64_op(st.st_mtime, OP_GE, now-1);
  4870. done:
  4871. ;
  4872. }
  4873. #ifndef _WIN32
  4874. static void
  4875. test_util_pwdb(void *arg)
  4876. {
  4877. (void) arg;
  4878. const struct passwd *me = NULL, *me2, *me3;
  4879. char *name = NULL;
  4880. char *dir = NULL;
  4881. /* Uncached case. */
  4882. /* Let's assume that we exist. */
  4883. me = tor_getpwuid(getuid());
  4884. tt_ptr_op(me, OP_NE, NULL);
  4885. name = tor_strdup(me->pw_name);
  4886. /* Uncached case */
  4887. me2 = tor_getpwnam(name);
  4888. tt_ptr_op(me2, OP_NE, NULL);
  4889. tt_int_op(me2->pw_uid, OP_EQ, getuid());
  4890. /* Cached case */
  4891. me3 = tor_getpwuid(getuid());
  4892. tt_ptr_op(me3, OP_NE, NULL);
  4893. tt_str_op(me3->pw_name, OP_EQ, name);
  4894. me3 = tor_getpwnam(name);
  4895. tt_ptr_op(me3, OP_NE, NULL);
  4896. tt_int_op(me3->pw_uid, OP_EQ, getuid());
  4897. dir = get_user_homedir(name);
  4898. tt_ptr_op(dir, OP_NE, NULL);
  4899. /* Try failing cases. First find a user that doesn't exist by name */
  4900. char randbytes[4];
  4901. char badname[9];
  4902. int i, found=0;
  4903. for (i = 0; i < 100; ++i) {
  4904. crypto_rand(randbytes, sizeof(randbytes));
  4905. base16_encode(badname, sizeof(badname), randbytes, sizeof(randbytes));
  4906. if (tor_getpwnam(badname) == NULL) {
  4907. found = 1;
  4908. break;
  4909. }
  4910. }
  4911. tt_assert(found);
  4912. tor_free(dir);
  4913. /* We should do a LOG_ERR */
  4914. setup_full_capture_of_logs(LOG_ERR);
  4915. dir = get_user_homedir(badname);
  4916. tt_ptr_op(dir, OP_EQ, NULL);
  4917. expect_log_msg_containing("not found");
  4918. tt_int_op(smartlist_len(mock_saved_logs()), OP_EQ, 1);
  4919. teardown_capture_of_logs();
  4920. /* Now try to find a user that doesn't exist by ID. */
  4921. found = 0;
  4922. for (i = 0; i < 1000; ++i) {
  4923. uid_t u;
  4924. crypto_rand((char*)&u, sizeof(u));
  4925. if (tor_getpwuid(u) == NULL) {
  4926. found = 1;
  4927. break;
  4928. }
  4929. }
  4930. tt_assert(found);
  4931. done:
  4932. tor_free(name);
  4933. tor_free(dir);
  4934. teardown_capture_of_logs();
  4935. }
  4936. #endif /* !defined(_WIN32) */
  4937. static void
  4938. test_util_calloc_check(void *arg)
  4939. {
  4940. (void) arg;
  4941. /* Easy cases that are good. */
  4942. tt_assert(size_mul_check(0,0));
  4943. tt_assert(size_mul_check(0,100));
  4944. tt_assert(size_mul_check(100,0));
  4945. tt_assert(size_mul_check(100,100));
  4946. /* Harder cases that are still good. */
  4947. tt_assert(size_mul_check(SIZE_MAX, 1));
  4948. tt_assert(size_mul_check(1, SIZE_MAX));
  4949. tt_assert(size_mul_check(SIZE_MAX / 10, 9));
  4950. tt_assert(size_mul_check(11, SIZE_MAX / 12));
  4951. const size_t sqrt_size_max_p1 = ((size_t)1) << (sizeof(size_t) * 4);
  4952. tt_assert(size_mul_check(sqrt_size_max_p1, sqrt_size_max_p1 - 1));
  4953. /* Cases that overflow */
  4954. tt_assert(! size_mul_check(SIZE_MAX, 2));
  4955. tt_assert(! size_mul_check(2, SIZE_MAX));
  4956. tt_assert(! size_mul_check(SIZE_MAX / 10, 11));
  4957. tt_assert(! size_mul_check(11, SIZE_MAX / 10));
  4958. tt_assert(! size_mul_check(SIZE_MAX / 8, 9));
  4959. tt_assert(! size_mul_check(sqrt_size_max_p1, sqrt_size_max_p1));
  4960. done:
  4961. ;
  4962. }
  4963. static void
  4964. test_util_monotonic_time(void *arg)
  4965. {
  4966. (void)arg;
  4967. monotime_t mt1, mt2;
  4968. monotime_coarse_t mtc1, mtc2;
  4969. uint64_t nsec1, nsec2, usec1, msec1;
  4970. uint64_t nsecc1, nsecc2, usecc1, msecc1;
  4971. uint32_t stamp1, stamp2;
  4972. monotime_init();
  4973. monotime_get(&mt1);
  4974. monotime_coarse_get(&mtc1);
  4975. nsec1 = monotime_absolute_nsec();
  4976. usec1 = monotime_absolute_usec();
  4977. msec1 = monotime_absolute_msec();
  4978. nsecc1 = monotime_coarse_absolute_nsec();
  4979. usecc1 = monotime_coarse_absolute_usec();
  4980. msecc1 = monotime_coarse_absolute_msec();
  4981. stamp1 = monotime_coarse_to_stamp(&mtc1);
  4982. tor_sleep_msec(200);
  4983. monotime_get(&mt2);
  4984. monotime_coarse_get(&mtc2);
  4985. nsec2 = monotime_absolute_nsec();
  4986. nsecc2 = monotime_coarse_absolute_nsec();
  4987. stamp2 = monotime_coarse_to_stamp(&mtc2);
  4988. /* We need to be a little careful here since we don't know the system load.
  4989. */
  4990. tt_i64_op(monotime_diff_msec(&mt1, &mt2), OP_GE, 175);
  4991. tt_i64_op(monotime_diff_msec(&mt1, &mt2), OP_LT, 1000);
  4992. tt_i64_op(monotime_coarse_diff_msec(&mtc1, &mtc2), OP_GE, 125);
  4993. tt_i64_op(monotime_coarse_diff_msec(&mtc1, &mtc2), OP_LT, 1000);
  4994. tt_u64_op(nsec2-nsec1, OP_GE, 175000000);
  4995. tt_u64_op(nsec2-nsec1, OP_LT, 1000000000);
  4996. tt_u64_op(nsecc2-nsecc1, OP_GE, 125000000);
  4997. tt_u64_op(nsecc2-nsecc1, OP_LT, 1000000000);
  4998. tt_u64_op(msec1, OP_GE, nsec1 / 1000000);
  4999. tt_u64_op(usec1, OP_GE, nsec1 / 1000);
  5000. tt_u64_op(msecc1, OP_GE, nsecc1 / 1000000);
  5001. tt_u64_op(usecc1, OP_GE, nsecc1 / 1000);
  5002. tt_u64_op(msec1, OP_LE, nsec1 / 1000000 + 10);
  5003. tt_u64_op(usec1, OP_LE, nsec1 / 1000 + 10000);
  5004. tt_u64_op(msecc1, OP_LE, nsecc1 / 1000000 + 10);
  5005. tt_u64_op(usecc1, OP_LE, nsecc1 / 1000 + 10000);
  5006. uint64_t coarse_stamp_diff =
  5007. monotime_coarse_stamp_units_to_approx_msec(stamp2-stamp1);
  5008. tt_u64_op(coarse_stamp_diff, OP_GE, 120);
  5009. tt_u64_op(coarse_stamp_diff, OP_LE, 1200);
  5010. {
  5011. uint64_t units = monotime_msec_to_approx_coarse_stamp_units(5000);
  5012. uint64_t ms = monotime_coarse_stamp_units_to_approx_msec(units);
  5013. tt_u64_op(ms, OP_GE, 4950);
  5014. tt_u64_op(ms, OP_LT, 5050);
  5015. }
  5016. done:
  5017. ;
  5018. }
  5019. static void
  5020. test_util_monotonic_time_ratchet(void *arg)
  5021. {
  5022. (void)arg;
  5023. monotime_init();
  5024. monotime_reset_ratchets_for_testing();
  5025. /* win32, performance counter ratchet. */
  5026. tt_i64_op(100, OP_EQ, ratchet_performance_counter(100));
  5027. tt_i64_op(101, OP_EQ, ratchet_performance_counter(101));
  5028. tt_i64_op(2000, OP_EQ, ratchet_performance_counter(2000));
  5029. tt_i64_op(2000, OP_EQ, ratchet_performance_counter(100));
  5030. tt_i64_op(2005, OP_EQ, ratchet_performance_counter(105));
  5031. tt_i64_op(3005, OP_EQ, ratchet_performance_counter(1105));
  5032. tt_i64_op(3005, OP_EQ, ratchet_performance_counter(1000));
  5033. tt_i64_op(3010, OP_EQ, ratchet_performance_counter(1005));
  5034. /* win32, GetTickCounts32 ratchet-and-rollover-detector. */
  5035. const int64_t R = ((int64_t)1) << 32;
  5036. tt_i64_op(5, OP_EQ, ratchet_coarse_performance_counter(5));
  5037. tt_i64_op(1000, OP_EQ, ratchet_coarse_performance_counter(1000));
  5038. tt_i64_op(5+R, OP_EQ, ratchet_coarse_performance_counter(5));
  5039. tt_i64_op(10+R, OP_EQ, ratchet_coarse_performance_counter(10));
  5040. tt_i64_op(4+R*2, OP_EQ, ratchet_coarse_performance_counter(4));
  5041. /* gettimeofday regular ratchet. */
  5042. struct timeval tv_in = {0,0}, tv_out;
  5043. tv_in.tv_usec = 9000;
  5044. ratchet_timeval(&tv_in, &tv_out);
  5045. tt_int_op(tv_out.tv_usec, OP_EQ, 9000);
  5046. tt_i64_op(tv_out.tv_sec, OP_EQ, 0);
  5047. tv_in.tv_sec = 1337;
  5048. tv_in.tv_usec = 0;
  5049. ratchet_timeval(&tv_in, &tv_out);
  5050. tt_int_op(tv_out.tv_usec, OP_EQ, 0);
  5051. tt_i64_op(tv_out.tv_sec, OP_EQ, 1337);
  5052. tv_in.tv_sec = 1336;
  5053. tv_in.tv_usec = 500000;
  5054. ratchet_timeval(&tv_in, &tv_out);
  5055. tt_int_op(tv_out.tv_usec, OP_EQ, 0);
  5056. tt_i64_op(tv_out.tv_sec, OP_EQ, 1337);
  5057. tv_in.tv_sec = 1337;
  5058. tv_in.tv_usec = 0;
  5059. ratchet_timeval(&tv_in, &tv_out);
  5060. tt_int_op(tv_out.tv_usec, OP_EQ, 500000);
  5061. tt_i64_op(tv_out.tv_sec, OP_EQ, 1337);
  5062. tv_in.tv_sec = 1337;
  5063. tv_in.tv_usec = 600000;
  5064. ratchet_timeval(&tv_in, &tv_out);
  5065. tt_int_op(tv_out.tv_usec, OP_EQ, 100000);
  5066. tt_i64_op(tv_out.tv_sec, OP_EQ, 1338);
  5067. tv_in.tv_sec = 1000;
  5068. tv_in.tv_usec = 1000;
  5069. ratchet_timeval(&tv_in, &tv_out);
  5070. tt_int_op(tv_out.tv_usec, OP_EQ, 100000);
  5071. tt_i64_op(tv_out.tv_sec, OP_EQ, 1338);
  5072. tv_in.tv_sec = 2000;
  5073. tv_in.tv_usec = 2000;
  5074. ratchet_timeval(&tv_in, &tv_out);
  5075. tt_int_op(tv_out.tv_usec, OP_EQ, 101000);
  5076. tt_i64_op(tv_out.tv_sec, OP_EQ, 2338);
  5077. done:
  5078. ;
  5079. }
  5080. static void
  5081. test_util_monotonic_time_zero(void *arg)
  5082. {
  5083. (void) arg;
  5084. monotime_t t1;
  5085. monotime_coarse_t ct1;
  5086. monotime_init();
  5087. /* Check 1: The current time is not zero. */
  5088. monotime_get(&t1);
  5089. monotime_coarse_get(&ct1);
  5090. tt_assert(!monotime_is_zero(&t1));
  5091. tt_assert(!monotime_coarse_is_zero(&ct1));
  5092. /* Check 2: The _zero() makes the time zero. */
  5093. monotime_zero(&t1);
  5094. monotime_coarse_zero(&ct1);
  5095. tt_assert(monotime_is_zero(&t1));
  5096. tt_assert(monotime_coarse_is_zero(&ct1));
  5097. done:
  5098. ;
  5099. }
  5100. static void
  5101. test_util_monotonic_time_add_msec(void *arg)
  5102. {
  5103. (void) arg;
  5104. monotime_t t1, t2;
  5105. monotime_coarse_t ct1, ct2;
  5106. monotime_init();
  5107. monotime_get(&t1);
  5108. monotime_coarse_get(&ct1);
  5109. /* adding zero does nothing */
  5110. monotime_add_msec(&t2, &t1, 0);
  5111. monotime_coarse_add_msec(&ct2, &ct1, 0);
  5112. tt_i64_op(monotime_diff_msec(&t1, &t2), OP_EQ, 0);
  5113. tt_i64_op(monotime_coarse_diff_msec(&ct1, &ct2), OP_EQ, 0);
  5114. /* Add 1337 msec; see if the diff function agree */
  5115. monotime_add_msec(&t2, &t1, 1337);
  5116. monotime_coarse_add_msec(&ct2, &ct1, 1337);
  5117. tt_i64_op(monotime_diff_msec(&t1, &t2), OP_EQ, 1337);
  5118. tt_i64_op(monotime_coarse_diff_msec(&ct1, &ct2), OP_EQ, 1337);
  5119. // The 32-bit variant must be within 1% of the regular one.
  5120. tt_int_op(monotime_coarse_diff_msec32_(&ct1, &ct2), OP_GT, 1323);
  5121. tt_int_op(monotime_coarse_diff_msec32_(&ct1, &ct2), OP_LT, 1350);
  5122. /* Add 1337 msec twice more; make sure that any second rollover issues
  5123. * worked. */
  5124. monotime_add_msec(&t2, &t2, 1337);
  5125. monotime_coarse_add_msec(&ct2, &ct2, 1337);
  5126. monotime_add_msec(&t2, &t2, 1337);
  5127. monotime_coarse_add_msec(&ct2, &ct2, 1337);
  5128. tt_i64_op(monotime_diff_msec(&t1, &t2), OP_EQ, 1337*3);
  5129. tt_i64_op(monotime_coarse_diff_msec(&ct1, &ct2), OP_EQ, 1337*3);
  5130. tt_int_op(monotime_coarse_diff_msec32_(&ct1, &ct2), OP_GT, 3970);
  5131. tt_int_op(monotime_coarse_diff_msec32_(&ct1, &ct2), OP_LT, 4051);
  5132. done:
  5133. ;
  5134. }
  5135. static void
  5136. test_util_nowrap_math(void *arg)
  5137. {
  5138. (void)arg;
  5139. tt_u64_op(0, OP_EQ, tor_add_u32_nowrap(0, 0));
  5140. tt_u64_op(1, OP_EQ, tor_add_u32_nowrap(0, 1));
  5141. tt_u64_op(1, OP_EQ, tor_add_u32_nowrap(1, 0));
  5142. tt_u64_op(4, OP_EQ, tor_add_u32_nowrap(2, 2));
  5143. tt_u64_op(UINT32_MAX, OP_EQ, tor_add_u32_nowrap(UINT32_MAX-1, 2));
  5144. tt_u64_op(UINT32_MAX, OP_EQ, tor_add_u32_nowrap(2, UINT32_MAX-1));
  5145. tt_u64_op(UINT32_MAX, OP_EQ, tor_add_u32_nowrap(UINT32_MAX, UINT32_MAX));
  5146. done:
  5147. ;
  5148. }
  5149. static void
  5150. test_util_htonll(void *arg)
  5151. {
  5152. (void)arg;
  5153. #ifdef WORDS_BIGENDIAN
  5154. const uint64_t res_be = 0x8877665544332211;
  5155. #else
  5156. const uint64_t res_le = 0x1122334455667788;
  5157. #endif
  5158. tt_u64_op(0, OP_EQ, tor_htonll(0));
  5159. tt_u64_op(0, OP_EQ, tor_ntohll(0));
  5160. tt_u64_op(UINT64_MAX, OP_EQ, tor_htonll(UINT64_MAX));
  5161. tt_u64_op(UINT64_MAX, OP_EQ, tor_ntohll(UINT64_MAX));
  5162. #ifdef WORDS_BIGENDIAN
  5163. tt_u64_op(res_be, OP_EQ, tor_htonll(0x8877665544332211));
  5164. tt_u64_op(res_be, OP_EQ, tor_ntohll(0x8877665544332211));
  5165. #else
  5166. tt_u64_op(res_le, OP_EQ, tor_htonll(0x8877665544332211));
  5167. tt_u64_op(res_le, OP_EQ, tor_ntohll(0x8877665544332211));
  5168. #endif /* defined(WORDS_BIGENDIAN) */
  5169. done:
  5170. ;
  5171. }
  5172. static void
  5173. test_util_get_unquoted_path(void *arg)
  5174. {
  5175. (void)arg;
  5176. char *r = NULL;
  5177. r = get_unquoted_path("\""); // "
  5178. tt_ptr_op(r, OP_EQ, NULL);
  5179. tor_free(r);
  5180. r = get_unquoted_path("\"\"\""); // """
  5181. tt_ptr_op(r, OP_EQ, NULL);
  5182. tor_free(r);
  5183. r = get_unquoted_path("\\\""); // \"
  5184. tt_ptr_op(r, OP_EQ, NULL);
  5185. tor_free(r);
  5186. r = get_unquoted_path("\\\"\\\""); // \"\"
  5187. tt_ptr_op(r, OP_EQ, NULL);
  5188. tor_free(r);
  5189. r = get_unquoted_path("A\\B\\C\""); // A\B\C"
  5190. tt_ptr_op(r, OP_EQ, NULL);
  5191. tor_free(r);
  5192. r = get_unquoted_path("\"A\\B\\C"); // "A\B\C
  5193. tt_ptr_op(r, OP_EQ, NULL);
  5194. tor_free(r);
  5195. r = get_unquoted_path("\"A\\B\"C\""); // "A\B"C"
  5196. tt_ptr_op(r, OP_EQ, NULL);
  5197. tor_free(r);
  5198. r = get_unquoted_path("A\\B\"C"); // A\B"C
  5199. tt_ptr_op(r, OP_EQ, NULL);
  5200. tor_free(r);
  5201. r = get_unquoted_path("");
  5202. tt_str_op(r, OP_EQ, "");
  5203. tor_free(r);
  5204. r = get_unquoted_path("\"\""); // ""
  5205. tt_str_op(r, OP_EQ, "");
  5206. tor_free(r);
  5207. r = get_unquoted_path("A\\B\\C"); // A\B\C
  5208. tt_str_op(r, OP_EQ, "A\\B\\C"); // A\B\C
  5209. tor_free(r);
  5210. r = get_unquoted_path("\"A\\B\\C\""); // "A\B\C"
  5211. tt_str_op(r, OP_EQ, "A\\B\\C"); // A\B\C
  5212. tor_free(r);
  5213. r = get_unquoted_path("\"\\\""); // "\"
  5214. tt_str_op(r, OP_EQ, "\\"); // \ /* comment to prevent line continuation */
  5215. tor_free(r);
  5216. r = get_unquoted_path("\"\\\"\""); // "\""
  5217. tt_str_op(r, OP_EQ, "\""); // "
  5218. tor_free(r);
  5219. r = get_unquoted_path("\"A\\B\\C\\\"\""); // "A\B\C\""
  5220. tt_str_op(r, OP_EQ, "A\\B\\C\""); // A\B\C"
  5221. tor_free(r);
  5222. r = get_unquoted_path("A\\B\\\"C"); // A\B\"C
  5223. tt_str_op(r, OP_EQ, "A\\B\"C"); // A\B"C
  5224. tor_free(r);
  5225. r = get_unquoted_path("\"A\\B\\\"C\""); // "A\B\"C"
  5226. tt_str_op(r, OP_EQ, "A\\B\"C"); // A\B"C
  5227. done:
  5228. tor_free(r);
  5229. }
  5230. #define UTIL_LEGACY(name) \
  5231. { #name, test_util_ ## name , 0, NULL, NULL }
  5232. #define UTIL_TEST(name, flags) \
  5233. { #name, test_util_ ## name, flags, NULL, NULL }
  5234. #define COMPRESS(name, identifier) \
  5235. { "compress/" #name, test_util_compress, 0, &compress_setup, \
  5236. (char*)(identifier) }
  5237. #define COMPRESS_CONCAT(name, identifier) \
  5238. { "compress_concat/" #name, test_util_decompress_concatenated, 0, \
  5239. &compress_setup, \
  5240. (char*)(identifier) }
  5241. #define COMPRESS_JUNK(name, identifier) \
  5242. { "compress_junk/" #name, test_util_decompress_junk, 0, \
  5243. &compress_setup, \
  5244. (char*)(identifier) }
  5245. #define COMPRESS_DOS(name, identifier) \
  5246. { "compress_dos/" #name, test_util_decompress_dos, 0, \
  5247. &compress_setup, \
  5248. (char*)(identifier) }
  5249. #ifdef _WIN32
  5250. #define UTIL_TEST_NO_WIN(n, f) { #n, NULL, TT_SKIP, NULL, NULL }
  5251. #define UTIL_TEST_WIN_ONLY(n, f) UTIL_TEST(n, (f))
  5252. #define UTIL_LEGACY_NO_WIN(n) UTIL_TEST_NO_WIN(n, 0)
  5253. #else
  5254. #define UTIL_TEST_NO_WIN(n, f) UTIL_TEST(n, (f))
  5255. #define UTIL_TEST_WIN_ONLY(n, f) { #n, NULL, TT_SKIP, NULL, NULL }
  5256. #define UTIL_LEGACY_NO_WIN(n) UTIL_LEGACY(n)
  5257. #endif /* defined(_WIN32) */
  5258. struct testcase_t util_tests[] = {
  5259. UTIL_LEGACY(time),
  5260. UTIL_TEST(parse_http_time, 0),
  5261. UTIL_LEGACY(config_line),
  5262. UTIL_LEGACY(config_line_quotes),
  5263. UTIL_LEGACY(config_line_comment_character),
  5264. UTIL_LEGACY(config_line_escaped_content),
  5265. UTIL_LEGACY(config_line_crlf),
  5266. UTIL_LEGACY_NO_WIN(expand_filename),
  5267. UTIL_LEGACY(escape_string_socks),
  5268. UTIL_LEGACY(string_is_key_value),
  5269. UTIL_LEGACY(strmisc),
  5270. UTIL_TEST(parse_integer, 0),
  5271. UTIL_LEGACY(pow2),
  5272. COMPRESS(zlib, "deflate"),
  5273. COMPRESS(gzip, "gzip"),
  5274. COMPRESS(lzma, "x-tor-lzma"),
  5275. COMPRESS(zstd, "x-zstd"),
  5276. COMPRESS(zstd_nostatic, "x-zstd:nostatic"),
  5277. COMPRESS(none, "identity"),
  5278. COMPRESS_CONCAT(zlib, "deflate"),
  5279. COMPRESS_CONCAT(gzip, "gzip"),
  5280. COMPRESS_CONCAT(lzma, "x-tor-lzma"),
  5281. COMPRESS_CONCAT(zstd, "x-zstd"),
  5282. COMPRESS_CONCAT(zstd_nostatic, "x-zstd:nostatic"),
  5283. COMPRESS_CONCAT(none, "identity"),
  5284. COMPRESS_JUNK(zlib, "deflate"),
  5285. COMPRESS_JUNK(gzip, "gzip"),
  5286. COMPRESS_JUNK(lzma, "x-tor-lzma"),
  5287. COMPRESS_DOS(zlib, "deflate"),
  5288. COMPRESS_DOS(gzip, "gzip"),
  5289. COMPRESS_DOS(lzma, "x-tor-lzma"),
  5290. COMPRESS_DOS(zstd, "x-zstd"),
  5291. COMPRESS_DOS(zstd_nostatic, "x-zstd:nostatic"),
  5292. UTIL_TEST(gzip_compression_bomb, TT_FORK),
  5293. UTIL_LEGACY(datadir),
  5294. UTIL_LEGACY(memarea),
  5295. UTIL_LEGACY(control_formats),
  5296. UTIL_LEGACY(mmap),
  5297. UTIL_TEST(sscanf, TT_FORK),
  5298. UTIL_LEGACY(format_time_interval),
  5299. UTIL_LEGACY(path_is_relative),
  5300. UTIL_LEGACY(strtok),
  5301. UTIL_LEGACY(di_ops),
  5302. UTIL_TEST(di_map, 0),
  5303. UTIL_TEST(round_to_next_multiple_of, 0),
  5304. UTIL_TEST(laplace, 0),
  5305. UTIL_TEST(clamp_double_to_int64, 0),
  5306. UTIL_TEST(find_str_at_start_of_line, 0),
  5307. UTIL_TEST(string_is_C_identifier, 0),
  5308. UTIL_TEST(asprintf, 0),
  5309. UTIL_TEST(listdir, 0),
  5310. UTIL_TEST(parent_dir, 0),
  5311. UTIL_TEST(ftruncate, 0),
  5312. UTIL_TEST(nowrap_math, 0),
  5313. UTIL_TEST(num_cpus, 0),
  5314. UTIL_TEST_WIN_ONLY(load_win_lib, 0),
  5315. UTIL_TEST_NO_WIN(exit_status, 0),
  5316. UTIL_TEST_NO_WIN(string_from_pipe, 0),
  5317. UTIL_TEST(format_hex_number, 0),
  5318. UTIL_TEST(format_dec_number, 0),
  5319. UTIL_TEST(join_win_cmdline, 0),
  5320. UTIL_TEST(split_lines, 0),
  5321. UTIL_TEST(n_bits_set, 0),
  5322. UTIL_TEST(eat_whitespace, 0),
  5323. UTIL_TEST(sl_new_from_text_lines, 0),
  5324. UTIL_TEST(envnames, 0),
  5325. UTIL_TEST(make_environment, 0),
  5326. UTIL_TEST(set_env_var_in_sl, 0),
  5327. UTIL_TEST(read_file_eof_tiny_limit, 0),
  5328. UTIL_TEST(read_file_eof_one_loop_a, 0),
  5329. UTIL_TEST(read_file_eof_one_loop_b, 0),
  5330. UTIL_TEST(read_file_eof_two_loops, 0),
  5331. UTIL_TEST(read_file_eof_two_loops_b, 0),
  5332. UTIL_TEST(read_file_eof_zero_bytes, 0),
  5333. UTIL_TEST(write_chunks_to_file, 0),
  5334. UTIL_TEST(mathlog, 0),
  5335. UTIL_TEST(fraction, 0),
  5336. UTIL_TEST(weak_random, 0),
  5337. { "socket_ipv4", test_util_socket, TT_FORK, &passthrough_setup,
  5338. (void*)"4" },
  5339. { "socket_ipv6", test_util_socket, TT_FORK,
  5340. &passthrough_setup, (void*)"6" },
  5341. { "socketpair", test_util_socketpair, TT_FORK, &passthrough_setup,
  5342. (void*)"0" },
  5343. { "socketpair_ersatz", test_util_socketpair, TT_FORK,
  5344. &passthrough_setup, (void*)"1" },
  5345. UTIL_TEST(max_mem, 0),
  5346. UTIL_TEST(hostname_validation, 0),
  5347. UTIL_TEST(dest_validation_edgecase, 0),
  5348. UTIL_TEST(ipv4_validation, 0),
  5349. UTIL_TEST(writepid, 0),
  5350. UTIL_TEST(get_avail_disk_space, 0),
  5351. UTIL_TEST(touch_file, 0),
  5352. UTIL_TEST_NO_WIN(pwdb, TT_FORK),
  5353. UTIL_TEST(calloc_check, 0),
  5354. UTIL_TEST(monotonic_time, 0),
  5355. UTIL_TEST(monotonic_time_ratchet, TT_FORK),
  5356. UTIL_TEST(monotonic_time_zero, 0),
  5357. UTIL_TEST(monotonic_time_add_msec, 0),
  5358. UTIL_TEST(htonll, 0),
  5359. UTIL_TEST(get_unquoted_path, 0),
  5360. END_OF_TESTCASES
  5361. };