test_util.c 195 KB

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