test_util.c 179 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774
  1. /* Copyright (c) 2001-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2016, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. #include "orconfig.h"
  6. #define COMPAT_PRIVATE
  7. #define COMPAT_TIME_PRIVATE
  8. #define CONTROL_PRIVATE
  9. #define UTIL_PRIVATE
  10. #include "or.h"
  11. #include "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 a line and close */
  3420. retlen = write(test_pipe[1], "AB", 2);
  3421. tt_int_op(retlen, OP_EQ, 2);
  3422. retval = close(test_pipe[1]);
  3423. tt_int_op(retval, OP_EQ, 0);
  3424. test_pipe[1] = -1;
  3425. status = get_string_from_pipe(test_pipe[0], buf, sizeof(buf)-1);
  3426. tt_int_op(errno, OP_EQ, 0);
  3427. tt_int_op(status, OP_EQ, IO_STREAM_OKAY);
  3428. tt_str_op(buf, OP_EQ, "AB");
  3429. errno = 0;
  3430. /* Check for EOF */
  3431. status = get_string_from_pipe(test_pipe[0], buf, sizeof(buf)-1);
  3432. tt_int_op(errno, OP_EQ, 0);
  3433. tt_int_op(status, OP_EQ, IO_STREAM_CLOSED);
  3434. errno = 0;
  3435. done:
  3436. if (test_pipe[0] != -1)
  3437. close(test_pipe[0]);
  3438. if (test_pipe[1] != -1)
  3439. close(test_pipe[1]);
  3440. }
  3441. #endif // _WIN32
  3442. /**
  3443. * Test for format_hex_number_sigsafe()
  3444. */
  3445. static void
  3446. test_util_format_hex_number(void *ptr)
  3447. {
  3448. int i, len;
  3449. char buf[33];
  3450. const struct {
  3451. const char *str;
  3452. unsigned int x;
  3453. } test_data[] = {
  3454. {"0", 0},
  3455. {"1", 1},
  3456. {"273A", 0x273a},
  3457. {"FFFF", 0xffff},
  3458. {"7FFFFFFF", 0x7fffffff},
  3459. {"FFFFFFFF", 0xffffffff},
  3460. #if UINT_MAX >= 0xffffffff
  3461. {"31BC421D", 0x31bc421d},
  3462. {"FFFFFFFF", 0xffffffff},
  3463. #endif
  3464. {NULL, 0}
  3465. };
  3466. (void)ptr;
  3467. for (i = 0; test_data[i].str != NULL; ++i) {
  3468. len = format_hex_number_sigsafe(test_data[i].x, buf, sizeof(buf));
  3469. tt_int_op(len,OP_NE, 0);
  3470. tt_int_op(len,OP_EQ, strlen(buf));
  3471. tt_str_op(buf,OP_EQ, test_data[i].str);
  3472. }
  3473. tt_int_op(4,OP_EQ, format_hex_number_sigsafe(0xffff, buf, 5));
  3474. tt_str_op(buf,OP_EQ, "FFFF");
  3475. tt_int_op(0,OP_EQ, format_hex_number_sigsafe(0xffff, buf, 4));
  3476. tt_int_op(0,OP_EQ, format_hex_number_sigsafe(0, buf, 1));
  3477. done:
  3478. return;
  3479. }
  3480. /**
  3481. * Test for format_hex_number_sigsafe()
  3482. */
  3483. static void
  3484. test_util_format_dec_number(void *ptr)
  3485. {
  3486. int i, len;
  3487. char buf[33];
  3488. const struct {
  3489. const char *str;
  3490. unsigned int x;
  3491. } test_data[] = {
  3492. {"0", 0},
  3493. {"1", 1},
  3494. {"1234", 1234},
  3495. {"12345678", 12345678},
  3496. {"99999999", 99999999},
  3497. {"100000000", 100000000},
  3498. {"4294967295", 4294967295u},
  3499. #if UINT_MAX > 0xffffffff
  3500. {"18446744073709551615", 18446744073709551615u },
  3501. #endif
  3502. {NULL, 0}
  3503. };
  3504. (void)ptr;
  3505. for (i = 0; test_data[i].str != NULL; ++i) {
  3506. len = format_dec_number_sigsafe(test_data[i].x, buf, sizeof(buf));
  3507. tt_int_op(len,OP_NE, 0);
  3508. tt_int_op(len,OP_EQ, strlen(buf));
  3509. tt_str_op(buf,OP_EQ, test_data[i].str);
  3510. len = format_dec_number_sigsafe(test_data[i].x, buf,
  3511. (int)(strlen(test_data[i].str) + 1));
  3512. tt_int_op(len,OP_EQ, strlen(buf));
  3513. tt_str_op(buf,OP_EQ, test_data[i].str);
  3514. }
  3515. tt_int_op(4,OP_EQ, format_dec_number_sigsafe(7331, buf, 5));
  3516. tt_str_op(buf,OP_EQ, "7331");
  3517. tt_int_op(0,OP_EQ, format_dec_number_sigsafe(7331, buf, 4));
  3518. tt_int_op(1,OP_EQ, format_dec_number_sigsafe(0, buf, 2));
  3519. tt_int_op(0,OP_EQ, format_dec_number_sigsafe(0, buf, 1));
  3520. done:
  3521. return;
  3522. }
  3523. /**
  3524. * Test that we can properly format a Windows command line
  3525. */
  3526. static void
  3527. test_util_join_win_cmdline(void *ptr)
  3528. {
  3529. /* Based on some test cases from "Parsing C++ Command-Line Arguments" in
  3530. * MSDN but we don't exercise all quoting rules because tor_join_win_cmdline
  3531. * will try to only generate simple cases for the child process to parse;
  3532. * i.e. we never embed quoted strings in arguments. */
  3533. const char *argvs[][4] = {
  3534. {"a", "bb", "CCC", NULL}, // Normal
  3535. {NULL, NULL, NULL, NULL}, // Empty argument list
  3536. {"", NULL, NULL, NULL}, // Empty argument
  3537. {"\"a", "b\"b", "CCC\"", NULL}, // Quotes
  3538. {"a\tbc", "dd dd", "E", NULL}, // Whitespace
  3539. {"a\\\\\\b", "de fg", "H", NULL}, // Backslashes
  3540. {"a\\\"b", "\\c", "D\\", NULL}, // Backslashes before quote
  3541. {"a\\\\b c", "d", "E", NULL}, // Backslashes not before quote
  3542. { NULL } // Terminator
  3543. };
  3544. const char *cmdlines[] = {
  3545. "a bb CCC",
  3546. "",
  3547. "\"\"",
  3548. "\\\"a b\\\"b CCC\\\"",
  3549. "\"a\tbc\" \"dd dd\" E",
  3550. "a\\\\\\b \"de fg\" H",
  3551. "a\\\\\\\"b \\c D\\",
  3552. "\"a\\\\b c\" d E",
  3553. NULL // Terminator
  3554. };
  3555. int i;
  3556. char *joined_argv = NULL;
  3557. (void)ptr;
  3558. for (i=0; cmdlines[i]!=NULL; i++) {
  3559. log_info(LD_GENERAL, "Joining argvs[%d], expecting <%s>", i, cmdlines[i]);
  3560. joined_argv = tor_join_win_cmdline(argvs[i]);
  3561. tt_str_op(cmdlines[i],OP_EQ, joined_argv);
  3562. tor_free(joined_argv);
  3563. }
  3564. done:
  3565. tor_free(joined_argv);
  3566. }
  3567. #define MAX_SPLIT_LINE_COUNT 4
  3568. struct split_lines_test_t {
  3569. const char *orig_line; // Line to be split (may contain \0's)
  3570. int orig_length; // Length of orig_line
  3571. const char *split_line[MAX_SPLIT_LINE_COUNT]; // Split lines
  3572. };
  3573. /**
  3574. * Test that we properly split a buffer into lines
  3575. */
  3576. static void
  3577. test_util_split_lines(void *ptr)
  3578. {
  3579. /* Test cases. orig_line of last test case must be NULL.
  3580. * The last element of split_line[i] must be NULL. */
  3581. struct split_lines_test_t tests[] = {
  3582. {"", 0, {NULL}},
  3583. {"foo", 3, {"foo", NULL}},
  3584. {"\n\rfoo\n\rbar\r\n", 12, {"foo", "bar", NULL}},
  3585. {"fo o\r\nb\tar", 10, {"fo o", "b.ar", NULL}},
  3586. {"\x0f""f\0o\0\n\x01""b\0r\0\r", 12, {".f.o.", ".b.r.", NULL}},
  3587. {"line 1\r\nline 2", 14, {"line 1", "line 2", NULL}},
  3588. {"line 1\r\n\r\nline 2", 16, {"line 1", "line 2", NULL}},
  3589. {"line 1\r\n\r\r\r\nline 2", 18, {"line 1", "line 2", NULL}},
  3590. {"line 1\r\n\n\n\n\rline 2", 18, {"line 1", "line 2", NULL}},
  3591. {"line 1\r\n\r\t\r\nline 3", 18, {"line 1", ".", "line 3", NULL}},
  3592. {"\n\t\r\t\nline 3", 11, {".", ".", "line 3", NULL}},
  3593. {NULL, 0, { NULL }}
  3594. };
  3595. int i, j;
  3596. char *orig_line=NULL;
  3597. smartlist_t *sl=NULL;
  3598. (void)ptr;
  3599. for (i=0; tests[i].orig_line; i++) {
  3600. sl = smartlist_new();
  3601. /* Allocate space for string and trailing NULL */
  3602. orig_line = tor_memdup(tests[i].orig_line, tests[i].orig_length + 1);
  3603. tor_split_lines(sl, orig_line, tests[i].orig_length);
  3604. j = 0;
  3605. log_info(LD_GENERAL, "Splitting test %d of length %d",
  3606. i, tests[i].orig_length);
  3607. SMARTLIST_FOREACH_BEGIN(sl, const char *, line) {
  3608. /* Check we have not got too many lines */
  3609. tt_int_op(MAX_SPLIT_LINE_COUNT, OP_GT, j);
  3610. /* Check that there actually should be a line here */
  3611. tt_assert(tests[i].split_line[j] != NULL);
  3612. log_info(LD_GENERAL, "Line %d of test %d, should be <%s>",
  3613. j, i, tests[i].split_line[j]);
  3614. /* Check that the line is as expected */
  3615. tt_str_op(line,OP_EQ, tests[i].split_line[j]);
  3616. j++;
  3617. } SMARTLIST_FOREACH_END(line);
  3618. /* Check that we didn't miss some lines */
  3619. tt_ptr_op(NULL,OP_EQ, tests[i].split_line[j]);
  3620. tor_free(orig_line);
  3621. smartlist_free(sl);
  3622. sl = NULL;
  3623. }
  3624. done:
  3625. tor_free(orig_line);
  3626. smartlist_free(sl);
  3627. }
  3628. static void
  3629. test_util_di_ops(void *arg)
  3630. {
  3631. #define LT -1
  3632. #define GT 1
  3633. #define EQ 0
  3634. const struct {
  3635. const char *a; int want_sign; const char *b;
  3636. } examples[] = {
  3637. { "Foo", EQ, "Foo" },
  3638. { "foo", GT, "bar", },
  3639. { "foobar", EQ ,"foobar" },
  3640. { "foobar", LT, "foobaw" },
  3641. { "foobar", GT, "f00bar" },
  3642. { "foobar", GT, "boobar" },
  3643. { "", EQ, "" },
  3644. { NULL, 0, NULL },
  3645. };
  3646. int i;
  3647. (void)arg;
  3648. for (i = 0; examples[i].a; ++i) {
  3649. size_t len = strlen(examples[i].a);
  3650. int eq1, eq2, neq1, neq2, cmp1, cmp2;
  3651. tt_int_op(len,OP_EQ, strlen(examples[i].b));
  3652. /* We do all of the operations, with operands in both orders. */
  3653. eq1 = tor_memeq(examples[i].a, examples[i].b, len);
  3654. eq2 = tor_memeq(examples[i].b, examples[i].a, len);
  3655. neq1 = tor_memneq(examples[i].a, examples[i].b, len);
  3656. neq2 = tor_memneq(examples[i].b, examples[i].a, len);
  3657. cmp1 = tor_memcmp(examples[i].a, examples[i].b, len);
  3658. cmp2 = tor_memcmp(examples[i].b, examples[i].a, len);
  3659. /* Check for correctness of cmp1 */
  3660. if (cmp1 < 0 && examples[i].want_sign != LT)
  3661. TT_DIE(("Assertion failed."));
  3662. else if (cmp1 > 0 && examples[i].want_sign != GT)
  3663. TT_DIE(("Assertion failed."));
  3664. else if (cmp1 == 0 && examples[i].want_sign != EQ)
  3665. TT_DIE(("Assertion failed."));
  3666. /* Check for consistency of everything else with cmp1 */
  3667. tt_int_op(eq1,OP_EQ, eq2);
  3668. tt_int_op(neq1,OP_EQ, neq2);
  3669. tt_int_op(cmp1,OP_EQ, -cmp2);
  3670. tt_int_op(eq1,OP_EQ, cmp1 == 0);
  3671. tt_int_op(neq1,OP_EQ, !eq1);
  3672. }
  3673. {
  3674. uint8_t zz = 0;
  3675. uint8_t ii = 0;
  3676. int z;
  3677. /* exhaustively test tor_memeq and tor_memcmp
  3678. * against each possible single-byte numeric difference
  3679. * some arithmetic bugs only appear with certain bit patterns */
  3680. for (z = 0; z < 256; z++) {
  3681. for (i = 0; i < 256; i++) {
  3682. ii = (uint8_t)i;
  3683. zz = (uint8_t)z;
  3684. tt_int_op(tor_memeq(&zz, &ii, 1),OP_EQ, zz == ii);
  3685. tt_int_op(tor_memcmp(&zz, &ii, 1) > 0 ? GT : EQ,OP_EQ,
  3686. zz > ii ? GT : EQ);
  3687. tt_int_op(tor_memcmp(&ii, &zz, 1) < 0 ? LT : EQ,OP_EQ,
  3688. ii < zz ? LT : EQ);
  3689. }
  3690. }
  3691. }
  3692. tt_int_op(1, OP_EQ, safe_mem_is_zero("", 0));
  3693. tt_int_op(1, OP_EQ, safe_mem_is_zero("", 1));
  3694. tt_int_op(0, OP_EQ, safe_mem_is_zero("a", 1));
  3695. tt_int_op(0, OP_EQ, safe_mem_is_zero("a", 2));
  3696. tt_int_op(0, OP_EQ, safe_mem_is_zero("\0a", 2));
  3697. tt_int_op(1, OP_EQ, safe_mem_is_zero("\0\0a", 2));
  3698. tt_int_op(1, OP_EQ, safe_mem_is_zero("\0\0\0\0\0\0\0\0", 8));
  3699. tt_int_op(1, OP_EQ, safe_mem_is_zero("\0\0\0\0\0\0\0\0a", 8));
  3700. tt_int_op(0, OP_EQ, safe_mem_is_zero("\0\0\0\0\0\0\0\0a", 9));
  3701. done:
  3702. ;
  3703. }
  3704. static void
  3705. test_util_di_map(void *arg)
  3706. {
  3707. (void)arg;
  3708. di_digest256_map_t *dimap = NULL;
  3709. uint8_t key1[] = "Robert Anton Wilson ";
  3710. uint8_t key2[] = "Martin Gardner, _Fads&fallacies";
  3711. uint8_t key3[] = "Tom Lehrer, _Be Prepared_. ";
  3712. uint8_t key4[] = "Ursula Le Guin,_A Wizard of... ";
  3713. char dflt_entry[] = "'You have made a good beginning', but no more";
  3714. tt_int_op(32, ==, sizeof(key1));
  3715. tt_int_op(32, ==, sizeof(key2));
  3716. tt_int_op(32, ==, sizeof(key3));
  3717. tt_ptr_op(dflt_entry, ==, dimap_search(dimap, key1, dflt_entry));
  3718. char *str1 = tor_strdup("You are precisely as big as what you love"
  3719. " and precisely as small as what you allow"
  3720. " to annoy you.");
  3721. char *str2 = tor_strdup("Let us hope that Lysenko's success in Russia will"
  3722. " serve for many generations to come as another"
  3723. " reminder to the world of how quickly and easily"
  3724. " a science can be corrupted when ignorant"
  3725. " political leaders deem themselves competent"
  3726. " to arbitrate scientific disputes");
  3727. char *str3 = tor_strdup("Don't write naughty words on walls "
  3728. "if you can't spell.");
  3729. dimap_add_entry(&dimap, key1, str1);
  3730. dimap_add_entry(&dimap, key2, str2);
  3731. dimap_add_entry(&dimap, key3, str3);
  3732. tt_ptr_op(str1, ==, dimap_search(dimap, key1, dflt_entry));
  3733. tt_ptr_op(str3, ==, dimap_search(dimap, key3, dflt_entry));
  3734. tt_ptr_op(str2, ==, dimap_search(dimap, key2, dflt_entry));
  3735. tt_ptr_op(dflt_entry, ==, dimap_search(dimap, key4, dflt_entry));
  3736. done:
  3737. dimap_free(dimap, tor_free_);
  3738. }
  3739. /**
  3740. * Test counting high bits
  3741. */
  3742. static void
  3743. test_util_n_bits_set(void *ptr)
  3744. {
  3745. (void)ptr;
  3746. tt_int_op(0,OP_EQ, n_bits_set_u8(0));
  3747. tt_int_op(1,OP_EQ, n_bits_set_u8(1));
  3748. tt_int_op(3,OP_EQ, n_bits_set_u8(7));
  3749. tt_int_op(1,OP_EQ, n_bits_set_u8(8));
  3750. tt_int_op(2,OP_EQ, n_bits_set_u8(129));
  3751. tt_int_op(8,OP_EQ, n_bits_set_u8(255));
  3752. done:
  3753. ;
  3754. }
  3755. /**
  3756. * Test LHS whitespace (and comment) eater
  3757. */
  3758. static void
  3759. test_util_eat_whitespace(void *ptr)
  3760. {
  3761. const char ws[] = { ' ', '\t', '\r' }; /* Except NL */
  3762. char str[80];
  3763. size_t i;
  3764. (void)ptr;
  3765. /* Try one leading ws */
  3766. strlcpy(str, "fuubaar", sizeof(str));
  3767. for (i = 0; i < sizeof(ws); ++i) {
  3768. str[0] = ws[i];
  3769. tt_ptr_op(str + 1,OP_EQ, eat_whitespace(str));
  3770. tt_ptr_op(str + 1,OP_EQ, eat_whitespace_eos(str, str + strlen(str)));
  3771. tt_ptr_op(str + 1,OP_EQ, eat_whitespace_no_nl(str));
  3772. tt_ptr_op(str + 1,OP_EQ, eat_whitespace_eos_no_nl(str, str + strlen(str)));
  3773. }
  3774. str[0] = '\n';
  3775. tt_ptr_op(str + 1,OP_EQ, eat_whitespace(str));
  3776. tt_ptr_op(str + 1,OP_EQ, eat_whitespace_eos(str, str + strlen(str)));
  3777. tt_ptr_op(str,OP_EQ, eat_whitespace_no_nl(str));
  3778. tt_ptr_op(str,OP_EQ, eat_whitespace_eos_no_nl(str, str + strlen(str)));
  3779. /* Empty string */
  3780. strlcpy(str, "", sizeof(str));
  3781. tt_ptr_op(str,OP_EQ, eat_whitespace(str));
  3782. tt_ptr_op(str,OP_EQ, eat_whitespace_eos(str, str));
  3783. tt_ptr_op(str,OP_EQ, eat_whitespace_no_nl(str));
  3784. tt_ptr_op(str,OP_EQ, eat_whitespace_eos_no_nl(str, str));
  3785. /* Only ws */
  3786. strlcpy(str, " \t\r\n", sizeof(str));
  3787. tt_ptr_op(str + strlen(str),OP_EQ, eat_whitespace(str));
  3788. tt_ptr_op(str + strlen(str),OP_EQ,
  3789. eat_whitespace_eos(str, str + strlen(str)));
  3790. tt_ptr_op(str + strlen(str) - 1,OP_EQ,
  3791. eat_whitespace_no_nl(str));
  3792. tt_ptr_op(str + strlen(str) - 1,OP_EQ,
  3793. eat_whitespace_eos_no_nl(str, str + strlen(str)));
  3794. strlcpy(str, " \t\r ", 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),OP_EQ, eat_whitespace_no_nl(str));
  3799. tt_ptr_op(str + strlen(str),OP_EQ,
  3800. eat_whitespace_eos_no_nl(str, str + strlen(str)));
  3801. /* Multiple ws */
  3802. strlcpy(str, "fuubaar", sizeof(str));
  3803. for (i = 0; i < sizeof(ws); ++i)
  3804. str[i] = ws[i];
  3805. tt_ptr_op(str + sizeof(ws),OP_EQ, eat_whitespace(str));
  3806. tt_ptr_op(str + sizeof(ws),OP_EQ,
  3807. eat_whitespace_eos(str, str + strlen(str)));
  3808. tt_ptr_op(str + sizeof(ws),OP_EQ, eat_whitespace_no_nl(str));
  3809. tt_ptr_op(str + sizeof(ws),OP_EQ,
  3810. eat_whitespace_eos_no_nl(str, str + strlen(str)));
  3811. /* Eat comment */
  3812. strlcpy(str, "# Comment \n No Comment", sizeof(str));
  3813. tt_str_op("No Comment",OP_EQ, eat_whitespace(str));
  3814. tt_str_op("No Comment",OP_EQ, eat_whitespace_eos(str, str + strlen(str)));
  3815. tt_ptr_op(str,OP_EQ, eat_whitespace_no_nl(str));
  3816. tt_ptr_op(str,OP_EQ, eat_whitespace_eos_no_nl(str, str + strlen(str)));
  3817. /* Eat comment & ws mix */
  3818. strlcpy(str, " # \t Comment \n\t\nNo Comment", sizeof(str));
  3819. tt_str_op("No Comment",OP_EQ, eat_whitespace(str));
  3820. tt_str_op("No Comment",OP_EQ, eat_whitespace_eos(str, str + strlen(str)));
  3821. tt_ptr_op(str + 1,OP_EQ, eat_whitespace_no_nl(str));
  3822. tt_ptr_op(str + 1,OP_EQ, eat_whitespace_eos_no_nl(str, str + strlen(str)));
  3823. /* Eat entire comment */
  3824. strlcpy(str, "#Comment", sizeof(str));
  3825. tt_ptr_op(str + strlen(str),OP_EQ, eat_whitespace(str));
  3826. tt_ptr_op(str + strlen(str),OP_EQ,
  3827. eat_whitespace_eos(str, str + strlen(str)));
  3828. tt_ptr_op(str,OP_EQ, eat_whitespace_no_nl(str));
  3829. tt_ptr_op(str,OP_EQ, eat_whitespace_eos_no_nl(str, str + strlen(str)));
  3830. /* Blank line, then comment */
  3831. strlcpy(str, " \t\n # Comment", sizeof(str));
  3832. tt_ptr_op(str + strlen(str),OP_EQ, eat_whitespace(str));
  3833. tt_ptr_op(str + strlen(str),OP_EQ,
  3834. eat_whitespace_eos(str, str + strlen(str)));
  3835. tt_ptr_op(str + 2,OP_EQ, eat_whitespace_no_nl(str));
  3836. tt_ptr_op(str + 2,OP_EQ, eat_whitespace_eos_no_nl(str, str + strlen(str)));
  3837. done:
  3838. ;
  3839. }
  3840. /** Return a newly allocated smartlist containing the lines of text in
  3841. * <b>lines</b>. The returned strings are heap-allocated, and must be
  3842. * freed by the caller.
  3843. *
  3844. * XXXX? Move to container.[hc] ? */
  3845. static smartlist_t *
  3846. smartlist_new_from_text_lines(const char *lines)
  3847. {
  3848. smartlist_t *sl = smartlist_new();
  3849. char *last_line;
  3850. smartlist_split_string(sl, lines, "\n", 0, 0);
  3851. last_line = smartlist_pop_last(sl);
  3852. if (last_line != NULL && *last_line != '\0') {
  3853. smartlist_add(sl, last_line);
  3854. } else {
  3855. tor_free(last_line);
  3856. }
  3857. return sl;
  3858. }
  3859. /** Test smartlist_new_from_text_lines */
  3860. static void
  3861. test_util_sl_new_from_text_lines(void *ptr)
  3862. {
  3863. (void)ptr;
  3864. { /* Normal usage */
  3865. smartlist_t *sl = smartlist_new_from_text_lines("foo\nbar\nbaz\n");
  3866. int sl_len = smartlist_len(sl);
  3867. tt_want_int_op(sl_len, OP_EQ, 3);
  3868. if (sl_len > 0) tt_want_str_op(smartlist_get(sl, 0), OP_EQ, "foo");
  3869. if (sl_len > 1) tt_want_str_op(smartlist_get(sl, 1), OP_EQ, "bar");
  3870. if (sl_len > 2) tt_want_str_op(smartlist_get(sl, 2), OP_EQ, "baz");
  3871. SMARTLIST_FOREACH(sl, void *, x, tor_free(x));
  3872. smartlist_free(sl);
  3873. }
  3874. { /* No final newline */
  3875. smartlist_t *sl = smartlist_new_from_text_lines("foo\nbar\nbaz");
  3876. int sl_len = smartlist_len(sl);
  3877. tt_want_int_op(sl_len, OP_EQ, 3);
  3878. if (sl_len > 0) tt_want_str_op(smartlist_get(sl, 0), OP_EQ, "foo");
  3879. if (sl_len > 1) tt_want_str_op(smartlist_get(sl, 1), OP_EQ, "bar");
  3880. if (sl_len > 2) tt_want_str_op(smartlist_get(sl, 2), OP_EQ, "baz");
  3881. SMARTLIST_FOREACH(sl, void *, x, tor_free(x));
  3882. smartlist_free(sl);
  3883. }
  3884. { /* No newlines */
  3885. smartlist_t *sl = smartlist_new_from_text_lines("foo");
  3886. int sl_len = smartlist_len(sl);
  3887. tt_want_int_op(sl_len, OP_EQ, 1);
  3888. if (sl_len > 0) tt_want_str_op(smartlist_get(sl, 0), OP_EQ, "foo");
  3889. SMARTLIST_FOREACH(sl, void *, x, tor_free(x));
  3890. smartlist_free(sl);
  3891. }
  3892. { /* No text at all */
  3893. smartlist_t *sl = smartlist_new_from_text_lines("");
  3894. int sl_len = smartlist_len(sl);
  3895. tt_want_int_op(sl_len, OP_EQ, 0);
  3896. SMARTLIST_FOREACH(sl, void *, x, tor_free(x));
  3897. smartlist_free(sl);
  3898. }
  3899. }
  3900. static void
  3901. test_util_envnames(void *ptr)
  3902. {
  3903. (void) ptr;
  3904. tt_assert(environment_variable_names_equal("abc", "abc"));
  3905. tt_assert(environment_variable_names_equal("abc", "abc="));
  3906. tt_assert(environment_variable_names_equal("abc", "abc=def"));
  3907. tt_assert(environment_variable_names_equal("abc=def", "abc"));
  3908. tt_assert(environment_variable_names_equal("abc=def", "abc=ghi"));
  3909. tt_assert(environment_variable_names_equal("abc", "abc"));
  3910. tt_assert(environment_variable_names_equal("abc", "abc="));
  3911. tt_assert(environment_variable_names_equal("abc", "abc=def"));
  3912. tt_assert(environment_variable_names_equal("abc=def", "abc"));
  3913. tt_assert(environment_variable_names_equal("abc=def", "abc=ghi"));
  3914. tt_assert(!environment_variable_names_equal("abc", "abcd"));
  3915. tt_assert(!environment_variable_names_equal("abc=", "abcd"));
  3916. tt_assert(!environment_variable_names_equal("abc=", "abcd"));
  3917. tt_assert(!environment_variable_names_equal("abc=", "def"));
  3918. tt_assert(!environment_variable_names_equal("abc=", "def="));
  3919. tt_assert(!environment_variable_names_equal("abc=x", "def=x"));
  3920. tt_assert(!environment_variable_names_equal("", "a=def"));
  3921. /* A bit surprising. */
  3922. tt_assert(environment_variable_names_equal("", "=def"));
  3923. tt_assert(environment_variable_names_equal("=y", "=x"));
  3924. done:
  3925. ;
  3926. }
  3927. /** Test process_environment_make */
  3928. static void
  3929. test_util_make_environment(void *ptr)
  3930. {
  3931. const char *env_vars_string =
  3932. "PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/bin\n"
  3933. "HOME=/home/foozer\n";
  3934. const char expected_windows_env_block[] =
  3935. "HOME=/home/foozer\000"
  3936. "PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/bin\000"
  3937. "\000";
  3938. size_t expected_windows_env_block_len =
  3939. sizeof(expected_windows_env_block) - 1;
  3940. smartlist_t *env_vars = smartlist_new_from_text_lines(env_vars_string);
  3941. smartlist_t *env_vars_sorted = smartlist_new();
  3942. smartlist_t *env_vars_in_unixoid_env_block_sorted = smartlist_new();
  3943. process_environment_t *env;
  3944. (void)ptr;
  3945. env = process_environment_make(env_vars);
  3946. /* Check that the Windows environment block is correct. */
  3947. tt_want(tor_memeq(expected_windows_env_block, env->windows_environment_block,
  3948. expected_windows_env_block_len));
  3949. /* Now for the Unixoid environment block. We don't care which order
  3950. * these environment variables are in, so we sort both lists first. */
  3951. smartlist_add_all(env_vars_sorted, env_vars);
  3952. {
  3953. char **v;
  3954. for (v = env->unixoid_environment_block; *v; ++v) {
  3955. smartlist_add(env_vars_in_unixoid_env_block_sorted, *v);
  3956. }
  3957. }
  3958. smartlist_sort_strings(env_vars_sorted);
  3959. smartlist_sort_strings(env_vars_in_unixoid_env_block_sorted);
  3960. tt_want_int_op(smartlist_len(env_vars_sorted), OP_EQ,
  3961. smartlist_len(env_vars_in_unixoid_env_block_sorted));
  3962. {
  3963. int len = smartlist_len(env_vars_sorted);
  3964. int i;
  3965. if (smartlist_len(env_vars_in_unixoid_env_block_sorted) < len) {
  3966. len = smartlist_len(env_vars_in_unixoid_env_block_sorted);
  3967. }
  3968. for (i = 0; i < len; ++i) {
  3969. tt_want_str_op(smartlist_get(env_vars_sorted, i), OP_EQ,
  3970. smartlist_get(env_vars_in_unixoid_env_block_sorted, i));
  3971. }
  3972. }
  3973. /* Clean up. */
  3974. smartlist_free(env_vars_in_unixoid_env_block_sorted);
  3975. smartlist_free(env_vars_sorted);
  3976. SMARTLIST_FOREACH(env_vars, char *, x, tor_free(x));
  3977. smartlist_free(env_vars);
  3978. process_environment_free(env);
  3979. }
  3980. /** Test set_environment_variable_in_smartlist */
  3981. static void
  3982. test_util_set_env_var_in_sl(void *ptr)
  3983. {
  3984. /* The environment variables in these strings are in arbitrary
  3985. * order; we sort the resulting lists before comparing them.
  3986. *
  3987. * (They *will not* end up in the order shown in
  3988. * expected_resulting_env_vars_string.) */
  3989. const char *base_env_vars_string =
  3990. "PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/bin\n"
  3991. "HOME=/home/foozer\n"
  3992. "TERM=xterm\n"
  3993. "SHELL=/bin/ksh\n"
  3994. "USER=foozer\n"
  3995. "LOGNAME=foozer\n"
  3996. "USERNAME=foozer\n"
  3997. "LANG=en_US.utf8\n"
  3998. ;
  3999. const char *new_env_vars_string =
  4000. "TERM=putty\n"
  4001. "DISPLAY=:18.0\n"
  4002. ;
  4003. const char *expected_resulting_env_vars_string =
  4004. "PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/bin\n"
  4005. "HOME=/home/foozer\n"
  4006. "TERM=putty\n"
  4007. "SHELL=/bin/ksh\n"
  4008. "USER=foozer\n"
  4009. "LOGNAME=foozer\n"
  4010. "USERNAME=foozer\n"
  4011. "LANG=en_US.utf8\n"
  4012. "DISPLAY=:18.0\n"
  4013. ;
  4014. smartlist_t *merged_env_vars =
  4015. smartlist_new_from_text_lines(base_env_vars_string);
  4016. smartlist_t *new_env_vars =
  4017. smartlist_new_from_text_lines(new_env_vars_string);
  4018. smartlist_t *expected_resulting_env_vars =
  4019. smartlist_new_from_text_lines(expected_resulting_env_vars_string);
  4020. /* Elements of merged_env_vars are heap-allocated, and must be
  4021. * freed. Some of them are (or should) be freed by
  4022. * set_environment_variable_in_smartlist.
  4023. *
  4024. * Elements of new_env_vars are heap-allocated, but are copied into
  4025. * merged_env_vars, so they are not freed separately at the end of
  4026. * the function.
  4027. *
  4028. * Elements of expected_resulting_env_vars are heap-allocated, and
  4029. * must be freed. */
  4030. (void)ptr;
  4031. SMARTLIST_FOREACH(new_env_vars, char *, env_var,
  4032. set_environment_variable_in_smartlist(merged_env_vars,
  4033. env_var,
  4034. tor_free_,
  4035. 1));
  4036. smartlist_sort_strings(merged_env_vars);
  4037. smartlist_sort_strings(expected_resulting_env_vars);
  4038. tt_want_int_op(smartlist_len(merged_env_vars), OP_EQ,
  4039. smartlist_len(expected_resulting_env_vars));
  4040. {
  4041. int len = smartlist_len(merged_env_vars);
  4042. int i;
  4043. if (smartlist_len(expected_resulting_env_vars) < len) {
  4044. len = smartlist_len(expected_resulting_env_vars);
  4045. }
  4046. for (i = 0; i < len; ++i) {
  4047. tt_want_str_op(smartlist_get(merged_env_vars, i), OP_EQ,
  4048. smartlist_get(expected_resulting_env_vars, i));
  4049. }
  4050. }
  4051. /* Clean up. */
  4052. SMARTLIST_FOREACH(merged_env_vars, char *, x, tor_free(x));
  4053. smartlist_free(merged_env_vars);
  4054. smartlist_free(new_env_vars);
  4055. SMARTLIST_FOREACH(expected_resulting_env_vars, char *, x, tor_free(x));
  4056. smartlist_free(expected_resulting_env_vars);
  4057. }
  4058. static void
  4059. test_util_weak_random(void *arg)
  4060. {
  4061. int i, j, n[16];
  4062. tor_weak_rng_t rng;
  4063. (void) arg;
  4064. tor_init_weak_random(&rng, (unsigned)time(NULL));
  4065. for (i = 1; i <= 256; ++i) {
  4066. for (j=0;j<100;++j) {
  4067. int r = tor_weak_random_range(&rng, i);
  4068. tt_int_op(0, OP_LE, r);
  4069. tt_int_op(r, OP_LT, i);
  4070. }
  4071. }
  4072. memset(n,0,sizeof(n));
  4073. for (j=0;j<8192;++j) {
  4074. n[tor_weak_random_range(&rng, 16)]++;
  4075. }
  4076. for (i=0;i<16;++i)
  4077. tt_int_op(n[i], OP_GT, 0);
  4078. done:
  4079. ;
  4080. }
  4081. static void
  4082. test_util_mathlog(void *arg)
  4083. {
  4084. double d;
  4085. (void) arg;
  4086. d = tor_mathlog(2.718281828);
  4087. tt_double_op(fabs(d - 1.0), OP_LT, .000001);
  4088. d = tor_mathlog(10);
  4089. tt_double_op(fabs(d - 2.30258509), OP_LT, .000001);
  4090. done:
  4091. ;
  4092. }
  4093. static void
  4094. test_util_fraction(void *arg)
  4095. {
  4096. uint64_t a,b;
  4097. (void)arg;
  4098. a = 99; b = 30;
  4099. simplify_fraction64(&a,&b);
  4100. tt_u64_op(a, OP_EQ, 33);
  4101. tt_u64_op(b, OP_EQ, 10);
  4102. a = 3000000; b = 10000000;
  4103. simplify_fraction64(&a,&b);
  4104. tt_u64_op(a, OP_EQ, 3);
  4105. tt_u64_op(b, OP_EQ, 10);
  4106. a = 0; b = 15;
  4107. simplify_fraction64(&a,&b);
  4108. tt_u64_op(a, OP_EQ, 0);
  4109. tt_u64_op(b, OP_EQ, 1);
  4110. done:
  4111. ;
  4112. }
  4113. static void
  4114. test_util_round_to_next_multiple_of(void *arg)
  4115. {
  4116. (void)arg;
  4117. tt_u64_op(round_uint64_to_next_multiple_of(0,1), ==, 0);
  4118. tt_u64_op(round_uint64_to_next_multiple_of(0,7), ==, 0);
  4119. tt_u64_op(round_uint64_to_next_multiple_of(99,1), ==, 99);
  4120. tt_u64_op(round_uint64_to_next_multiple_of(99,7), ==, 105);
  4121. tt_u64_op(round_uint64_to_next_multiple_of(99,9), ==, 99);
  4122. tt_u64_op(round_uint64_to_next_multiple_of(UINT64_MAX,2), ==,
  4123. UINT64_MAX);
  4124. tt_int_op(round_uint32_to_next_multiple_of(0,1), ==, 0);
  4125. tt_int_op(round_uint32_to_next_multiple_of(0,7), ==, 0);
  4126. tt_int_op(round_uint32_to_next_multiple_of(99,1), ==, 99);
  4127. tt_int_op(round_uint32_to_next_multiple_of(99,7), ==, 105);
  4128. tt_int_op(round_uint32_to_next_multiple_of(99,9), ==, 99);
  4129. tt_int_op(round_uint32_to_next_multiple_of(UINT32_MAX,2), ==,
  4130. UINT32_MAX);
  4131. tt_uint_op(round_to_next_multiple_of(0,1), ==, 0);
  4132. tt_uint_op(round_to_next_multiple_of(0,7), ==, 0);
  4133. tt_uint_op(round_to_next_multiple_of(99,1), ==, 99);
  4134. tt_uint_op(round_to_next_multiple_of(99,7), ==, 105);
  4135. tt_uint_op(round_to_next_multiple_of(99,9), ==, 99);
  4136. tt_uint_op(round_to_next_multiple_of(UINT_MAX,2), ==,
  4137. UINT_MAX);
  4138. done:
  4139. ;
  4140. }
  4141. static void
  4142. test_util_laplace(void *arg)
  4143. {
  4144. /* Sample values produced using Python's SciPy:
  4145. *
  4146. * >>> from scipy.stats import laplace
  4147. * >>> laplace.ppf([-0.01, 0.0, 0.01, 0.5, 0.51, 0.99, 1.0, 1.01],
  4148. ... loc = 24, scale = 24)
  4149. * array([ nan, -inf, -69.88855213, 24. ,
  4150. * 24.48486498, 117.88855213, inf, nan])
  4151. */
  4152. const double mu = 24.0, b = 24.0;
  4153. const double delta_f = 15.0, epsilon = 0.3; /* b = 15.0 / 0.3 = 50.0 */
  4154. (void)arg;
  4155. tt_i64_op(INT64_MIN, ==, sample_laplace_distribution(mu, b, 0.0));
  4156. tt_i64_op(-69, ==, sample_laplace_distribution(mu, b, 0.01));
  4157. tt_i64_op(24, ==, sample_laplace_distribution(mu, b, 0.5));
  4158. tt_i64_op(24, ==, sample_laplace_distribution(mu, b, 0.51));
  4159. tt_i64_op(117, ==, sample_laplace_distribution(mu, b, 0.99));
  4160. /* >>> laplace.ppf([0.0, 0.1, 0.25, 0.5, 0.75, 0.9, 0.99],
  4161. * ... loc = 0, scale = 50)
  4162. * array([ -inf, -80.47189562, -34.65735903, 0. ,
  4163. * 34.65735903, 80.47189562, 195.60115027])
  4164. */
  4165. tt_i64_op(INT64_MIN + 20, ==,
  4166. add_laplace_noise(20, 0.0, delta_f, epsilon));
  4167. tt_i64_op(-60, ==, add_laplace_noise(20, 0.1, delta_f, epsilon));
  4168. tt_i64_op(-14, ==, add_laplace_noise(20, 0.25, delta_f, epsilon));
  4169. tt_i64_op(20, ==, add_laplace_noise(20, 0.5, delta_f, epsilon));
  4170. tt_i64_op(54, ==, add_laplace_noise(20, 0.75, delta_f, epsilon));
  4171. tt_i64_op(100, ==, add_laplace_noise(20, 0.9, delta_f, epsilon));
  4172. tt_i64_op(215, ==, add_laplace_noise(20, 0.99, delta_f, epsilon));
  4173. /* Test extreme values of signal with maximally negative values of noise
  4174. * 1.0000000000000002 is the smallest number > 1
  4175. * 0.0000000000000002 is the double epsilon (error when calculating near 1)
  4176. * this is approximately 1/(2^52)
  4177. * per https://en.wikipedia.org/wiki/Double_precision
  4178. * (let's not descend into the world of subnormals)
  4179. * >>> laplace.ppf([0, 0.0000000000000002], loc = 0, scale = 1)
  4180. * array([ -inf, -35.45506713])
  4181. */
  4182. const double noscale_df = 1.0, noscale_eps = 1.0;
  4183. tt_i64_op(INT64_MIN, ==,
  4184. add_laplace_noise(0, 0.0, noscale_df, noscale_eps));
  4185. /* is it clipped to INT64_MIN? */
  4186. tt_i64_op(INT64_MIN, ==,
  4187. add_laplace_noise(-1, 0.0, noscale_df, noscale_eps));
  4188. tt_i64_op(INT64_MIN, ==,
  4189. add_laplace_noise(INT64_MIN, 0.0,
  4190. noscale_df, noscale_eps));
  4191. /* ... even when scaled? */
  4192. tt_i64_op(INT64_MIN, ==,
  4193. add_laplace_noise(0, 0.0, delta_f, epsilon));
  4194. tt_i64_op(INT64_MIN, ==,
  4195. add_laplace_noise(0, 0.0,
  4196. DBL_MAX, 1));
  4197. tt_i64_op(INT64_MIN, ==,
  4198. add_laplace_noise(INT64_MIN, 0.0,
  4199. DBL_MAX, 1));
  4200. /* does it play nice with INT64_MAX? */
  4201. tt_i64_op((INT64_MIN + INT64_MAX), ==,
  4202. add_laplace_noise(INT64_MAX, 0.0,
  4203. noscale_df, noscale_eps));
  4204. /* do near-zero fractional values work? */
  4205. const double min_dbl_error = 0.0000000000000002;
  4206. tt_i64_op(-35, ==,
  4207. add_laplace_noise(0, min_dbl_error,
  4208. noscale_df, noscale_eps));
  4209. tt_i64_op(INT64_MIN, ==,
  4210. add_laplace_noise(INT64_MIN, min_dbl_error,
  4211. noscale_df, noscale_eps));
  4212. tt_i64_op((-35 + INT64_MAX), ==,
  4213. add_laplace_noise(INT64_MAX, min_dbl_error,
  4214. noscale_df, noscale_eps));
  4215. tt_i64_op(INT64_MIN, ==,
  4216. add_laplace_noise(0, min_dbl_error,
  4217. DBL_MAX, 1));
  4218. tt_i64_op((INT64_MAX + INT64_MIN), ==,
  4219. add_laplace_noise(INT64_MAX, min_dbl_error,
  4220. DBL_MAX, 1));
  4221. tt_i64_op(INT64_MIN, ==,
  4222. add_laplace_noise(INT64_MIN, min_dbl_error,
  4223. DBL_MAX, 1));
  4224. /* does it play nice with INT64_MAX? */
  4225. tt_i64_op((INT64_MAX - 35), ==,
  4226. add_laplace_noise(INT64_MAX, min_dbl_error,
  4227. noscale_df, noscale_eps));
  4228. /* Test extreme values of signal with maximally positive values of noise
  4229. * 1.0000000000000002 is the smallest number > 1
  4230. * 0.9999999999999998 is the greatest number < 1 by calculation
  4231. * per https://en.wikipedia.org/wiki/Double_precision
  4232. * >>> laplace.ppf([1.0, 0.9999999999999998], loc = 0, scale = 1)
  4233. * array([inf, 35.35050621])
  4234. * but the function rejects p == 1.0, so we just use max_dbl_lt_one
  4235. */
  4236. const double max_dbl_lt_one = 0.9999999999999998;
  4237. /* do near-one fractional values work? */
  4238. tt_i64_op(35, ==,
  4239. add_laplace_noise(0, max_dbl_lt_one, noscale_df, noscale_eps));
  4240. /* is it clipped to INT64_MAX? */
  4241. tt_i64_op(INT64_MAX, ==,
  4242. add_laplace_noise(INT64_MAX - 35, max_dbl_lt_one,
  4243. noscale_df, noscale_eps));
  4244. tt_i64_op(INT64_MAX, ==,
  4245. add_laplace_noise(INT64_MAX - 34, max_dbl_lt_one,
  4246. noscale_df, noscale_eps));
  4247. tt_i64_op(INT64_MAX, ==,
  4248. add_laplace_noise(INT64_MAX, max_dbl_lt_one,
  4249. noscale_df, noscale_eps));
  4250. /* ... even when scaled? */
  4251. tt_i64_op(INT64_MAX, ==,
  4252. add_laplace_noise(INT64_MAX, max_dbl_lt_one,
  4253. delta_f, epsilon));
  4254. tt_i64_op((INT64_MIN + INT64_MAX), ==,
  4255. add_laplace_noise(INT64_MIN, max_dbl_lt_one,
  4256. DBL_MAX, 1));
  4257. tt_i64_op(INT64_MAX, ==,
  4258. add_laplace_noise(INT64_MAX, max_dbl_lt_one,
  4259. DBL_MAX, 1));
  4260. /* does it play nice with INT64_MIN? */
  4261. tt_i64_op((INT64_MIN + 35), ==,
  4262. add_laplace_noise(INT64_MIN, max_dbl_lt_one,
  4263. noscale_df, noscale_eps));
  4264. done:
  4265. ;
  4266. }
  4267. static void
  4268. test_util_clamp_double_to_int64(void *arg)
  4269. {
  4270. (void)arg;
  4271. tt_i64_op(INT64_MIN, ==, clamp_double_to_int64(-INFINITY_DBL));
  4272. tt_i64_op(INT64_MIN, ==,
  4273. clamp_double_to_int64(-1.0 * pow(2.0, 64.0) - 1.0));
  4274. tt_i64_op(INT64_MIN, ==,
  4275. clamp_double_to_int64(-1.0 * pow(2.0, 63.0) - 1.0));
  4276. tt_i64_op(((uint64_t) -1) << 53, ==,
  4277. clamp_double_to_int64(-1.0 * pow(2.0, 53.0)));
  4278. tt_i64_op((((uint64_t) -1) << 53) + 1, ==,
  4279. clamp_double_to_int64(-1.0 * pow(2.0, 53.0) + 1.0));
  4280. tt_i64_op(-1, ==, clamp_double_to_int64(-1.0));
  4281. tt_i64_op(0, ==, clamp_double_to_int64(-0.9));
  4282. tt_i64_op(0, ==, clamp_double_to_int64(-0.1));
  4283. tt_i64_op(0, ==, clamp_double_to_int64(0.0));
  4284. tt_i64_op(0, ==, clamp_double_to_int64(NAN_DBL));
  4285. tt_i64_op(0, ==, clamp_double_to_int64(0.1));
  4286. tt_i64_op(0, ==, clamp_double_to_int64(0.9));
  4287. tt_i64_op(1, ==, clamp_double_to_int64(1.0));
  4288. tt_i64_op((((int64_t) 1) << 53) - 1, ==,
  4289. clamp_double_to_int64(pow(2.0, 53.0) - 1.0));
  4290. tt_i64_op(((int64_t) 1) << 53, ==,
  4291. clamp_double_to_int64(pow(2.0, 53.0)));
  4292. tt_i64_op(INT64_MAX, ==,
  4293. clamp_double_to_int64(pow(2.0, 63.0)));
  4294. tt_i64_op(INT64_MAX, ==,
  4295. clamp_double_to_int64(pow(2.0, 64.0)));
  4296. tt_i64_op(INT64_MAX, ==, clamp_double_to_int64(INFINITY_DBL));
  4297. done:
  4298. ;
  4299. }
  4300. #ifdef FD_CLOEXEC
  4301. #define CAN_CHECK_CLOEXEC
  4302. static int
  4303. fd_is_cloexec(tor_socket_t fd)
  4304. {
  4305. int flags = fcntl(fd, F_GETFD, 0);
  4306. return (flags & FD_CLOEXEC) == FD_CLOEXEC;
  4307. }
  4308. #endif
  4309. #ifndef _WIN32
  4310. #define CAN_CHECK_NONBLOCK
  4311. static int
  4312. fd_is_nonblocking(tor_socket_t fd)
  4313. {
  4314. int flags = fcntl(fd, F_GETFL, 0);
  4315. return (flags & O_NONBLOCK) == O_NONBLOCK;
  4316. }
  4317. #endif
  4318. #define ERRNO_IS_EPROTO(e) (e == SOCK_ERRNO(EPROTONOSUPPORT))
  4319. #define SOCK_ERR_IS_EPROTO(s) ERRNO_IS_EPROTO(tor_socket_errno(s))
  4320. /* Test for tor_open_socket*, using IPv4 or IPv6 depending on arg. */
  4321. static void
  4322. test_util_socket(void *arg)
  4323. {
  4324. const int domain = !strcmp(arg, "4") ? AF_INET : AF_INET6;
  4325. tor_socket_t fd1 = TOR_INVALID_SOCKET;
  4326. tor_socket_t fd2 = TOR_INVALID_SOCKET;
  4327. tor_socket_t fd3 = TOR_INVALID_SOCKET;
  4328. tor_socket_t fd4 = TOR_INVALID_SOCKET;
  4329. int n = get_n_open_sockets();
  4330. TT_BLATHER(("Starting with %d open sockets.", n));
  4331. (void)arg;
  4332. fd1 = tor_open_socket_with_extensions(domain, SOCK_STREAM, 0, 0, 0);
  4333. int err = tor_socket_errno(fd1);
  4334. if (fd1 < 0 && (err == SOCK_ERRNO(EPROTONOSUPPORT) ||
  4335. err == SOCK_ERRNO(EAFNOSUPPORT))) {
  4336. /* Assume we're on an IPv4-only or IPv6-only system, and give up now. */
  4337. goto done;
  4338. }
  4339. fd2 = tor_open_socket_with_extensions(domain, SOCK_STREAM, 0, 0, 1);
  4340. tt_assert(SOCKET_OK(fd1));
  4341. tt_assert(SOCKET_OK(fd2));
  4342. tt_int_op(get_n_open_sockets(), OP_EQ, n + 2);
  4343. //fd3 = tor_open_socket_with_extensions(domain, SOCK_STREAM, 0, 1, 0);
  4344. //fd4 = tor_open_socket_with_extensions(domain, SOCK_STREAM, 0, 1, 1);
  4345. fd3 = tor_open_socket(domain, SOCK_STREAM, 0);
  4346. fd4 = tor_open_socket_nonblocking(domain, SOCK_STREAM, 0);
  4347. tt_assert(SOCKET_OK(fd3));
  4348. tt_assert(SOCKET_OK(fd4));
  4349. tt_int_op(get_n_open_sockets(), OP_EQ, n + 4);
  4350. #ifdef CAN_CHECK_CLOEXEC
  4351. tt_int_op(fd_is_cloexec(fd1), OP_EQ, 0);
  4352. tt_int_op(fd_is_cloexec(fd2), OP_EQ, 0);
  4353. tt_int_op(fd_is_cloexec(fd3), OP_EQ, 1);
  4354. tt_int_op(fd_is_cloexec(fd4), OP_EQ, 1);
  4355. #endif
  4356. #ifdef CAN_CHECK_NONBLOCK
  4357. tt_int_op(fd_is_nonblocking(fd1), OP_EQ, 0);
  4358. tt_int_op(fd_is_nonblocking(fd2), OP_EQ, 1);
  4359. tt_int_op(fd_is_nonblocking(fd3), OP_EQ, 0);
  4360. tt_int_op(fd_is_nonblocking(fd4), OP_EQ, 1);
  4361. #endif
  4362. tor_assert(tor_close_socket == tor_close_socket__real);
  4363. /* we use close_socket__real here so that coverity can tell that we are
  4364. * really closing these sockets. */
  4365. tor_close_socket__real(fd1);
  4366. tor_close_socket__real(fd2);
  4367. fd1 = fd2 = TOR_INVALID_SOCKET;
  4368. tt_int_op(get_n_open_sockets(), OP_EQ, n + 2);
  4369. tor_close_socket__real(fd3);
  4370. tor_close_socket__real(fd4);
  4371. fd3 = fd4 = TOR_INVALID_SOCKET;
  4372. tt_int_op(get_n_open_sockets(), OP_EQ, n);
  4373. done:
  4374. if (SOCKET_OK(fd1))
  4375. tor_close_socket__real(fd1);
  4376. if (SOCKET_OK(fd2))
  4377. tor_close_socket__real(fd2);
  4378. if (SOCKET_OK(fd3))
  4379. tor_close_socket__real(fd3);
  4380. if (SOCKET_OK(fd4))
  4381. tor_close_socket__real(fd4);
  4382. }
  4383. #if 0
  4384. static int
  4385. is_there_a_localhost(int family)
  4386. {
  4387. tor_socket_t s;
  4388. s = tor_open_socket(family, SOCK_STREAM, IPPROTO_TCP);
  4389. tor_assert(SOCKET_OK(s));
  4390. int result = 0;
  4391. if (family == AF_INET) {
  4392. struct sockaddr_in s_in;
  4393. memset(&s_in, 0, sizeof(s_in));
  4394. s_in.sin_family = AF_INET;
  4395. s_in.sin_addr.s_addr = htonl(0x7f000001);
  4396. s_in.sin_port = 0;
  4397. if (bind(s, (void*)&s_in, sizeof(s_in)) == 0) {
  4398. result = 1;
  4399. }
  4400. } else if (family == AF_INET6) {
  4401. struct sockaddr_in6 sin6;
  4402. memset(&sin6, 0, sizeof(sin6));
  4403. sin6.sin6_family = AF_INET6;
  4404. sin6.sin6_addr.s6_addr[15] = 1;
  4405. sin6.sin6_port = 0;
  4406. }
  4407. tor_close_socket(s);
  4408. return result;
  4409. }
  4410. #endif
  4411. /* Test for socketpair and ersatz_socketpair(). We test them both, since
  4412. * the latter is a tolerably good way to exersize tor_accept_socket(). */
  4413. static void
  4414. test_util_socketpair(void *arg)
  4415. {
  4416. const int ersatz = !strcmp(arg, "1");
  4417. int (*const tor_socketpair_fn)(int, int, int, tor_socket_t[2]) =
  4418. ersatz ? tor_ersatz_socketpair : tor_socketpair;
  4419. int n = get_n_open_sockets();
  4420. tor_socket_t fds[2] = {TOR_INVALID_SOCKET, TOR_INVALID_SOCKET};
  4421. const int family = AF_UNIX;
  4422. int socketpair_result = 0;
  4423. socketpair_result = tor_socketpair_fn(family, SOCK_STREAM, 0, fds);
  4424. #ifdef __FreeBSD__
  4425. /* If there is no 127.0.0.1, tor_ersatz_socketpair will and must fail.
  4426. * Otherwise, we risk exposing a socketpair on a routable IP address. (Some
  4427. * BSD jails use a routable address for localhost. Fortunately, they have
  4428. * the real AF_UNIX socketpair.) */
  4429. if (ersatz && socketpair_result < 0) {
  4430. /* In my testing, an IPv6-only FreeBSD jail without ::1 returned EINVAL.
  4431. * Assume we're on a machine without 127.0.0.1 or ::1 and give up now. */
  4432. tt_skip();
  4433. }
  4434. #endif
  4435. tt_int_op(0, OP_EQ, socketpair_result);
  4436. tt_assert(SOCKET_OK(fds[0]));
  4437. tt_assert(SOCKET_OK(fds[1]));
  4438. tt_int_op(get_n_open_sockets(), OP_EQ, n + 2);
  4439. #ifdef CAN_CHECK_CLOEXEC
  4440. tt_int_op(fd_is_cloexec(fds[0]), OP_EQ, 1);
  4441. tt_int_op(fd_is_cloexec(fds[1]), OP_EQ, 1);
  4442. #endif
  4443. #ifdef CAN_CHECK_NONBLOCK
  4444. tt_int_op(fd_is_nonblocking(fds[0]), OP_EQ, 0);
  4445. tt_int_op(fd_is_nonblocking(fds[1]), OP_EQ, 0);
  4446. #endif
  4447. done:
  4448. if (SOCKET_OK(fds[0]))
  4449. tor_close_socket(fds[0]);
  4450. if (SOCKET_OK(fds[1]))
  4451. tor_close_socket(fds[1]);
  4452. }
  4453. #undef SOCKET_EPROTO
  4454. static void
  4455. test_util_max_mem(void *arg)
  4456. {
  4457. size_t memory1, memory2;
  4458. int r, r2;
  4459. (void) arg;
  4460. r = get_total_system_memory(&memory1);
  4461. r2 = get_total_system_memory(&memory2);
  4462. tt_int_op(r, OP_EQ, r2);
  4463. tt_uint_op(memory2, OP_EQ, memory1);
  4464. TT_BLATHER(("System memory: "U64_FORMAT, U64_PRINTF_ARG(memory1)));
  4465. if (r==0) {
  4466. /* You have at least a megabyte. */
  4467. tt_uint_op(memory1, OP_GT, (1<<20));
  4468. } else {
  4469. /* You do not have a petabyte. */
  4470. #if SIZEOF_SIZE_T == SIZEOF_UINT64_T
  4471. tt_u64_op(memory1, OP_LT, (U64_LITERAL(1)<<50));
  4472. #endif
  4473. }
  4474. done:
  4475. ;
  4476. }
  4477. static void
  4478. test_util_hostname_validation(void *arg)
  4479. {
  4480. (void)arg;
  4481. // Lets try valid hostnames first.
  4482. tt_assert(string_is_valid_hostname("torproject.org"));
  4483. tt_assert(string_is_valid_hostname("ocw.mit.edu"));
  4484. tt_assert(string_is_valid_hostname("i.4cdn.org"));
  4485. tt_assert(string_is_valid_hostname("stanford.edu"));
  4486. tt_assert(string_is_valid_hostname("multiple-words-with-hypens.jp"));
  4487. // Subdomain name cannot start with '-' or '_'.
  4488. tt_assert(!string_is_valid_hostname("-torproject.org"));
  4489. tt_assert(!string_is_valid_hostname("subdomain.-domain.org"));
  4490. tt_assert(!string_is_valid_hostname("-subdomain.domain.org"));
  4491. tt_assert(!string_is_valid_hostname("___abc.org"));
  4492. // Hostnames cannot contain non-alphanumeric characters.
  4493. tt_assert(!string_is_valid_hostname("%%domain.\\org."));
  4494. tt_assert(!string_is_valid_hostname("***x.net"));
  4495. tt_assert(!string_is_valid_hostname("\xff\xffxyz.org"));
  4496. tt_assert(!string_is_valid_hostname("word1 word2.net"));
  4497. // Test workaround for nytimes.com stupidity, technically invalid,
  4498. // but we allow it since they are big, even though they are failing to
  4499. // comply with a ~30 year old standard.
  4500. tt_assert(string_is_valid_hostname("core3_euw1.fabrik.nytimes.com"));
  4501. // Firefox passes FQDNs with trailing '.'s directly to the SOCKS proxy,
  4502. // which is redundant since the spec states DOMAINNAME addresses are fully
  4503. // qualified. While unusual, this should be tollerated.
  4504. tt_assert(string_is_valid_hostname("core9_euw1.fabrik.nytimes.com."));
  4505. tt_assert(!string_is_valid_hostname("..washingtonpost.is.better.com"));
  4506. tt_assert(!string_is_valid_hostname("so.is..ft.com"));
  4507. tt_assert(!string_is_valid_hostname("..."));
  4508. // XXX: do we allow single-label DNS names?
  4509. // We shouldn't for SOCKS (spec says "contains a fully-qualified domain name"
  4510. // but only test pathologically malformed traling '.' cases for now.
  4511. tt_assert(!string_is_valid_hostname("."));
  4512. tt_assert(!string_is_valid_hostname(".."));
  4513. done:
  4514. return;
  4515. }
  4516. static void
  4517. test_util_ipv4_validation(void *arg)
  4518. {
  4519. (void)arg;
  4520. tt_assert(string_is_valid_ipv4_address("192.168.0.1"));
  4521. tt_assert(string_is_valid_ipv4_address("8.8.8.8"));
  4522. tt_assert(!string_is_valid_ipv4_address("abcd"));
  4523. tt_assert(!string_is_valid_ipv4_address("300.300.300.300"));
  4524. tt_assert(!string_is_valid_ipv4_address("8.8."));
  4525. done:
  4526. return;
  4527. }
  4528. static void
  4529. test_util_writepid(void *arg)
  4530. {
  4531. (void) arg;
  4532. char *contents = NULL;
  4533. const char *fname = get_fname("tmp_pid");
  4534. unsigned long pid;
  4535. char c;
  4536. write_pidfile(fname);
  4537. contents = read_file_to_str(fname, 0, NULL);
  4538. tt_assert(contents);
  4539. int n = tor_sscanf(contents, "%lu\n%c", &pid, &c);
  4540. tt_int_op(n, OP_EQ, 1);
  4541. #ifdef _WIN32
  4542. tt_uint_op(pid, OP_EQ, _getpid());
  4543. #else
  4544. tt_uint_op(pid, OP_EQ, getpid());
  4545. #endif
  4546. done:
  4547. tor_free(contents);
  4548. }
  4549. static void
  4550. test_util_get_avail_disk_space(void *arg)
  4551. {
  4552. (void) arg;
  4553. int64_t val;
  4554. /* No answer for nonexistent directory */
  4555. val = tor_get_avail_disk_space("/akljasdfklsajdklasjkldjsa");
  4556. tt_i64_op(val, OP_EQ, -1);
  4557. /* Try the current directory */
  4558. val = tor_get_avail_disk_space(".");
  4559. #if !defined(HAVE_STATVFS) && !defined(_WIN32)
  4560. tt_i64_op(val, OP_EQ, -1); /* You don't have an implementation for this */
  4561. #else
  4562. tt_i64_op(val, OP_GT, 0); /* You have some space. */
  4563. tt_i64_op(val, OP_LT, ((int64_t)1)<<56); /* You don't have a zebibyte */
  4564. #endif
  4565. done:
  4566. ;
  4567. }
  4568. static void
  4569. test_util_touch_file(void *arg)
  4570. {
  4571. (void) arg;
  4572. const char *fname = get_fname("touch");
  4573. const time_t now = time(NULL);
  4574. struct stat st;
  4575. write_bytes_to_file(fname, "abc", 3, 1);
  4576. tt_int_op(0, OP_EQ, stat(fname, &st));
  4577. /* A subtle point: the filesystem time is not necessarily equal to the
  4578. * system clock time, since one can be using a monotonic clock, or coarse
  4579. * monotonic clock, or whatever. So we might wind up with an mtime a few
  4580. * microseconds ago. Let's just give it a lot of wiggle room. */
  4581. tt_i64_op(st.st_mtime, OP_GE, now - 1);
  4582. const time_t five_sec_ago = now - 5;
  4583. struct utimbuf u = { five_sec_ago, five_sec_ago };
  4584. tt_int_op(0, OP_EQ, utime(fname, &u));
  4585. tt_int_op(0, OP_EQ, stat(fname, &st));
  4586. /* Let's hope that utime/stat give the same second as a round-trip? */
  4587. tt_i64_op(st.st_mtime, OP_EQ, five_sec_ago);
  4588. /* Finally we can touch the file */
  4589. tt_int_op(0, OP_EQ, touch_file(fname));
  4590. tt_int_op(0, OP_EQ, stat(fname, &st));
  4591. tt_i64_op(st.st_mtime, OP_GE, now-1);
  4592. done:
  4593. ;
  4594. }
  4595. #ifndef _WIN32
  4596. static void
  4597. test_util_pwdb(void *arg)
  4598. {
  4599. (void) arg;
  4600. const struct passwd *me = NULL, *me2, *me3;
  4601. char *name = NULL;
  4602. char *dir = NULL;
  4603. /* Uncached case. */
  4604. /* Let's assume that we exist. */
  4605. me = tor_getpwuid(getuid());
  4606. tt_assert(me != NULL);
  4607. name = tor_strdup(me->pw_name);
  4608. /* Uncached case */
  4609. me2 = tor_getpwnam(name);
  4610. tt_assert(me2 != NULL);
  4611. tt_int_op(me2->pw_uid, OP_EQ, getuid());
  4612. /* Cached case */
  4613. me3 = tor_getpwuid(getuid());
  4614. tt_assert(me3 != NULL);
  4615. tt_str_op(me3->pw_name, OP_EQ, name);
  4616. me3 = tor_getpwnam(name);
  4617. tt_assert(me3 != NULL);
  4618. tt_int_op(me3->pw_uid, OP_EQ, getuid());
  4619. dir = get_user_homedir(name);
  4620. tt_assert(dir != NULL);
  4621. /* Try failing cases. First find a user that doesn't exist by name */
  4622. char randbytes[4];
  4623. char badname[9];
  4624. int i, found=0;
  4625. for (i = 0; i < 100; ++i) {
  4626. crypto_rand(randbytes, sizeof(randbytes));
  4627. base16_encode(badname, sizeof(badname), randbytes, sizeof(randbytes));
  4628. if (tor_getpwnam(badname) == NULL) {
  4629. found = 1;
  4630. break;
  4631. }
  4632. }
  4633. tt_assert(found);
  4634. tor_free(dir);
  4635. /* We should do a LOG_ERR */
  4636. setup_full_capture_of_logs(LOG_ERR);
  4637. dir = get_user_homedir(badname);
  4638. tt_assert(dir == NULL);
  4639. expect_log_msg_containing("not found");
  4640. tt_int_op(smartlist_len(mock_saved_logs()), OP_EQ, 1);
  4641. teardown_capture_of_logs();
  4642. /* Now try to find a user that doesn't exist by ID. */
  4643. found = 0;
  4644. for (i = 0; i < 1000; ++i) {
  4645. uid_t u;
  4646. crypto_rand((char*)&u, sizeof(u));
  4647. if (tor_getpwuid(u) == NULL) {
  4648. found = 1;
  4649. break;
  4650. }
  4651. }
  4652. tt_assert(found);
  4653. done:
  4654. tor_free(name);
  4655. tor_free(dir);
  4656. teardown_capture_of_logs();
  4657. }
  4658. #endif
  4659. static void
  4660. test_util_calloc_check(void *arg)
  4661. {
  4662. (void) arg;
  4663. /* Easy cases that are good. */
  4664. tt_assert(size_mul_check(0,0));
  4665. tt_assert(size_mul_check(0,100));
  4666. tt_assert(size_mul_check(100,0));
  4667. tt_assert(size_mul_check(100,100));
  4668. /* Harder cases that are still good. */
  4669. tt_assert(size_mul_check(SIZE_MAX, 1));
  4670. tt_assert(size_mul_check(1, SIZE_MAX));
  4671. tt_assert(size_mul_check(SIZE_MAX / 10, 9));
  4672. tt_assert(size_mul_check(11, SIZE_MAX / 12));
  4673. const size_t sqrt_size_max_p1 = ((size_t)1) << (sizeof(size_t) * 4);
  4674. tt_assert(size_mul_check(sqrt_size_max_p1, sqrt_size_max_p1 - 1));
  4675. /* Cases that overflow */
  4676. tt_assert(! size_mul_check(SIZE_MAX, 2));
  4677. tt_assert(! size_mul_check(2, SIZE_MAX));
  4678. tt_assert(! size_mul_check(SIZE_MAX / 10, 11));
  4679. tt_assert(! size_mul_check(11, SIZE_MAX / 10));
  4680. tt_assert(! size_mul_check(SIZE_MAX / 8, 9));
  4681. tt_assert(! size_mul_check(sqrt_size_max_p1, sqrt_size_max_p1));
  4682. done:
  4683. ;
  4684. }
  4685. static void
  4686. test_util_monotonic_time(void *arg)
  4687. {
  4688. (void)arg;
  4689. monotime_t mt1, mt2;
  4690. monotime_coarse_t mtc1, mtc2;
  4691. uint64_t nsec1, nsec2, usec1, msec1;
  4692. uint64_t nsecc1, nsecc2, usecc1, msecc1;
  4693. monotime_init();
  4694. monotime_get(&mt1);
  4695. monotime_coarse_get(&mtc1);
  4696. nsec1 = monotime_absolute_nsec();
  4697. usec1 = monotime_absolute_usec();
  4698. msec1 = monotime_absolute_msec();
  4699. nsecc1 = monotime_coarse_absolute_nsec();
  4700. usecc1 = monotime_coarse_absolute_usec();
  4701. msecc1 = monotime_coarse_absolute_msec();
  4702. tor_sleep_msec(200);
  4703. monotime_get(&mt2);
  4704. monotime_coarse_get(&mtc2);
  4705. nsec2 = monotime_absolute_nsec();
  4706. nsecc2 = monotime_coarse_absolute_nsec();
  4707. /* We need to be a little careful here since we don't know the system load.
  4708. */
  4709. tt_i64_op(monotime_diff_msec(&mt1, &mt2), OP_GE, 175);
  4710. tt_i64_op(monotime_diff_msec(&mt1, &mt2), OP_LT, 1000);
  4711. tt_i64_op(monotime_coarse_diff_msec(&mtc1, &mtc2), OP_GE, 125);
  4712. tt_i64_op(monotime_coarse_diff_msec(&mtc1, &mtc2), OP_LT, 1000);
  4713. tt_u64_op(nsec2-nsec1, OP_GE, 175000000);
  4714. tt_u64_op(nsec2-nsec1, OP_LT, 1000000000);
  4715. tt_u64_op(nsecc2-nsecc1, OP_GE, 125000000);
  4716. tt_u64_op(nsecc2-nsecc1, OP_LT, 1000000000);
  4717. tt_u64_op(msec1, OP_GE, nsec1 / 1000000);
  4718. tt_u64_op(usec1, OP_GE, nsec1 / 1000);
  4719. tt_u64_op(msecc1, OP_GE, nsecc1 / 1000000);
  4720. tt_u64_op(usecc1, OP_GE, nsecc1 / 1000);
  4721. tt_u64_op(msec1, OP_LE, nsec1 / 1000000 + 1);
  4722. tt_u64_op(usec1, OP_LE, nsec1 / 1000 + 1000);
  4723. tt_u64_op(msecc1, OP_LE, nsecc1 / 1000000 + 1);
  4724. tt_u64_op(usecc1, OP_LE, nsecc1 / 1000 + 1000);
  4725. done:
  4726. ;
  4727. }
  4728. static void
  4729. test_util_monotonic_time_ratchet(void *arg)
  4730. {
  4731. (void)arg;
  4732. monotime_init();
  4733. monotime_reset_ratchets_for_testing();
  4734. /* win32, performance counter ratchet. */
  4735. tt_i64_op(100, OP_EQ, ratchet_performance_counter(100));
  4736. tt_i64_op(101, OP_EQ, ratchet_performance_counter(101));
  4737. tt_i64_op(2000, OP_EQ, ratchet_performance_counter(2000));
  4738. tt_i64_op(2000, OP_EQ, ratchet_performance_counter(100));
  4739. tt_i64_op(2005, OP_EQ, ratchet_performance_counter(105));
  4740. tt_i64_op(3005, OP_EQ, ratchet_performance_counter(1105));
  4741. tt_i64_op(3005, OP_EQ, ratchet_performance_counter(1000));
  4742. tt_i64_op(3010, OP_EQ, ratchet_performance_counter(1005));
  4743. /* win32, GetTickCounts32 ratchet-and-rollover-detector. */
  4744. const int64_t R = ((int64_t)1) << 32;
  4745. tt_i64_op(5, OP_EQ, ratchet_coarse_performance_counter(5));
  4746. tt_i64_op(1000, OP_EQ, ratchet_coarse_performance_counter(1000));
  4747. tt_i64_op(5+R, OP_EQ, ratchet_coarse_performance_counter(5));
  4748. tt_i64_op(10+R, OP_EQ, ratchet_coarse_performance_counter(10));
  4749. tt_i64_op(4+R*2, OP_EQ, ratchet_coarse_performance_counter(4));
  4750. /* gettimeofday regular ratchet. */
  4751. struct timeval tv_in = {0,0}, tv_out;
  4752. tv_in.tv_usec = 9000;
  4753. ratchet_timeval(&tv_in, &tv_out);
  4754. tt_int_op(tv_out.tv_usec, OP_EQ, 9000);
  4755. tt_i64_op(tv_out.tv_sec, OP_EQ, 0);
  4756. tv_in.tv_sec = 1337;
  4757. tv_in.tv_usec = 0;
  4758. ratchet_timeval(&tv_in, &tv_out);
  4759. tt_int_op(tv_out.tv_usec, OP_EQ, 0);
  4760. tt_i64_op(tv_out.tv_sec, OP_EQ, 1337);
  4761. tv_in.tv_sec = 1336;
  4762. tv_in.tv_usec = 500000;
  4763. ratchet_timeval(&tv_in, &tv_out);
  4764. tt_int_op(tv_out.tv_usec, OP_EQ, 0);
  4765. tt_i64_op(tv_out.tv_sec, OP_EQ, 1337);
  4766. tv_in.tv_sec = 1337;
  4767. tv_in.tv_usec = 0;
  4768. ratchet_timeval(&tv_in, &tv_out);
  4769. tt_int_op(tv_out.tv_usec, OP_EQ, 500000);
  4770. tt_i64_op(tv_out.tv_sec, OP_EQ, 1337);
  4771. tv_in.tv_sec = 1337;
  4772. tv_in.tv_usec = 600000;
  4773. ratchet_timeval(&tv_in, &tv_out);
  4774. tt_int_op(tv_out.tv_usec, OP_EQ, 100000);
  4775. tt_i64_op(tv_out.tv_sec, OP_EQ, 1338);
  4776. tv_in.tv_sec = 1000;
  4777. tv_in.tv_usec = 1000;
  4778. ratchet_timeval(&tv_in, &tv_out);
  4779. tt_int_op(tv_out.tv_usec, OP_EQ, 100000);
  4780. tt_i64_op(tv_out.tv_sec, OP_EQ, 1338);
  4781. tv_in.tv_sec = 2000;
  4782. tv_in.tv_usec = 2000;
  4783. ratchet_timeval(&tv_in, &tv_out);
  4784. tt_int_op(tv_out.tv_usec, OP_EQ, 101000);
  4785. tt_i64_op(tv_out.tv_sec, OP_EQ, 2338);
  4786. done:
  4787. ;
  4788. }
  4789. static void
  4790. test_util_htonll(void *arg)
  4791. {
  4792. (void)arg;
  4793. #ifdef WORDS_BIGENDIAN
  4794. const uint64_t res_be = 0x8877665544332211;
  4795. #else
  4796. const uint64_t res_le = 0x1122334455667788;
  4797. #endif
  4798. tt_u64_op(0, OP_EQ, tor_htonll(0));
  4799. tt_u64_op(0, OP_EQ, tor_ntohll(0));
  4800. tt_u64_op(UINT64_MAX, OP_EQ, tor_htonll(UINT64_MAX));
  4801. tt_u64_op(UINT64_MAX, OP_EQ, tor_ntohll(UINT64_MAX));
  4802. #ifdef WORDS_BIGENDIAN
  4803. tt_u64_op(res_be, OP_EQ, tor_htonll(0x8877665544332211));
  4804. tt_u64_op(res_be, OP_EQ, tor_ntohll(0x8877665544332211));
  4805. #else
  4806. tt_u64_op(res_le, OP_EQ, tor_htonll(0x8877665544332211));
  4807. tt_u64_op(res_le, OP_EQ, tor_ntohll(0x8877665544332211));
  4808. #endif
  4809. done:
  4810. ;
  4811. }
  4812. #define UTIL_LEGACY(name) \
  4813. { #name, test_util_ ## name , 0, NULL, NULL }
  4814. #define UTIL_TEST(name, flags) \
  4815. { #name, test_util_ ## name, flags, NULL, NULL }
  4816. #ifdef _WIN32
  4817. #define UTIL_TEST_NO_WIN(n, f) { #n, NULL, TT_SKIP, NULL, NULL }
  4818. #define UTIL_TEST_WIN_ONLY(n, f) UTIL_TEST(n, (f))
  4819. #define UTIL_LEGACY_NO_WIN(n) UTIL_TEST_NO_WIN(n, 0)
  4820. #else
  4821. #define UTIL_TEST_NO_WIN(n, f) UTIL_TEST(n, (f))
  4822. #define UTIL_TEST_WIN_ONLY(n, f) { #n, NULL, TT_SKIP, NULL, NULL }
  4823. #define UTIL_LEGACY_NO_WIN(n) UTIL_LEGACY(n)
  4824. #endif
  4825. struct testcase_t util_tests[] = {
  4826. UTIL_LEGACY(time),
  4827. UTIL_TEST(parse_http_time, 0),
  4828. UTIL_LEGACY(config_line),
  4829. UTIL_LEGACY(config_line_quotes),
  4830. UTIL_LEGACY(config_line_comment_character),
  4831. UTIL_LEGACY(config_line_escaped_content),
  4832. UTIL_LEGACY(config_line_crlf),
  4833. UTIL_LEGACY_NO_WIN(expand_filename),
  4834. UTIL_LEGACY(escape_string_socks),
  4835. UTIL_LEGACY(string_is_key_value),
  4836. UTIL_LEGACY(strmisc),
  4837. UTIL_TEST(parse_integer, 0),
  4838. UTIL_LEGACY(pow2),
  4839. UTIL_LEGACY(gzip),
  4840. UTIL_TEST(gzip_compression_bomb, TT_FORK),
  4841. UTIL_LEGACY(datadir),
  4842. UTIL_LEGACY(memarea),
  4843. UTIL_LEGACY(control_formats),
  4844. UTIL_LEGACY(mmap),
  4845. UTIL_TEST(sscanf, TT_FORK),
  4846. UTIL_LEGACY(format_time_interval),
  4847. UTIL_LEGACY(path_is_relative),
  4848. UTIL_LEGACY(strtok),
  4849. UTIL_LEGACY(di_ops),
  4850. UTIL_TEST(di_map, 0),
  4851. UTIL_TEST(round_to_next_multiple_of, 0),
  4852. UTIL_TEST(laplace, 0),
  4853. UTIL_TEST(clamp_double_to_int64, 0),
  4854. UTIL_TEST(find_str_at_start_of_line, 0),
  4855. UTIL_TEST(string_is_C_identifier, 0),
  4856. UTIL_TEST(asprintf, 0),
  4857. UTIL_TEST(listdir, 0),
  4858. UTIL_TEST(parent_dir, 0),
  4859. UTIL_TEST(ftruncate, 0),
  4860. UTIL_TEST(num_cpus, 0),
  4861. UTIL_TEST_WIN_ONLY(load_win_lib, 0),
  4862. UTIL_TEST_NO_WIN(exit_status, 0),
  4863. UTIL_TEST_NO_WIN(string_from_pipe, 0),
  4864. UTIL_TEST(format_hex_number, 0),
  4865. UTIL_TEST(format_dec_number, 0),
  4866. UTIL_TEST(join_win_cmdline, 0),
  4867. UTIL_TEST(split_lines, 0),
  4868. UTIL_TEST(n_bits_set, 0),
  4869. UTIL_TEST(eat_whitespace, 0),
  4870. UTIL_TEST(sl_new_from_text_lines, 0),
  4871. UTIL_TEST(envnames, 0),
  4872. UTIL_TEST(make_environment, 0),
  4873. UTIL_TEST(set_env_var_in_sl, 0),
  4874. UTIL_TEST(read_file_eof_tiny_limit, 0),
  4875. UTIL_TEST(read_file_eof_one_loop_a, 0),
  4876. UTIL_TEST(read_file_eof_one_loop_b, 0),
  4877. UTIL_TEST(read_file_eof_two_loops, 0),
  4878. UTIL_TEST(read_file_eof_two_loops_b, 0),
  4879. UTIL_TEST(read_file_eof_zero_bytes, 0),
  4880. UTIL_TEST(write_chunks_to_file, 0),
  4881. UTIL_TEST(mathlog, 0),
  4882. UTIL_TEST(fraction, 0),
  4883. UTIL_TEST(weak_random, 0),
  4884. { "socket_ipv4", test_util_socket, TT_FORK, &passthrough_setup,
  4885. (void*)"4" },
  4886. { "socket_ipv6", test_util_socket, TT_FORK,
  4887. &passthrough_setup, (void*)"6" },
  4888. { "socketpair", test_util_socketpair, TT_FORK, &passthrough_setup,
  4889. (void*)"0" },
  4890. { "socketpair_ersatz", test_util_socketpair, TT_FORK,
  4891. &passthrough_setup, (void*)"1" },
  4892. UTIL_TEST(max_mem, 0),
  4893. UTIL_TEST(hostname_validation, 0),
  4894. UTIL_TEST(ipv4_validation, 0),
  4895. UTIL_TEST(writepid, 0),
  4896. UTIL_TEST(get_avail_disk_space, 0),
  4897. UTIL_TEST(touch_file, 0),
  4898. UTIL_TEST_NO_WIN(pwdb, TT_FORK),
  4899. UTIL_TEST(calloc_check, 0),
  4900. UTIL_TEST(monotonic_time, 0),
  4901. UTIL_TEST(monotonic_time_ratchet, TT_FORK),
  4902. UTIL_TEST(htonll, 0),
  4903. END_OF_TESTCASES
  4904. };