test_util.c 98 KB

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