test_util.c 179 KB

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