test_util.c 196 KB

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