test_util.c 201 KB

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