test_util.c 195 KB

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