test_util.c 159 KB

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