test_util.c 150 KB

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