test_util.c 145 KB

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