test_util.c 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638
  1. /* Copyright (c) 2001-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2011, 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. static void
  16. test_util_time(void)
  17. {
  18. struct timeval start, end;
  19. struct tm a_time;
  20. char timestr[RFC1123_TIME_LEN+1];
  21. time_t t_res;
  22. int i;
  23. start.tv_sec = 5;
  24. start.tv_usec = 5000;
  25. end.tv_sec = 5;
  26. end.tv_usec = 5000;
  27. test_eq(0L, tv_udiff(&start, &end));
  28. end.tv_usec = 7000;
  29. test_eq(2000L, tv_udiff(&start, &end));
  30. end.tv_sec = 6;
  31. test_eq(1002000L, tv_udiff(&start, &end));
  32. end.tv_usec = 0;
  33. test_eq(995000L, tv_udiff(&start, &end));
  34. end.tv_sec = 4;
  35. test_eq(-1005000L, tv_udiff(&start, &end));
  36. end.tv_usec = 999990;
  37. start.tv_sec = 1;
  38. start.tv_usec = 500;
  39. /* The test values here are confirmed to be correct on a platform
  40. * with a working timegm. */
  41. a_time.tm_year = 2003-1900;
  42. a_time.tm_mon = 7;
  43. a_time.tm_mday = 30;
  44. a_time.tm_hour = 6;
  45. a_time.tm_min = 14;
  46. a_time.tm_sec = 55;
  47. test_eq((time_t) 1062224095UL, tor_timegm(&a_time));
  48. a_time.tm_year = 2004-1900; /* Try a leap year, after feb. */
  49. test_eq((time_t) 1093846495UL, tor_timegm(&a_time));
  50. a_time.tm_mon = 1; /* Try a leap year, in feb. */
  51. a_time.tm_mday = 10;
  52. test_eq((time_t) 1076393695UL, tor_timegm(&a_time));
  53. format_rfc1123_time(timestr, 0);
  54. test_streq("Thu, 01 Jan 1970 00:00:00 GMT", timestr);
  55. format_rfc1123_time(timestr, (time_t)1091580502UL);
  56. test_streq("Wed, 04 Aug 2004 00:48:22 GMT", timestr);
  57. t_res = 0;
  58. i = parse_rfc1123_time(timestr, &t_res);
  59. test_eq(i,0);
  60. test_eq(t_res, (time_t)1091580502UL);
  61. test_eq(-1, parse_rfc1123_time("Wed, zz Aug 2004 99-99x99 GMT", &t_res));
  62. tor_gettimeofday(&start);
  63. /* now make sure time works. */
  64. tor_gettimeofday(&end);
  65. /* We might've timewarped a little. */
  66. tt_int_op(tv_udiff(&start, &end), >=, -5000);
  67. done:
  68. ;
  69. }
  70. static void
  71. test_util_config_line(void)
  72. {
  73. char buf[1024];
  74. char *k=NULL, *v=NULL;
  75. const char *str;
  76. /* Test parse_config_line_from_str */
  77. strlcpy(buf, "k v\n" " key value with spaces \n" "keykey val\n"
  78. "k2\n"
  79. "k3 \n" "\n" " \n" "#comment\n"
  80. "k4#a\n" "k5#abc\n" "k6 val #with comment\n"
  81. "kseven \"a quoted 'string\"\n"
  82. "k8 \"a \\x71uoted\\n\\\"str\\\\ing\\t\\001\\01\\1\\\"\"\n"
  83. "k9 a line that\\\n spans two lines.\n\n"
  84. "k10 more than\\\n one contin\\\nuation\n"
  85. "k11 \\\ncontinuation at the start\n"
  86. "k12 line with a\\\n#comment\n embedded\n"
  87. "k13\\\ncontinuation at the very start\n"
  88. "k14 a line that has a comment and # ends with a slash \\\n"
  89. "k15 this should be the next new line\n"
  90. "k16 a line that has a comment and # ends without a slash \n"
  91. "k17 this should be the next new line\n"
  92. , sizeof(buf));
  93. str = buf;
  94. str = parse_config_line_from_str(str, &k, &v);
  95. test_streq(k, "k");
  96. test_streq(v, "v");
  97. tor_free(k); tor_free(v);
  98. test_assert(!strcmpstart(str, "key value with"));
  99. str = parse_config_line_from_str(str, &k, &v);
  100. test_streq(k, "key");
  101. test_streq(v, "value with spaces");
  102. tor_free(k); tor_free(v);
  103. test_assert(!strcmpstart(str, "keykey"));
  104. str = parse_config_line_from_str(str, &k, &v);
  105. test_streq(k, "keykey");
  106. test_streq(v, "val");
  107. tor_free(k); tor_free(v);
  108. test_assert(!strcmpstart(str, "k2\n"));
  109. str = parse_config_line_from_str(str, &k, &v);
  110. test_streq(k, "k2");
  111. test_streq(v, "");
  112. tor_free(k); tor_free(v);
  113. test_assert(!strcmpstart(str, "k3 \n"));
  114. str = parse_config_line_from_str(str, &k, &v);
  115. test_streq(k, "k3");
  116. test_streq(v, "");
  117. tor_free(k); tor_free(v);
  118. test_assert(!strcmpstart(str, "#comment"));
  119. str = parse_config_line_from_str(str, &k, &v);
  120. test_streq(k, "k4");
  121. test_streq(v, "");
  122. tor_free(k); tor_free(v);
  123. test_assert(!strcmpstart(str, "k5#abc"));
  124. str = parse_config_line_from_str(str, &k, &v);
  125. test_streq(k, "k5");
  126. test_streq(v, "");
  127. tor_free(k); tor_free(v);
  128. test_assert(!strcmpstart(str, "k6"));
  129. str = parse_config_line_from_str(str, &k, &v);
  130. test_streq(k, "k6");
  131. test_streq(v, "val");
  132. tor_free(k); tor_free(v);
  133. test_assert(!strcmpstart(str, "kseven"));
  134. str = parse_config_line_from_str(str, &k, &v);
  135. test_streq(k, "kseven");
  136. test_streq(v, "a quoted \'string");
  137. tor_free(k); tor_free(v);
  138. test_assert(!strcmpstart(str, "k8 "));
  139. str = parse_config_line_from_str(str, &k, &v);
  140. test_streq(k, "k8");
  141. test_streq(v, "a quoted\n\"str\\ing\t\x01\x01\x01\"");
  142. tor_free(k); tor_free(v);
  143. str = parse_config_line_from_str(str, &k, &v);
  144. test_streq(k, "k9");
  145. test_streq(v, "a line that spans two lines.");
  146. tor_free(k); tor_free(v);
  147. str = parse_config_line_from_str(str, &k, &v);
  148. test_streq(k, "k10");
  149. test_streq(v, "more than one continuation");
  150. tor_free(k); tor_free(v);
  151. str = parse_config_line_from_str(str, &k, &v);
  152. test_streq(k, "k11");
  153. test_streq(v, "continuation at the start");
  154. tor_free(k); tor_free(v);
  155. str = parse_config_line_from_str(str, &k, &v);
  156. test_streq(k, "k12");
  157. test_streq(v, "line with a embedded");
  158. tor_free(k); tor_free(v);
  159. str = parse_config_line_from_str(str, &k, &v);
  160. test_streq(k, "k13");
  161. test_streq(v, "continuation at the very start");
  162. tor_free(k); tor_free(v);
  163. str = parse_config_line_from_str(str, &k, &v);
  164. test_streq(k, "k14");
  165. test_streq(v, "a line that has a comment and" );
  166. tor_free(k); tor_free(v);
  167. str = parse_config_line_from_str(str, &k, &v);
  168. test_streq(k, "k15");
  169. test_streq(v, "this should be the next new line");
  170. tor_free(k); tor_free(v);
  171. str = parse_config_line_from_str(str, &k, &v);
  172. test_streq(k, "k16");
  173. test_streq(v, "a line that has a comment and" );
  174. tor_free(k); tor_free(v);
  175. str = parse_config_line_from_str(str, &k, &v);
  176. test_streq(k, "k17");
  177. test_streq(v, "this should be the next new line");
  178. tor_free(k); tor_free(v);
  179. test_streq(str, "");
  180. done:
  181. tor_free(k);
  182. tor_free(v);
  183. }
  184. /** Test basic string functionality. */
  185. static void
  186. test_util_strmisc(void)
  187. {
  188. char buf[1024];
  189. int i;
  190. char *cp;
  191. /* Tests for corner cases of strl operations */
  192. test_eq(5, strlcpy(buf, "Hello", 0));
  193. strlcpy(buf, "Hello", sizeof(buf));
  194. test_eq(10, strlcat(buf, "Hello", 5));
  195. /* Test tor_strstrip() */
  196. strlcpy(buf, "Testing 1 2 3", sizeof(buf));
  197. tor_strstrip(buf, ",!");
  198. test_streq(buf, "Testing 1 2 3");
  199. strlcpy(buf, "!Testing 1 2 3?", sizeof(buf));
  200. tor_strstrip(buf, "!? ");
  201. test_streq(buf, "Testing123");
  202. /* Test tor_parse_long. */
  203. test_eq(10L, tor_parse_long("10",10,0,100,NULL,NULL));
  204. test_eq(0L, tor_parse_long("10",10,50,100,NULL,NULL));
  205. test_eq(-50L, tor_parse_long("-50",10,-100,100,NULL,NULL));
  206. /* Test tor_parse_ulong */
  207. test_eq(10UL, tor_parse_ulong("10",10,0,100,NULL,NULL));
  208. test_eq(0UL, tor_parse_ulong("10",10,50,100,NULL,NULL));
  209. /* Test tor_parse_uint64. */
  210. test_assert(U64_LITERAL(10) == tor_parse_uint64("10 x",10,0,100, &i, &cp));
  211. test_assert(i == 1);
  212. test_streq(cp, " x");
  213. test_assert(U64_LITERAL(12345678901) ==
  214. tor_parse_uint64("12345678901",10,0,UINT64_MAX, &i, &cp));
  215. test_assert(i == 1);
  216. test_streq(cp, "");
  217. test_assert(U64_LITERAL(0) ==
  218. tor_parse_uint64("12345678901",10,500,INT32_MAX, &i, &cp));
  219. test_assert(i == 0);
  220. {
  221. /* Test tor_parse_double. */
  222. double d = tor_parse_double("10", 0, UINT64_MAX,&i,NULL);
  223. test_assert(i == 1);
  224. test_assert(DBL_TO_U64(d) == 10);
  225. d = tor_parse_double("0", 0, UINT64_MAX,&i,NULL);
  226. test_assert(i == 1);
  227. test_assert(DBL_TO_U64(d) == 0);
  228. d = tor_parse_double(" ", 0, UINT64_MAX,&i,NULL);
  229. test_assert(i == 0);
  230. d = tor_parse_double(".0a", 0, UINT64_MAX,&i,NULL);
  231. test_assert(i == 0);
  232. d = tor_parse_double(".0a", 0, UINT64_MAX,&i,&cp);
  233. test_assert(i == 1);
  234. d = tor_parse_double("-.0", 0, UINT64_MAX,&i,NULL);
  235. test_assert(i == 1);
  236. }
  237. /* Test failing snprintf cases */
  238. test_eq(-1, tor_snprintf(buf, 0, "Foo"));
  239. test_eq(-1, tor_snprintf(buf, 2, "Foo"));
  240. /* Test printf with uint64 */
  241. tor_snprintf(buf, sizeof(buf), "x!"U64_FORMAT"!x",
  242. U64_PRINTF_ARG(U64_LITERAL(12345678901)));
  243. test_streq(buf, "x!12345678901!x");
  244. /* Test for strcmpstart and strcmpend. */
  245. test_assert(strcmpstart("abcdef", "abcdef")==0);
  246. test_assert(strcmpstart("abcdef", "abc")==0);
  247. test_assert(strcmpstart("abcdef", "abd")<0);
  248. test_assert(strcmpstart("abcdef", "abb")>0);
  249. test_assert(strcmpstart("ab", "abb")<0);
  250. test_assert(strcmpend("abcdef", "abcdef")==0);
  251. test_assert(strcmpend("abcdef", "def")==0);
  252. test_assert(strcmpend("abcdef", "deg")<0);
  253. test_assert(strcmpend("abcdef", "dee")>0);
  254. test_assert(strcmpend("ab", "abb")<0);
  255. test_assert(strcasecmpend("AbcDEF", "abcdef")==0);
  256. test_assert(strcasecmpend("abcdef", "dEF")==0);
  257. test_assert(strcasecmpend("abcDEf", "deg")<0);
  258. test_assert(strcasecmpend("abcdef", "DEE")>0);
  259. test_assert(strcasecmpend("ab", "abB")<0);
  260. /* Test mem_is_zero */
  261. memset(buf,0,128);
  262. buf[128] = 'x';
  263. test_assert(tor_digest_is_zero(buf));
  264. test_assert(tor_mem_is_zero(buf, 10));
  265. test_assert(tor_mem_is_zero(buf, 20));
  266. test_assert(tor_mem_is_zero(buf, 128));
  267. test_assert(!tor_mem_is_zero(buf, 129));
  268. buf[60] = (char)255;
  269. test_assert(!tor_mem_is_zero(buf, 128));
  270. buf[0] = (char)1;
  271. test_assert(!tor_mem_is_zero(buf, 10));
  272. /* Test 'escaped' */
  273. test_streq("\"\"", escaped(""));
  274. test_streq("\"abcd\"", escaped("abcd"));
  275. test_streq("\"\\\\\\n\\r\\t\\\"\\'\"", escaped("\\\n\r\t\"\'"));
  276. test_streq("\"z\\001abc\\277d\"", escaped("z\001abc\277d"));
  277. test_assert(NULL == escaped(NULL));
  278. /* Test strndup and memdup */
  279. {
  280. const char *s = "abcdefghijklmnopqrstuvwxyz";
  281. cp = tor_strndup(s, 30);
  282. test_streq(cp, s); /* same string, */
  283. test_neq(cp, s); /* but different pointers. */
  284. tor_free(cp);
  285. cp = tor_strndup(s, 5);
  286. test_streq(cp, "abcde");
  287. tor_free(cp);
  288. s = "a\0b\0c\0d\0e\0";
  289. cp = tor_memdup(s,10);
  290. test_memeq(cp, s, 10); /* same ram, */
  291. test_neq(cp, s); /* but different pointers. */
  292. tor_free(cp);
  293. }
  294. /* Test str-foo functions */
  295. cp = tor_strdup("abcdef");
  296. test_assert(tor_strisnonupper(cp));
  297. cp[3] = 'D';
  298. test_assert(!tor_strisnonupper(cp));
  299. tor_strupper(cp);
  300. test_streq(cp, "ABCDEF");
  301. test_assert(tor_strisprint(cp));
  302. cp[3] = 3;
  303. test_assert(!tor_strisprint(cp));
  304. tor_free(cp);
  305. /* Test eat_whitespace. */
  306. {
  307. const char *s = " \n a";
  308. test_eq_ptr(eat_whitespace(s), s+4);
  309. s = "abcd";
  310. test_eq_ptr(eat_whitespace(s), s);
  311. s = "#xyz\nab";
  312. test_eq_ptr(eat_whitespace(s), s+5);
  313. }
  314. /* Test memmem and memstr */
  315. {
  316. const char *haystack = "abcde";
  317. tt_assert(!tor_memmem(haystack, 5, "ef", 2));
  318. test_eq_ptr(tor_memmem(haystack, 5, "cd", 2), haystack + 2);
  319. test_eq_ptr(tor_memmem(haystack, 5, "cde", 3), haystack + 2);
  320. haystack = "ababcad";
  321. test_eq_ptr(tor_memmem(haystack, 7, "abc", 3), haystack + 2);
  322. test_eq_ptr(tor_memstr(haystack, 7, "abc"), haystack + 2);
  323. test_assert(!tor_memstr(haystack, 7, "fe"));
  324. test_assert(!tor_memstr(haystack, 7, "longerthantheoriginal"));
  325. }
  326. /* Test wrap_string */
  327. {
  328. smartlist_t *sl = smartlist_create();
  329. wrap_string(sl, "This is a test of string wrapping functionality: woot.",
  330. 10, "", "");
  331. cp = smartlist_join_strings(sl, "", 0, NULL);
  332. test_streq(cp,
  333. "This is a\ntest of\nstring\nwrapping\nfunctional\nity: woot.\n");
  334. tor_free(cp);
  335. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  336. smartlist_clear(sl);
  337. wrap_string(sl, "This is a test of string wrapping functionality: woot.",
  338. 16, "### ", "# ");
  339. cp = smartlist_join_strings(sl, "", 0, NULL);
  340. test_streq(cp,
  341. "### This is a\n# test of string\n# wrapping\n# functionality:\n"
  342. "# woot.\n");
  343. tor_free(cp);
  344. SMARTLIST_FOREACH(sl, char *, cp, tor_free(cp));
  345. smartlist_free(sl);
  346. }
  347. done:
  348. ;
  349. }
  350. static void
  351. test_util_pow2(void)
  352. {
  353. /* Test tor_log2(). */
  354. test_eq(tor_log2(64), 6);
  355. test_eq(tor_log2(65), 6);
  356. test_eq(tor_log2(63), 5);
  357. test_eq(tor_log2(1), 0);
  358. test_eq(tor_log2(2), 1);
  359. test_eq(tor_log2(3), 1);
  360. test_eq(tor_log2(4), 2);
  361. test_eq(tor_log2(5), 2);
  362. test_eq(tor_log2(U64_LITERAL(40000000000000000)), 55);
  363. test_eq(tor_log2(UINT64_MAX), 63);
  364. /* Test round_to_power_of_2 */
  365. test_eq(round_to_power_of_2(120), 128);
  366. test_eq(round_to_power_of_2(128), 128);
  367. test_eq(round_to_power_of_2(130), 128);
  368. test_eq(round_to_power_of_2(U64_LITERAL(40000000000000000)),
  369. U64_LITERAL(1)<<55);
  370. test_eq(round_to_power_of_2(0), 2);
  371. done:
  372. ;
  373. }
  374. /** mutex for thread test to stop the threads hitting data at the same time. */
  375. static tor_mutex_t *_thread_test_mutex = NULL;
  376. /** mutexes for the thread test to make sure that the threads have to
  377. * interleave somewhat. */
  378. static tor_mutex_t *_thread_test_start1 = NULL,
  379. *_thread_test_start2 = NULL;
  380. /** Shared strmap for the thread test. */
  381. static strmap_t *_thread_test_strmap = NULL;
  382. /** The name of thread1 for the thread test */
  383. static char *_thread1_name = NULL;
  384. /** The name of thread2 for the thread test */
  385. static char *_thread2_name = NULL;
  386. static void _thread_test_func(void* _s) ATTR_NORETURN;
  387. /** How many iterations have the threads in the unit test run? */
  388. static int t1_count = 0, t2_count = 0;
  389. /** Helper function for threading unit tests: This function runs in a
  390. * subthread. It grabs its own mutex (start1 or start2) to make sure that it
  391. * should start, then it repeatedly alters _test_thread_strmap protected by
  392. * _thread_test_mutex. */
  393. static void
  394. _thread_test_func(void* _s)
  395. {
  396. char *s = _s;
  397. int i, *count;
  398. tor_mutex_t *m;
  399. char buf[64];
  400. char **cp;
  401. if (!strcmp(s, "thread 1")) {
  402. m = _thread_test_start1;
  403. cp = &_thread1_name;
  404. count = &t1_count;
  405. } else {
  406. m = _thread_test_start2;
  407. cp = &_thread2_name;
  408. count = &t2_count;
  409. }
  410. tor_snprintf(buf, sizeof(buf), "%lu", tor_get_thread_id());
  411. *cp = tor_strdup(buf);
  412. tor_mutex_acquire(m);
  413. for (i=0; i<10000; ++i) {
  414. tor_mutex_acquire(_thread_test_mutex);
  415. strmap_set(_thread_test_strmap, "last to run", *cp);
  416. ++*count;
  417. tor_mutex_release(_thread_test_mutex);
  418. }
  419. tor_mutex_acquire(_thread_test_mutex);
  420. strmap_set(_thread_test_strmap, s, *cp);
  421. tor_mutex_release(_thread_test_mutex);
  422. tor_mutex_release(m);
  423. spawn_exit();
  424. }
  425. /** Run unit tests for threading logic. */
  426. static void
  427. test_util_threads(void)
  428. {
  429. char *s1 = NULL, *s2 = NULL;
  430. int done = 0, timedout = 0;
  431. time_t started;
  432. #ifndef MS_WINDOWS
  433. struct timeval tv;
  434. tv.tv_sec=0;
  435. tv.tv_usec=10;
  436. #endif
  437. #ifndef TOR_IS_MULTITHREADED
  438. /* Skip this test if we aren't threading. We should be threading most
  439. * everywhere by now. */
  440. if (1)
  441. return;
  442. #endif
  443. _thread_test_mutex = tor_mutex_new();
  444. _thread_test_start1 = tor_mutex_new();
  445. _thread_test_start2 = tor_mutex_new();
  446. _thread_test_strmap = strmap_new();
  447. s1 = tor_strdup("thread 1");
  448. s2 = tor_strdup("thread 2");
  449. tor_mutex_acquire(_thread_test_start1);
  450. tor_mutex_acquire(_thread_test_start2);
  451. spawn_func(_thread_test_func, s1);
  452. spawn_func(_thread_test_func, s2);
  453. tor_mutex_release(_thread_test_start2);
  454. tor_mutex_release(_thread_test_start1);
  455. started = time(NULL);
  456. while (!done) {
  457. tor_mutex_acquire(_thread_test_mutex);
  458. strmap_assert_ok(_thread_test_strmap);
  459. if (strmap_get(_thread_test_strmap, "thread 1") &&
  460. strmap_get(_thread_test_strmap, "thread 2")) {
  461. done = 1;
  462. } else if (time(NULL) > started + 25) {
  463. timedout = done = 1;
  464. }
  465. tor_mutex_release(_thread_test_mutex);
  466. #ifndef MS_WINDOWS
  467. /* Prevent the main thread from starving the worker threads. */
  468. select(0, NULL, NULL, NULL, &tv);
  469. #endif
  470. }
  471. tor_mutex_acquire(_thread_test_start1);
  472. tor_mutex_release(_thread_test_start1);
  473. tor_mutex_acquire(_thread_test_start2);
  474. tor_mutex_release(_thread_test_start2);
  475. tor_mutex_free(_thread_test_mutex);
  476. if (timedout) {
  477. printf("\nTimed out: %d %d", t1_count, t2_count);
  478. test_assert(strmap_get(_thread_test_strmap, "thread 1"));
  479. test_assert(strmap_get(_thread_test_strmap, "thread 2"));
  480. test_assert(!timedout);
  481. }
  482. /* different thread IDs. */
  483. test_assert(strcmp(strmap_get(_thread_test_strmap, "thread 1"),
  484. strmap_get(_thread_test_strmap, "thread 2")));
  485. test_assert(!strcmp(strmap_get(_thread_test_strmap, "thread 1"),
  486. strmap_get(_thread_test_strmap, "last to run")) ||
  487. !strcmp(strmap_get(_thread_test_strmap, "thread 2"),
  488. strmap_get(_thread_test_strmap, "last to run")));
  489. done:
  490. tor_free(s1);
  491. tor_free(s2);
  492. tor_free(_thread1_name);
  493. tor_free(_thread2_name);
  494. if (_thread_test_strmap)
  495. strmap_free(_thread_test_strmap, NULL);
  496. if (_thread_test_start1)
  497. tor_mutex_free(_thread_test_start1);
  498. if (_thread_test_start2)
  499. tor_mutex_free(_thread_test_start2);
  500. }
  501. /** Run unit tests for compression functions */
  502. static void
  503. test_util_gzip(void)
  504. {
  505. char *buf1=NULL, *buf2=NULL, *buf3=NULL, *cp1, *cp2;
  506. const char *ccp2;
  507. size_t len1, len2;
  508. tor_zlib_state_t *state = NULL;
  509. buf1 = tor_strdup("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ");
  510. test_assert(detect_compression_method(buf1, strlen(buf1)) == UNKNOWN_METHOD);
  511. if (is_gzip_supported()) {
  512. test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
  513. GZIP_METHOD));
  514. test_assert(buf2);
  515. test_assert(!memcmp(buf2, "\037\213", 2)); /* Gzip magic. */
  516. test_assert(detect_compression_method(buf2, len1) == GZIP_METHOD);
  517. test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1,
  518. GZIP_METHOD, 1, LOG_INFO));
  519. test_assert(buf3);
  520. test_streq(buf1,buf3);
  521. tor_free(buf2);
  522. tor_free(buf3);
  523. }
  524. test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
  525. ZLIB_METHOD));
  526. test_assert(buf2);
  527. test_assert(!memcmp(buf2, "\x78\xDA", 2)); /* deflate magic. */
  528. test_assert(detect_compression_method(buf2, len1) == ZLIB_METHOD);
  529. test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1,
  530. ZLIB_METHOD, 1, LOG_INFO));
  531. test_assert(buf3);
  532. test_streq(buf1,buf3);
  533. /* Check whether we can uncompress concatenated, compressed strings. */
  534. tor_free(buf3);
  535. buf2 = tor_realloc(buf2, len1*2);
  536. memcpy(buf2+len1, buf2, len1);
  537. test_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1*2,
  538. ZLIB_METHOD, 1, LOG_INFO));
  539. test_eq(len2, (strlen(buf1)+1)*2);
  540. test_memeq(buf3,
  541. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ\0"
  542. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZAAAAAAAAAAAAAAAAAAAZ\0",
  543. (strlen(buf1)+1)*2);
  544. tor_free(buf1);
  545. tor_free(buf2);
  546. tor_free(buf3);
  547. /* Check whether we can uncompress partial strings. */
  548. buf1 =
  549. tor_strdup("String with low redundancy that won't be compressed much.");
  550. test_assert(!tor_gzip_compress(&buf2, &len1, buf1, strlen(buf1)+1,
  551. ZLIB_METHOD));
  552. tt_assert(len1>16);
  553. /* when we allow an incomplete string, we should succeed.*/
  554. tt_assert(!tor_gzip_uncompress(&buf3, &len2, buf2, len1-16,
  555. ZLIB_METHOD, 0, LOG_INFO));
  556. buf3[len2]='\0';
  557. tt_assert(len2 > 5);
  558. tt_assert(!strcmpstart(buf1, buf3));
  559. /* when we demand a complete string, this must fail. */
  560. tor_free(buf3);
  561. tt_assert(tor_gzip_uncompress(&buf3, &len2, buf2, len1-16,
  562. ZLIB_METHOD, 1, LOG_INFO));
  563. tt_assert(!buf3);
  564. /* Now, try streaming compression. */
  565. tor_free(buf1);
  566. tor_free(buf2);
  567. tor_free(buf3);
  568. state = tor_zlib_new(1, ZLIB_METHOD);
  569. tt_assert(state);
  570. cp1 = buf1 = tor_malloc(1024);
  571. len1 = 1024;
  572. ccp2 = "ABCDEFGHIJABCDEFGHIJ";
  573. len2 = 21;
  574. test_assert(tor_zlib_process(state, &cp1, &len1, &ccp2, &len2, 0)
  575. == TOR_ZLIB_OK);
  576. test_eq(len2, 0); /* Make sure we compressed it all. */
  577. test_assert(cp1 > buf1);
  578. len2 = 0;
  579. cp2 = cp1;
  580. test_assert(tor_zlib_process(state, &cp1, &len1, &ccp2, &len2, 1)
  581. == TOR_ZLIB_DONE);
  582. test_eq(len2, 0);
  583. test_assert(cp1 > cp2); /* Make sure we really added something. */
  584. tt_assert(!tor_gzip_uncompress(&buf3, &len2, buf1, 1024-len1,
  585. ZLIB_METHOD, 1, LOG_WARN));
  586. test_streq(buf3, "ABCDEFGHIJABCDEFGHIJ"); /*Make sure it compressed right.*/
  587. done:
  588. if (state)
  589. tor_zlib_free(state);
  590. tor_free(buf2);
  591. tor_free(buf3);
  592. tor_free(buf1);
  593. }
  594. /** Run unit tests for mmap() wrapper functionality. */
  595. static void
  596. test_util_mmap(void)
  597. {
  598. char *fname1 = tor_strdup(get_fname("mapped_1"));
  599. char *fname2 = tor_strdup(get_fname("mapped_2"));
  600. char *fname3 = tor_strdup(get_fname("mapped_3"));
  601. const size_t buflen = 17000;
  602. char *buf = tor_malloc(17000);
  603. tor_mmap_t *mapping = NULL;
  604. crypto_rand(buf, buflen);
  605. mapping = tor_mmap_file(fname1);
  606. test_assert(! mapping);
  607. write_str_to_file(fname1, "Short file.", 1);
  608. write_bytes_to_file(fname2, buf, buflen, 1);
  609. write_bytes_to_file(fname3, buf, 16384, 1);
  610. mapping = tor_mmap_file(fname1);
  611. test_assert(mapping);
  612. test_eq(mapping->size, strlen("Short file."));
  613. test_streq(mapping->data, "Short file.");
  614. #ifdef MS_WINDOWS
  615. tor_munmap_file(mapping);
  616. mapping = NULL;
  617. test_assert(unlink(fname1) == 0);
  618. #else
  619. /* make sure we can unlink. */
  620. test_assert(unlink(fname1) == 0);
  621. test_streq(mapping->data, "Short file.");
  622. tor_munmap_file(mapping);
  623. mapping = NULL;
  624. #endif
  625. /* Now a zero-length file. */
  626. write_str_to_file(fname1, "", 1);
  627. mapping = tor_mmap_file(fname1);
  628. test_eq(mapping, NULL);
  629. test_eq(ERANGE, errno);
  630. unlink(fname1);
  631. /* Make sure that we fail to map a no-longer-existent file. */
  632. mapping = tor_mmap_file(fname1);
  633. test_assert(mapping == NULL);
  634. /* Now try a big file that stretches across a few pages and isn't aligned */
  635. mapping = tor_mmap_file(fname2);
  636. test_assert(mapping);
  637. test_eq(mapping->size, buflen);
  638. test_memeq(mapping->data, buf, buflen);
  639. tor_munmap_file(mapping);
  640. mapping = NULL;
  641. /* Now try a big aligned file. */
  642. mapping = tor_mmap_file(fname3);
  643. test_assert(mapping);
  644. test_eq(mapping->size, 16384);
  645. test_memeq(mapping->data, buf, 16384);
  646. tor_munmap_file(mapping);
  647. mapping = NULL;
  648. done:
  649. unlink(fname1);
  650. unlink(fname2);
  651. unlink(fname3);
  652. tor_free(fname1);
  653. tor_free(fname2);
  654. tor_free(fname3);
  655. tor_free(buf);
  656. if (mapping)
  657. tor_munmap_file(mapping);
  658. }
  659. /** Run unit tests for escaping/unescaping data for use by controllers. */
  660. static void
  661. test_util_control_formats(void)
  662. {
  663. char *out = NULL;
  664. const char *inp =
  665. "..This is a test\r\nof the emergency \nbroadcast\r\n..system.\r\nZ.\r\n";
  666. size_t sz;
  667. sz = read_escaped_data(inp, strlen(inp), &out);
  668. test_streq(out,
  669. ".This is a test\nof the emergency \nbroadcast\n.system.\nZ.\n");
  670. test_eq(sz, strlen(out));
  671. done:
  672. tor_free(out);
  673. }
  674. static void
  675. test_util_sscanf(void)
  676. {
  677. unsigned u1, u2, u3;
  678. char s1[10], s2[10], s3[10], ch;
  679. int r;
  680. r = tor_sscanf("hello world", "hello world"); /* String match: success */
  681. test_eq(r, 0);
  682. r = tor_sscanf("hello world 3", "hello worlb %u", &u1); /* String fail */
  683. test_eq(r, 0);
  684. r = tor_sscanf("12345", "%u", &u1); /* Simple number */
  685. test_eq(r, 1);
  686. test_eq(u1, 12345u);
  687. r = tor_sscanf("", "%u", &u1); /* absent number */
  688. test_eq(r, 0);
  689. r = tor_sscanf("A", "%u", &u1); /* bogus number */
  690. test_eq(r, 0);
  691. r = tor_sscanf("4294967295", "%u", &u1); /* UINT32_MAX should work. */
  692. test_eq(r, 1);
  693. test_eq(u1, 4294967295u);
  694. r = tor_sscanf("4294967296", "%u", &u1); /* Always say -1 at 32 bits. */
  695. test_eq(r, 0);
  696. r = tor_sscanf("123456", "%2u%u", &u1, &u2); /* Width */
  697. test_eq(r, 2);
  698. test_eq(u1, 12u);
  699. test_eq(u2, 3456u);
  700. r = tor_sscanf("!12:3:456", "!%2u:%2u:%3u", &u1, &u2, &u3); /* separators */
  701. test_eq(r, 3);
  702. test_eq(u1, 12u);
  703. test_eq(u2, 3u);
  704. test_eq(u3, 456u);
  705. r = tor_sscanf("12:3:045", "%2u:%2u:%3u", &u1, &u2, &u3); /* 0s */
  706. test_eq(r, 3);
  707. test_eq(u1, 12u);
  708. test_eq(u2, 3u);
  709. test_eq(u3, 45u);
  710. /* %u does not match space.*/
  711. r = tor_sscanf("12:3: 45", "%2u:%2u:%3u", &u1, &u2, &u3);
  712. test_eq(r, 2);
  713. /* %u does not match negative numbers. */
  714. r = tor_sscanf("12:3:-4", "%2u:%2u:%3u", &u1, &u2, &u3);
  715. test_eq(r, 2);
  716. /* Arbitrary amounts of 0-padding are okay */
  717. r = tor_sscanf("12:03:000000000000000099", "%2u:%2u:%u", &u1, &u2, &u3);
  718. test_eq(r, 3);
  719. test_eq(u1, 12u);
  720. test_eq(u2, 3u);
  721. test_eq(u3, 99u);
  722. /* %x should work. */
  723. r = tor_sscanf("1234 02aBcdEf", "%x %x", &u1, &u2);
  724. test_eq(r, 2);
  725. test_eq(u1, 0x1234);
  726. test_eq(u2, 0x2ABCDEF);
  727. /* Width works on %x */
  728. r = tor_sscanf("f00dcafe444", "%4x%4x%u", &u1, &u2, &u3);
  729. test_eq(r, 3);
  730. test_eq(u1, 0xf00d);
  731. test_eq(u2, 0xcafe);
  732. test_eq(u3, 444);
  733. r = tor_sscanf("99% fresh", "%3u%% fresh", &u1); /* percents are scannable.*/
  734. test_eq(r, 1);
  735. test_eq(u1, 99);
  736. r = tor_sscanf("hello", "%s", s1); /* %s needs a number. */
  737. test_eq(r, -1);
  738. r = tor_sscanf("hello", "%3s%7s", s1, s2); /* %s matches characters. */
  739. test_eq(r, 2);
  740. test_streq(s1, "hel");
  741. test_streq(s2, "lo");
  742. r = tor_sscanf("WD40", "%2s%u", s3, &u1); /* %s%u */
  743. test_eq(r, 2);
  744. test_streq(s3, "WD");
  745. test_eq(u1, 40);
  746. r = tor_sscanf("76trombones", "%6u%9s", &u1, s1); /* %u%s */
  747. test_eq(r, 2);
  748. test_eq(u1, 76);
  749. test_streq(s1, "trombones");
  750. r = tor_sscanf("hello world", "%9s %9s", s1, s2); /* %s doesn't eat space. */
  751. test_eq(r, 2);
  752. test_streq(s1, "hello");
  753. test_streq(s2, "world");
  754. r = tor_sscanf("hi", "%9s%9s%3s", s1, s2, s3); /* %s can be empty. */
  755. test_eq(r, 3);
  756. test_streq(s1, "hi");
  757. test_streq(s2, "");
  758. test_streq(s3, "");
  759. r = tor_sscanf("1.2.3", "%u.%u.%u%c", &u1, &u2, &u3, &ch);
  760. test_eq(r, 3);
  761. r = tor_sscanf("1.2.3 foobar", "%u.%u.%u%c", &u1, &u2, &u3, &ch);
  762. test_eq(r, 4);
  763. done:
  764. ;
  765. }
  766. /** Run unittests for memory pool allocator */
  767. static void
  768. test_util_mempool(void)
  769. {
  770. mp_pool_t *pool = NULL;
  771. smartlist_t *allocated = NULL;
  772. int i;
  773. pool = mp_pool_new(1, 100);
  774. test_assert(pool);
  775. test_assert(pool->new_chunk_capacity >= 100);
  776. test_assert(pool->item_alloc_size >= sizeof(void*)+1);
  777. mp_pool_destroy(pool);
  778. pool = NULL;
  779. pool = mp_pool_new(241, 2500);
  780. test_assert(pool);
  781. test_assert(pool->new_chunk_capacity >= 10);
  782. test_assert(pool->item_alloc_size >= sizeof(void*)+241);
  783. test_eq(pool->item_alloc_size & 0x03, 0);
  784. test_assert(pool->new_chunk_capacity < 60);
  785. allocated = smartlist_create();
  786. for (i = 0; i < 20000; ++i) {
  787. if (smartlist_len(allocated) < 20 || crypto_rand_int(2)) {
  788. void *m = mp_pool_get(pool);
  789. memset(m, 0x09, 241);
  790. smartlist_add(allocated, m);
  791. //printf("%d: %p\n", i, m);
  792. //mp_pool_assert_ok(pool);
  793. } else {
  794. int idx = crypto_rand_int(smartlist_len(allocated));
  795. void *m = smartlist_get(allocated, idx);
  796. //printf("%d: free %p\n", i, m);
  797. smartlist_del(allocated, idx);
  798. mp_pool_release(m);
  799. //mp_pool_assert_ok(pool);
  800. }
  801. if (crypto_rand_int(777)==0)
  802. mp_pool_clean(pool, 1, 1);
  803. if (i % 777)
  804. mp_pool_assert_ok(pool);
  805. }
  806. done:
  807. if (allocated) {
  808. SMARTLIST_FOREACH(allocated, void *, m, mp_pool_release(m));
  809. mp_pool_assert_ok(pool);
  810. mp_pool_clean(pool, 0, 0);
  811. mp_pool_assert_ok(pool);
  812. smartlist_free(allocated);
  813. }
  814. if (pool)
  815. mp_pool_destroy(pool);
  816. }
  817. /** Run unittests for memory area allocator */
  818. static void
  819. test_util_memarea(void)
  820. {
  821. memarea_t *area = memarea_new();
  822. char *p1, *p2, *p3, *p1_orig;
  823. void *malloced_ptr = NULL;
  824. int i;
  825. test_assert(area);
  826. p1_orig = p1 = memarea_alloc(area,64);
  827. p2 = memarea_alloc_zero(area,52);
  828. p3 = memarea_alloc(area,11);
  829. test_assert(memarea_owns_ptr(area, p1));
  830. test_assert(memarea_owns_ptr(area, p2));
  831. test_assert(memarea_owns_ptr(area, p3));
  832. /* Make sure we left enough space. */
  833. test_assert(p1+64 <= p2);
  834. test_assert(p2+52 <= p3);
  835. /* Make sure we aligned. */
  836. test_eq(((uintptr_t)p1) % sizeof(void*), 0);
  837. test_eq(((uintptr_t)p2) % sizeof(void*), 0);
  838. test_eq(((uintptr_t)p3) % sizeof(void*), 0);
  839. test_assert(!memarea_owns_ptr(area, p3+8192));
  840. test_assert(!memarea_owns_ptr(area, p3+30));
  841. test_assert(tor_mem_is_zero(p2, 52));
  842. /* Make sure we don't overalign. */
  843. p1 = memarea_alloc(area, 1);
  844. p2 = memarea_alloc(area, 1);
  845. test_eq(p1+sizeof(void*), p2);
  846. {
  847. malloced_ptr = tor_malloc(64);
  848. test_assert(!memarea_owns_ptr(area, malloced_ptr));
  849. tor_free(malloced_ptr);
  850. }
  851. /* memarea_memdup */
  852. {
  853. malloced_ptr = tor_malloc(64);
  854. crypto_rand((char*)malloced_ptr, 64);
  855. p1 = memarea_memdup(area, malloced_ptr, 64);
  856. test_assert(p1 != malloced_ptr);
  857. test_memeq(p1, malloced_ptr, 64);
  858. tor_free(malloced_ptr);
  859. }
  860. /* memarea_strdup. */
  861. p1 = memarea_strdup(area,"");
  862. p2 = memarea_strdup(area, "abcd");
  863. test_assert(p1);
  864. test_assert(p2);
  865. test_streq(p1, "");
  866. test_streq(p2, "abcd");
  867. /* memarea_strndup. */
  868. {
  869. const char *s = "Ad ogni porta batte la morte e grida: il nome!";
  870. /* (From Turandot, act 3.) */
  871. size_t len = strlen(s);
  872. p1 = memarea_strndup(area, s, 1000);
  873. p2 = memarea_strndup(area, s, 10);
  874. test_streq(p1, s);
  875. test_assert(p2 >= p1 + len + 1);
  876. test_memeq(s, p2, 10);
  877. test_eq(p2[10], '\0');
  878. p3 = memarea_strndup(area, s, len);
  879. test_streq(p3, s);
  880. p3 = memarea_strndup(area, s, len-1);
  881. test_memeq(s, p3, len-1);
  882. test_eq(p3[len-1], '\0');
  883. }
  884. memarea_clear(area);
  885. p1 = memarea_alloc(area, 1);
  886. test_eq(p1, p1_orig);
  887. memarea_clear(area);
  888. /* Check for running over an area's size. */
  889. for (i = 0; i < 512; ++i) {
  890. p1 = memarea_alloc(area, crypto_rand_int(5)+1);
  891. test_assert(memarea_owns_ptr(area, p1));
  892. }
  893. memarea_assert_ok(area);
  894. /* Make sure we can allocate a too-big object. */
  895. p1 = memarea_alloc_zero(area, 9000);
  896. p2 = memarea_alloc_zero(area, 16);
  897. test_assert(memarea_owns_ptr(area, p1));
  898. test_assert(memarea_owns_ptr(area, p2));
  899. done:
  900. memarea_drop_all(area);
  901. tor_free(malloced_ptr);
  902. }
  903. /** Run unit tests for utility functions to get file names relative to
  904. * the data directory. */
  905. static void
  906. test_util_datadir(void)
  907. {
  908. char buf[1024];
  909. char *f = NULL;
  910. char *temp_dir = NULL;
  911. temp_dir = get_datadir_fname(NULL);
  912. f = get_datadir_fname("state");
  913. tor_snprintf(buf, sizeof(buf), "%s"PATH_SEPARATOR"state", temp_dir);
  914. test_streq(f, buf);
  915. tor_free(f);
  916. f = get_datadir_fname2("cache", "thingy");
  917. tor_snprintf(buf, sizeof(buf),
  918. "%s"PATH_SEPARATOR"cache"PATH_SEPARATOR"thingy", temp_dir);
  919. test_streq(f, buf);
  920. tor_free(f);
  921. f = get_datadir_fname2_suffix("cache", "thingy", ".foo");
  922. tor_snprintf(buf, sizeof(buf),
  923. "%s"PATH_SEPARATOR"cache"PATH_SEPARATOR"thingy.foo", temp_dir);
  924. test_streq(f, buf);
  925. tor_free(f);
  926. f = get_datadir_fname_suffix("cache", ".foo");
  927. tor_snprintf(buf, sizeof(buf), "%s"PATH_SEPARATOR"cache.foo",
  928. temp_dir);
  929. test_streq(f, buf);
  930. done:
  931. tor_free(f);
  932. tor_free(temp_dir);
  933. }
  934. static void
  935. test_util_strtok(void)
  936. {
  937. char buf[128];
  938. char buf2[128];
  939. char *cp1, *cp2;
  940. strlcpy(buf, "Graved on the dark in gestures of descent", sizeof(buf));
  941. strlcpy(buf2, "they.seemed;their!own;most.perfect;monument", sizeof(buf2));
  942. /* -- "Year's End", Richard Wilbur */
  943. test_streq("Graved", tor_strtok_r_impl(buf, " ", &cp1));
  944. test_streq("they", tor_strtok_r_impl(buf2, ".!..;!", &cp2));
  945. #define S1() tor_strtok_r_impl(NULL, " ", &cp1)
  946. #define S2() tor_strtok_r_impl(NULL, ".!..;!", &cp2)
  947. test_streq("on", S1());
  948. test_streq("the", S1());
  949. test_streq("dark", S1());
  950. test_streq("seemed", S2());
  951. test_streq("their", S2());
  952. test_streq("own", S2());
  953. test_streq("in", S1());
  954. test_streq("gestures", S1());
  955. test_streq("of", S1());
  956. test_streq("most", S2());
  957. test_streq("perfect", S2());
  958. test_streq("descent", S1());
  959. test_streq("monument", S2());
  960. test_assert(NULL == S1());
  961. test_assert(NULL == S2());
  962. done:
  963. ;
  964. }
  965. static void
  966. test_util_find_str_at_start_of_line(void *ptr)
  967. {
  968. const char *long_string =
  969. "hello world. hello world. hello hello. howdy.\n"
  970. "hello hello world\n";
  971. (void)ptr;
  972. /* not-found case. */
  973. tt_assert(! find_str_at_start_of_line(long_string, "fred"));
  974. /* not-found case where haystack doesn't end with \n */
  975. tt_assert(! find_str_at_start_of_line("foobar\nbaz", "fred"));
  976. /* start-of-string case */
  977. tt_assert(long_string ==
  978. find_str_at_start_of_line(long_string, "hello world."));
  979. /* start-of-line case */
  980. tt_assert(strchr(long_string,'\n')+1 ==
  981. find_str_at_start_of_line(long_string, "hello hello"));
  982. done:
  983. ;
  984. }
  985. static void
  986. test_util_asprintf(void *ptr)
  987. {
  988. #define LOREMIPSUM \
  989. "Lorem ipsum dolor sit amet, consectetur adipisicing elit"
  990. char *cp=NULL, *cp2=NULL;
  991. int r;
  992. (void)ptr;
  993. /* empty string. */
  994. r = tor_asprintf(&cp, "%s", "");
  995. tt_assert(cp);
  996. tt_int_op(r, ==, strlen(cp));
  997. tt_str_op(cp, ==, "");
  998. /* Short string with some printing in it. */
  999. r = tor_asprintf(&cp2, "First=%d, Second=%d", 101, 202);
  1000. tt_assert(cp2);
  1001. tt_int_op(r, ==, strlen(cp2));
  1002. tt_str_op(cp2, ==, "First=101, Second=202");
  1003. tt_assert(cp != cp2);
  1004. tor_free(cp);
  1005. tor_free(cp2);
  1006. /* Glass-box test: a string exactly 128 characters long. */
  1007. r = tor_asprintf(&cp, "Lorem1: %sLorem2: %s", LOREMIPSUM, LOREMIPSUM);
  1008. tt_assert(cp);
  1009. tt_int_op(r, ==, 128);
  1010. tt_assert(cp[128] == '\0');
  1011. tt_str_op(cp, ==,
  1012. "Lorem1: "LOREMIPSUM"Lorem2: "LOREMIPSUM);
  1013. tor_free(cp);
  1014. /* String longer than 128 characters */
  1015. r = tor_asprintf(&cp, "1: %s 2: %s 3: %s",
  1016. LOREMIPSUM, LOREMIPSUM, LOREMIPSUM);
  1017. tt_assert(cp);
  1018. tt_int_op(r, ==, strlen(cp));
  1019. tt_str_op(cp, ==, "1: "LOREMIPSUM" 2: "LOREMIPSUM" 3: "LOREMIPSUM);
  1020. done:
  1021. tor_free(cp);
  1022. tor_free(cp2);
  1023. }
  1024. static void
  1025. test_util_listdir(void *ptr)
  1026. {
  1027. smartlist_t *dir_contents = NULL;
  1028. char *fname1=NULL, *fname2=NULL, *dirname=NULL;
  1029. (void)ptr;
  1030. fname1 = tor_strdup(get_fname("hopscotch"));
  1031. fname2 = tor_strdup(get_fname("mumblety-peg"));
  1032. dirname = tor_strdup(get_fname(NULL));
  1033. tt_int_op(write_str_to_file(fname1, "X\n", 0), ==, 0);
  1034. tt_int_op(write_str_to_file(fname2, "Y\n", 0), ==, 0);
  1035. dir_contents = tor_listdir(dirname);
  1036. tt_assert(dir_contents);
  1037. /* make sure that each filename is listed. */
  1038. tt_assert(smartlist_string_isin_case(dir_contents, "hopscotch"));
  1039. tt_assert(smartlist_string_isin_case(dir_contents, "mumblety-peg"));
  1040. tt_assert(!smartlist_string_isin(dir_contents, "."));
  1041. tt_assert(!smartlist_string_isin(dir_contents, ".."));
  1042. done:
  1043. tor_free(fname1);
  1044. tor_free(fname2);
  1045. tor_free(dirname);
  1046. if (dir_contents) {
  1047. SMARTLIST_FOREACH(dir_contents, char *, cp, tor_free(cp));
  1048. smartlist_free(dir_contents);
  1049. }
  1050. }
  1051. static void
  1052. test_util_parent_dir(void *ptr)
  1053. {
  1054. char *cp;
  1055. (void)ptr;
  1056. #define T(input,expect_ok,output) \
  1057. do { \
  1058. int ok; \
  1059. cp = tor_strdup(input); \
  1060. ok = get_parent_directory(cp); \
  1061. tt_int_op(ok, ==, expect_ok); \
  1062. if (ok==0) \
  1063. tt_str_op(cp, ==, output); \
  1064. tor_free(cp); \
  1065. } while (0);
  1066. T("/home/wombat/knish", 0, "/home/wombat");
  1067. T("/home/wombat/knish/", 0, "/home/wombat");
  1068. T("./home/wombat/knish/", 0, "./home/wombat");
  1069. T("./wombat", 0, ".");
  1070. T("", -1, "");
  1071. T("/", -1, "");
  1072. T("////", -1, "");
  1073. done:
  1074. tor_free(cp);
  1075. }
  1076. #ifdef MS_WINDOWS
  1077. static void
  1078. test_util_load_win_lib(void *ptr)
  1079. {
  1080. HANDLE h = load_windows_system_library("advapi32.dll");
  1081. (void) ptr;
  1082. tt_assert(h);
  1083. done:
  1084. if (h)
  1085. CloseHandle(h);
  1086. }
  1087. #endif
  1088. static void
  1089. clear_hex_errno(char *hex_errno)
  1090. {
  1091. memset(hex_errno, '\0', HEX_ERRNO_SIZE + 1);
  1092. }
  1093. static void
  1094. test_util_exit_status(void *ptr)
  1095. {
  1096. /* Leave an extra byte for a \0 so we can do string comparison */
  1097. char hex_errno[HEX_ERRNO_SIZE + 1];
  1098. (void)ptr;
  1099. clear_hex_errno(hex_errno);
  1100. format_helper_exit_status(0, 0, hex_errno);
  1101. tt_str_op(hex_errno, ==, " 0/0\n");
  1102. clear_hex_errno(hex_errno);
  1103. format_helper_exit_status(0, 0x7FFFFFFF, hex_errno);
  1104. tt_str_op(hex_errno, ==, " 0/7FFFFFFF\n");
  1105. clear_hex_errno(hex_errno);
  1106. format_helper_exit_status(0xFF, -0x80000000, hex_errno);
  1107. tt_str_op(hex_errno, ==, "FF/-80000000\n");
  1108. clear_hex_errno(hex_errno);
  1109. format_helper_exit_status(0x7F, 0, hex_errno);
  1110. tt_str_op(hex_errno, ==, " 7F/0\n");
  1111. clear_hex_errno(hex_errno);
  1112. format_helper_exit_status(0x08, -0x242, hex_errno);
  1113. tt_str_op(hex_errno, ==, " 8/-242\n");
  1114. done:
  1115. ;
  1116. }
  1117. #ifndef MS_WINDOWS
  1118. /** Check that fgets waits until a full line, and not return a partial line, on
  1119. * a EAGAIN with a non-blocking pipe */
  1120. static void
  1121. test_util_fgets_eagain(void *ptr)
  1122. {
  1123. int test_pipe[2] = {-1, -1};
  1124. int retval;
  1125. ssize_t retlen;
  1126. char *retptr;
  1127. FILE *test_stream = NULL;
  1128. char buf[10];
  1129. (void)ptr;
  1130. /* Set up a pipe to test on */
  1131. retval = pipe(test_pipe);
  1132. tt_int_op(retval, >=, 0);
  1133. /* Set up the read-end to be non-blocking */
  1134. retval = fcntl(test_pipe[0], F_SETFL, O_NONBLOCK);
  1135. tt_int_op(retval, >=, 0);
  1136. /* Open it as a stdio stream */
  1137. test_stream = fdopen(test_pipe[0], "r");
  1138. tt_ptr_op(test_stream, !=, NULL);
  1139. /* Send in a partial line */
  1140. retlen = write(test_pipe[1], "A", 1);
  1141. tt_int_op(retlen, ==, 1);
  1142. retptr = fgets(buf, sizeof(buf), test_stream);
  1143. tt_want(retptr == NULL);
  1144. tt_int_op(errno, ==, EAGAIN);
  1145. /* Send in the rest */
  1146. retlen = write(test_pipe[1], "B\n", 2);
  1147. tt_int_op(retlen, ==, 2);
  1148. retptr = fgets(buf, sizeof(buf), test_stream);
  1149. tt_ptr_op(retptr, ==, buf);
  1150. tt_str_op(buf, ==, "AB\n");
  1151. /* Send in a full line */
  1152. retlen = write(test_pipe[1], "CD\n", 3);
  1153. tt_int_op(retlen, ==, 3);
  1154. retptr = fgets(buf, sizeof(buf), test_stream);
  1155. tt_ptr_op(retptr, ==, buf);
  1156. tt_str_op(buf, ==, "CD\n");
  1157. /* Send in a partial line */
  1158. retlen = write(test_pipe[1], "E", 1);
  1159. tt_int_op(retlen, ==, 1);
  1160. retptr = fgets(buf, sizeof(buf), test_stream);
  1161. tt_ptr_op(retptr, ==, NULL);
  1162. tt_int_op(errno, ==, EAGAIN);
  1163. /* Send in the rest */
  1164. retlen = write(test_pipe[1], "F\n", 2);
  1165. tt_int_op(retlen, ==, 2);
  1166. retptr = fgets(buf, sizeof(buf), test_stream);
  1167. tt_ptr_op(retptr, ==, buf);
  1168. tt_str_op(buf, ==, "EF\n");
  1169. /* Send in a full line and close */
  1170. retlen = write(test_pipe[1], "GH", 2);
  1171. tt_int_op(retlen, ==, 2);
  1172. retval = close(test_pipe[1]);
  1173. test_pipe[1] = -1;
  1174. tt_int_op(retval, ==, 0);
  1175. retptr = fgets(buf, sizeof(buf), test_stream);
  1176. tt_ptr_op(retptr, ==, buf);
  1177. tt_str_op(buf, ==, "GH");
  1178. /* Check for EOF */
  1179. retptr = fgets(buf, sizeof(buf), test_stream);
  1180. tt_ptr_op(retptr, ==, NULL);
  1181. tt_int_op(feof(test_stream), >, 0);
  1182. done:
  1183. if (test_stream != NULL)
  1184. fclose(test_stream);
  1185. if (test_pipe[0] != -1)
  1186. close(test_pipe[0]);
  1187. if (test_pipe[1] != -1)
  1188. close(test_pipe[1]);
  1189. }
  1190. #endif
  1191. /** Helper function for testing tor_spawn_background */
  1192. static void
  1193. run_util_spawn_background(const char *argv[], const char *expected_out,
  1194. const char *expected_err, int expected_exit,
  1195. int expected_status)
  1196. {
  1197. int retval;
  1198. ssize_t pos;
  1199. process_handle_t process_handle;
  1200. char stdout_buf[100], stderr_buf[100];
  1201. /* Start the program */
  1202. process_handle = tor_spawn_background(argv[0], argv);
  1203. tt_int_op(process_handle.status, ==, expected_status);
  1204. /* If the process failed to start, don't bother continuing */
  1205. if (process_handle.status == -1)
  1206. return;
  1207. tt_int_op(process_handle.stdout_pipe, >, 0);
  1208. tt_int_op(process_handle.stderr_pipe, >, 0);
  1209. /* Check stdout */
  1210. pos = tor_read_all_from_process_stdout(process_handle, stdout_buf,
  1211. sizeof(stdout_buf) - 1);
  1212. tt_assert(pos >= 0);
  1213. stdout_buf[pos] = '\0';
  1214. tt_str_op(stdout_buf, ==, expected_out);
  1215. tt_int_op(pos, ==, strlen(expected_out));
  1216. /* Check it terminated correctly */
  1217. retval = tor_get_exit_code(process_handle);
  1218. tt_int_op(retval, ==, expected_exit);
  1219. // TODO: Make test-child exit with something other than 0
  1220. /* Check stderr */
  1221. pos = tor_read_all_from_process_stderr(process_handle, stderr_buf,
  1222. sizeof(stderr_buf) - 1);
  1223. tt_assert(pos >= 0);
  1224. stderr_buf[pos] = '\0';
  1225. tt_str_op(stderr_buf, ==, expected_err);
  1226. tt_int_op(pos, ==, strlen(expected_err));
  1227. done:
  1228. ;
  1229. }
  1230. /** Check that we can launch a process and read the output */
  1231. static void
  1232. test_util_spawn_background_ok(void *ptr)
  1233. {
  1234. #ifdef MS_WINDOWS
  1235. // TODO: Under MSYS, BUILDDIR in orconfig.h needs to be tweaked
  1236. const char *argv[] = {BUILDDIR "/src/test/test-child.exe", "--test", NULL};
  1237. const char *expected_out = "OUT\r\n--test\r\nSLEEPING\r\nDONE\r\n";
  1238. const char *expected_err = "ERR\r\n";
  1239. #else
  1240. const char *argv[] = {BUILDDIR "/src/test/test-child", "--test", NULL};
  1241. const char *expected_out = "OUT\n--test\nSLEEPING\nDONE\n";
  1242. const char *expected_err = "ERR\n";
  1243. #endif
  1244. (void)ptr;
  1245. run_util_spawn_background(argv, expected_out, expected_err, 0, 0);
  1246. }
  1247. /** Check that failing to find the executable works as expected */
  1248. static void
  1249. test_util_spawn_background_fail(void *ptr)
  1250. {
  1251. #ifdef MS_WINDOWS
  1252. const char *argv[] = {BUILDDIR "/src/test/no-such-file", "--test", NULL};
  1253. const char *expected_out = "ERR: Failed to spawn background process "
  1254. "- code 9/2\n";
  1255. const char *expected_err = "";
  1256. const int expected_status = -1;
  1257. #else
  1258. const char *argv[] = {BUILDDIR "/src/test/no-such-file", "--test", NULL};
  1259. const char *expected_out = "ERR: Failed to spawn background process "
  1260. "- code 9/2\n";
  1261. const char *expected_err = "";
  1262. // TODO: Once we can signal failure to exec, set this to be -1;
  1263. const int expected_status = 0;
  1264. #endif
  1265. (void)ptr;
  1266. run_util_spawn_background(argv, expected_out, expected_err, 255, expected_status);
  1267. }
  1268. /** Helper function for testing tor_spawn_background */
  1269. static void
  1270. test_util_spawn_background_partial_read(void *ptr)
  1271. {
  1272. #ifdef MS_WINDOWS
  1273. // TODO: Under MSYS, BUILDDIR in orconfig.h needs to be tweaked
  1274. const char *argv[] = {BUILDDIR "/src/test/test-child.exe", "--test", NULL};
  1275. const char *expected_out[] = { "OUT\r\n--test\r\nSLEEPING\r\n",
  1276. "DONE\r\n",
  1277. NULL };
  1278. const char *expected_err = "ERR\r\n";
  1279. int expected_out_ctr;
  1280. #else
  1281. const char *argv[] = {BUILDDIR "/src/test/test-child", "--test", NULL};
  1282. const char *expected_out = "OUT\n--test\nSLEEPING\nDONE\n";
  1283. const char *expected_err = "ERR\r\n";
  1284. #endif
  1285. const int expected_exit = 0;
  1286. const int expected_status = 0;
  1287. int retval;
  1288. ssize_t pos;
  1289. process_handle_t process_handle;
  1290. char stdout_buf[100], stderr_buf[100];
  1291. /* Start the program */
  1292. process_handle = tor_spawn_background(argv[0], argv);
  1293. tt_int_op(process_handle.status, ==, expected_status);
  1294. /* Check stdout */
  1295. #ifdef MS_WINDOWS
  1296. for (expected_out_ctr =0; expected_out[expected_out_ctr] != NULL;) {
  1297. pos = tor_read_all_handle(process_handle.stdout_pipe, stdout_buf,
  1298. sizeof(stdout_buf) - 1, NULL);
  1299. log_info(LD_GENERAL, "tor_read_all_handle() returned %d", (int)pos);
  1300. /* We would have blocked, keep on trying */
  1301. if (0 == pos)
  1302. continue;
  1303. tt_assert(pos >= 0);
  1304. stdout_buf[pos] = '\0';
  1305. tt_str_op(stdout_buf, ==, expected_out[expected_out_ctr]);
  1306. tt_int_op(pos, ==, strlen(expected_out[expected_out_ctr]));
  1307. expected_out_ctr++;
  1308. }
  1309. /* The process should have exited without writing more */
  1310. pos = tor_read_all_handle(process_handle.stdout_pipe, stdout_buf,
  1311. sizeof(stdout_buf) - 1,
  1312. process_handle.pid.hProcess);
  1313. tt_int_op(pos, ==, 0);
  1314. #else
  1315. pos = tor_read_all_from_process_stdout(process_handle, stdout_buf,
  1316. sizeof(stdout_buf) - 1);
  1317. tt_assert(pos >= 0);
  1318. stdout_buf[pos] = '\0';
  1319. tt_str_op(stdout_buf, ==, expected_out);
  1320. tt_int_op(pos, ==, strlen(expected_out));
  1321. #endif
  1322. /* Check it terminated correctly */
  1323. retval = tor_get_exit_code(process_handle);
  1324. tt_int_op(retval, ==, expected_exit);
  1325. // TODO: Make test-child exit with something other than 0
  1326. /* Check stderr */
  1327. pos = tor_read_all_from_process_stderr(process_handle, stderr_buf,
  1328. sizeof(stderr_buf) - 1);
  1329. tt_assert(pos >= 0);
  1330. stderr_buf[pos] = '\0';
  1331. tt_str_op(stderr_buf, ==, expected_err);
  1332. tt_int_op(pos, ==, strlen(expected_err));
  1333. done:
  1334. ;
  1335. }
  1336. static void
  1337. test_util_di_ops(void)
  1338. {
  1339. #define LT -1
  1340. #define GT 1
  1341. #define EQ 0
  1342. const struct {
  1343. const char *a; int want_sign; const char *b;
  1344. } examples[] = {
  1345. { "Foo", EQ, "Foo" },
  1346. { "foo", GT, "bar", },
  1347. { "foobar", EQ ,"foobar" },
  1348. { "foobar", LT, "foobaw" },
  1349. { "foobar", GT, "f00bar" },
  1350. { "foobar", GT, "boobar" },
  1351. { "", EQ, "" },
  1352. { NULL, 0, NULL },
  1353. };
  1354. int i;
  1355. for (i = 0; examples[i].a; ++i) {
  1356. size_t len = strlen(examples[i].a);
  1357. int eq1, eq2, neq1, neq2, cmp1, cmp2;
  1358. test_eq(len, strlen(examples[i].b));
  1359. /* We do all of the operations, with operands in both orders. */
  1360. eq1 = tor_memeq(examples[i].a, examples[i].b, len);
  1361. eq2 = tor_memeq(examples[i].b, examples[i].a, len);
  1362. neq1 = tor_memneq(examples[i].a, examples[i].b, len);
  1363. neq2 = tor_memneq(examples[i].b, examples[i].a, len);
  1364. cmp1 = tor_memcmp(examples[i].a, examples[i].b, len);
  1365. cmp2 = tor_memcmp(examples[i].b, examples[i].a, len);
  1366. /* Check for correctness of cmp1 */
  1367. if (cmp1 < 0 && examples[i].want_sign != LT)
  1368. test_fail();
  1369. else if (cmp1 > 0 && examples[i].want_sign != GT)
  1370. test_fail();
  1371. else if (cmp1 == 0 && examples[i].want_sign != EQ)
  1372. test_fail();
  1373. /* Check for consistency of everything else with cmp1 */
  1374. test_eq(eq1, eq2);
  1375. test_eq(neq1, neq2);
  1376. test_eq(cmp1, -cmp2);
  1377. test_eq(eq1, cmp1 == 0);
  1378. test_eq(neq1, !eq1);
  1379. }
  1380. done:
  1381. ;
  1382. }
  1383. #define UTIL_LEGACY(name) \
  1384. { #name, legacy_test_helper, 0, &legacy_setup, test_util_ ## name }
  1385. #define UTIL_TEST(name, flags) \
  1386. { #name, test_util_ ## name, flags, NULL, NULL }
  1387. struct testcase_t util_tests[] = {
  1388. UTIL_LEGACY(time),
  1389. UTIL_LEGACY(config_line),
  1390. UTIL_LEGACY(strmisc),
  1391. UTIL_LEGACY(pow2),
  1392. UTIL_LEGACY(gzip),
  1393. UTIL_LEGACY(datadir),
  1394. UTIL_LEGACY(mempool),
  1395. UTIL_LEGACY(memarea),
  1396. UTIL_LEGACY(control_formats),
  1397. UTIL_LEGACY(mmap),
  1398. UTIL_LEGACY(threads),
  1399. UTIL_LEGACY(sscanf),
  1400. UTIL_LEGACY(strtok),
  1401. UTIL_LEGACY(di_ops),
  1402. UTIL_TEST(find_str_at_start_of_line, 0),
  1403. UTIL_TEST(asprintf, 0),
  1404. UTIL_TEST(listdir, 0),
  1405. UTIL_TEST(parent_dir, 0),
  1406. #ifdef MS_WINDOWS
  1407. UTIL_TEST(load_win_lib, 0),
  1408. #endif
  1409. UTIL_TEST(exit_status, 0),
  1410. #ifndef MS_WINDOWS
  1411. UTIL_TEST(fgets_eagain, TT_SKIP),
  1412. #endif
  1413. UTIL_TEST(spawn_background_ok, 0),
  1414. UTIL_TEST(spawn_background_fail, 0),
  1415. UTIL_TEST(spawn_background_partial_read, 0),
  1416. END_OF_TESTCASES
  1417. };