test_util.c 99 KB

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