test_util.c 108 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680
  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. #include "mempool.h"
  15. #include "memarea.h"
  16. #ifdef _WIN32
  17. #include <tchar.h>
  18. #endif
  19. #include <math.h>
  20. /* XXXX this is a minimal wrapper to make the unit tests compile with the
  21. * changed tor_timegm interface. */
  22. static time_t
  23. tor_timegm_wrapper(const struct tm *tm)
  24. {
  25. time_t t;
  26. if (tor_timegm(tm, &t) < 0)
  27. return -1;
  28. return t;
  29. }
  30. #define tor_timegm tor_timegm_wrapper
  31. static void
  32. test_util_read_until_eof_impl(const char *fname, size_t file_len,
  33. size_t read_limit)
  34. {
  35. char *fifo_name = NULL;
  36. char *test_str = NULL;
  37. char *str = NULL;
  38. size_t sz = 9999999;
  39. int fd = -1;
  40. int r;
  41. fifo_name = tor_strdup(get_fname(fname));
  42. test_str = tor_malloc(file_len);
  43. crypto_rand(test_str, file_len);
  44. r = write_bytes_to_file(fifo_name, test_str, file_len, 1);
  45. tt_int_op(r, ==, 0);
  46. fd = open(fifo_name, O_RDONLY|O_BINARY);
  47. tt_int_op(fd, >=, 0);
  48. str = read_file_to_str_until_eof(fd, read_limit, &sz);
  49. tt_assert(str != NULL);
  50. if (read_limit < file_len)
  51. tt_int_op(sz, ==, read_limit);
  52. else
  53. tt_int_op(sz, ==, file_len);
  54. test_mem_op(test_str, ==, str, sz);
  55. test_assert(str[sz] == '\0');
  56. done:
  57. unlink(fifo_name);
  58. tor_free(fifo_name);
  59. tor_free(test_str);
  60. tor_free(str);
  61. if (fd >= 0)
  62. close(fd);
  63. }
  64. static void
  65. test_util_read_file_eof_tiny_limit(void *arg)
  66. {
  67. (void)arg;
  68. // purposely set limit shorter than what we wrote to the FIFO to
  69. // test the maximum, and that it puts the NUL in the right spot
  70. test_util_read_until_eof_impl("tor_test_fifo_tiny", 5, 4);
  71. }
  72. static void
  73. test_util_read_file_eof_two_loops(void *arg)
  74. {
  75. (void)arg;
  76. // write more than 1024 bytes to the FIFO to test two passes through
  77. // the loop in the method; if the re-alloc size is changed this
  78. // should be updated as well.
  79. test_util_read_until_eof_impl("tor_test_fifo_2k", 2048, 10000);
  80. }
  81. static void
  82. test_util_read_file_eof_zero_bytes(void *arg)
  83. {
  84. (void)arg;
  85. // zero-byte fifo
  86. test_util_read_until_eof_impl("tor_test_fifo_empty", 0, 10000);
  87. }
  88. /* Test the basic expected behaviour for write_chunks_to_file.
  89. * NOTE: This will need to be updated if we ever change the tempfile location
  90. * or extension */
  91. static void
  92. test_util_write_chunks_to_file(void *arg)
  93. {
  94. char *fname = NULL;
  95. char *tempname = NULL;
  96. char *str = NULL;
  97. int r;
  98. struct stat st;
  99. /* These should be two different sizes to ensure the data is different
  100. * between the data file and the temp file's 'known string' */
  101. int temp_str_len = 1024;
  102. int data_str_len = 512;
  103. char *data_str = tor_malloc(data_str_len);
  104. char *temp_str = tor_malloc(temp_str_len);
  105. smartlist_t *chunks = smartlist_new();
  106. sized_chunk_t c = {data_str, data_str_len/2};
  107. sized_chunk_t c2 = {data_str + data_str_len/2, data_str_len/2};
  108. (void)arg;
  109. crypto_rand(temp_str, temp_str_len);
  110. crypto_rand(data_str, data_str_len);
  111. // Ensure it can write multiple chunks
  112. smartlist_add(chunks, &c);
  113. smartlist_add(chunks, &c2);
  114. /*
  115. * Check if it writes using a tempfile
  116. */
  117. fname = tor_strdup(get_fname("write_chunks_with_tempfile"));
  118. tor_asprintf(&tempname, "%s.tmp", fname);
  119. // write a known string to a file where the tempfile will be
  120. r = write_bytes_to_file(tempname, temp_str, temp_str_len, 1);
  121. tt_int_op(r, ==, 0);
  122. // call write_chunks_to_file
  123. r = write_chunks_to_file(fname, chunks, 1, 0);
  124. tt_int_op(r, ==, 0);
  125. // assert the file has been written (expected size)
  126. str = read_file_to_str(fname, RFTS_BIN, &st);
  127. tt_assert(str != NULL);
  128. tt_int_op(st.st_size, ==, data_str_len);
  129. test_mem_op(data_str, ==, str, data_str_len);
  130. tor_free(str);
  131. // assert that the tempfile is removed (should not leave artifacts)
  132. str = read_file_to_str(tempname, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
  133. tt_assert(str == NULL);
  134. // Remove old testfile for second test
  135. r = unlink(fname);
  136. tt_int_op(r, ==, 0);
  137. tor_free(fname);
  138. tor_free(tempname);
  139. /*
  140. * Check if it skips using a tempfile with flags
  141. */
  142. fname = tor_strdup(get_fname("write_chunks_with_no_tempfile"));
  143. tor_asprintf(&tempname, "%s.tmp", fname);
  144. // write a known string to a file where the tempfile will be
  145. r = write_bytes_to_file(tempname, temp_str, temp_str_len, 1);
  146. tt_int_op(r, ==, 0);
  147. // call write_chunks_to_file with no_tempfile = true
  148. r = write_chunks_to_file(fname, chunks, 1, 1);
  149. tt_int_op(r, ==, 0);
  150. // assert the file has been written (expected size)
  151. str = read_file_to_str(fname, RFTS_BIN, &st);
  152. tt_assert(str != NULL);
  153. tt_int_op(st.st_size, ==, data_str_len);
  154. test_mem_op(data_str, ==, str, data_str_len);
  155. tor_free(str);
  156. // assert the tempfile still contains the known string
  157. str = read_file_to_str(tempname, RFTS_BIN, &st);
  158. tt_assert(str != NULL);
  159. tt_int_op(st.st_size, ==, temp_str_len);
  160. test_mem_op(temp_str, ==, str, temp_str_len);
  161. done:
  162. unlink(fname);
  163. unlink(tempname);
  164. smartlist_free(chunks);
  165. tor_free(fname);
  166. tor_free(tempname);
  167. tor_free(str);
  168. tor_free(data_str);
  169. tor_free(temp_str);
  170. }
  171. static void
  172. test_util_time(void)
  173. {
  174. struct timeval start, end;
  175. struct tm a_time;
  176. char timestr[128];
  177. time_t t_res;
  178. int i;
  179. struct timeval tv;
  180. /* Test tv_udiff */
  181. start.tv_sec = 5;
  182. start.tv_usec = 5000;
  183. end.tv_sec = 5;
  184. end.tv_usec = 5000;
  185. test_eq(0L, tv_udiff(&start, &end));
  186. end.tv_usec = 7000;
  187. test_eq(2000L, tv_udiff(&start, &end));
  188. end.tv_sec = 6;
  189. test_eq(1002000L, tv_udiff(&start, &end));
  190. end.tv_usec = 0;
  191. test_eq(995000L, tv_udiff(&start, &end));
  192. end.tv_sec = 4;
  193. test_eq(-1005000L, tv_udiff(&start, &end));
  194. /* Test tor_timegm */
  195. /* The test values here are confirmed to be correct on a platform
  196. * with a working timegm. */
  197. a_time.tm_year = 2003-1900;
  198. a_time.tm_mon = 7;
  199. a_time.tm_mday = 30;
  200. a_time.tm_hour = 6;
  201. a_time.tm_min = 14;
  202. a_time.tm_sec = 55;
  203. test_eq((time_t) 1062224095UL, tor_timegm(&a_time));
  204. a_time.tm_year = 2004-1900; /* Try a leap year, after feb. */
  205. test_eq((time_t) 1093846495UL, tor_timegm(&a_time));
  206. a_time.tm_mon = 1; /* Try a leap year, in feb. */
  207. a_time.tm_mday = 10;
  208. test_eq((time_t) 1076393695UL, tor_timegm(&a_time));
  209. a_time.tm_mon = 0;
  210. a_time.tm_mday = 10;
  211. test_eq((time_t) 1073715295UL, tor_timegm(&a_time));
  212. a_time.tm_mon = 12; /* Wrong month, it's 0-based */
  213. a_time.tm_mday = 10;
  214. test_eq((time_t) -1, tor_timegm(&a_time));
  215. a_time.tm_mon = -1; /* Wrong month */
  216. a_time.tm_mday = 10;
  217. test_eq((time_t) -1, tor_timegm(&a_time));
  218. /* Test {format,parse}_rfc1123_time */
  219. format_rfc1123_time(timestr, 0);
  220. test_streq("Thu, 01 Jan 1970 00:00:00 GMT", timestr);
  221. format_rfc1123_time(timestr, (time_t)1091580502UL);
  222. test_streq("Wed, 04 Aug 2004 00:48:22 GMT", timestr);
  223. t_res = 0;
  224. i = parse_rfc1123_time(timestr, &t_res);
  225. test_eq(0,i);
  226. test_eq(t_res, (time_t)1091580502UL);
  227. /* The timezone doesn't matter */
  228. t_res = 0;
  229. test_eq(0, parse_rfc1123_time("Wed, 04 Aug 2004 00:48:22 ZUL", &t_res));
  230. test_eq(t_res, (time_t)1091580502UL);
  231. test_eq(-1, parse_rfc1123_time("Wed, zz Aug 2004 99-99x99 GMT", &t_res));
  232. test_eq(-1, parse_rfc1123_time("Wed, 32 Mar 2011 00:00:00 GMT", &t_res));
  233. test_eq(-1, parse_rfc1123_time("Wed, 30 Mar 2011 24:00:00 GMT", &t_res));
  234. test_eq(-1, parse_rfc1123_time("Wed, 30 Mar 2011 23:60:00 GMT", &t_res));
  235. test_eq(-1, parse_rfc1123_time("Wed, 30 Mar 2011 23:59:62 GMT", &t_res));
  236. test_eq(-1, parse_rfc1123_time("Wed, 30 Mar 1969 23:59:59 GMT", &t_res));
  237. test_eq(-1, parse_rfc1123_time("Wed, 30 Ene 2011 23:59:59 GMT", &t_res));
  238. test_eq(-1, parse_rfc1123_time("Wed, 30 Mar 2011 23:59:59 GM", &t_res));
  239. #if 0
  240. /* This fails, I imagine it's important and should be fixed? */
  241. test_eq(-1, parse_rfc1123_time("Wed, 29 Feb 2011 16:00:00 GMT", &t_res));
  242. /* Why is this string valid (ie. the test fails because it doesn't
  243. return -1)? */
  244. test_eq(-1, parse_rfc1123_time("Wed, 30 Mar 2011 23:59:61 GMT", &t_res));
  245. #endif
  246. /* Test parse_iso_time */
  247. t_res = 0;
  248. i = parse_iso_time("", &t_res);
  249. test_eq(-1, i);
  250. t_res = 0;
  251. i = parse_iso_time("2004-08-32 00:48:22", &t_res);
  252. test_eq(-1, i);
  253. t_res = 0;
  254. i = parse_iso_time("1969-08-03 00:48:22", &t_res);
  255. test_eq(-1, i);
  256. t_res = 0;
  257. i = parse_iso_time("2004-08-04 00:48:22", &t_res);
  258. test_eq(0,i);
  259. test_eq(t_res, (time_t)1091580502UL);
  260. t_res = 0;
  261. i = parse_iso_time("2004-8-4 0:48:22", &t_res);
  262. test_eq(0, i);
  263. test_eq(t_res, (time_t)1091580502UL);
  264. test_eq(-1, parse_iso_time("2004-08-zz 99-99x99 GMT", &t_res));
  265. test_eq(-1, parse_iso_time("2011-03-32 00:00:00 GMT", &t_res));
  266. test_eq(-1, parse_iso_time("2011-03-30 24:00:00 GMT", &t_res));
  267. test_eq(-1, parse_iso_time("2011-03-30 23:60:00 GMT", &t_res));
  268. test_eq(-1, parse_iso_time("2011-03-30 23:59:62 GMT", &t_res));
  269. test_eq(-1, parse_iso_time("1969-03-30 23:59:59 GMT", &t_res));
  270. test_eq(-1, parse_iso_time("2011-00-30 23:59:59 GMT", &t_res));
  271. test_eq(-1, parse_iso_time("2147483647-08-29 14:00:00", &t_res));
  272. test_eq(-1, parse_iso_time("2011-03-30 23:59", &t_res));
  273. /* Test tor_gettimeofday */
  274. end.tv_sec = 4;
  275. end.tv_usec = 999990;
  276. start.tv_sec = 1;
  277. start.tv_usec = 500;
  278. tor_gettimeofday(&start);
  279. /* now make sure time works. */
  280. tor_gettimeofday(&end);
  281. /* We might've timewarped a little. */
  282. tt_int_op(tv_udiff(&start, &end), >=, -5000);
  283. /* Test format_iso_time */
  284. tv.tv_sec = (time_t)1326296338;
  285. tv.tv_usec = 3060;
  286. format_iso_time(timestr, tv.tv_sec);
  287. test_streq("2012-01-11 15:38:58", timestr);
  288. /* The output of format_local_iso_time will vary by timezone, and setting
  289. our timezone for testing purposes would be a nontrivial flaky pain.
  290. Skip this test for now.
  291. format_local_iso_time(timestr, tv.tv_sec);
  292. test_streq("2012-01-11 10:38:58", timestr);
  293. */
  294. format_iso_time_nospace(timestr, tv.tv_sec);
  295. test_streq("2012-01-11T15:38:58", timestr);
  296. test_eq(strlen(timestr), ISO_TIME_LEN);
  297. format_iso_time_nospace_usec(timestr, &tv);
  298. test_streq("2012-01-11T15:38:58.003060", timestr);
  299. test_eq(strlen(timestr), ISO_TIME_USEC_LEN);
  300. done:
  301. ;
  302. }
  303. static void
  304. test_util_parse_http_time(void *arg)
  305. {
  306. struct tm a_time;
  307. char b[ISO_TIME_LEN+1];
  308. (void)arg;
  309. #define T(s) do { \
  310. format_iso_time(b, tor_timegm(&a_time)); \
  311. tt_str_op(b, ==, (s)); \
  312. b[0]='\0'; \
  313. } while (0)
  314. /* Test parse_http_time */
  315. test_eq(-1, parse_http_time("", &a_time));
  316. test_eq(-1, parse_http_time("Sunday, 32 Aug 2004 00:48:22 GMT", &a_time));
  317. test_eq(-1, parse_http_time("Sunday, 3 Aug 1869 00:48:22 GMT", &a_time));
  318. test_eq(-1, parse_http_time("Sunday, 32-Aug-94 00:48:22 GMT", &a_time));
  319. test_eq(-1, parse_http_time("Sunday, 3-Ago-04 00:48:22", &a_time));
  320. test_eq(-1, parse_http_time("Sunday, August the third", &a_time));
  321. test_eq(-1, parse_http_time("Wednesday,,04 Aug 1994 00:48:22 GMT", &a_time));
  322. test_eq(0, parse_http_time("Wednesday, 04 Aug 1994 00:48:22 GMT", &a_time));
  323. test_eq((time_t)775961302UL, tor_timegm(&a_time));
  324. T("1994-08-04 00:48:22");
  325. test_eq(0, parse_http_time("Wednesday, 4 Aug 1994 0:48:22 GMT", &a_time));
  326. test_eq((time_t)775961302UL, tor_timegm(&a_time));
  327. T("1994-08-04 00:48:22");
  328. test_eq(0, parse_http_time("Miercoles, 4 Aug 1994 0:48:22 GMT", &a_time));
  329. test_eq((time_t)775961302UL, tor_timegm(&a_time));
  330. T("1994-08-04 00:48:22");
  331. test_eq(0, parse_http_time("Wednesday, 04-Aug-94 00:48:22 GMT", &a_time));
  332. test_eq((time_t)775961302UL, tor_timegm(&a_time));
  333. T("1994-08-04 00:48:22");
  334. test_eq(0, parse_http_time("Wednesday, 4-Aug-94 0:48:22 GMT", &a_time));
  335. test_eq((time_t)775961302UL, tor_timegm(&a_time));
  336. T("1994-08-04 00:48:22");
  337. test_eq(0, parse_http_time("Miercoles, 4-Aug-94 0:48:22 GMT", &a_time));
  338. test_eq((time_t)775961302UL, tor_timegm(&a_time));
  339. T("1994-08-04 00:48:22");
  340. test_eq(0, parse_http_time("Wed Aug 04 00:48:22 1994", &a_time));
  341. test_eq((time_t)775961302UL, tor_timegm(&a_time));
  342. T("1994-08-04 00:48:22");
  343. test_eq(0, parse_http_time("Wed Aug 4 0:48:22 1994", &a_time));
  344. test_eq((time_t)775961302UL, tor_timegm(&a_time));
  345. T("1994-08-04 00:48:22");
  346. test_eq(0, parse_http_time("Mie Aug 4 0:48:22 1994", &a_time));
  347. test_eq((time_t)775961302UL, tor_timegm(&a_time));
  348. T("1994-08-04 00:48:22");
  349. test_eq(0, parse_http_time("Sun, 1 Jan 2012 00:00:00 GMT", &a_time));
  350. test_eq((time_t)1325376000UL, tor_timegm(&a_time));
  351. T("2012-01-01 00:00:00");
  352. test_eq(0, parse_http_time("Mon, 31 Dec 2012 00:00:00 GMT", &a_time));
  353. test_eq((time_t)1356912000UL, tor_timegm(&a_time));
  354. T("2012-12-31 00:00:00");
  355. test_eq(-1, parse_http_time("2004-08-zz 99-99x99 GMT", &a_time));
  356. test_eq(-1, parse_http_time("2011-03-32 00:00:00 GMT", &a_time));
  357. test_eq(-1, parse_http_time("2011-03-30 24:00:00 GMT", &a_time));
  358. test_eq(-1, parse_http_time("2011-03-30 23:60:00 GMT", &a_time));
  359. test_eq(-1, parse_http_time("2011-03-30 23:59:62 GMT", &a_time));
  360. test_eq(-1, parse_http_time("1969-03-30 23:59:59 GMT", &a_time));
  361. test_eq(-1, parse_http_time("2011-00-30 23:59:59 GMT", &a_time));
  362. test_eq(-1, parse_http_time("2011-03-30 23:59", &a_time));
  363. #undef T
  364. done:
  365. ;
  366. }
  367. static void
  368. test_util_config_line(void)
  369. {
  370. char buf[1024];
  371. char *k=NULL, *v=NULL;
  372. const char *str;
  373. /* Test parse_config_line_from_str */
  374. strlcpy(buf, "k v\n" " key value with spaces \n" "keykey val\n"
  375. "k2\n"
  376. "k3 \n" "\n" " \n" "#comment\n"
  377. "k4#a\n" "k5#abc\n" "k6 val #with comment\n"
  378. "kseven \"a quoted 'string\"\n"
  379. "k8 \"a \\x71uoted\\n\\\"str\\\\ing\\t\\001\\01\\1\\\"\"\n"
  380. "k9 a line that\\\n spans two lines.\n\n"
  381. "k10 more than\\\n one contin\\\nuation\n"
  382. "k11 \\\ncontinuation at the start\n"
  383. "k12 line with a\\\n#comment\n embedded\n"
  384. "k13\\\ncontinuation at the very start\n"
  385. "k14 a line that has a comment and # ends with a slash \\\n"
  386. "k15 this should be the next new line\n"
  387. "k16 a line that has a comment and # ends without a slash \n"
  388. "k17 this should be the next new line\n"
  389. , sizeof(buf));
  390. str = buf;
  391. str = parse_config_line_from_str(str, &k, &v);
  392. test_streq(k, "k");
  393. test_streq(v, "v");
  394. tor_free(k); tor_free(v);
  395. test_assert(!strcmpstart(str, "key value with"));
  396. str = parse_config_line_from_str(str, &k, &v);
  397. test_streq(k, "key");
  398. test_streq(v, "value with spaces");
  399. tor_free(k); tor_free(v);
  400. test_assert(!strcmpstart(str, "keykey"));
  401. str = parse_config_line_from_str(str, &k, &v);
  402. test_streq(k, "keykey");
  403. test_streq(v, "val");
  404. tor_free(k); tor_free(v);
  405. test_assert(!strcmpstart(str, "k2\n"));
  406. str = parse_config_line_from_str(str, &k, &v);
  407. test_streq(k, "k2");
  408. test_streq(v, "");
  409. tor_free(k); tor_free(v);
  410. test_assert(!strcmpstart(str, "k3 \n"));
  411. str = parse_config_line_from_str(str, &k, &v);
  412. test_streq(k, "k3");
  413. test_streq(v, "");
  414. tor_free(k); tor_free(v);
  415. test_assert(!strcmpstart(str, "#comment"));
  416. str = parse_config_line_from_str(str, &k, &v);
  417. test_streq(k, "k4");
  418. test_streq(v, "");
  419. tor_free(k); tor_free(v);
  420. test_assert(!strcmpstart(str, "k5#abc"));
  421. str = parse_config_line_from_str(str, &k, &v);
  422. test_streq(k, "k5");
  423. test_streq(v, "");
  424. tor_free(k); tor_free(v);
  425. test_assert(!strcmpstart(str, "k6"));
  426. str = parse_config_line_from_str(str, &k, &v);
  427. test_streq(k, "k6");
  428. test_streq(v, "val");
  429. tor_free(k); tor_free(v);
  430. test_assert(!strcmpstart(str, "kseven"));
  431. str = parse_config_line_from_str(str, &k, &v);
  432. test_streq(k, "kseven");
  433. test_streq(v, "a quoted \'string");
  434. tor_free(k); tor_free(v);
  435. test_assert(!strcmpstart(str, "k8 "));
  436. str = parse_config_line_from_str(str, &k, &v);
  437. test_streq(k, "k8");
  438. test_streq(v, "a quoted\n\"str\\ing\t\x01\x01\x01\"");
  439. tor_free(k); tor_free(v);
  440. str = parse_config_line_from_str(str, &k, &v);
  441. test_streq(k, "k9");
  442. test_streq(v, "a line that spans two lines.");
  443. tor_free(k); tor_free(v);
  444. str = parse_config_line_from_str(str, &k, &v);
  445. test_streq(k, "k10");
  446. test_streq(v, "more than one continuation");
  447. tor_free(k); tor_free(v);
  448. str = parse_config_line_from_str(str, &k, &v);
  449. test_streq(k, "k11");
  450. test_streq(v, "continuation at the start");
  451. tor_free(k); tor_free(v);
  452. str = parse_config_line_from_str(str, &k, &v);
  453. test_streq(k, "k12");
  454. test_streq(v, "line with a embedded");
  455. tor_free(k); tor_free(v);
  456. str = parse_config_line_from_str(str, &k, &v);
  457. test_streq(k, "k13");
  458. test_streq(v, "continuation at the very start");
  459. tor_free(k); tor_free(v);
  460. str = parse_config_line_from_str(str, &k, &v);
  461. test_streq(k, "k14");
  462. test_streq(v, "a line that has a comment and" );
  463. tor_free(k); tor_free(v);
  464. str = parse_config_line_from_str(str, &k, &v);
  465. test_streq(k, "k15");
  466. test_streq(v, "this should be the next new line");
  467. tor_free(k); tor_free(v);
  468. str = parse_config_line_from_str(str, &k, &v);
  469. test_streq(k, "k16");
  470. test_streq(v, "a line that has a comment and" );
  471. tor_free(k); tor_free(v);
  472. str = parse_config_line_from_str(str, &k, &v);
  473. test_streq(k, "k17");
  474. test_streq(v, "this should be the next new line");
  475. tor_free(k); tor_free(v);
  476. test_streq(str, "");
  477. done:
  478. tor_free(k);
  479. tor_free(v);
  480. }
  481. static void
  482. test_util_config_line_quotes(void)
  483. {
  484. char buf1[1024];
  485. char buf2[128];
  486. char buf3[128];
  487. char buf4[128];
  488. char *k=NULL, *v=NULL;
  489. const char *str;
  490. /* Test parse_config_line_from_str */
  491. strlcpy(buf1, "kTrailingSpace \"quoted value\" \n"
  492. "kTrailingGarbage \"quoted value\"trailing garbage\n"
  493. , sizeof(buf1));
  494. strlcpy(buf2, "kTrailingSpaceAndGarbage \"quoted value\" trailing space+g\n"
  495. , sizeof(buf2));
  496. strlcpy(buf3, "kMultilineTrailingSpace \"mline\\ \nvalue w/ trailing sp\"\n"
  497. , sizeof(buf3));
  498. strlcpy(buf4, "kMultilineNoTrailingBackslash \"naked multiline\nvalue\"\n"
  499. , sizeof(buf4));
  500. str = buf1;
  501. str = parse_config_line_from_str(str, &k, &v);
  502. test_streq(k, "kTrailingSpace");
  503. test_streq(v, "quoted value");
  504. tor_free(k); tor_free(v);
  505. str = parse_config_line_from_str(str, &k, &v);
  506. test_eq_ptr(str, NULL);
  507. tor_free(k); tor_free(v);
  508. str = buf2;
  509. str = parse_config_line_from_str(str, &k, &v);
  510. test_eq_ptr(str, NULL);
  511. tor_free(k); tor_free(v);
  512. str = buf3;
  513. str = parse_config_line_from_str(str, &k, &v);
  514. test_eq_ptr(str, NULL);
  515. tor_free(k); tor_free(v);
  516. str = buf4;
  517. str = parse_config_line_from_str(str, &k, &v);
  518. test_eq_ptr(str, NULL);
  519. tor_free(k); tor_free(v);
  520. done:
  521. tor_free(k);
  522. tor_free(v);
  523. }
  524. static void
  525. test_util_config_line_comment_character(void)
  526. {
  527. char buf[1024];
  528. char *k=NULL, *v=NULL;
  529. const char *str;
  530. /* Test parse_config_line_from_str */
  531. strlcpy(buf, "k1 \"# in quotes\"\n"
  532. "k2 some value # some comment\n"
  533. "k3 /home/user/myTorNetwork#2\n" /* Testcase for #1323 */
  534. , sizeof(buf));
  535. str = buf;
  536. str = parse_config_line_from_str(str, &k, &v);
  537. test_streq(k, "k1");
  538. test_streq(v, "# in quotes");
  539. tor_free(k); tor_free(v);
  540. str = parse_config_line_from_str(str, &k, &v);
  541. test_streq(k, "k2");
  542. test_streq(v, "some value");
  543. tor_free(k); tor_free(v);
  544. test_streq(str, "k3 /home/user/myTorNetwork#2\n");
  545. #if 0
  546. str = parse_config_line_from_str(str, &k, &v);
  547. test_streq(k, "k3");
  548. test_streq(v, "/home/user/myTorNetwork#2");
  549. tor_free(k); tor_free(v);
  550. test_streq(str, "");
  551. #endif
  552. done:
  553. tor_free(k);
  554. tor_free(v);
  555. }
  556. static void
  557. test_util_config_line_escaped_content(void)
  558. {
  559. char buf1[1024];
  560. char buf2[128];
  561. char buf3[128];
  562. char buf4[128];
  563. char buf5[128];
  564. char buf6[128];
  565. char *k=NULL, *v=NULL;
  566. const char *str;
  567. /* Test parse_config_line_from_str */
  568. strlcpy(buf1, "HexadecimalLower \"\\x2a\"\n"
  569. "HexadecimalUpper \"\\x2A\"\n"
  570. "HexadecimalUpperX \"\\X2A\"\n"
  571. "Octal \"\\52\"\n"
  572. "Newline \"\\n\"\n"
  573. "Tab \"\\t\"\n"
  574. "CarriageReturn \"\\r\"\n"
  575. "DoubleQuote \"\\\"\"\n"
  576. "SimpleQuote \"\\'\"\n"
  577. "Backslash \"\\\\\"\n"
  578. "Mix \"This is a \\\"star\\\":\\t\\'\\x2a\\'\\nAnd second line\"\n"
  579. , sizeof(buf1));
  580. strlcpy(buf2, "BrokenEscapedContent \"\\a\"\n"
  581. , sizeof(buf2));
  582. strlcpy(buf3, "BrokenEscapedContent \"\\x\"\n"
  583. , sizeof(buf3));
  584. strlcpy(buf4, "BrokenOctal \"\\8\"\n"
  585. , sizeof(buf4));
  586. strlcpy(buf5, "BrokenHex \"\\xg4\"\n"
  587. , sizeof(buf5));
  588. strlcpy(buf6, "BrokenEscape \"\\"
  589. , sizeof(buf6));
  590. str = buf1;
  591. str = parse_config_line_from_str(str, &k, &v);
  592. test_streq(k, "HexadecimalLower");
  593. test_streq(v, "*");
  594. tor_free(k); tor_free(v);
  595. str = parse_config_line_from_str(str, &k, &v);
  596. test_streq(k, "HexadecimalUpper");
  597. test_streq(v, "*");
  598. tor_free(k); tor_free(v);
  599. str = parse_config_line_from_str(str, &k, &v);
  600. test_streq(k, "HexadecimalUpperX");
  601. test_streq(v, "*");
  602. tor_free(k); tor_free(v);
  603. str = parse_config_line_from_str(str, &k, &v);
  604. test_streq(k, "Octal");
  605. test_streq(v, "*");
  606. tor_free(k); tor_free(v);
  607. str = parse_config_line_from_str(str, &k, &v);
  608. test_streq(k, "Newline");
  609. test_streq(v, "\n");
  610. tor_free(k); tor_free(v);
  611. str = parse_config_line_from_str(str, &k, &v);
  612. test_streq(k, "Tab");
  613. test_streq(v, "\t");
  614. tor_free(k); tor_free(v);
  615. str = parse_config_line_from_str(str, &k, &v);
  616. test_streq(k, "CarriageReturn");
  617. test_streq(v, "\r");
  618. tor_free(k); tor_free(v);
  619. str = parse_config_line_from_str(str, &k, &v);
  620. test_streq(k, "DoubleQuote");
  621. test_streq(v, "\"");
  622. tor_free(k); tor_free(v);
  623. str = parse_config_line_from_str(str, &k, &v);
  624. test_streq(k, "SimpleQuote");
  625. test_streq(v, "'");
  626. tor_free(k); tor_free(v);
  627. str = parse_config_line_from_str(str, &k, &v);
  628. test_streq(k, "Backslash");
  629. test_streq(v, "\\");
  630. tor_free(k); tor_free(v);
  631. str = parse_config_line_from_str(str, &k, &v);
  632. test_streq(k, "Mix");
  633. test_streq(v, "This is a \"star\":\t'*'\nAnd second line");
  634. tor_free(k); tor_free(v);
  635. test_streq(str, "");
  636. str = buf2;
  637. str = parse_config_line_from_str(str, &k, &v);
  638. test_eq_ptr(str, NULL);
  639. tor_free(k); tor_free(v);
  640. str = buf3;
  641. str = parse_config_line_from_str(str, &k, &v);
  642. test_eq_ptr(str, NULL);
  643. tor_free(k); tor_free(v);
  644. str = buf4;
  645. str = parse_config_line_from_str(str, &k, &v);
  646. test_eq_ptr(str, NULL);
  647. tor_free(k); tor_free(v);
  648. #if 0
  649. str = buf5;
  650. str = parse_config_line_from_str(str, &k, &v);
  651. test_eq_ptr(str, NULL);
  652. tor_free(k); tor_free(v);
  653. #endif
  654. str = buf6;
  655. str = parse_config_line_from_str(str, &k, &v);
  656. test_eq_ptr(str, NULL);
  657. tor_free(k); tor_free(v);
  658. done:
  659. tor_free(k);
  660. tor_free(v);
  661. }
  662. #ifndef _WIN32
  663. static void
  664. test_util_expand_filename(void)
  665. {
  666. char *str;
  667. setenv("HOME", "/home/itv", 1); /* For "internal test value" */
  668. str = expand_filename("");
  669. test_streq("", str);
  670. tor_free(str);
  671. str = expand_filename("/normal/path");
  672. test_streq("/normal/path", str);
  673. tor_free(str);
  674. str = expand_filename("/normal/trailing/path/");
  675. test_streq("/normal/trailing/path/", str);
  676. tor_free(str);
  677. str = expand_filename("~");
  678. test_streq("/home/itv/", str);
  679. tor_free(str);
  680. str = expand_filename("$HOME/nodice");
  681. test_streq("$HOME/nodice", str);
  682. tor_free(str);
  683. str = expand_filename("~/");
  684. test_streq("/home/itv/", str);
  685. tor_free(str);
  686. str = expand_filename("~/foobarqux");
  687. test_streq("/home/itv/foobarqux", str);
  688. tor_free(str);
  689. str = expand_filename("~/../../etc/passwd");
  690. test_streq("/home/itv/../../etc/passwd", str);
  691. tor_free(str);
  692. str = expand_filename("~/trailing/");
  693. test_streq("/home/itv/trailing/", str);
  694. tor_free(str);
  695. /* Ideally we'd test ~anotheruser, but that's shady to test (we'd
  696. have to somehow inject/fake the get_user_homedir call) */
  697. /* $HOME ending in a trailing slash */
  698. setenv("HOME", "/home/itv/", 1);
  699. str = expand_filename("~");
  700. test_streq("/home/itv/", str);
  701. tor_free(str);
  702. str = expand_filename("~/");
  703. test_streq("/home/itv/", str);
  704. tor_free(str);
  705. str = expand_filename("~/foo");
  706. test_streq("/home/itv/foo", str);
  707. tor_free(str);
  708. /* Try with empty $HOME */
  709. setenv("HOME", "", 1);
  710. str = expand_filename("~");
  711. test_streq("/", str);
  712. tor_free(str);
  713. str = expand_filename("~/");
  714. test_streq("/", str);
  715. tor_free(str);
  716. str = expand_filename("~/foobar");
  717. test_streq("/foobar", str);
  718. tor_free(str);
  719. /* Try with $HOME unset */
  720. unsetenv("HOME");
  721. str = expand_filename("~");
  722. test_streq("/", str);
  723. tor_free(str);
  724. str = expand_filename("~/");
  725. test_streq("/", str);
  726. tor_free(str);
  727. str = expand_filename("~/foobar");
  728. test_streq("/foobar", str);
  729. tor_free(str);
  730. done:
  731. tor_free(str);
  732. }
  733. #endif
  734. /** Test tor_escape_str_for_pt_args(). */
  735. static void
  736. test_util_escape_string_socks(void)
  737. {
  738. char *escaped_string = NULL;
  739. /** Simple backslash escape. */
  740. escaped_string = tor_escape_str_for_pt_args("This is a backslash: \\",";\\");
  741. test_assert(escaped_string);
  742. test_streq(escaped_string, "This is a backslash: \\\\");
  743. tor_free(escaped_string);
  744. /** Simple semicolon escape. */
  745. escaped_string = tor_escape_str_for_pt_args("First rule:Do not use ;",";\\");
  746. test_assert(escaped_string);
  747. test_streq(escaped_string, "First rule:Do not use \\;");
  748. tor_free(escaped_string);
  749. /** Empty string. */
  750. escaped_string = tor_escape_str_for_pt_args("", ";\\");
  751. test_assert(escaped_string);
  752. test_streq(escaped_string, "");
  753. tor_free(escaped_string);
  754. /** Escape all characters. */
  755. escaped_string = tor_escape_str_for_pt_args(";\\;\\", ";\\");
  756. test_assert(escaped_string);
  757. test_streq(escaped_string, "\\;\\\\\\;\\\\");
  758. tor_free(escaped_string);
  759. escaped_string = tor_escape_str_for_pt_args(";", ";\\");
  760. test_assert(escaped_string);
  761. test_streq(escaped_string, "\\;");
  762. tor_free(escaped_string);
  763. done:
  764. tor_free(escaped_string);
  765. }
  766. static void
  767. test_util_string_is_key_value(void *ptr)
  768. {
  769. (void)ptr;
  770. test_assert(string_is_key_value(LOG_WARN, "key=value"));
  771. test_assert(string_is_key_value(LOG_WARN, "k=v"));
  772. test_assert(string_is_key_value(LOG_WARN, "key="));
  773. test_assert(string_is_key_value(LOG_WARN, "x="));
  774. test_assert(string_is_key_value(LOG_WARN, "xx="));
  775. test_assert(!string_is_key_value(LOG_WARN, "=value"));
  776. test_assert(!string_is_key_value(LOG_WARN, "=x"));
  777. test_assert(!string_is_key_value(LOG_WARN, "="));
  778. /* ??? */
  779. /* test_assert(!string_is_key_value(LOG_WARN, "===")); */
  780. done:
  781. ;
  782. }
  783. /** Test basic string functionality. */
  784. static void
  785. test_util_strmisc(void)
  786. {
  787. char buf[1024];
  788. int i;
  789. char *cp, *cp_tmp = NULL;
  790. /* Test strl operations */
  791. test_eq(5, strlcpy(buf, "Hello", 0));
  792. test_eq(5, strlcpy(buf, "Hello", 10));
  793. test_streq(buf, "Hello");
  794. test_eq(5, strlcpy(buf, "Hello", 6));
  795. test_streq(buf, "Hello");
  796. test_eq(5, strlcpy(buf, "Hello", 5));
  797. test_streq(buf, "Hell");
  798. strlcpy(buf, "Hello", sizeof(buf));
  799. test_eq(10, strlcat(buf, "Hello", 5));
  800. /* Test strstrip() */
  801. strlcpy(buf, "Testing 1 2 3", sizeof(buf));
  802. tor_strstrip(buf, ",!");
  803. test_streq(buf, "Testing 1 2 3");
  804. strlcpy(buf, "!Testing 1 2 3?", sizeof(buf));
  805. tor_strstrip(buf, "!? ");
  806. test_streq(buf, "Testing123");
  807. strlcpy(buf, "!!!Testing 1 2 3??", sizeof(buf));
  808. tor_strstrip(buf, "!? ");
  809. test_streq(buf, "Testing123");
  810. /* Test parse_long */
  811. /* Empty/zero input */
  812. test_eq(0L, tor_parse_long("",10,0,100,&i,NULL));
  813. test_eq(0, i);
  814. test_eq(0L, tor_parse_long("0",10,0,100,&i,NULL));
  815. test_eq(1, i);
  816. /* Normal cases */
  817. test_eq(10L, tor_parse_long("10",10,0,100,&i,NULL));
  818. test_eq(1, i);
  819. test_eq(10L, tor_parse_long("10",10,0,10,&i,NULL));
  820. test_eq(1, i);
  821. test_eq(10L, tor_parse_long("10",10,10,100,&i,NULL));
  822. test_eq(1, i);
  823. test_eq(-50L, tor_parse_long("-50",10,-100,100,&i,NULL));
  824. test_eq(1, i);
  825. test_eq(-50L, tor_parse_long("-50",10,-100,0,&i,NULL));
  826. test_eq(1, i);
  827. test_eq(-50L, tor_parse_long("-50",10,-50,0,&i,NULL));
  828. test_eq(1, i);
  829. /* Extra garbage */
  830. test_eq(0L, tor_parse_long("10m",10,0,100,&i,NULL));
  831. test_eq(0, i);
  832. test_eq(0L, tor_parse_long("-50 plus garbage",10,-100,100,&i,NULL));
  833. test_eq(0, i);
  834. test_eq(10L, tor_parse_long("10m",10,0,100,&i,&cp));
  835. test_eq(1, i);
  836. test_streq(cp, "m");
  837. test_eq(-50L, tor_parse_long("-50 plus garbage",10,-100,100,&i,&cp));
  838. test_eq(1, i);
  839. test_streq(cp, " plus garbage");
  840. /* Out of bounds */
  841. test_eq(0L, tor_parse_long("10",10,50,100,&i,NULL));
  842. test_eq(0, i);
  843. test_eq(0L, tor_parse_long("-50",10,0,100,&i,NULL));
  844. test_eq(0, i);
  845. /* Base different than 10 */
  846. test_eq(2L, tor_parse_long("10",2,0,100,NULL,NULL));
  847. test_eq(0L, tor_parse_long("2",2,0,100,NULL,NULL));
  848. test_eq(0L, tor_parse_long("10",-2,0,100,NULL,NULL));
  849. test_eq(68284L, tor_parse_long("10abc",16,0,70000,NULL,NULL));
  850. test_eq(68284L, tor_parse_long("10ABC",16,0,70000,NULL,NULL));
  851. test_eq(0, tor_parse_long("10ABC",-1,0,70000,&i,NULL));
  852. test_eq(i, 0);
  853. /* Test parse_ulong */
  854. test_eq(0UL, tor_parse_ulong("",10,0,100,NULL,NULL));
  855. test_eq(0UL, tor_parse_ulong("0",10,0,100,NULL,NULL));
  856. test_eq(10UL, tor_parse_ulong("10",10,0,100,NULL,NULL));
  857. test_eq(0UL, tor_parse_ulong("10",10,50,100,NULL,NULL));
  858. test_eq(10UL, tor_parse_ulong("10",10,0,10,NULL,NULL));
  859. test_eq(10UL, tor_parse_ulong("10",10,10,100,NULL,NULL));
  860. test_eq(0UL, tor_parse_ulong("8",8,0,100,NULL,NULL));
  861. test_eq(50UL, tor_parse_ulong("50",10,50,100,NULL,NULL));
  862. test_eq(0UL, tor_parse_ulong("-50",10,-100,100,NULL,NULL));
  863. test_eq(0UL, tor_parse_ulong("50",-1,50,100,&i,NULL));
  864. test_eq(0, i);
  865. /* Test parse_uint64 */
  866. test_assert(U64_LITERAL(10) == tor_parse_uint64("10 x",10,0,100, &i, &cp));
  867. test_eq(1, i);
  868. test_streq(cp, " x");
  869. test_assert(U64_LITERAL(12345678901) ==
  870. tor_parse_uint64("12345678901",10,0,UINT64_MAX, &i, &cp));
  871. test_eq(1, i);
  872. test_streq(cp, "");
  873. test_assert(U64_LITERAL(0) ==
  874. tor_parse_uint64("12345678901",10,500,INT32_MAX, &i, &cp));
  875. test_eq(0, i);
  876. test_assert(U64_LITERAL(0) ==
  877. tor_parse_uint64("123",-1,0,INT32_MAX, &i, &cp));
  878. test_eq(0, i);
  879. {
  880. /* Test parse_double */
  881. double d = tor_parse_double("10", 0, UINT64_MAX,&i,NULL);
  882. test_eq(1, i);
  883. test_assert(DBL_TO_U64(d) == 10);
  884. d = tor_parse_double("0", 0, UINT64_MAX,&i,NULL);
  885. test_eq(1, i);
  886. test_assert(DBL_TO_U64(d) == 0);
  887. d = tor_parse_double(" ", 0, UINT64_MAX,&i,NULL);
  888. test_eq(0, i);
  889. d = tor_parse_double(".0a", 0, UINT64_MAX,&i,NULL);
  890. test_eq(0, i);
  891. d = tor_parse_double(".0a", 0, UINT64_MAX,&i,&cp);
  892. test_eq(1, i);
  893. d = tor_parse_double("-.0", 0, UINT64_MAX,&i,NULL);
  894. test_eq(1, i);
  895. test_assert(DBL_TO_U64(d) == 0);
  896. d = tor_parse_double("-10", -100.0, 100.0,&i,NULL);
  897. test_eq(1, i);
  898. test_eq(-10.0, d);
  899. }
  900. {
  901. /* Test tor_parse_* where we overflow/underflow the underlying type. */
  902. /* This string should overflow 64-bit ints. */
  903. #define TOOBIG "100000000000000000000000000"
  904. test_eq(0L, tor_parse_long(TOOBIG, 10, LONG_MIN, LONG_MAX, &i, NULL));
  905. test_eq(i, 0);
  906. test_eq(0L, tor_parse_long("-"TOOBIG, 10, LONG_MIN, LONG_MAX, &i, NULL));
  907. test_eq(i, 0);
  908. test_eq(0UL, tor_parse_ulong(TOOBIG, 10, 0, ULONG_MAX, &i, NULL));
  909. test_eq(i, 0);
  910. test_eq(U64_LITERAL(0), tor_parse_uint64(TOOBIG, 10,
  911. 0, UINT64_MAX, &i, NULL));
  912. test_eq(i, 0);
  913. }
  914. /* Test snprintf */
  915. /* Returning -1 when there's not enough room in the output buffer */
  916. test_eq(-1, tor_snprintf(buf, 0, "Foo"));
  917. test_eq(-1, tor_snprintf(buf, 2, "Foo"));
  918. test_eq(-1, tor_snprintf(buf, 3, "Foo"));
  919. test_neq(-1, tor_snprintf(buf, 4, "Foo"));
  920. /* Always NUL-terminate the output */
  921. tor_snprintf(buf, 5, "abcdef");
  922. test_eq(0, buf[4]);
  923. tor_snprintf(buf, 10, "abcdef");
  924. test_eq(0, buf[6]);
  925. /* uint64 */
  926. tor_snprintf(buf, sizeof(buf), "x!"U64_FORMAT"!x",
  927. U64_PRINTF_ARG(U64_LITERAL(12345678901)));
  928. test_streq("x!12345678901!x", buf);
  929. /* Test str{,case}cmpstart */
  930. test_assert(strcmpstart("abcdef", "abcdef")==0);
  931. test_assert(strcmpstart("abcdef", "abc")==0);
  932. test_assert(strcmpstart("abcdef", "abd")<0);
  933. test_assert(strcmpstart("abcdef", "abb")>0);
  934. test_assert(strcmpstart("ab", "abb")<0);
  935. test_assert(strcmpstart("ab", "")==0);
  936. test_assert(strcmpstart("ab", "ab ")<0);
  937. test_assert(strcasecmpstart("abcdef", "abCdEF")==0);
  938. test_assert(strcasecmpstart("abcDeF", "abc")==0);
  939. test_assert(strcasecmpstart("abcdef", "Abd")<0);
  940. test_assert(strcasecmpstart("Abcdef", "abb")>0);
  941. test_assert(strcasecmpstart("ab", "Abb")<0);
  942. test_assert(strcasecmpstart("ab", "")==0);
  943. test_assert(strcasecmpstart("ab", "ab ")<0);
  944. /* Test str{,case}cmpend */
  945. test_assert(strcmpend("abcdef", "abcdef")==0);
  946. test_assert(strcmpend("abcdef", "def")==0);
  947. test_assert(strcmpend("abcdef", "deg")<0);
  948. test_assert(strcmpend("abcdef", "dee")>0);
  949. test_assert(strcmpend("ab", "aab")>0);
  950. test_assert(strcasecmpend("AbcDEF", "abcdef")==0);
  951. test_assert(strcasecmpend("abcdef", "dEF")==0);
  952. test_assert(strcasecmpend("abcdef", "Deg")<0);
  953. test_assert(strcasecmpend("abcDef", "dee")>0);
  954. test_assert(strcasecmpend("AB", "abb")<0);
  955. /* Test digest_is_zero */
  956. memset(buf,0,20);
  957. buf[20] = 'x';
  958. test_assert(tor_digest_is_zero(buf));
  959. buf[19] = 'x';
  960. test_assert(!tor_digest_is_zero(buf));
  961. /* Test mem_is_zero */
  962. memset(buf,0,128);
  963. buf[128] = 'x';
  964. test_assert(tor_mem_is_zero(buf, 10));
  965. test_assert(tor_mem_is_zero(buf, 20));
  966. test_assert(tor_mem_is_zero(buf, 128));
  967. test_assert(!tor_mem_is_zero(buf, 129));
  968. buf[60] = (char)255;
  969. test_assert(!tor_mem_is_zero(buf, 128));
  970. buf[0] = (char)1;
  971. test_assert(!tor_mem_is_zero(buf, 10));
  972. /* Test 'escaped' */
  973. test_assert(NULL == escaped(NULL));
  974. test_streq("\"\"", escaped(""));
  975. test_streq("\"abcd\"", escaped("abcd"));
  976. test_streq("\"\\\\ \\n\\r\\t\\\"\\'\"", escaped("\\ \n\r\t\"'"));
  977. test_streq("\"unnecessary \\'backslashes\\'\"",
  978. escaped("unnecessary \'backslashes\'"));
  979. /* Non-printable characters appear as octal */
  980. test_streq("\"z\\001abc\\277d\"", escaped("z\001abc\277d"));
  981. test_streq("\"z\\336\\255 ;foo\"", escaped("z\xde\xad\x20;foo"));
  982. /* Test strndup and memdup */
  983. {
  984. const char *s = "abcdefghijklmnopqrstuvwxyz";
  985. cp_tmp = tor_strndup(s, 30);
  986. test_streq(cp_tmp, s); /* same string, */
  987. test_neq_ptr(cp_tmp, s); /* but different pointers. */
  988. tor_free(cp_tmp);
  989. cp_tmp = tor_strndup(s, 5);
  990. test_streq(cp_tmp, "abcde");
  991. tor_free(cp_tmp);
  992. s = "a\0b\0c\0d\0e\0";
  993. cp_tmp = tor_memdup(s,10);
  994. test_memeq(cp_tmp, s, 10); /* same ram, */
  995. test_neq_ptr(cp_tmp, s); /* but different pointers. */
  996. tor_free(cp_tmp);
  997. }
  998. /* Test str-foo functions */
  999. cp_tmp = tor_strdup("abcdef");
  1000. test_assert(tor_strisnonupper(cp_tmp));
  1001. cp_tmp[3] = 'D';
  1002. test_assert(!tor_strisnonupper(cp_tmp));
  1003. tor_strupper(cp_tmp);
  1004. test_streq(cp_tmp, "ABCDEF");
  1005. tor_strlower(cp_tmp);
  1006. test_streq(cp_tmp, "abcdef");
  1007. test_assert(tor_strisnonupper(cp_tmp));
  1008. test_assert(tor_strisprint(cp_tmp));
  1009. cp_tmp[3] = 3;
  1010. test_assert(!tor_strisprint(cp_tmp));
  1011. tor_free(cp_tmp);
  1012. /* Test memmem and memstr */
  1013. {
  1014. const char *haystack = "abcde";
  1015. test_assert(!tor_memmem(haystack, 5, "ef", 2));
  1016. test_eq_ptr(tor_memmem(haystack, 5, "cd", 2), haystack + 2);
  1017. test_eq_ptr(tor_memmem(haystack, 5, "cde", 3), haystack + 2);
  1018. test_assert(!tor_memmem(haystack, 4, "cde", 3));
  1019. haystack = "ababcad";
  1020. test_eq_ptr(tor_memmem(haystack, 7, "abc", 3), haystack + 2);
  1021. test_eq_ptr(tor_memmem(haystack, 7, "ad", 2), haystack + 5);
  1022. test_eq_ptr(tor_memmem(haystack, 7, "cad", 3), haystack + 4);
  1023. test_assert(!tor_memmem(haystack, 7, "dadad", 5));
  1024. test_assert(!tor_memmem(haystack, 7, "abcdefghij", 10));
  1025. /* memstr */
  1026. test_eq_ptr(tor_memstr(haystack, 7, "abc"), haystack + 2);
  1027. test_eq_ptr(tor_memstr(haystack, 7, "cad"), haystack + 4);
  1028. test_assert(!tor_memstr(haystack, 6, "cad"));
  1029. test_assert(!tor_memstr(haystack, 7, "cadd"));
  1030. test_assert(!tor_memstr(haystack, 7, "fe"));
  1031. test_assert(!tor_memstr(haystack, 7, "ababcade"));
  1032. }
  1033. /* Test hex_str */
  1034. {
  1035. char binary_data[68];
  1036. size_t i;
  1037. for (i = 0; i < sizeof(binary_data); ++i)
  1038. binary_data[i] = i;
  1039. test_streq(hex_str(binary_data, 0), "");
  1040. test_streq(hex_str(binary_data, 1), "00");
  1041. test_streq(hex_str(binary_data, 17), "000102030405060708090A0B0C0D0E0F10");
  1042. test_streq(hex_str(binary_data, 32),
  1043. "000102030405060708090A0B0C0D0E0F"
  1044. "101112131415161718191A1B1C1D1E1F");
  1045. test_streq(hex_str(binary_data, 34),
  1046. "000102030405060708090A0B0C0D0E0F"
  1047. "101112131415161718191A1B1C1D1E1F");
  1048. /* Repeat these tests for shorter strings after longer strings
  1049. have been tried, to make sure we're correctly terminating strings */
  1050. test_streq(hex_str(binary_data, 1), "00");
  1051. test_streq(hex_str(binary_data, 0), "");
  1052. }
  1053. /* Test strcmp_opt */
  1054. tt_int_op(strcmp_opt("", "foo"), <, 0);
  1055. tt_int_op(strcmp_opt("", ""), ==, 0);
  1056. tt_int_op(strcmp_opt("foo", ""), >, 0);
  1057. tt_int_op(strcmp_opt(NULL, ""), <, 0);
  1058. tt_int_op(strcmp_opt(NULL, NULL), ==, 0);
  1059. tt_int_op(strcmp_opt("", NULL), >, 0);
  1060. tt_int_op(strcmp_opt(NULL, "foo"), <, 0);
  1061. tt_int_op(strcmp_opt("foo", NULL), >, 0);
  1062. /* Test strcmp_len */
  1063. tt_int_op(strcmp_len("foo", "bar", 3), >, 0);
  1064. tt_int_op(strcmp_len("foo", "bar", 2), <, 0); /* First len, then lexical */
  1065. tt_int_op(strcmp_len("foo2", "foo1", 4), >, 0);
  1066. tt_int_op(strcmp_len("foo2", "foo1", 3), <, 0); /* Really stop at len */
  1067. tt_int_op(strcmp_len("foo2", "foo", 3), ==, 0); /* Really stop at len */
  1068. tt_int_op(strcmp_len("blah", "", 4), >, 0);
  1069. tt_int_op(strcmp_len("blah", "", 0), ==, 0);
  1070. done:
  1071. tor_free(cp_tmp);
  1072. }
  1073. static void
  1074. test_util_pow2(void)
  1075. {
  1076. /* Test tor_log2(). */
  1077. test_eq(tor_log2(64), 6);
  1078. test_eq(tor_log2(65), 6);
  1079. test_eq(tor_log2(63), 5);
  1080. test_eq(tor_log2(0), 0); /* incorrect mathematically, but as specified */
  1081. test_eq(tor_log2(1), 0);
  1082. test_eq(tor_log2(2), 1);
  1083. test_eq(tor_log2(3), 1);
  1084. test_eq(tor_log2(4), 2);
  1085. test_eq(tor_log2(5), 2);
  1086. test_eq(tor_log2(U64_LITERAL(40000000000000000)), 55);
  1087. test_eq(tor_log2(UINT64_MAX), 63);
  1088. /* Test round_to_power_of_2 */
  1089. test_eq(round_to_power_of_2(120), 128);
  1090. test_eq(round_to_power_of_2(128), 128);
  1091. test_eq(round_to_power_of_2(130), 128);
  1092. test_eq(round_to_power_of_2(U64_LITERAL(40000000000000000)),
  1093. U64_LITERAL(1)<<55);
  1094. test_eq(round_to_power_of_2(U64_LITERAL(0xffffffffffffffff)),
  1095. U64_LITERAL(1)<<63);
  1096. test_eq(round_to_power_of_2(0), 1);
  1097. test_eq(round_to_power_of_2(1), 1);
  1098. test_eq(round_to_power_of_2(2), 2);
  1099. test_eq(round_to_power_of_2(3), 2);
  1100. test_eq(round_to_power_of_2(4), 4);
  1101. test_eq(round_to_power_of_2(5), 4);
  1102. test_eq(round_to_power_of_2(6), 4);
  1103. test_eq(round_to_power_of_2(7), 8);
  1104. done:
  1105. ;
  1106. }
  1107. /** mutex for thread test to stop the threads hitting data at the same time. */
  1108. static tor_mutex_t *thread_test_mutex_ = NULL;
  1109. /** mutexes for the thread test to make sure that the threads have to
  1110. * interleave somewhat. */
  1111. static tor_mutex_t *thread_test_start1_ = NULL,
  1112. *thread_test_start2_ = NULL;
  1113. /** Shared strmap for the thread test. */
  1114. static strmap_t *thread_test_strmap_ = NULL;
  1115. /** The name of thread1 for the thread test */
  1116. static char *thread1_name_ = NULL;
  1117. /** The name of thread2 for the thread test */
  1118. static char *thread2_name_ = NULL;
  1119. static void thread_test_func_(void* _s) ATTR_NORETURN;
  1120. /** How many iterations have the threads in the unit test run? */
  1121. static int t1_count = 0, t2_count = 0;
  1122. /** Helper function for threading unit tests: This function runs in a
  1123. * subthread. It grabs its own mutex (start1 or start2) to make sure that it
  1124. * should start, then it repeatedly alters _test_thread_strmap protected by
  1125. * thread_test_mutex_. */
  1126. static void
  1127. thread_test_func_(void* _s)
  1128. {
  1129. char *s = _s;
  1130. int i, *count;
  1131. tor_mutex_t *m;
  1132. char buf[64];
  1133. char **cp;
  1134. if (!strcmp(s, "thread 1")) {
  1135. m = thread_test_start1_;
  1136. cp = &thread1_name_;
  1137. count = &t1_count;
  1138. } else {
  1139. m = thread_test_start2_;
  1140. cp = &thread2_name_;
  1141. count = &t2_count;
  1142. }
  1143. tor_snprintf(buf, sizeof(buf), "%lu", tor_get_thread_id());
  1144. *cp = tor_strdup(buf);
  1145. tor_mutex_acquire(m);
  1146. for (i=0; i<10000; ++i) {
  1147. tor_mutex_acquire(thread_test_mutex_);
  1148. strmap_set(thread_test_strmap_, "last to run", *cp);
  1149. ++*count;
  1150. tor_mutex_release(thread_test_mutex_);
  1151. }
  1152. tor_mutex_acquire(thread_test_mutex_);
  1153. strmap_set(thread_test_strmap_, s, *cp);
  1154. tor_mutex_release(thread_test_mutex_);
  1155. tor_mutex_release(m);
  1156. spawn_exit();
  1157. }
  1158. /** Run unit tests for threading logic. */
  1159. static void
  1160. test_util_threads(void)
  1161. {
  1162. char *s1 = NULL, *s2 = NULL;
  1163. int done = 0, timedout = 0;
  1164. time_t started;
  1165. #ifndef _WIN32
  1166. struct timeval tv;
  1167. tv.tv_sec=0;
  1168. tv.tv_usec=100*1000;
  1169. #endif
  1170. #ifndef TOR_IS_MULTITHREADED
  1171. /* Skip this test if we aren't threading. We should be threading most
  1172. * everywhere by now. */
  1173. if (1)
  1174. return;
  1175. #endif
  1176. thread_test_mutex_ = tor_mutex_new();
  1177. thread_test_start1_ = tor_mutex_new();
  1178. thread_test_start2_ = tor_mutex_new();
  1179. thread_test_strmap_ = strmap_new();
  1180. s1 = tor_strdup("thread 1");
  1181. s2 = tor_strdup("thread 2");
  1182. tor_mutex_acquire(thread_test_start1_);
  1183. tor_mutex_acquire(thread_test_start2_);
  1184. spawn_func(thread_test_func_, s1);
  1185. spawn_func(thread_test_func_, s2);
  1186. tor_mutex_release(thread_test_start2_);
  1187. tor_mutex_release(thread_test_start1_);
  1188. started = time(NULL);
  1189. while (!done) {
  1190. tor_mutex_acquire(thread_test_mutex_);
  1191. strmap_assert_ok(thread_test_strmap_);
  1192. if (strmap_get(thread_test_strmap_, "thread 1") &&
  1193. strmap_get(thread_test_strmap_, "thread 2")) {
  1194. done = 1;
  1195. } else if (time(NULL) > started + 150) {
  1196. timedout = done = 1;
  1197. }
  1198. tor_mutex_release(thread_test_mutex_);
  1199. #ifndef _WIN32
  1200. /* Prevent the main thread from starving the worker threads. */
  1201. select(0, NULL, NULL, NULL, &tv);
  1202. #endif
  1203. }
  1204. tor_mutex_acquire(thread_test_start1_);
  1205. tor_mutex_release(thread_test_start1_);
  1206. tor_mutex_acquire(thread_test_start2_);
  1207. tor_mutex_release(thread_test_start2_);
  1208. tor_mutex_free(thread_test_mutex_);
  1209. if (timedout) {
  1210. printf("\nTimed out: %d %d", t1_count, t2_count);
  1211. test_assert(strmap_get(thread_test_strmap_, "thread 1"));
  1212. test_assert(strmap_get(thread_test_strmap_, "thread 2"));
  1213. test_assert(!timedout);
  1214. }
  1215. /* different thread IDs. */
  1216. test_assert(strcmp(strmap_get(thread_test_strmap_, "thread 1"),
  1217. strmap_get(thread_test_strmap_, "thread 2")));
  1218. test_assert(!strcmp(strmap_get(thread_test_strmap_, "thread 1"),
  1219. strmap_get(thread_test_strmap_, "last to run")) ||
  1220. !strcmp(strmap_get(thread_test_strmap_, "thread 2"),
  1221. strmap_get(thread_test_strmap_, "last to run")));
  1222. done:
  1223. tor_free(s1);
  1224. tor_free(s2);
  1225. tor_free(thread1_name_);
  1226. tor_free(thread2_name_);
  1227. if (thread_test_strmap_)
  1228. strmap_free(thread_test_strmap_, NULL);
  1229. if (thread_test_start1_)
  1230. tor_mutex_free(thread_test_start1_);
  1231. if (thread_test_start2_)
  1232. tor_mutex_free(thread_test_start2_);
  1233. }
  1234. /** Run unit tests for compression functions */
  1235. static void
  1236. test_util_gzip(void)
  1237. {
  1238. char *buf1=NULL, *buf2=NULL, *buf3=NULL, *cp1, *cp2;
  1239. const char *ccp2;
  1240. size_t len1, len2;
  1241. tor_zlib_state_t *state = NULL;
  1242. buf1 = tor_strdup("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ");
  1243. test_assert(detect_compression_method(buf1, strlen(buf1)) == UNKNOWN_METHOD);
  1244. if (is_gzip_supported()) {
  1245. test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
  1246. GZIP_METHOD));
  1247. test_assert(buf2);
  1248. test_assert(len1 < strlen(buf1));
  1249. test_assert(detect_compression_method(buf2, len1) == GZIP_METHOD);
  1250. test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1,
  1251. GZIP_METHOD, 1, LOG_INFO));
  1252. test_assert(buf3);
  1253. test_eq(strlen(buf1) + 1, len2);
  1254. test_streq(buf1, buf3);
  1255. tor_free(buf2);
  1256. tor_free(buf3);
  1257. }
  1258. test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
  1259. ZLIB_METHOD));
  1260. test_assert(buf2);
  1261. test_assert(detect_compression_method(buf2, len1) == ZLIB_METHOD);
  1262. test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1,
  1263. ZLIB_METHOD, 1, LOG_INFO));
  1264. test_assert(buf3);
  1265. test_eq(strlen(buf1) + 1, len2);
  1266. test_streq(buf1, buf3);
  1267. /* Check whether we can uncompress concatenated, compressed strings. */
  1268. tor_free(buf3);
  1269. buf2 = tor_realloc(buf2, len1*2);
  1270. memcpy(buf2+len1, buf2, len1);
  1271. test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1*2,
  1272. ZLIB_METHOD, 1, LOG_INFO));
  1273. test_eq((strlen(buf1)+1)*2, len2);
  1274. test_memeq(buf3,
  1275. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ\0"
  1276. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ\0",
  1277. (strlen(buf1)+1)*2);
  1278. tor_free(buf1);
  1279. tor_free(buf2);
  1280. tor_free(buf3);
  1281. /* Check whether we can uncompress partial strings. */
  1282. buf1 =
  1283. tor_strdup("String with low redundancy that won't be compressed much.");
  1284. test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
  1285. ZLIB_METHOD));
  1286. tt_assert(len1>16);
  1287. /* when we allow an incomplete string, we should succeed.*/
  1288. tt_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1-16,
  1289. ZLIB_METHOD, 0, LOG_INFO));
  1290. tt_assert(len2 > 5);
  1291. buf3[len2]='\0';
  1292. tt_assert(!strcmpstart(buf1, buf3));
  1293. /* when we demand a complete string, this must fail. */
  1294. tor_free(buf3);
  1295. tt_assert(tor_gzip_uncompress(&buf3, &len2, buf2, len1-16,
  1296. ZLIB_METHOD, 1, LOG_INFO));
  1297. tt_assert(!buf3);
  1298. /* Now, try streaming compression. */
  1299. tor_free(buf1);
  1300. tor_free(buf2);
  1301. tor_free(buf3);
  1302. state = tor_zlib_new(1, ZLIB_METHOD);
  1303. tt_assert(state);
  1304. cp1 = buf1 = tor_malloc(1024);
  1305. len1 = 1024;
  1306. ccp2 = "ABCDEFGHIJABCDEFGHIJ";
  1307. len2 = 21;
  1308. test_assert(tor_zlib_process(state, &cp1, &len1, &ccp2, &len2, 0)
  1309. == TOR_ZLIB_OK);
  1310. test_eq(0, len2); /* Make sure we compressed it all. */
  1311. test_assert(cp1 > buf1);
  1312. len2 = 0;
  1313. cp2 = cp1;
  1314. test_assert(tor_zlib_process(state, &cp1, &len1, &ccp2, &len2, 1)
  1315. == TOR_ZLIB_DONE);
  1316. test_eq(0, len2);
  1317. test_assert(cp1 > cp2); /* Make sure we really added something. */
  1318. tt_assert(!tor_gzip_uncompress(&buf3, &len2, buf1, 1024-len1,
  1319. ZLIB_METHOD, 1, LOG_WARN));
  1320. test_streq(buf3, "ABCDEFGHIJABCDEFGHIJ"); /*Make sure it compressed right.*/
  1321. test_eq(21, len2);
  1322. done:
  1323. if (state)
  1324. tor_zlib_free(state);
  1325. tor_free(buf2);
  1326. tor_free(buf3);
  1327. tor_free(buf1);
  1328. }
  1329. /** Run unit tests for mmap() wrapper functionality. */
  1330. static void
  1331. test_util_mmap(void)
  1332. {
  1333. char *fname1 = tor_strdup(get_fname("mapped_1"));
  1334. char *fname2 = tor_strdup(get_fname("mapped_2"));
  1335. char *fname3 = tor_strdup(get_fname("mapped_3"));
  1336. const size_t buflen = 17000;
  1337. char *buf = tor_malloc(17000);
  1338. tor_mmap_t *mapping = NULL;
  1339. crypto_rand(buf, buflen);
  1340. mapping = tor_mmap_file(fname1);
  1341. test_assert(! mapping);
  1342. write_str_to_file(fname1, "Short file.", 1);
  1343. mapping = tor_mmap_file(fname1);
  1344. test_assert(mapping);
  1345. test_eq(mapping->size, strlen("Short file."));
  1346. test_streq(mapping->data, "Short file.");
  1347. #ifdef _WIN32
  1348. tt_int_op(0, ==, tor_munmap_file(mapping));
  1349. mapping = NULL;
  1350. test_assert(unlink(fname1) == 0);
  1351. #else
  1352. /* make sure we can unlink. */
  1353. test_assert(unlink(fname1) == 0);
  1354. test_streq(mapping->data, "Short file.");
  1355. tt_int_op(0, ==, tor_munmap_file(mapping));
  1356. mapping = NULL;
  1357. #endif
  1358. /* Now a zero-length file. */
  1359. write_str_to_file(fname1, "", 1);
  1360. mapping = tor_mmap_file(fname1);
  1361. test_eq_ptr(mapping, NULL);
  1362. test_eq(ERANGE, errno);
  1363. unlink(fname1);
  1364. /* Make sure that we fail to map a no-longer-existent file. */
  1365. mapping = tor_mmap_file(fname1);
  1366. test_assert(! mapping);
  1367. /* Now try a big file that stretches across a few pages and isn't aligned */
  1368. write_bytes_to_file(fname2, buf, buflen, 1);
  1369. mapping = tor_mmap_file(fname2);
  1370. test_assert(mapping);
  1371. test_eq(mapping->size, buflen);
  1372. test_memeq(mapping->data, buf, buflen);
  1373. tt_int_op(0, ==, tor_munmap_file(mapping));
  1374. mapping = NULL;
  1375. /* Now try a big aligned file. */
  1376. write_bytes_to_file(fname3, buf, 16384, 1);
  1377. mapping = tor_mmap_file(fname3);
  1378. test_assert(mapping);
  1379. test_eq(mapping->size, 16384);
  1380. test_memeq(mapping->data, buf, 16384);
  1381. tt_int_op(0, ==, tor_munmap_file(mapping));
  1382. mapping = NULL;
  1383. done:
  1384. unlink(fname1);
  1385. unlink(fname2);
  1386. unlink(fname3);
  1387. tor_free(fname1);
  1388. tor_free(fname2);
  1389. tor_free(fname3);
  1390. tor_free(buf);
  1391. tor_munmap_file(mapping);
  1392. }
  1393. /** Run unit tests for escaping/unescaping data for use by controllers. */
  1394. static void
  1395. test_util_control_formats(void)
  1396. {
  1397. char *out = NULL;
  1398. const char *inp =
  1399. "..This is a test\r\n.of the emergency \n..system.\r\n\rZ.\r\n";
  1400. size_t sz;
  1401. sz = read_escaped_data(inp, strlen(inp), &out);
  1402. test_streq(out,
  1403. ".This is a test\nof the emergency \n.system.\n\rZ.\n");
  1404. test_eq(sz, strlen(out));
  1405. done:
  1406. tor_free(out);
  1407. }
  1408. #define test_feq(value1,value2) do { \
  1409. double v1 = (value1), v2=(value2); \
  1410. double tf_diff = v1-v2; \
  1411. double tf_tolerance = ((v1+v2)/2.0)/1e8; \
  1412. if (tf_diff<0) tf_diff=-tf_diff; \
  1413. if (tf_tolerance<0) tf_tolerance=-tf_tolerance; \
  1414. if (tf_diff<tf_tolerance) { \
  1415. TT_BLATHER(("%s ~~ %s: %f ~~ %f",#value1,#value2,v1,v2)); \
  1416. } else { \
  1417. TT_FAIL(("%s ~~ %s: %f != %f",#value1,#value2,v1,v2)); \
  1418. } \
  1419. } while (0)
  1420. static void
  1421. test_util_sscanf(void)
  1422. {
  1423. unsigned u1, u2, u3;
  1424. char s1[20], s2[10], s3[10], ch;
  1425. int r;
  1426. long lng1,lng2;
  1427. int int1, int2;
  1428. double d1,d2,d3,d4;
  1429. /* Simple tests (malformed patterns, literal matching, ...) */
  1430. test_eq(-1, tor_sscanf("123", "%i", &r)); /* %i is not supported */
  1431. test_eq(-1, tor_sscanf("wrong", "%5c", s1)); /* %c cannot have a number. */
  1432. test_eq(-1, tor_sscanf("hello", "%s", s1)); /* %s needs a number. */
  1433. test_eq(-1, tor_sscanf("prettylongstring", "%999999s", s1));
  1434. #if 0
  1435. /* GCC thinks these two are illegal. */
  1436. test_eq(-1, tor_sscanf("prettylongstring", "%0s", s1));
  1437. test_eq(0, tor_sscanf("prettylongstring", "%10s", NULL));
  1438. #endif
  1439. /* No '%'-strings: always "success" */
  1440. test_eq(0, tor_sscanf("hello world", "hello world"));
  1441. test_eq(0, tor_sscanf("hello world", "good bye"));
  1442. /* Excess data */
  1443. test_eq(0, tor_sscanf("hello 3", "%u", &u1)); /* have to match the start */
  1444. test_eq(0, tor_sscanf(" 3 hello", "%u", &u1));
  1445. test_eq(0, tor_sscanf(" 3 hello", "%2u", &u1)); /* not even in this case */
  1446. test_eq(1, tor_sscanf("3 hello", "%u", &u1)); /* but trailing is alright */
  1447. /* Numbers (ie. %u) */
  1448. test_eq(0, tor_sscanf("hello world 3", "hello worlb %u", &u1)); /* d vs b */
  1449. test_eq(1, tor_sscanf("12345", "%u", &u1));
  1450. test_eq(12345u, u1);
  1451. test_eq(1, tor_sscanf("12346 ", "%u", &u1));
  1452. test_eq(12346u, u1);
  1453. test_eq(0, tor_sscanf(" 12347", "%u", &u1));
  1454. test_eq(1, tor_sscanf(" 12348", " %u", &u1));
  1455. test_eq(12348u, u1);
  1456. test_eq(1, tor_sscanf("0", "%u", &u1));
  1457. test_eq(0u, u1);
  1458. test_eq(1, tor_sscanf("0000", "%u", &u2));
  1459. test_eq(0u, u2);
  1460. test_eq(0, tor_sscanf("", "%u", &u1)); /* absent number */
  1461. test_eq(0, tor_sscanf("A", "%u", &u1)); /* bogus number */
  1462. test_eq(0, tor_sscanf("-1", "%u", &u1)); /* negative number */
  1463. test_eq(1, tor_sscanf("4294967295", "%u", &u1)); /* UINT32_MAX should work */
  1464. test_eq(4294967295u, u1);
  1465. test_eq(0, tor_sscanf("4294967296", "%u", &u1)); /* But not at 32 bits */
  1466. test_eq(1, tor_sscanf("4294967296", "%9u", &u1)); /* but parsing only 9... */
  1467. test_eq(429496729u, u1);
  1468. /* Numbers with size (eg. %2u) */
  1469. test_eq(0, tor_sscanf("-1", "%2u", &u1));
  1470. test_eq(2, tor_sscanf("123456", "%2u%u", &u1, &u2));
  1471. test_eq(12u, u1);
  1472. test_eq(3456u, u2);
  1473. test_eq(1, tor_sscanf("123456", "%8u", &u1));
  1474. test_eq(123456u, u1);
  1475. test_eq(1, tor_sscanf("123457 ", "%8u", &u1));
  1476. test_eq(123457u, u1);
  1477. test_eq(0, tor_sscanf(" 123456", "%8u", &u1));
  1478. test_eq(3, tor_sscanf("!12:3:456", "!%2u:%2u:%3u", &u1, &u2, &u3));
  1479. test_eq(12u, u1);
  1480. test_eq(3u, u2);
  1481. test_eq(456u, u3);
  1482. test_eq(3, tor_sscanf("67:8:099", "%2u:%2u:%3u", &u1, &u2, &u3)); /* 0s */
  1483. test_eq(67u, u1);
  1484. test_eq(8u, u2);
  1485. test_eq(99u, u3);
  1486. /* %u does not match space.*/
  1487. test_eq(2, tor_sscanf("12:3: 45", "%2u:%2u:%3u", &u1, &u2, &u3));
  1488. test_eq(12u, u1);
  1489. test_eq(3u, u2);
  1490. /* %u does not match negative numbers. */
  1491. test_eq(2, tor_sscanf("67:8:-9", "%2u:%2u:%3u", &u1, &u2, &u3));
  1492. test_eq(67u, u1);
  1493. test_eq(8u, u2);
  1494. /* Arbitrary amounts of 0-padding are okay */
  1495. test_eq(3, tor_sscanf("12:03:000000000000000099", "%2u:%2u:%u",
  1496. &u1, &u2, &u3));
  1497. test_eq(12u, u1);
  1498. test_eq(3u, u2);
  1499. test_eq(99u, u3);
  1500. /* Hex (ie. %x) */
  1501. test_eq(3, tor_sscanf("1234 02aBcdEf ff", "%x %x %x", &u1, &u2, &u3));
  1502. test_eq(0x1234, u1);
  1503. test_eq(0x2ABCDEF, u2);
  1504. test_eq(0xFF, u3);
  1505. /* Width works on %x */
  1506. test_eq(3, tor_sscanf("f00dcafe444", "%4x%4x%u", &u1, &u2, &u3));
  1507. test_eq(0xf00d, u1);
  1508. test_eq(0xcafe, u2);
  1509. test_eq(444, u3);
  1510. /* Literal '%' (ie. '%%') */
  1511. test_eq(1, tor_sscanf("99% fresh", "%3u%% fresh", &u1));
  1512. test_eq(99, u1);
  1513. test_eq(0, tor_sscanf("99 fresh", "%% %3u %s", &u1, s1));
  1514. test_eq(1, tor_sscanf("99 fresh", "%3u%% %s", &u1, s1));
  1515. test_eq(2, tor_sscanf("99 fresh", "%3u %5s %%", &u1, s1));
  1516. test_eq(99, u1);
  1517. test_streq(s1, "fresh");
  1518. test_eq(1, tor_sscanf("% boo", "%% %3s", s1));
  1519. test_streq("boo", s1);
  1520. /* Strings (ie. %s) */
  1521. test_eq(2, tor_sscanf("hello", "%3s%7s", s1, s2));
  1522. test_streq(s1, "hel");
  1523. test_streq(s2, "lo");
  1524. test_eq(2, tor_sscanf("WD40", "%2s%u", s3, &u1)); /* %s%u */
  1525. test_streq(s3, "WD");
  1526. test_eq(40, u1);
  1527. test_eq(2, tor_sscanf("WD40", "%3s%u", s3, &u1)); /* %s%u */
  1528. test_streq(s3, "WD4");
  1529. test_eq(0, u1);
  1530. test_eq(2, tor_sscanf("76trombones", "%6u%9s", &u1, s1)); /* %u%s */
  1531. test_eq(76, u1);
  1532. test_streq(s1, "trombones");
  1533. test_eq(1, tor_sscanf("prettylongstring", "%999s", s1));
  1534. test_streq(s1, "prettylongstring");
  1535. /* %s doesn't eat spaces */
  1536. test_eq(2, tor_sscanf("hello world", "%9s %9s", s1, s2));
  1537. test_streq(s1, "hello");
  1538. test_streq(s2, "world");
  1539. test_eq(2, tor_sscanf("bye world?", "%9s %9s", s1, s2));
  1540. test_streq(s1, "bye");
  1541. test_streq(s2, "");
  1542. test_eq(3, tor_sscanf("hi", "%9s%9s%3s", s1, s2, s3)); /* %s can be empty. */
  1543. test_streq(s1, "hi");
  1544. test_streq(s2, "");
  1545. test_streq(s3, "");
  1546. test_eq(3, tor_sscanf("1.2.3", "%u.%u.%u%c", &u1, &u2, &u3, &ch));
  1547. test_eq(4, tor_sscanf("1.2.3 foobar", "%u.%u.%u%c", &u1, &u2, &u3, &ch));
  1548. test_eq(' ', ch);
  1549. r = tor_sscanf("12345 -67890 -1", "%d %ld %d", &int1, &lng1, &int2);
  1550. test_eq(r,3);
  1551. test_eq(int1, 12345);
  1552. test_eq(lng1, -67890);
  1553. test_eq(int2, -1);
  1554. #if SIZEOF_INT == 4
  1555. r = tor_sscanf("-2147483648. 2147483647.", "%d. %d.", &int1, &int2);
  1556. test_eq(r,2);
  1557. test_eq(int1, -2147483647-1);
  1558. test_eq(int2, 2147483647);
  1559. r = tor_sscanf("-2147483679.", "%d.", &int1);
  1560. test_eq(r,0);
  1561. r = tor_sscanf("2147483678.", "%d.", &int1);
  1562. test_eq(r,0);
  1563. #elif SIZEOF_INT == 8
  1564. r = tor_sscanf("-9223372036854775808. 9223372036854775807.",
  1565. "%d. %d.", &int1, &int2);
  1566. test_eq(r,2);
  1567. test_eq(int1, -9223372036854775807-1);
  1568. test_eq(int2, 9223372036854775807);
  1569. r = tor_sscanf("-9223372036854775809.", "%d.", &int1);
  1570. test_eq(r,0);
  1571. r = tor_sscanf("9223372036854775808.", "%d.", &int1);
  1572. test_eq(r,0);
  1573. #endif
  1574. #if SIZEOF_LONG == 4
  1575. r = tor_sscanf("-2147483648. 2147483647.", "%ld. %ld.", &lng1, &lng2);
  1576. test_eq(r,2);
  1577. test_eq(lng1, -2147483647 - 1);
  1578. test_eq(lng2, 2147483647);
  1579. #elif SIZEOF_LONG == 8
  1580. r = tor_sscanf("-9223372036854775808. 9223372036854775807.",
  1581. "%ld. %ld.", &lng1, &lng2);
  1582. test_eq(r,2);
  1583. test_eq(lng1, -9223372036854775807L - 1);
  1584. test_eq(lng2, 9223372036854775807L);
  1585. r = tor_sscanf("-9223372036854775808. 9223372036854775808.",
  1586. "%ld. %ld.", &lng1, &lng2);
  1587. test_eq(r,1);
  1588. r = tor_sscanf("-9223372036854775809. 9223372036854775808.",
  1589. "%ld. %ld.", &lng1, &lng2);
  1590. test_eq(r,0);
  1591. #endif
  1592. r = tor_sscanf("123.456 .000007 -900123123.2000787 00003.2",
  1593. "%lf %lf %lf %lf", &d1,&d2,&d3,&d4);
  1594. test_eq(r,4);
  1595. test_feq(d1, 123.456);
  1596. test_feq(d2, .000007);
  1597. test_feq(d3, -900123123.2000787);
  1598. test_feq(d4, 3.2);
  1599. done:
  1600. ;
  1601. }
  1602. static void
  1603. test_util_path_is_relative(void)
  1604. {
  1605. /* OS-independent tests */
  1606. test_eq(1, path_is_relative(""));
  1607. test_eq(1, path_is_relative("dir"));
  1608. test_eq(1, path_is_relative("dir/"));
  1609. test_eq(1, path_is_relative("./dir"));
  1610. test_eq(1, path_is_relative("../dir"));
  1611. test_eq(0, path_is_relative("/"));
  1612. test_eq(0, path_is_relative("/dir"));
  1613. test_eq(0, path_is_relative("/dir/"));
  1614. /* Windows */
  1615. #ifdef _WIN32
  1616. /* I don't have Windows so I can't test this, hence the "#ifdef
  1617. 0". These are tests that look useful, so please try to get them
  1618. running and uncomment if it all works as it should */
  1619. test_eq(1, path_is_relative("dir"));
  1620. test_eq(1, path_is_relative("dir\\"));
  1621. test_eq(1, path_is_relative("dir\\a:"));
  1622. test_eq(1, path_is_relative("dir\\a:\\"));
  1623. test_eq(1, path_is_relative("http:\\dir"));
  1624. test_eq(0, path_is_relative("\\dir"));
  1625. test_eq(0, path_is_relative("a:\\dir"));
  1626. test_eq(0, path_is_relative("z:\\dir"));
  1627. #endif
  1628. done:
  1629. ;
  1630. }
  1631. /** Run unittests for memory pool allocator */
  1632. static void
  1633. test_util_mempool(void)
  1634. {
  1635. mp_pool_t *pool = NULL;
  1636. smartlist_t *allocated = NULL;
  1637. int i;
  1638. pool = mp_pool_new(1, 100);
  1639. test_assert(pool);
  1640. test_assert(pool->new_chunk_capacity >= 100);
  1641. test_assert(pool->item_alloc_size >= sizeof(void*)+1);
  1642. mp_pool_destroy(pool);
  1643. pool = NULL;
  1644. pool = mp_pool_new(241, 2500);
  1645. test_assert(pool);
  1646. test_assert(pool->new_chunk_capacity >= 10);
  1647. test_assert(pool->item_alloc_size >= sizeof(void*)+241);
  1648. test_eq(pool->item_alloc_size & 0x03, 0);
  1649. test_assert(pool->new_chunk_capacity < 60);
  1650. allocated = smartlist_new();
  1651. for (i = 0; i < 20000; ++i) {
  1652. if (smartlist_len(allocated) < 20 || crypto_rand_int(2)) {
  1653. void *m = mp_pool_get(pool);
  1654. memset(m, 0x09, 241);
  1655. smartlist_add(allocated, m);
  1656. //printf("%d: %p\n", i, m);
  1657. //mp_pool_assert_ok(pool);
  1658. } else {
  1659. int idx = crypto_rand_int(smartlist_len(allocated));
  1660. void *m = smartlist_get(allocated, idx);
  1661. //printf("%d: free %p\n", i, m);
  1662. smartlist_del(allocated, idx);
  1663. mp_pool_release(m);
  1664. //mp_pool_assert_ok(pool);
  1665. }
  1666. if (crypto_rand_int(777)==0)
  1667. mp_pool_clean(pool, 1, 1);
  1668. if (i % 777)
  1669. mp_pool_assert_ok(pool);
  1670. }
  1671. done:
  1672. if (allocated) {
  1673. SMARTLIST_FOREACH(allocated, void *, m, mp_pool_release(m));
  1674. mp_pool_assert_ok(pool);
  1675. mp_pool_clean(pool, 0, 0);
  1676. mp_pool_assert_ok(pool);
  1677. smartlist_free(allocated);
  1678. }
  1679. if (pool)
  1680. mp_pool_destroy(pool);
  1681. }
  1682. /** Run unittests for memory area allocator */
  1683. static void
  1684. test_util_memarea(void)
  1685. {
  1686. memarea_t *area = memarea_new();
  1687. char *p1, *p2, *p3, *p1_orig;
  1688. void *malloced_ptr = NULL;
  1689. int i;
  1690. test_assert(area);
  1691. p1_orig = p1 = memarea_alloc(area,64);
  1692. p2 = memarea_alloc_zero(area,52);
  1693. p3 = memarea_alloc(area,11);
  1694. test_assert(memarea_owns_ptr(area, p1));
  1695. test_assert(memarea_owns_ptr(area, p2));
  1696. test_assert(memarea_owns_ptr(area, p3));
  1697. /* Make sure we left enough space. */
  1698. test_assert(p1+64 <= p2);
  1699. test_assert(p2+52 <= p3);
  1700. /* Make sure we aligned. */
  1701. test_eq(((uintptr_t)p1) % sizeof(void*), 0);
  1702. test_eq(((uintptr_t)p2) % sizeof(void*), 0);
  1703. test_eq(((uintptr_t)p3) % sizeof(void*), 0);
  1704. test_assert(!memarea_owns_ptr(area, p3+8192));
  1705. test_assert(!memarea_owns_ptr(area, p3+30));
  1706. test_assert(tor_mem_is_zero(p2, 52));
  1707. /* Make sure we don't overalign. */
  1708. p1 = memarea_alloc(area, 1);
  1709. p2 = memarea_alloc(area, 1);
  1710. test_eq_ptr(p1+sizeof(void*), p2);
  1711. {
  1712. malloced_ptr = tor_malloc(64);
  1713. test_assert(!memarea_owns_ptr(area, malloced_ptr));
  1714. tor_free(malloced_ptr);
  1715. }
  1716. /* memarea_memdup */
  1717. {
  1718. malloced_ptr = tor_malloc(64);
  1719. crypto_rand((char*)malloced_ptr, 64);
  1720. p1 = memarea_memdup(area, malloced_ptr, 64);
  1721. test_assert(p1 != malloced_ptr);
  1722. test_memeq(p1, malloced_ptr, 64);
  1723. tor_free(malloced_ptr);
  1724. }
  1725. /* memarea_strdup. */
  1726. p1 = memarea_strdup(area,"");
  1727. p2 = memarea_strdup(area, "abcd");
  1728. test_assert(p1);
  1729. test_assert(p2);
  1730. test_streq(p1, "");
  1731. test_streq(p2, "abcd");
  1732. /* memarea_strndup. */
  1733. {
  1734. const char *s = "Ad ogni porta batte la morte e grida: il nome!";
  1735. /* (From Turandot, act 3.) */
  1736. size_t len = strlen(s);
  1737. p1 = memarea_strndup(area, s, 1000);
  1738. p2 = memarea_strndup(area, s, 10);
  1739. test_streq(p1, s);
  1740. test_assert(p2 >= p1 + len + 1);
  1741. test_memeq(s, p2, 10);
  1742. test_eq(p2[10], '\0');
  1743. p3 = memarea_strndup(area, s, len);
  1744. test_streq(p3, s);
  1745. p3 = memarea_strndup(area, s, len-1);
  1746. test_memeq(s, p3, len-1);
  1747. test_eq(p3[len-1], '\0');
  1748. }
  1749. memarea_clear(area);
  1750. p1 = memarea_alloc(area, 1);
  1751. test_eq_ptr(p1, p1_orig);
  1752. memarea_clear(area);
  1753. /* Check for running over an area's size. */
  1754. for (i = 0; i < 512; ++i) {
  1755. p1 = memarea_alloc(area, crypto_rand_int(5)+1);
  1756. test_assert(memarea_owns_ptr(area, p1));
  1757. }
  1758. memarea_assert_ok(area);
  1759. /* Make sure we can allocate a too-big object. */
  1760. p1 = memarea_alloc_zero(area, 9000);
  1761. p2 = memarea_alloc_zero(area, 16);
  1762. test_assert(memarea_owns_ptr(area, p1));
  1763. test_assert(memarea_owns_ptr(area, p2));
  1764. done:
  1765. memarea_drop_all(area);
  1766. tor_free(malloced_ptr);
  1767. }
  1768. /** Run unit tests for utility functions to get file names relative to
  1769. * the data directory. */
  1770. static void
  1771. test_util_datadir(void)
  1772. {
  1773. char buf[1024];
  1774. char *f = NULL;
  1775. char *temp_dir = NULL;
  1776. temp_dir = get_datadir_fname(NULL);
  1777. f = get_datadir_fname("state");
  1778. tor_snprintf(buf, sizeof(buf), "%s"PATH_SEPARATOR"state", temp_dir);
  1779. test_streq(f, buf);
  1780. tor_free(f);
  1781. f = get_datadir_fname2("cache", "thingy");
  1782. tor_snprintf(buf, sizeof(buf),
  1783. "%s"PATH_SEPARATOR"cache"PATH_SEPARATOR"thingy", temp_dir);
  1784. test_streq(f, buf);
  1785. tor_free(f);
  1786. f = get_datadir_fname2_suffix("cache", "thingy", ".foo");
  1787. tor_snprintf(buf, sizeof(buf),
  1788. "%s"PATH_SEPARATOR"cache"PATH_SEPARATOR"thingy.foo", temp_dir);
  1789. test_streq(f, buf);
  1790. tor_free(f);
  1791. f = get_datadir_fname_suffix("cache", ".foo");
  1792. tor_snprintf(buf, sizeof(buf), "%s"PATH_SEPARATOR"cache.foo",
  1793. temp_dir);
  1794. test_streq(f, buf);
  1795. done:
  1796. tor_free(f);
  1797. tor_free(temp_dir);
  1798. }
  1799. static void
  1800. test_util_strtok(void)
  1801. {
  1802. char buf[128];
  1803. char buf2[128];
  1804. int i;
  1805. char *cp1, *cp2;
  1806. for (i = 0; i < 3; i++) {
  1807. const char *pad1="", *pad2="";
  1808. switch (i) {
  1809. case 0:
  1810. break;
  1811. case 1:
  1812. pad1 = " ";
  1813. pad2 = "!";
  1814. break;
  1815. case 2:
  1816. pad1 = " ";
  1817. pad2 = ";!";
  1818. break;
  1819. }
  1820. tor_snprintf(buf, sizeof(buf), "%s", pad1);
  1821. tor_snprintf(buf2, sizeof(buf2), "%s", pad2);
  1822. test_assert(NULL == tor_strtok_r_impl(buf, " ", &cp1));
  1823. test_assert(NULL == tor_strtok_r_impl(buf2, ".!..;!", &cp2));
  1824. tor_snprintf(buf, sizeof(buf),
  1825. "%sGraved on the dark in gestures of descent%s", pad1, pad1);
  1826. tor_snprintf(buf2, sizeof(buf2),
  1827. "%sthey.seemed;;their!.own;most.perfect;monument%s",pad2,pad2);
  1828. /* -- "Year's End", Richard Wilbur */
  1829. test_streq("Graved", tor_strtok_r_impl(buf, " ", &cp1));
  1830. test_streq("they", tor_strtok_r_impl(buf2, ".!..;!", &cp2));
  1831. #define S1() tor_strtok_r_impl(NULL, " ", &cp1)
  1832. #define S2() tor_strtok_r_impl(NULL, ".!..;!", &cp2)
  1833. test_streq("on", S1());
  1834. test_streq("the", S1());
  1835. test_streq("dark", S1());
  1836. test_streq("seemed", S2());
  1837. test_streq("their", S2());
  1838. test_streq("own", S2());
  1839. test_streq("in", S1());
  1840. test_streq("gestures", S1());
  1841. test_streq("of", S1());
  1842. test_streq("most", S2());
  1843. test_streq("perfect", S2());
  1844. test_streq("descent", S1());
  1845. test_streq("monument", S2());
  1846. test_eq_ptr(NULL, S1());
  1847. test_eq_ptr(NULL, S2());
  1848. }
  1849. buf[0] = 0;
  1850. test_eq_ptr(NULL, tor_strtok_r_impl(buf, " ", &cp1));
  1851. test_eq_ptr(NULL, tor_strtok_r_impl(buf, "!", &cp1));
  1852. strlcpy(buf, "Howdy!", sizeof(buf));
  1853. test_streq("Howdy", tor_strtok_r_impl(buf, "!", &cp1));
  1854. test_eq_ptr(NULL, tor_strtok_r_impl(NULL, "!", &cp1));
  1855. strlcpy(buf, " ", sizeof(buf));
  1856. test_eq_ptr(NULL, tor_strtok_r_impl(buf, " ", &cp1));
  1857. strlcpy(buf, " ", sizeof(buf));
  1858. test_eq_ptr(NULL, tor_strtok_r_impl(buf, " ", &cp1));
  1859. strlcpy(buf, "something ", sizeof(buf));
  1860. test_streq("something", tor_strtok_r_impl(buf, " ", &cp1));
  1861. test_eq_ptr(NULL, tor_strtok_r_impl(NULL, ";", &cp1));
  1862. done:
  1863. ;
  1864. }
  1865. static void
  1866. test_util_find_str_at_start_of_line(void *ptr)
  1867. {
  1868. const char *long_string =
  1869. "howdy world. how are you? i hope it's fine.\n"
  1870. "hello kitty\n"
  1871. "third line";
  1872. char *line2 = strchr(long_string,'\n')+1;
  1873. char *line3 = strchr(line2,'\n')+1;
  1874. const char *short_string = "hello kitty\n"
  1875. "second line\n";
  1876. char *short_line2 = strchr(short_string,'\n')+1;
  1877. (void)ptr;
  1878. test_eq_ptr(long_string, find_str_at_start_of_line(long_string, ""));
  1879. test_eq_ptr(NULL, find_str_at_start_of_line(short_string, "nonsense"));
  1880. test_eq_ptr(NULL, find_str_at_start_of_line(long_string, "nonsense"));
  1881. test_eq_ptr(NULL, find_str_at_start_of_line(long_string, "\n"));
  1882. test_eq_ptr(NULL, find_str_at_start_of_line(long_string, "how "));
  1883. test_eq_ptr(NULL, find_str_at_start_of_line(long_string, "kitty"));
  1884. test_eq_ptr(long_string, find_str_at_start_of_line(long_string, "h"));
  1885. test_eq_ptr(long_string, find_str_at_start_of_line(long_string, "how"));
  1886. test_eq_ptr(line2, find_str_at_start_of_line(long_string, "he"));
  1887. test_eq_ptr(line2, find_str_at_start_of_line(long_string, "hell"));
  1888. test_eq_ptr(line2, find_str_at_start_of_line(long_string, "hello k"));
  1889. test_eq_ptr(line2, find_str_at_start_of_line(long_string, "hello kitty\n"));
  1890. test_eq_ptr(line2, find_str_at_start_of_line(long_string, "hello kitty\nt"));
  1891. test_eq_ptr(line3, find_str_at_start_of_line(long_string, "third"));
  1892. test_eq_ptr(line3, find_str_at_start_of_line(long_string, "third line"));
  1893. test_eq_ptr(NULL, find_str_at_start_of_line(long_string, "third line\n"));
  1894. test_eq_ptr(short_line2, find_str_at_start_of_line(short_string,
  1895. "second line\n"));
  1896. done:
  1897. ;
  1898. }
  1899. static void
  1900. test_util_string_is_C_identifier(void *ptr)
  1901. {
  1902. (void)ptr;
  1903. test_eq(1, string_is_C_identifier("string_is_C_identifier"));
  1904. test_eq(1, string_is_C_identifier("_string_is_C_identifier"));
  1905. test_eq(1, string_is_C_identifier("_"));
  1906. test_eq(1, string_is_C_identifier("i"));
  1907. test_eq(1, string_is_C_identifier("_____"));
  1908. test_eq(1, string_is_C_identifier("__00__"));
  1909. test_eq(1, string_is_C_identifier("__init__"));
  1910. test_eq(1, string_is_C_identifier("_0"));
  1911. test_eq(1, string_is_C_identifier("_0string_is_C_identifier"));
  1912. test_eq(1, string_is_C_identifier("_0"));
  1913. test_eq(0, string_is_C_identifier("0_string_is_C_identifier"));
  1914. test_eq(0, string_is_C_identifier("0"));
  1915. test_eq(0, string_is_C_identifier(""));
  1916. test_eq(0, string_is_C_identifier(";"));
  1917. test_eq(0, string_is_C_identifier("i;"));
  1918. test_eq(0, string_is_C_identifier("_;"));
  1919. test_eq(0, string_is_C_identifier("í"));
  1920. test_eq(0, string_is_C_identifier("ñ"));
  1921. done:
  1922. ;
  1923. }
  1924. static void
  1925. test_util_asprintf(void *ptr)
  1926. {
  1927. #define LOREMIPSUM \
  1928. "Lorem ipsum dolor sit amet, consectetur adipisicing elit"
  1929. char *cp=NULL, *cp2=NULL;
  1930. int r;
  1931. (void)ptr;
  1932. /* simple string */
  1933. r = tor_asprintf(&cp, "simple string 100%% safe");
  1934. test_assert(cp);
  1935. test_streq("simple string 100% safe", cp);
  1936. test_eq(strlen(cp), r);
  1937. /* empty string */
  1938. r = tor_asprintf(&cp, "%s", "");
  1939. test_assert(cp);
  1940. test_streq("", cp);
  1941. test_eq(strlen(cp), r);
  1942. /* numbers (%i) */
  1943. r = tor_asprintf(&cp, "I like numbers-%2i, %i, etc.", -1, 2);
  1944. test_assert(cp);
  1945. test_streq("I like numbers--1, 2, etc.", cp);
  1946. test_eq(strlen(cp), r);
  1947. /* numbers (%d) */
  1948. r = tor_asprintf(&cp2, "First=%d, Second=%d", 101, 202);
  1949. test_assert(cp2);
  1950. test_eq(strlen(cp2), r);
  1951. test_streq("First=101, Second=202", cp2);
  1952. test_assert(cp != cp2);
  1953. tor_free(cp);
  1954. tor_free(cp2);
  1955. /* Glass-box test: a string exactly 128 characters long. */
  1956. r = tor_asprintf(&cp, "Lorem1: %sLorem2: %s", LOREMIPSUM, LOREMIPSUM);
  1957. test_assert(cp);
  1958. test_eq(128, r);
  1959. test_assert(cp[128] == '\0');
  1960. test_streq("Lorem1: "LOREMIPSUM"Lorem2: "LOREMIPSUM, cp);
  1961. tor_free(cp);
  1962. /* String longer than 128 characters */
  1963. r = tor_asprintf(&cp, "1: %s 2: %s 3: %s",
  1964. LOREMIPSUM, LOREMIPSUM, LOREMIPSUM);
  1965. test_assert(cp);
  1966. test_eq(strlen(cp), r);
  1967. test_streq("1: "LOREMIPSUM" 2: "LOREMIPSUM" 3: "LOREMIPSUM, cp);
  1968. done:
  1969. tor_free(cp);
  1970. tor_free(cp2);
  1971. }
  1972. static void
  1973. test_util_listdir(void *ptr)
  1974. {
  1975. smartlist_t *dir_contents = NULL;
  1976. char *fname1=NULL, *fname2=NULL, *fname3=NULL, *dir1=NULL, *dirname=NULL;
  1977. int r;
  1978. (void)ptr;
  1979. fname1 = tor_strdup(get_fname("hopscotch"));
  1980. fname2 = tor_strdup(get_fname("mumblety-peg"));
  1981. fname3 = tor_strdup(get_fname(".hidden-file"));
  1982. dir1 = tor_strdup(get_fname("some-directory"));
  1983. dirname = tor_strdup(get_fname(NULL));
  1984. test_eq(0, write_str_to_file(fname1, "X\n", 0));
  1985. test_eq(0, write_str_to_file(fname2, "Y\n", 0));
  1986. test_eq(0, write_str_to_file(fname3, "Z\n", 0));
  1987. #ifdef _WIN32
  1988. r = mkdir(dir1);
  1989. #else
  1990. r = mkdir(dir1, 0700);
  1991. #endif
  1992. if (r) {
  1993. fprintf(stderr, "Can't create directory %s:", dir1);
  1994. perror("");
  1995. exit(1);
  1996. }
  1997. dir_contents = tor_listdir(dirname);
  1998. test_assert(dir_contents);
  1999. /* make sure that each filename is listed. */
  2000. test_assert(smartlist_contains_string_case(dir_contents, "hopscotch"));
  2001. test_assert(smartlist_contains_string_case(dir_contents, "mumblety-peg"));
  2002. test_assert(smartlist_contains_string_case(dir_contents, ".hidden-file"));
  2003. test_assert(smartlist_contains_string_case(dir_contents, "some-directory"));
  2004. test_assert(!smartlist_contains_string(dir_contents, "."));
  2005. test_assert(!smartlist_contains_string(dir_contents, ".."));
  2006. done:
  2007. tor_free(fname1);
  2008. tor_free(fname2);
  2009. tor_free(fname3);
  2010. tor_free(dir1);
  2011. tor_free(dirname);
  2012. if (dir_contents) {
  2013. SMARTLIST_FOREACH(dir_contents, char *, cp, tor_free(cp));
  2014. smartlist_free(dir_contents);
  2015. }
  2016. }
  2017. static void
  2018. test_util_parent_dir(void *ptr)
  2019. {
  2020. char *cp;
  2021. (void)ptr;
  2022. #define T(output,expect_ok,input) \
  2023. do { \
  2024. int ok; \
  2025. cp = tor_strdup(input); \
  2026. ok = get_parent_directory(cp); \
  2027. tt_int_op(expect_ok, ==, ok); \
  2028. if (ok==0) \
  2029. tt_str_op(output, ==, cp); \
  2030. tor_free(cp); \
  2031. } while (0);
  2032. T("/home/wombat", 0, "/home/wombat/knish");
  2033. T("/home/wombat", 0, "/home/wombat/knish/");
  2034. T("/home/wombat", 0, "/home/wombat/knish///");
  2035. T("./home/wombat", 0, "./home/wombat/knish/");
  2036. T("/", 0, "/home");
  2037. T("/", 0, "/home//");
  2038. T(".", 0, "./wombat");
  2039. T(".", 0, "./wombat/");
  2040. T(".", 0, "./wombat//");
  2041. T("wombat", 0, "wombat/foo");
  2042. T("wombat/..", 0, "wombat/../foo");
  2043. T("wombat/../", 0, "wombat/..//foo"); /* Is this correct? */
  2044. T("wombat/.", 0, "wombat/./foo");
  2045. T("wombat/./", 0, "wombat/.//foo"); /* Is this correct? */
  2046. T("wombat", 0, "wombat/..//");
  2047. T("wombat", 0, "wombat/foo/");
  2048. T("wombat", 0, "wombat/.foo");
  2049. T("wombat", 0, "wombat/.foo/");
  2050. T("wombat", -1, "");
  2051. T("w", -1, "");
  2052. T("wombat", 0, "wombat/knish");
  2053. T("/", 0, "/");
  2054. T("/", 0, "////");
  2055. done:
  2056. tor_free(cp);
  2057. }
  2058. #ifdef _WIN32
  2059. static void
  2060. test_util_load_win_lib(void *ptr)
  2061. {
  2062. HANDLE h = load_windows_system_library(_T("advapi32.dll"));
  2063. (void) ptr;
  2064. tt_assert(h);
  2065. done:
  2066. if (h)
  2067. FreeLibrary(h);
  2068. }
  2069. #endif
  2070. #ifndef _WIN32
  2071. static void
  2072. clear_hex_errno(char *hex_errno)
  2073. {
  2074. memset(hex_errno, '\0', HEX_ERRNO_SIZE + 1);
  2075. }
  2076. static void
  2077. test_util_exit_status(void *ptr)
  2078. {
  2079. /* Leave an extra byte for a \0 so we can do string comparison */
  2080. char hex_errno[HEX_ERRNO_SIZE + 1];
  2081. int n;
  2082. (void)ptr;
  2083. clear_hex_errno(hex_errno);
  2084. n = format_helper_exit_status(0, 0, hex_errno);
  2085. test_streq("0/0\n", hex_errno);
  2086. test_eq(n, strlen(hex_errno));
  2087. clear_hex_errno(hex_errno);
  2088. n = format_helper_exit_status(0, 0x7FFFFFFF, hex_errno);
  2089. test_streq("0/7FFFFFFF\n", hex_errno);
  2090. test_eq(n, strlen(hex_errno));
  2091. clear_hex_errno(hex_errno);
  2092. n = format_helper_exit_status(0xFF, -0x80000000, hex_errno);
  2093. test_streq("FF/-80000000\n", hex_errno);
  2094. test_eq(n, strlen(hex_errno));
  2095. test_eq(n, HEX_ERRNO_SIZE);
  2096. clear_hex_errno(hex_errno);
  2097. n = format_helper_exit_status(0x7F, 0, hex_errno);
  2098. test_streq("7F/0\n", hex_errno);
  2099. test_eq(n, strlen(hex_errno));
  2100. clear_hex_errno(hex_errno);
  2101. n = format_helper_exit_status(0x08, -0x242, hex_errno);
  2102. test_streq("8/-242\n", hex_errno);
  2103. test_eq(n, strlen(hex_errno));
  2104. done:
  2105. ;
  2106. }
  2107. #endif
  2108. #ifndef _WIN32
  2109. /** Check that fgets waits until a full line, and not return a partial line, on
  2110. * a EAGAIN with a non-blocking pipe */
  2111. static void
  2112. test_util_fgets_eagain(void *ptr)
  2113. {
  2114. int test_pipe[2] = {-1, -1};
  2115. int retval;
  2116. ssize_t retlen;
  2117. char *retptr;
  2118. FILE *test_stream = NULL;
  2119. char buf[10];
  2120. (void)ptr;
  2121. /* Set up a pipe to test on */
  2122. retval = pipe(test_pipe);
  2123. tt_int_op(retval, >=, 0);
  2124. /* Set up the read-end to be non-blocking */
  2125. retval = fcntl(test_pipe[0], F_SETFL, O_NONBLOCK);
  2126. tt_int_op(retval, >=, 0);
  2127. /* Open it as a stdio stream */
  2128. test_stream = fdopen(test_pipe[0], "r");
  2129. tt_ptr_op(test_stream, !=, NULL);
  2130. /* Send in a partial line */
  2131. retlen = write(test_pipe[1], "A", 1);
  2132. tt_int_op(retlen, ==, 1);
  2133. retptr = fgets(buf, sizeof(buf), test_stream);
  2134. tt_want(retptr == NULL);
  2135. tt_int_op(errno, ==, EAGAIN);
  2136. /* Send in the rest */
  2137. retlen = write(test_pipe[1], "B\n", 2);
  2138. tt_int_op(retlen, ==, 2);
  2139. retptr = fgets(buf, sizeof(buf), test_stream);
  2140. tt_ptr_op(retptr, ==, buf);
  2141. tt_str_op(buf, ==, "AB\n");
  2142. /* Send in a full line */
  2143. retlen = write(test_pipe[1], "CD\n", 3);
  2144. tt_int_op(retlen, ==, 3);
  2145. retptr = fgets(buf, sizeof(buf), test_stream);
  2146. tt_ptr_op(retptr, ==, buf);
  2147. tt_str_op(buf, ==, "CD\n");
  2148. /* Send in a partial line */
  2149. retlen = write(test_pipe[1], "E", 1);
  2150. tt_int_op(retlen, ==, 1);
  2151. retptr = fgets(buf, sizeof(buf), test_stream);
  2152. tt_ptr_op(retptr, ==, NULL);
  2153. tt_int_op(errno, ==, EAGAIN);
  2154. /* Send in the rest */
  2155. retlen = write(test_pipe[1], "F\n", 2);
  2156. tt_int_op(retlen, ==, 2);
  2157. retptr = fgets(buf, sizeof(buf), test_stream);
  2158. tt_ptr_op(retptr, ==, buf);
  2159. tt_str_op(buf, ==, "EF\n");
  2160. /* Send in a full line and close */
  2161. retlen = write(test_pipe[1], "GH", 2);
  2162. tt_int_op(retlen, ==, 2);
  2163. retval = close(test_pipe[1]);
  2164. test_pipe[1] = -1;
  2165. tt_int_op(retval, ==, 0);
  2166. retptr = fgets(buf, sizeof(buf), test_stream);
  2167. tt_ptr_op(retptr, ==, buf);
  2168. tt_str_op(buf, ==, "GH");
  2169. /* Check for EOF */
  2170. retptr = fgets(buf, sizeof(buf), test_stream);
  2171. tt_ptr_op(retptr, ==, NULL);
  2172. tt_int_op(feof(test_stream), >, 0);
  2173. done:
  2174. if (test_stream != NULL)
  2175. fclose(test_stream);
  2176. if (test_pipe[0] != -1)
  2177. close(test_pipe[0]);
  2178. if (test_pipe[1] != -1)
  2179. close(test_pipe[1]);
  2180. }
  2181. #endif
  2182. /** Helper function for testing tor_spawn_background */
  2183. static void
  2184. run_util_spawn_background(const char *argv[], const char *expected_out,
  2185. const char *expected_err, int expected_exit,
  2186. int expected_status)
  2187. {
  2188. int retval, exit_code;
  2189. ssize_t pos;
  2190. process_handle_t *process_handle=NULL;
  2191. char stdout_buf[100], stderr_buf[100];
  2192. int status;
  2193. /* Start the program */
  2194. #ifdef _WIN32
  2195. status = tor_spawn_background(NULL, argv, NULL, &process_handle);
  2196. #else
  2197. status = tor_spawn_background(argv[0], argv, NULL, &process_handle);
  2198. #endif
  2199. test_eq(expected_status, status);
  2200. if (status == PROCESS_STATUS_ERROR)
  2201. return;
  2202. test_assert(process_handle != NULL);
  2203. test_eq(expected_status, process_handle->status);
  2204. #ifdef _WIN32
  2205. test_assert(process_handle->stdout_pipe != INVALID_HANDLE_VALUE);
  2206. test_assert(process_handle->stderr_pipe != INVALID_HANDLE_VALUE);
  2207. #else
  2208. test_assert(process_handle->stdout_pipe > 0);
  2209. test_assert(process_handle->stderr_pipe > 0);
  2210. #endif
  2211. /* Check stdout */
  2212. pos = tor_read_all_from_process_stdout(process_handle, stdout_buf,
  2213. sizeof(stdout_buf) - 1);
  2214. tt_assert(pos >= 0);
  2215. stdout_buf[pos] = '\0';
  2216. test_eq(strlen(expected_out), pos);
  2217. test_streq(expected_out, stdout_buf);
  2218. /* Check it terminated correctly */
  2219. retval = tor_get_exit_code(process_handle, 1, &exit_code);
  2220. test_eq(PROCESS_EXIT_EXITED, retval);
  2221. test_eq(expected_exit, exit_code);
  2222. // TODO: Make test-child exit with something other than 0
  2223. /* Check stderr */
  2224. pos = tor_read_all_from_process_stderr(process_handle, stderr_buf,
  2225. sizeof(stderr_buf) - 1);
  2226. test_assert(pos >= 0);
  2227. stderr_buf[pos] = '\0';
  2228. test_streq(expected_err, stderr_buf);
  2229. test_eq(strlen(expected_err), pos);
  2230. done:
  2231. if (process_handle)
  2232. tor_process_handle_destroy(process_handle, 1);
  2233. }
  2234. /** Check that we can launch a process and read the output */
  2235. static void
  2236. test_util_spawn_background_ok(void *ptr)
  2237. {
  2238. #ifdef _WIN32
  2239. const char *argv[] = {"test-child.exe", "--test", NULL};
  2240. const char *expected_out = "OUT\r\n--test\r\nSLEEPING\r\nDONE\r\n";
  2241. const char *expected_err = "ERR\r\n";
  2242. #else
  2243. const char *argv[] = {BUILDDIR "/src/test/test-child", "--test", NULL};
  2244. const char *expected_out = "OUT\n--test\nSLEEPING\nDONE\n";
  2245. const char *expected_err = "ERR\n";
  2246. #endif
  2247. (void)ptr;
  2248. run_util_spawn_background(argv, expected_out, expected_err, 0,
  2249. PROCESS_STATUS_RUNNING);
  2250. }
  2251. /** Check that failing to find the executable works as expected */
  2252. static void
  2253. test_util_spawn_background_fail(void *ptr)
  2254. {
  2255. #ifndef BUILDDIR
  2256. #define BUILDDIR "."
  2257. #endif
  2258. const char *argv[] = {BUILDDIR "/src/test/no-such-file", "--test", NULL};
  2259. const char *expected_err = "";
  2260. char expected_out[1024];
  2261. char code[32];
  2262. #ifdef _WIN32
  2263. const int expected_status = PROCESS_STATUS_ERROR;
  2264. #else
  2265. /* TODO: Once we can signal failure to exec, set this to be
  2266. * PROCESS_STATUS_ERROR */
  2267. const int expected_status = PROCESS_STATUS_RUNNING;
  2268. #endif
  2269. (void)ptr;
  2270. tor_snprintf(code, sizeof(code), "%x/%x",
  2271. 9 /* CHILD_STATE_FAILEXEC */ , ENOENT);
  2272. tor_snprintf(expected_out, sizeof(expected_out),
  2273. "ERR: Failed to spawn background process - code %s\n", code);
  2274. run_util_spawn_background(argv, expected_out, expected_err, 255,
  2275. expected_status);
  2276. }
  2277. /** Test that reading from a handle returns a partial read rather than
  2278. * blocking */
  2279. static void
  2280. test_util_spawn_background_partial_read(void *ptr)
  2281. {
  2282. const int expected_exit = 0;
  2283. const int expected_status = PROCESS_STATUS_RUNNING;
  2284. int retval, exit_code;
  2285. ssize_t pos = -1;
  2286. process_handle_t *process_handle=NULL;
  2287. int status;
  2288. char stdout_buf[100], stderr_buf[100];
  2289. #ifdef _WIN32
  2290. const char *argv[] = {"test-child.exe", "--test", NULL};
  2291. const char *expected_out[] = { "OUT\r\n--test\r\nSLEEPING\r\n",
  2292. "DONE\r\n",
  2293. NULL };
  2294. const char *expected_err = "ERR\r\n";
  2295. #else
  2296. const char *argv[] = {BUILDDIR "/src/test/test-child", "--test", NULL};
  2297. const char *expected_out[] = { "OUT\n--test\nSLEEPING\n",
  2298. "DONE\n",
  2299. NULL };
  2300. const char *expected_err = "ERR\n";
  2301. int eof = 0;
  2302. #endif
  2303. int expected_out_ctr;
  2304. (void)ptr;
  2305. /* Start the program */
  2306. #ifdef _WIN32
  2307. status = tor_spawn_background(NULL, argv, NULL, &process_handle);
  2308. #else
  2309. status = tor_spawn_background(argv[0], argv, NULL, &process_handle);
  2310. #endif
  2311. test_eq(expected_status, status);
  2312. test_assert(process_handle);
  2313. test_eq(expected_status, process_handle->status);
  2314. /* Check stdout */
  2315. for (expected_out_ctr = 0; expected_out[expected_out_ctr] != NULL;) {
  2316. #ifdef _WIN32
  2317. pos = tor_read_all_handle(process_handle->stdout_pipe, stdout_buf,
  2318. sizeof(stdout_buf) - 1, NULL);
  2319. #else
  2320. /* Check that we didn't read the end of file last time */
  2321. test_assert(!eof);
  2322. pos = tor_read_all_handle(process_handle->stdout_handle, stdout_buf,
  2323. sizeof(stdout_buf) - 1, NULL, &eof);
  2324. #endif
  2325. log_info(LD_GENERAL, "tor_read_all_handle() returned %d", (int)pos);
  2326. /* We would have blocked, keep on trying */
  2327. if (0 == pos)
  2328. continue;
  2329. test_assert(pos > 0);
  2330. stdout_buf[pos] = '\0';
  2331. test_streq(expected_out[expected_out_ctr], stdout_buf);
  2332. test_eq(strlen(expected_out[expected_out_ctr]), pos);
  2333. expected_out_ctr++;
  2334. }
  2335. /* The process should have exited without writing more */
  2336. #ifdef _WIN32
  2337. pos = tor_read_all_handle(process_handle->stdout_pipe, stdout_buf,
  2338. sizeof(stdout_buf) - 1,
  2339. process_handle);
  2340. test_eq(0, pos);
  2341. #else
  2342. if (!eof) {
  2343. /* We should have got all the data, but maybe not the EOF flag */
  2344. pos = tor_read_all_handle(process_handle->stdout_handle, stdout_buf,
  2345. sizeof(stdout_buf) - 1,
  2346. process_handle, &eof);
  2347. test_eq(0, pos);
  2348. test_assert(eof);
  2349. }
  2350. /* Otherwise, we got the EOF on the last read */
  2351. #endif
  2352. /* Check it terminated correctly */
  2353. retval = tor_get_exit_code(process_handle, 1, &exit_code);
  2354. test_eq(PROCESS_EXIT_EXITED, retval);
  2355. test_eq(expected_exit, exit_code);
  2356. // TODO: Make test-child exit with something other than 0
  2357. /* Check stderr */
  2358. pos = tor_read_all_from_process_stderr(process_handle, stderr_buf,
  2359. sizeof(stderr_buf) - 1);
  2360. test_assert(pos >= 0);
  2361. stderr_buf[pos] = '\0';
  2362. test_streq(expected_err, stderr_buf);
  2363. test_eq(strlen(expected_err), pos);
  2364. done:
  2365. tor_process_handle_destroy(process_handle, 1);
  2366. }
  2367. /**
  2368. * Test for format_hex_number_sigsafe()
  2369. */
  2370. static void
  2371. test_util_format_hex_number(void *ptr)
  2372. {
  2373. int i, len;
  2374. char buf[33];
  2375. const struct {
  2376. const char *str;
  2377. unsigned int x;
  2378. } test_data[] = {
  2379. {"0", 0},
  2380. {"1", 1},
  2381. {"273A", 0x273a},
  2382. {"FFFF", 0xffff},
  2383. {"7FFFFFFF", 0x7fffffff},
  2384. {"FFFFFFFF", 0xffffffff},
  2385. #if UINT_MAX >= 0xffffffff
  2386. {"31BC421D", 0x31bc421d},
  2387. {"FFFFFFFF", 0xffffffff},
  2388. #endif
  2389. {NULL, 0}
  2390. };
  2391. (void)ptr;
  2392. for (i = 0; test_data[i].str != NULL; ++i) {
  2393. len = format_hex_number_sigsafe(test_data[i].x, buf, sizeof(buf));
  2394. test_neq(len, 0);
  2395. test_eq(len, strlen(buf));
  2396. test_streq(buf, test_data[i].str);
  2397. }
  2398. test_eq(4, format_hex_number_sigsafe(0xffff, buf, 5));
  2399. test_streq(buf, "FFFF");
  2400. test_eq(0, format_hex_number_sigsafe(0xffff, buf, 4));
  2401. test_eq(0, format_hex_number_sigsafe(0, buf, 1));
  2402. done:
  2403. return;
  2404. }
  2405. /**
  2406. * Test for format_hex_number_sigsafe()
  2407. */
  2408. static void
  2409. test_util_format_dec_number(void *ptr)
  2410. {
  2411. int i, len;
  2412. char buf[33];
  2413. const struct {
  2414. const char *str;
  2415. unsigned int x;
  2416. } test_data[] = {
  2417. {"0", 0},
  2418. {"1", 1},
  2419. {"1234", 1234},
  2420. {"12345678", 12345678},
  2421. {"99999999", 99999999},
  2422. {"100000000", 100000000},
  2423. {"4294967295", 4294967295u},
  2424. #if UINT_MAX > 0xffffffff
  2425. {"18446744073709551615", 18446744073709551615u },
  2426. #endif
  2427. {NULL, 0}
  2428. };
  2429. (void)ptr;
  2430. for (i = 0; test_data[i].str != NULL; ++i) {
  2431. len = format_dec_number_sigsafe(test_data[i].x, buf, sizeof(buf));
  2432. test_neq(len, 0);
  2433. test_eq(len, strlen(buf));
  2434. test_streq(buf, test_data[i].str);
  2435. len = format_dec_number_sigsafe(test_data[i].x, buf,
  2436. (int)(strlen(test_data[i].str) + 1));
  2437. test_eq(len, strlen(buf));
  2438. test_streq(buf, test_data[i].str);
  2439. }
  2440. test_eq(4, format_dec_number_sigsafe(7331, buf, 5));
  2441. test_streq(buf, "7331");
  2442. test_eq(0, format_dec_number_sigsafe(7331, buf, 4));
  2443. test_eq(1, format_dec_number_sigsafe(0, buf, 2));
  2444. test_eq(0, format_dec_number_sigsafe(0, buf, 1));
  2445. done:
  2446. return;
  2447. }
  2448. /**
  2449. * Test that we can properly format a Windows command line
  2450. */
  2451. static void
  2452. test_util_join_win_cmdline(void *ptr)
  2453. {
  2454. /* Based on some test cases from "Parsing C++ Command-Line Arguments" in
  2455. * MSDN but we don't exercise all quoting rules because tor_join_win_cmdline
  2456. * will try to only generate simple cases for the child process to parse;
  2457. * i.e. we never embed quoted strings in arguments. */
  2458. const char *argvs[][4] = {
  2459. {"a", "bb", "CCC", NULL}, // Normal
  2460. {NULL, NULL, NULL, NULL}, // Empty argument list
  2461. {"", NULL, NULL, NULL}, // Empty argument
  2462. {"\"a", "b\"b", "CCC\"", NULL}, // Quotes
  2463. {"a\tbc", "dd dd", "E", NULL}, // Whitespace
  2464. {"a\\\\\\b", "de fg", "H", NULL}, // Backslashes
  2465. {"a\\\"b", "\\c", "D\\", NULL}, // Backslashes before quote
  2466. {"a\\\\b c", "d", "E", NULL}, // Backslashes not before quote
  2467. { NULL } // Terminator
  2468. };
  2469. const char *cmdlines[] = {
  2470. "a bb CCC",
  2471. "",
  2472. "\"\"",
  2473. "\\\"a b\\\"b CCC\\\"",
  2474. "\"a\tbc\" \"dd dd\" E",
  2475. "a\\\\\\b \"de fg\" H",
  2476. "a\\\\\\\"b \\c D\\",
  2477. "\"a\\\\b c\" d E",
  2478. NULL // Terminator
  2479. };
  2480. int i;
  2481. char *joined_argv = NULL;
  2482. (void)ptr;
  2483. for (i=0; cmdlines[i]!=NULL; i++) {
  2484. log_info(LD_GENERAL, "Joining argvs[%d], expecting <%s>", i, cmdlines[i]);
  2485. joined_argv = tor_join_win_cmdline(argvs[i]);
  2486. test_streq(cmdlines[i], joined_argv);
  2487. tor_free(joined_argv);
  2488. }
  2489. done:
  2490. tor_free(joined_argv);
  2491. }
  2492. #define MAX_SPLIT_LINE_COUNT 4
  2493. struct split_lines_test_t {
  2494. const char *orig_line; // Line to be split (may contain \0's)
  2495. int orig_length; // Length of orig_line
  2496. const char *split_line[MAX_SPLIT_LINE_COUNT]; // Split lines
  2497. };
  2498. /**
  2499. * Test that we properly split a buffer into lines
  2500. */
  2501. static void
  2502. test_util_split_lines(void *ptr)
  2503. {
  2504. /* Test cases. orig_line of last test case must be NULL.
  2505. * The last element of split_line[i] must be NULL. */
  2506. struct split_lines_test_t tests[] = {
  2507. {"", 0, {NULL}},
  2508. {"foo", 3, {"foo", NULL}},
  2509. {"\n\rfoo\n\rbar\r\n", 12, {"foo", "bar", NULL}},
  2510. {"fo o\r\nb\tar", 10, {"fo o", "b.ar", NULL}},
  2511. {"\x0f""f\0o\0\n\x01""b\0r\0\r", 12, {".f.o.", ".b.r.", NULL}},
  2512. {"line 1\r\nline 2", 14, {"line 1", "line 2", NULL}},
  2513. {"line 1\r\n\r\nline 2", 16, {"line 1", "line 2", NULL}},
  2514. {"line 1\r\n\r\r\r\nline 2", 18, {"line 1", "line 2", NULL}},
  2515. {"line 1\r\n\n\n\n\rline 2", 18, {"line 1", "line 2", NULL}},
  2516. {"line 1\r\n\r\t\r\nline 3", 18, {"line 1", ".", "line 3", NULL}},
  2517. {"\n\t\r\t\nline 3", 11, {".", ".", "line 3", NULL}},
  2518. {NULL, 0, { NULL }}
  2519. };
  2520. int i, j;
  2521. char *orig_line=NULL;
  2522. smartlist_t *sl=NULL;
  2523. (void)ptr;
  2524. for (i=0; tests[i].orig_line; i++) {
  2525. sl = smartlist_new();
  2526. /* Allocate space for string and trailing NULL */
  2527. orig_line = tor_memdup(tests[i].orig_line, tests[i].orig_length + 1);
  2528. tor_split_lines(sl, orig_line, tests[i].orig_length);
  2529. j = 0;
  2530. log_info(LD_GENERAL, "Splitting test %d of length %d",
  2531. i, tests[i].orig_length);
  2532. SMARTLIST_FOREACH_BEGIN(sl, const char *, line) {
  2533. /* Check we have not got too many lines */
  2534. test_assert(j < MAX_SPLIT_LINE_COUNT);
  2535. /* Check that there actually should be a line here */
  2536. test_assert(tests[i].split_line[j] != NULL);
  2537. log_info(LD_GENERAL, "Line %d of test %d, should be <%s>",
  2538. j, i, tests[i].split_line[j]);
  2539. /* Check that the line is as expected */
  2540. test_streq(line, tests[i].split_line[j]);
  2541. j++;
  2542. } SMARTLIST_FOREACH_END(line);
  2543. /* Check that we didn't miss some lines */
  2544. test_eq_ptr(NULL, tests[i].split_line[j]);
  2545. tor_free(orig_line);
  2546. smartlist_free(sl);
  2547. sl = NULL;
  2548. }
  2549. done:
  2550. tor_free(orig_line);
  2551. smartlist_free(sl);
  2552. }
  2553. static void
  2554. test_util_di_ops(void)
  2555. {
  2556. #define LT -1
  2557. #define GT 1
  2558. #define EQ 0
  2559. const struct {
  2560. const char *a; int want_sign; const char *b;
  2561. } examples[] = {
  2562. { "Foo", EQ, "Foo" },
  2563. { "foo", GT, "bar", },
  2564. { "foobar", EQ ,"foobar" },
  2565. { "foobar", LT, "foobaw" },
  2566. { "foobar", GT, "f00bar" },
  2567. { "foobar", GT, "boobar" },
  2568. { "", EQ, "" },
  2569. { NULL, 0, NULL },
  2570. };
  2571. int i;
  2572. for (i = 0; examples[i].a; ++i) {
  2573. size_t len = strlen(examples[i].a);
  2574. int eq1, eq2, neq1, neq2, cmp1, cmp2;
  2575. test_eq(len, strlen(examples[i].b));
  2576. /* We do all of the operations, with operands in both orders. */
  2577. eq1 = tor_memeq(examples[i].a, examples[i].b, len);
  2578. eq2 = tor_memeq(examples[i].b, examples[i].a, len);
  2579. neq1 = tor_memneq(examples[i].a, examples[i].b, len);
  2580. neq2 = tor_memneq(examples[i].b, examples[i].a, len);
  2581. cmp1 = tor_memcmp(examples[i].a, examples[i].b, len);
  2582. cmp2 = tor_memcmp(examples[i].b, examples[i].a, len);
  2583. /* Check for correctness of cmp1 */
  2584. if (cmp1 < 0 && examples[i].want_sign != LT)
  2585. test_fail();
  2586. else if (cmp1 > 0 && examples[i].want_sign != GT)
  2587. test_fail();
  2588. else if (cmp1 == 0 && examples[i].want_sign != EQ)
  2589. test_fail();
  2590. /* Check for consistency of everything else with cmp1 */
  2591. test_eq(eq1, eq2);
  2592. test_eq(neq1, neq2);
  2593. test_eq(cmp1, -cmp2);
  2594. test_eq(eq1, cmp1 == 0);
  2595. test_eq(neq1, !eq1);
  2596. }
  2597. tt_int_op(1, ==, safe_mem_is_zero("", 0));
  2598. tt_int_op(1, ==, safe_mem_is_zero("", 1));
  2599. tt_int_op(0, ==, safe_mem_is_zero("a", 1));
  2600. tt_int_op(0, ==, safe_mem_is_zero("a", 2));
  2601. tt_int_op(0, ==, safe_mem_is_zero("\0a", 2));
  2602. tt_int_op(1, ==, safe_mem_is_zero("\0\0a", 2));
  2603. tt_int_op(1, ==, safe_mem_is_zero("\0\0\0\0\0\0\0\0", 8));
  2604. tt_int_op(1, ==, safe_mem_is_zero("\0\0\0\0\0\0\0\0a", 8));
  2605. tt_int_op(0, ==, safe_mem_is_zero("\0\0\0\0\0\0\0\0a", 9));
  2606. done:
  2607. ;
  2608. }
  2609. /**
  2610. * Test counting high bits
  2611. */
  2612. static void
  2613. test_util_n_bits_set(void *ptr)
  2614. {
  2615. (void)ptr;
  2616. test_eq(0, n_bits_set_u8(0));
  2617. test_eq(1, n_bits_set_u8(1));
  2618. test_eq(3, n_bits_set_u8(7));
  2619. test_eq(1, n_bits_set_u8(8));
  2620. test_eq(2, n_bits_set_u8(129));
  2621. test_eq(8, n_bits_set_u8(255));
  2622. done:
  2623. ;
  2624. }
  2625. /**
  2626. * Test LHS whitespace (and comment) eater
  2627. */
  2628. static void
  2629. test_util_eat_whitespace(void *ptr)
  2630. {
  2631. const char ws[] = { ' ', '\t', '\r' }; /* Except NL */
  2632. char str[80];
  2633. size_t i;
  2634. (void)ptr;
  2635. /* Try one leading ws */
  2636. strlcpy(str, "fuubaar", sizeof(str));
  2637. for (i = 0; i < sizeof(ws); ++i) {
  2638. str[0] = ws[i];
  2639. test_eq_ptr(str + 1, eat_whitespace(str));
  2640. test_eq_ptr(str + 1, eat_whitespace_eos(str, str + strlen(str)));
  2641. test_eq_ptr(str + 1, eat_whitespace_no_nl(str));
  2642. test_eq_ptr(str + 1, eat_whitespace_eos_no_nl(str, str + strlen(str)));
  2643. }
  2644. str[0] = '\n';
  2645. test_eq_ptr(str + 1, eat_whitespace(str));
  2646. test_eq_ptr(str + 1, eat_whitespace_eos(str, str + strlen(str)));
  2647. test_eq_ptr(str, eat_whitespace_no_nl(str));
  2648. test_eq_ptr(str, eat_whitespace_eos_no_nl(str, str + strlen(str)));
  2649. /* Empty string */
  2650. strlcpy(str, "", sizeof(str));
  2651. test_eq_ptr(str, eat_whitespace(str));
  2652. test_eq_ptr(str, eat_whitespace_eos(str, str));
  2653. test_eq_ptr(str, eat_whitespace_no_nl(str));
  2654. test_eq_ptr(str, eat_whitespace_eos_no_nl(str, str));
  2655. /* Only ws */
  2656. strlcpy(str, " \t\r\n", sizeof(str));
  2657. test_eq_ptr(str + strlen(str), eat_whitespace(str));
  2658. test_eq_ptr(str + strlen(str), eat_whitespace_eos(str, str + strlen(str)));
  2659. test_eq_ptr(str + strlen(str) - 1,
  2660. eat_whitespace_no_nl(str));
  2661. test_eq_ptr(str + strlen(str) - 1,
  2662. eat_whitespace_eos_no_nl(str, str + strlen(str)));
  2663. strlcpy(str, " \t\r ", sizeof(str));
  2664. test_eq_ptr(str + strlen(str), eat_whitespace(str));
  2665. test_eq_ptr(str + strlen(str),
  2666. eat_whitespace_eos(str, str + strlen(str)));
  2667. test_eq_ptr(str + strlen(str), eat_whitespace_no_nl(str));
  2668. test_eq_ptr(str + strlen(str),
  2669. eat_whitespace_eos_no_nl(str, str + strlen(str)));
  2670. /* Multiple ws */
  2671. strlcpy(str, "fuubaar", sizeof(str));
  2672. for (i = 0; i < sizeof(ws); ++i)
  2673. str[i] = ws[i];
  2674. test_eq_ptr(str + sizeof(ws), eat_whitespace(str));
  2675. test_eq_ptr(str + sizeof(ws), eat_whitespace_eos(str, str + strlen(str)));
  2676. test_eq_ptr(str + sizeof(ws), eat_whitespace_no_nl(str));
  2677. test_eq_ptr(str + sizeof(ws),
  2678. eat_whitespace_eos_no_nl(str, str + strlen(str)));
  2679. /* Eat comment */
  2680. strlcpy(str, "# Comment \n No Comment", sizeof(str));
  2681. test_streq("No Comment", eat_whitespace(str));
  2682. test_streq("No Comment", eat_whitespace_eos(str, str + strlen(str)));
  2683. test_eq_ptr(str, eat_whitespace_no_nl(str));
  2684. test_eq_ptr(str, eat_whitespace_eos_no_nl(str, str + strlen(str)));
  2685. /* Eat comment & ws mix */
  2686. strlcpy(str, " # \t Comment \n\t\nNo Comment", sizeof(str));
  2687. test_streq("No Comment", eat_whitespace(str));
  2688. test_streq("No Comment", eat_whitespace_eos(str, str + strlen(str)));
  2689. test_eq_ptr(str + 1, eat_whitespace_no_nl(str));
  2690. test_eq_ptr(str + 1, eat_whitespace_eos_no_nl(str, str + strlen(str)));
  2691. /* Eat entire comment */
  2692. strlcpy(str, "#Comment", sizeof(str));
  2693. test_eq_ptr(str + strlen(str), eat_whitespace(str));
  2694. test_eq_ptr(str + strlen(str), eat_whitespace_eos(str, str + strlen(str)));
  2695. test_eq_ptr(str, eat_whitespace_no_nl(str));
  2696. test_eq_ptr(str, eat_whitespace_eos_no_nl(str, str + strlen(str)));
  2697. /* Blank line, then comment */
  2698. strlcpy(str, " \t\n # Comment", sizeof(str));
  2699. test_eq_ptr(str + strlen(str), eat_whitespace(str));
  2700. test_eq_ptr(str + strlen(str), eat_whitespace_eos(str, str + strlen(str)));
  2701. test_eq_ptr(str + 2, eat_whitespace_no_nl(str));
  2702. test_eq_ptr(str + 2, eat_whitespace_eos_no_nl(str, str + strlen(str)));
  2703. done:
  2704. ;
  2705. }
  2706. /** Return a newly allocated smartlist containing the lines of text in
  2707. * <b>lines</b>. The returned strings are heap-allocated, and must be
  2708. * freed by the caller.
  2709. *
  2710. * XXXX? Move to container.[hc] ? */
  2711. static smartlist_t *
  2712. smartlist_new_from_text_lines(const char *lines)
  2713. {
  2714. smartlist_t *sl = smartlist_new();
  2715. char *last_line;
  2716. smartlist_split_string(sl, lines, "\n", 0, 0);
  2717. last_line = smartlist_pop_last(sl);
  2718. if (last_line != NULL && *last_line != '\0') {
  2719. smartlist_add(sl, last_line);
  2720. }
  2721. return sl;
  2722. }
  2723. /** Test smartlist_new_from_text_lines */
  2724. static void
  2725. test_util_sl_new_from_text_lines(void *ptr)
  2726. {
  2727. (void)ptr;
  2728. { /* Normal usage */
  2729. smartlist_t *sl = smartlist_new_from_text_lines("foo\nbar\nbaz\n");
  2730. int sl_len = smartlist_len(sl);
  2731. tt_want_int_op(sl_len, ==, 3);
  2732. if (sl_len > 0) tt_want_str_op(smartlist_get(sl, 0), ==, "foo");
  2733. if (sl_len > 1) tt_want_str_op(smartlist_get(sl, 1), ==, "bar");
  2734. if (sl_len > 2) tt_want_str_op(smartlist_get(sl, 2), ==, "baz");
  2735. SMARTLIST_FOREACH(sl, void *, x, tor_free(x));
  2736. smartlist_free(sl);
  2737. }
  2738. { /* No final newline */
  2739. smartlist_t *sl = smartlist_new_from_text_lines("foo\nbar\nbaz");
  2740. int sl_len = smartlist_len(sl);
  2741. tt_want_int_op(sl_len, ==, 3);
  2742. if (sl_len > 0) tt_want_str_op(smartlist_get(sl, 0), ==, "foo");
  2743. if (sl_len > 1) tt_want_str_op(smartlist_get(sl, 1), ==, "bar");
  2744. if (sl_len > 2) tt_want_str_op(smartlist_get(sl, 2), ==, "baz");
  2745. SMARTLIST_FOREACH(sl, void *, x, tor_free(x));
  2746. smartlist_free(sl);
  2747. }
  2748. { /* No newlines */
  2749. smartlist_t *sl = smartlist_new_from_text_lines("foo");
  2750. int sl_len = smartlist_len(sl);
  2751. tt_want_int_op(sl_len, ==, 1);
  2752. if (sl_len > 0) tt_want_str_op(smartlist_get(sl, 0), ==, "foo");
  2753. SMARTLIST_FOREACH(sl, void *, x, tor_free(x));
  2754. smartlist_free(sl);
  2755. }
  2756. { /* No text at all */
  2757. smartlist_t *sl = smartlist_new_from_text_lines("");
  2758. int sl_len = smartlist_len(sl);
  2759. tt_want_int_op(sl_len, ==, 0);
  2760. SMARTLIST_FOREACH(sl, void *, x, tor_free(x));
  2761. smartlist_free(sl);
  2762. }
  2763. }
  2764. static void
  2765. test_util_envnames(void *ptr)
  2766. {
  2767. (void) ptr;
  2768. tt_assert(environment_variable_names_equal("abc", "abc"));
  2769. tt_assert(environment_variable_names_equal("abc", "abc="));
  2770. tt_assert(environment_variable_names_equal("abc", "abc=def"));
  2771. tt_assert(environment_variable_names_equal("abc=def", "abc"));
  2772. tt_assert(environment_variable_names_equal("abc=def", "abc=ghi"));
  2773. tt_assert(environment_variable_names_equal("abc", "abc"));
  2774. tt_assert(environment_variable_names_equal("abc", "abc="));
  2775. tt_assert(environment_variable_names_equal("abc", "abc=def"));
  2776. tt_assert(environment_variable_names_equal("abc=def", "abc"));
  2777. tt_assert(environment_variable_names_equal("abc=def", "abc=ghi"));
  2778. tt_assert(!environment_variable_names_equal("abc", "abcd"));
  2779. tt_assert(!environment_variable_names_equal("abc=", "abcd"));
  2780. tt_assert(!environment_variable_names_equal("abc=", "abcd"));
  2781. tt_assert(!environment_variable_names_equal("abc=", "def"));
  2782. tt_assert(!environment_variable_names_equal("abc=", "def="));
  2783. tt_assert(!environment_variable_names_equal("abc=x", "def=x"));
  2784. tt_assert(!environment_variable_names_equal("", "a=def"));
  2785. /* A bit surprising. */
  2786. tt_assert(environment_variable_names_equal("", "=def"));
  2787. tt_assert(environment_variable_names_equal("=y", "=x"));
  2788. done:
  2789. ;
  2790. }
  2791. /** Test process_environment_make */
  2792. static void
  2793. test_util_make_environment(void *ptr)
  2794. {
  2795. const char *env_vars_string =
  2796. "PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/bin\n"
  2797. "HOME=/home/foozer\n";
  2798. const char expected_windows_env_block[] =
  2799. "HOME=/home/foozer\000"
  2800. "PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/bin\000"
  2801. "\000";
  2802. size_t expected_windows_env_block_len =
  2803. sizeof(expected_windows_env_block) - 1;
  2804. smartlist_t *env_vars = smartlist_new_from_text_lines(env_vars_string);
  2805. smartlist_t *env_vars_sorted = smartlist_new();
  2806. smartlist_t *env_vars_in_unixoid_env_block_sorted = smartlist_new();
  2807. process_environment_t *env;
  2808. (void)ptr;
  2809. env = process_environment_make(env_vars);
  2810. /* Check that the Windows environment block is correct. */
  2811. tt_want(tor_memeq(expected_windows_env_block, env->windows_environment_block,
  2812. expected_windows_env_block_len));
  2813. /* Now for the Unixoid environment block. We don't care which order
  2814. * these environment variables are in, so we sort both lists first. */
  2815. smartlist_add_all(env_vars_sorted, env_vars);
  2816. {
  2817. char **v;
  2818. for (v = env->unixoid_environment_block; *v; ++v) {
  2819. smartlist_add(env_vars_in_unixoid_env_block_sorted, *v);
  2820. }
  2821. }
  2822. smartlist_sort_strings(env_vars_sorted);
  2823. smartlist_sort_strings(env_vars_in_unixoid_env_block_sorted);
  2824. tt_want_int_op(smartlist_len(env_vars_sorted), ==,
  2825. smartlist_len(env_vars_in_unixoid_env_block_sorted));
  2826. {
  2827. int len = smartlist_len(env_vars_sorted);
  2828. int i;
  2829. if (smartlist_len(env_vars_in_unixoid_env_block_sorted) < len) {
  2830. len = smartlist_len(env_vars_in_unixoid_env_block_sorted);
  2831. }
  2832. for (i = 0; i < len; ++i) {
  2833. tt_want_str_op(smartlist_get(env_vars_sorted, i), ==,
  2834. smartlist_get(env_vars_in_unixoid_env_block_sorted, i));
  2835. }
  2836. }
  2837. /* Clean up. */
  2838. smartlist_free(env_vars_in_unixoid_env_block_sorted);
  2839. smartlist_free(env_vars_sorted);
  2840. SMARTLIST_FOREACH(env_vars, char *, x, tor_free(x));
  2841. smartlist_free(env_vars);
  2842. process_environment_free(env);
  2843. }
  2844. /** Test set_environment_variable_in_smartlist */
  2845. static void
  2846. test_util_set_env_var_in_sl(void *ptr)
  2847. {
  2848. /* The environment variables in these strings are in arbitrary
  2849. * order; we sort the resulting lists before comparing them.
  2850. *
  2851. * (They *will not* end up in the order shown in
  2852. * expected_resulting_env_vars_string.) */
  2853. const char *base_env_vars_string =
  2854. "PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/bin\n"
  2855. "HOME=/home/foozer\n"
  2856. "TERM=xterm\n"
  2857. "SHELL=/bin/ksh\n"
  2858. "USER=foozer\n"
  2859. "LOGNAME=foozer\n"
  2860. "USERNAME=foozer\n"
  2861. "LANG=en_US.utf8\n"
  2862. ;
  2863. const char *new_env_vars_string =
  2864. "TERM=putty\n"
  2865. "DISPLAY=:18.0\n"
  2866. ;
  2867. const char *expected_resulting_env_vars_string =
  2868. "PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/bin\n"
  2869. "HOME=/home/foozer\n"
  2870. "TERM=putty\n"
  2871. "SHELL=/bin/ksh\n"
  2872. "USER=foozer\n"
  2873. "LOGNAME=foozer\n"
  2874. "USERNAME=foozer\n"
  2875. "LANG=en_US.utf8\n"
  2876. "DISPLAY=:18.0\n"
  2877. ;
  2878. smartlist_t *merged_env_vars =
  2879. smartlist_new_from_text_lines(base_env_vars_string);
  2880. smartlist_t *new_env_vars =
  2881. smartlist_new_from_text_lines(new_env_vars_string);
  2882. smartlist_t *expected_resulting_env_vars =
  2883. smartlist_new_from_text_lines(expected_resulting_env_vars_string);
  2884. /* Elements of merged_env_vars are heap-allocated, and must be
  2885. * freed. Some of them are (or should) be freed by
  2886. * set_environment_variable_in_smartlist.
  2887. *
  2888. * Elements of new_env_vars are heap-allocated, but are copied into
  2889. * merged_env_vars, so they are not freed separately at the end of
  2890. * the function.
  2891. *
  2892. * Elements of expected_resulting_env_vars are heap-allocated, and
  2893. * must be freed. */
  2894. (void)ptr;
  2895. SMARTLIST_FOREACH(new_env_vars, char *, env_var,
  2896. set_environment_variable_in_smartlist(merged_env_vars,
  2897. env_var,
  2898. tor_free_,
  2899. 1));
  2900. smartlist_sort_strings(merged_env_vars);
  2901. smartlist_sort_strings(expected_resulting_env_vars);
  2902. tt_want_int_op(smartlist_len(merged_env_vars), ==,
  2903. smartlist_len(expected_resulting_env_vars));
  2904. {
  2905. int len = smartlist_len(merged_env_vars);
  2906. int i;
  2907. if (smartlist_len(expected_resulting_env_vars) < len) {
  2908. len = smartlist_len(expected_resulting_env_vars);
  2909. }
  2910. for (i = 0; i < len; ++i) {
  2911. tt_want_str_op(smartlist_get(merged_env_vars, i), ==,
  2912. smartlist_get(expected_resulting_env_vars, i));
  2913. }
  2914. }
  2915. /* Clean up. */
  2916. SMARTLIST_FOREACH(merged_env_vars, char *, x, tor_free(x));
  2917. smartlist_free(merged_env_vars);
  2918. smartlist_free(new_env_vars);
  2919. SMARTLIST_FOREACH(expected_resulting_env_vars, char *, x, tor_free(x));
  2920. smartlist_free(expected_resulting_env_vars);
  2921. }
  2922. static void
  2923. test_util_weak_random(void *arg)
  2924. {
  2925. int i, j, n[16];
  2926. tor_weak_rng_t rng;
  2927. (void) arg;
  2928. tor_init_weak_random(&rng, (unsigned)time(NULL));
  2929. for (i = 1; i <= 256; ++i) {
  2930. for (j=0;j<100;++j) {
  2931. int r = tor_weak_random_range(&rng, i);
  2932. tt_int_op(0, <=, r);
  2933. tt_int_op(r, <, i);
  2934. }
  2935. }
  2936. memset(n,0,sizeof(n));
  2937. for (j=0;j<8192;++j) {
  2938. n[tor_weak_random_range(&rng, 16)]++;
  2939. }
  2940. for (i=0;i<16;++i)
  2941. tt_int_op(n[i], >, 0);
  2942. done:
  2943. ;
  2944. }
  2945. static void
  2946. test_util_mathlog(void *arg)
  2947. {
  2948. double d;
  2949. (void) arg;
  2950. d = tor_mathlog(2.718281828);
  2951. tt_double_op(fabs(d - 1.0), <, .000001);
  2952. d = tor_mathlog(10);
  2953. tt_double_op(fabs(d - 2.30258509), <, .000001);
  2954. done:
  2955. ;
  2956. }
  2957. static void
  2958. test_util_round_to_next_multiple_of(void *arg)
  2959. {
  2960. (void)arg;
  2961. test_assert(round_uint64_to_next_multiple_of(0,1) == 0);
  2962. test_assert(round_uint64_to_next_multiple_of(0,7) == 0);
  2963. test_assert(round_uint64_to_next_multiple_of(99,1) == 99);
  2964. test_assert(round_uint64_to_next_multiple_of(99,7) == 105);
  2965. test_assert(round_uint64_to_next_multiple_of(99,9) == 99);
  2966. done:
  2967. ;
  2968. }
  2969. static void
  2970. test_util_strclear(void *arg)
  2971. {
  2972. static const char *vals[] = { "", "a", "abcdef", "abcdefgh", NULL };
  2973. int i;
  2974. char *v = NULL;
  2975. (void)arg;
  2976. for (i = 0; vals[i]; ++i) {
  2977. size_t n;
  2978. v = tor_strdup(vals[i]);
  2979. n = strlen(v);
  2980. tor_strclear(v);
  2981. tt_assert(tor_mem_is_zero(v, n+1));
  2982. tor_free(v);
  2983. }
  2984. done:
  2985. tor_free(v);
  2986. }
  2987. #define UTIL_LEGACY(name) \
  2988. { #name, legacy_test_helper, 0, &legacy_setup, test_util_ ## name }
  2989. #define UTIL_TEST(name, flags) \
  2990. { #name, test_util_ ## name, flags, NULL, NULL }
  2991. #ifdef FD_CLOEXEC
  2992. #define CAN_CHECK_CLOEXEC
  2993. static int
  2994. fd_is_cloexec(tor_socket_t fd)
  2995. {
  2996. int flags = fcntl(fd, F_GETFD, 0);
  2997. return (flags & FD_CLOEXEC) == FD_CLOEXEC;
  2998. }
  2999. #endif
  3000. #ifndef _WIN32
  3001. #define CAN_CHECK_NONBLOCK
  3002. static int
  3003. fd_is_nonblocking(tor_socket_t fd)
  3004. {
  3005. int flags = fcntl(fd, F_GETFL, 0);
  3006. return (flags & O_NONBLOCK) == O_NONBLOCK;
  3007. }
  3008. #endif
  3009. static void
  3010. test_util_socket(void *arg)
  3011. {
  3012. tor_socket_t fd1 = TOR_INVALID_SOCKET;
  3013. tor_socket_t fd2 = TOR_INVALID_SOCKET;
  3014. tor_socket_t fd3 = TOR_INVALID_SOCKET;
  3015. tor_socket_t fd4 = TOR_INVALID_SOCKET;
  3016. int n = get_n_open_sockets();
  3017. TT_BLATHER(("Starting with %d open sockets.", n));
  3018. (void)arg;
  3019. fd1 = tor_open_socket_with_extensions(AF_INET, SOCK_STREAM, 0, 0, 0);
  3020. fd2 = tor_open_socket_with_extensions(AF_INET, SOCK_STREAM, 0, 0, 1);
  3021. tt_assert(SOCKET_OK(fd1));
  3022. tt_assert(SOCKET_OK(fd2));
  3023. tt_int_op(get_n_open_sockets(), ==, n + 2);
  3024. //fd3 = tor_open_socket_with_extensions(AF_INET, SOCK_STREAM, 0, 1, 0);
  3025. //fd4 = tor_open_socket_with_extensions(AF_INET, SOCK_STREAM, 0, 1, 1);
  3026. fd3 = tor_open_socket(AF_INET, SOCK_STREAM, 0);
  3027. fd4 = tor_open_socket_nonblocking(AF_INET, SOCK_STREAM, 0);
  3028. tt_assert(SOCKET_OK(fd3));
  3029. tt_assert(SOCKET_OK(fd4));
  3030. tt_int_op(get_n_open_sockets(), ==, n + 4);
  3031. #ifdef CAN_CHECK_CLOEXEC
  3032. tt_int_op(fd_is_cloexec(fd1), ==, 0);
  3033. tt_int_op(fd_is_cloexec(fd2), ==, 0);
  3034. tt_int_op(fd_is_cloexec(fd3), ==, 1);
  3035. tt_int_op(fd_is_cloexec(fd4), ==, 1);
  3036. #endif
  3037. #ifdef CAN_CHECK_NONBLOCK
  3038. tt_int_op(fd_is_nonblocking(fd1), ==, 0);
  3039. tt_int_op(fd_is_nonblocking(fd2), ==, 1);
  3040. tt_int_op(fd_is_nonblocking(fd3), ==, 0);
  3041. tt_int_op(fd_is_nonblocking(fd4), ==, 1);
  3042. #endif
  3043. tor_close_socket(fd1);
  3044. tor_close_socket(fd2);
  3045. fd1 = fd2 = TOR_INVALID_SOCKET;
  3046. tt_int_op(get_n_open_sockets(), ==, n + 2);
  3047. tor_close_socket(fd3);
  3048. tor_close_socket(fd4);
  3049. fd3 = fd4 = TOR_INVALID_SOCKET;
  3050. tt_int_op(get_n_open_sockets(), ==, n);
  3051. done:
  3052. if (SOCKET_OK(fd1))
  3053. tor_close_socket(fd1);
  3054. if (SOCKET_OK(fd2))
  3055. tor_close_socket(fd2);
  3056. if (SOCKET_OK(fd3))
  3057. tor_close_socket(fd3);
  3058. if (SOCKET_OK(fd4))
  3059. tor_close_socket(fd4);
  3060. }
  3061. static void *
  3062. socketpair_test_setup(const struct testcase_t *testcase)
  3063. {
  3064. return testcase->setup_data;
  3065. }
  3066. static int
  3067. socketpair_test_cleanup(const struct testcase_t *testcase, void *ptr)
  3068. {
  3069. (void)testcase;
  3070. (void)ptr;
  3071. return 1;
  3072. }
  3073. static const struct testcase_setup_t socketpair_setup = {
  3074. socketpair_test_setup, socketpair_test_cleanup
  3075. };
  3076. /* Test for socketpair and ersatz_socketpair(). We test them both, since
  3077. * the latter is a tolerably good way to exersize tor_accept_socket(). */
  3078. static void
  3079. test_util_socketpair(void *arg)
  3080. {
  3081. const int ersatz = !strcmp(arg, "1");
  3082. int (*const tor_socketpair_fn)(int, int, int, tor_socket_t[2]) =
  3083. ersatz ? tor_ersatz_socketpair : tor_socketpair;
  3084. int n = get_n_open_sockets();
  3085. tor_socket_t fds[2] = {TOR_INVALID_SOCKET, TOR_INVALID_SOCKET};
  3086. const int family = AF_UNIX;
  3087. tt_int_op(0, ==, tor_socketpair_fn(family, SOCK_STREAM, 0, fds));
  3088. tt_assert(SOCKET_OK(fds[0]));
  3089. tt_assert(SOCKET_OK(fds[1]));
  3090. tt_int_op(get_n_open_sockets(), ==, n + 2);
  3091. #ifdef CAN_CHECK_CLOEXEC
  3092. tt_int_op(fd_is_cloexec(fds[0]), ==, 1);
  3093. tt_int_op(fd_is_cloexec(fds[1]), ==, 1);
  3094. #endif
  3095. #ifdef CAN_CHECK_NONBLOCK
  3096. tt_int_op(fd_is_nonblocking(fds[0]), ==, 0);
  3097. tt_int_op(fd_is_nonblocking(fds[1]), ==, 0);
  3098. #endif
  3099. done:
  3100. if (SOCKET_OK(fds[0]))
  3101. tor_close_socket(fds[0]);
  3102. if (SOCKET_OK(fds[1]))
  3103. tor_close_socket(fds[1]);
  3104. }
  3105. struct testcase_t util_tests[] = {
  3106. UTIL_LEGACY(time),
  3107. UTIL_TEST(parse_http_time, 0),
  3108. UTIL_LEGACY(config_line),
  3109. UTIL_LEGACY(config_line_quotes),
  3110. UTIL_LEGACY(config_line_comment_character),
  3111. UTIL_LEGACY(config_line_escaped_content),
  3112. #ifndef _WIN32
  3113. UTIL_LEGACY(expand_filename),
  3114. #endif
  3115. UTIL_LEGACY(escape_string_socks),
  3116. UTIL_LEGACY(string_is_key_value),
  3117. UTIL_LEGACY(strmisc),
  3118. UTIL_LEGACY(pow2),
  3119. UTIL_LEGACY(gzip),
  3120. UTIL_LEGACY(datadir),
  3121. UTIL_LEGACY(mempool),
  3122. UTIL_LEGACY(memarea),
  3123. UTIL_LEGACY(control_formats),
  3124. UTIL_LEGACY(mmap),
  3125. UTIL_LEGACY(threads),
  3126. UTIL_LEGACY(sscanf),
  3127. UTIL_LEGACY(path_is_relative),
  3128. UTIL_LEGACY(strtok),
  3129. UTIL_LEGACY(di_ops),
  3130. UTIL_TEST(round_to_next_multiple_of, 0),
  3131. UTIL_TEST(strclear, 0),
  3132. UTIL_TEST(find_str_at_start_of_line, 0),
  3133. UTIL_TEST(string_is_C_identifier, 0),
  3134. UTIL_TEST(asprintf, 0),
  3135. UTIL_TEST(listdir, 0),
  3136. UTIL_TEST(parent_dir, 0),
  3137. #ifdef _WIN32
  3138. UTIL_TEST(load_win_lib, 0),
  3139. #endif
  3140. #ifndef _WIN32
  3141. UTIL_TEST(exit_status, 0),
  3142. UTIL_TEST(fgets_eagain, TT_SKIP),
  3143. #endif
  3144. UTIL_TEST(spawn_background_ok, 0),
  3145. UTIL_TEST(spawn_background_fail, 0),
  3146. UTIL_TEST(spawn_background_partial_read, 0),
  3147. UTIL_TEST(format_hex_number, 0),
  3148. UTIL_TEST(format_dec_number, 0),
  3149. UTIL_TEST(join_win_cmdline, 0),
  3150. UTIL_TEST(split_lines, 0),
  3151. UTIL_TEST(n_bits_set, 0),
  3152. UTIL_TEST(eat_whitespace, 0),
  3153. UTIL_TEST(sl_new_from_text_lines, 0),
  3154. UTIL_TEST(envnames, 0),
  3155. UTIL_TEST(make_environment, 0),
  3156. UTIL_TEST(set_env_var_in_sl, 0),
  3157. UTIL_TEST(read_file_eof_tiny_limit, 0),
  3158. UTIL_TEST(read_file_eof_two_loops, 0),
  3159. UTIL_TEST(read_file_eof_zero_bytes, 0),
  3160. UTIL_TEST(write_chunks_to_file, 0),
  3161. UTIL_TEST(mathlog, 0),
  3162. UTIL_TEST(weak_random, 0),
  3163. UTIL_TEST(socket, TT_FORK),
  3164. { "socketpair", test_util_socketpair, TT_FORK, &socketpair_setup,
  3165. (void*)"0" },
  3166. { "socketpair_ersatz", test_util_socketpair, TT_FORK,
  3167. &socketpair_setup, (void*)"1" },
  3168. END_OF_TESTCASES
  3169. };