test_util.c 181 KB

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