test_util.c 54 KB

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