test_util.c 195 KB

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