test_util.c 178 KB

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