test_util.c 202 KB

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