test_util.c 196 KB

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