utils.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  1. /*
  2. * Platform-independent utility routines used throughout this code base.
  3. *
  4. * This file is linked into stand-alone test utilities which only want
  5. * to include the things they really need, so functions in here should
  6. * avoid depending on any functions outside it. Utility routines that
  7. * are more tightly integrated into the main code should live in
  8. * misc.c.
  9. */
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include <stdarg.h>
  13. #include <limits.h>
  14. #include <ctype.h>
  15. #include <assert.h>
  16. #include "defs.h"
  17. #include "misc.h"
  18. /*
  19. * Parse a string block size specification. This is approximately a
  20. * subset of the block size specs supported by GNU fileutils:
  21. * "nk" = n kilobytes
  22. * "nM" = n megabytes
  23. * "nG" = n gigabytes
  24. * All numbers are decimal, and suffixes refer to powers of two.
  25. * Case-insensitive.
  26. */
  27. unsigned long parse_blocksize(const char *bs)
  28. {
  29. char *suf;
  30. unsigned long r = strtoul(bs, &suf, 10);
  31. if (*suf != '\0') {
  32. while (*suf && isspace((unsigned char)*suf)) suf++;
  33. switch (*suf) {
  34. case 'k': case 'K':
  35. r *= 1024ul;
  36. break;
  37. case 'm': case 'M':
  38. r *= 1024ul * 1024ul;
  39. break;
  40. case 'g': case 'G':
  41. r *= 1024ul * 1024ul * 1024ul;
  42. break;
  43. case '\0':
  44. default:
  45. break;
  46. }
  47. }
  48. return r;
  49. }
  50. /*
  51. * Parse a ^C style character specification.
  52. * Returns NULL in `next' if we didn't recognise it as a control character,
  53. * in which case `c' should be ignored.
  54. * The precise current parsing is an oddity inherited from the terminal
  55. * answerback-string parsing code. All sequences start with ^; all except
  56. * ^<123> are two characters. The ones that are worth keeping are probably:
  57. * ^? 127
  58. * ^@A-Z[\]^_ 0-31
  59. * a-z 1-26
  60. * <num> specified by number (decimal, 0octal, 0xHEX)
  61. * ~ ^ escape
  62. */
  63. char ctrlparse(char *s, char **next)
  64. {
  65. char c = 0;
  66. if (*s != '^') {
  67. *next = NULL;
  68. } else {
  69. s++;
  70. if (*s == '\0') {
  71. *next = NULL;
  72. } else if (*s == '<') {
  73. s++;
  74. c = (char)strtol(s, next, 0);
  75. if ((*next == s) || (**next != '>')) {
  76. c = 0;
  77. *next = NULL;
  78. } else
  79. (*next)++;
  80. } else if (*s >= 'a' && *s <= 'z') {
  81. c = (*s - ('a' - 1));
  82. *next = s+1;
  83. } else if ((*s >= '@' && *s <= '_') || *s == '?' || (*s & 0x80)) {
  84. c = ('@' ^ *s);
  85. *next = s+1;
  86. } else if (*s == '~') {
  87. c = '^';
  88. *next = s+1;
  89. }
  90. }
  91. return c;
  92. }
  93. /*
  94. * Find a character in a string, unless it's a colon contained within
  95. * square brackets. Used for untangling strings of the form
  96. * 'host:port', where host can be an IPv6 literal.
  97. *
  98. * We provide several variants of this function, with semantics like
  99. * various standard string.h functions.
  100. */
  101. static const char *host_strchr_internal(const char *s, const char *set,
  102. bool first)
  103. {
  104. int brackets = 0;
  105. const char *ret = NULL;
  106. while (1) {
  107. if (!*s)
  108. return ret;
  109. if (*s == '[')
  110. brackets++;
  111. else if (*s == ']' && brackets > 0)
  112. brackets--;
  113. else if (brackets && *s == ':')
  114. /* never match */ ;
  115. else if (strchr(set, *s)) {
  116. ret = s;
  117. if (first)
  118. return ret;
  119. }
  120. s++;
  121. }
  122. }
  123. size_t host_strcspn(const char *s, const char *set)
  124. {
  125. const char *answer = host_strchr_internal(s, set, true);
  126. if (answer)
  127. return answer - s;
  128. else
  129. return strlen(s);
  130. }
  131. char *host_strchr(const char *s, int c)
  132. {
  133. char set[2];
  134. set[0] = c;
  135. set[1] = '\0';
  136. return (char *) host_strchr_internal(s, set, true);
  137. }
  138. char *host_strrchr(const char *s, int c)
  139. {
  140. char set[2];
  141. set[0] = c;
  142. set[1] = '\0';
  143. return (char *) host_strchr_internal(s, set, false);
  144. }
  145. #ifdef TEST_HOST_STRFOO
  146. int main(void)
  147. {
  148. int passes = 0, fails = 0;
  149. #define TEST1(func, string, arg2, suffix, result) do \
  150. { \
  151. const char *str = string; \
  152. unsigned ret = func(string, arg2) suffix; \
  153. if (ret == result) { \
  154. passes++; \
  155. } else { \
  156. printf("fail: %s(%s,%s)%s = %u, expected %u\n", \
  157. #func, #string, #arg2, #suffix, ret, \
  158. (unsigned)result); \
  159. fails++; \
  160. } \
  161. } while (0)
  162. TEST1(host_strchr, "[1:2:3]:4:5", ':', -str, 7);
  163. TEST1(host_strrchr, "[1:2:3]:4:5", ':', -str, 9);
  164. TEST1(host_strcspn, "[1:2:3]:4:5", "/:",, 7);
  165. TEST1(host_strchr, "[1:2:3]", ':', == NULL, 1);
  166. TEST1(host_strrchr, "[1:2:3]", ':', == NULL, 1);
  167. TEST1(host_strcspn, "[1:2:3]", "/:",, 7);
  168. TEST1(host_strcspn, "[1:2/3]", "/:",, 4);
  169. TEST1(host_strcspn, "[1:2:3]/", "/:",, 7);
  170. printf("passed %d failed %d total %d\n", passes, fails, passes+fails);
  171. return fails != 0 ? 1 : 0;
  172. }
  173. /* Stubs to stop the rest of this module causing compile failures. */
  174. void modalfatalbox(const char *fmt, ...) {}
  175. int conf_get_int(Conf *conf, int primary) { return 0; }
  176. char *conf_get_str(Conf *conf, int primary) { return NULL; }
  177. #endif /* TEST_HOST_STRFOO */
  178. /*
  179. * Trim square brackets off the outside of an IPv6 address literal.
  180. * Leave all other strings unchanged. Returns a fresh dynamically
  181. * allocated string.
  182. */
  183. char *host_strduptrim(const char *s)
  184. {
  185. if (s[0] == '[') {
  186. const char *p = s+1;
  187. int colons = 0;
  188. while (*p && *p != ']') {
  189. if (isxdigit((unsigned char)*p))
  190. /* OK */;
  191. else if (*p == ':')
  192. colons++;
  193. else
  194. break;
  195. p++;
  196. }
  197. if (*p == '%') {
  198. /*
  199. * This delimiter character introduces an RFC 4007 scope
  200. * id suffix (e.g. suffixing the address literal with
  201. * %eth1 or %2 or some such). There's no syntax
  202. * specification for the scope id, so just accept anything
  203. * except the closing ].
  204. */
  205. p += strcspn(p, "]");
  206. }
  207. if (*p == ']' && !p[1] && colons > 1) {
  208. /*
  209. * This looks like an IPv6 address literal (hex digits and
  210. * at least two colons, plus optional scope id, contained
  211. * in square brackets). Trim off the brackets.
  212. */
  213. return dupprintf("%.*s", (int)(p - (s+1)), s+1);
  214. }
  215. }
  216. /*
  217. * Any other shape of string is simply duplicated.
  218. */
  219. return dupstr(s);
  220. }
  221. /* ----------------------------------------------------------------------
  222. * String handling routines.
  223. */
  224. char *dupstr(const char *s)
  225. {
  226. char *p = NULL;
  227. if (s) {
  228. int len = strlen(s);
  229. p = snewn(len + 1, char);
  230. strcpy(p, s);
  231. }
  232. return p;
  233. }
  234. /* Allocate the concatenation of N strings. Terminate arg list with NULL. */
  235. char *dupcat(const char *s1, ...)
  236. {
  237. int len;
  238. char *p, *q, *sn;
  239. va_list ap;
  240. len = strlen(s1);
  241. va_start(ap, s1);
  242. while (1) {
  243. sn = va_arg(ap, char *);
  244. if (!sn)
  245. break;
  246. len += strlen(sn);
  247. }
  248. va_end(ap);
  249. p = snewn(len + 1, char);
  250. strcpy(p, s1);
  251. q = p + strlen(p);
  252. va_start(ap, s1);
  253. while (1) {
  254. sn = va_arg(ap, char *);
  255. if (!sn)
  256. break;
  257. strcpy(q, sn);
  258. q += strlen(q);
  259. }
  260. va_end(ap);
  261. return p;
  262. }
  263. void burnstr(char *string) /* sfree(str), only clear it first */
  264. {
  265. if (string) {
  266. smemclr(string, strlen(string));
  267. sfree(string);
  268. }
  269. }
  270. int string_length_for_printf(size_t s)
  271. {
  272. /* Truncate absurdly long strings (should one show up) to fit
  273. * within a positive 'int', which is what the "%.*s" format will
  274. * expect. */
  275. if (s > INT_MAX)
  276. return INT_MAX;
  277. return s;
  278. }
  279. /* Work around lack of va_copy in old MSC */
  280. #if (defined _MSC_VER || defined WINSCP) && !defined va_copy
  281. #define va_copy(a, b) TYPECHECK( \
  282. (va_list *)0 == &(a) && (va_list *)0 == &(b), \
  283. memcpy(&a, &b, sizeof(va_list)))
  284. #endif
  285. /* Also lack of vsnprintf before VS2015 */
  286. #if defined _WINDOWS && !defined __WINE__ && _MSC_VER < 1900
  287. #define vsnprintf _vsnprintf
  288. #endif
  289. /*
  290. * Do an sprintf(), but into a custom-allocated buffer.
  291. *
  292. * Currently I'm doing this via vsnprintf. This has worked so far,
  293. * but it's not good, because vsnprintf is not available on all
  294. * platforms. There's an ifdef to use `_vsnprintf', which seems
  295. * to be the local name for it on Windows. Other platforms may
  296. * lack it completely, in which case it'll be time to rewrite
  297. * this function in a totally different way.
  298. *
  299. * The only `properly' portable solution I can think of is to
  300. * implement my own format string scanner, which figures out an
  301. * upper bound for the length of each formatting directive,
  302. * allocates the buffer as it goes along, and calls sprintf() to
  303. * actually process each directive. If I ever need to actually do
  304. * this, some caveats:
  305. *
  306. * - It's very hard to find a reliable upper bound for
  307. * floating-point values. %f, in particular, when supplied with
  308. * a number near to the upper or lower limit of representable
  309. * numbers, could easily take several hundred characters. It's
  310. * probably feasible to predict this statically using the
  311. * constants in <float.h>, or even to predict it dynamically by
  312. * looking at the exponent of the specific float provided, but
  313. * it won't be fun.
  314. *
  315. * - Don't forget to _check_, after calling sprintf, that it's
  316. * used at most the amount of space we had available.
  317. *
  318. * - Fault any formatting directive we don't fully understand. The
  319. * aim here is to _guarantee_ that we never overflow the buffer,
  320. * because this is a security-critical function. If we see a
  321. * directive we don't know about, we should panic and die rather
  322. * than run any risk.
  323. */
  324. static char *dupvprintf_inner(char *buf, size_t oldlen, size_t *sizeptr,
  325. const char *fmt, va_list ap)
  326. {
  327. size_t size = *sizeptr;
  328. sgrowarrayn_nm(buf, size, oldlen, 512);
  329. while (1) {
  330. va_list aq;
  331. va_copy(aq, ap);
  332. { // WINSCP
  333. #if defined _DEBUG && defined IDE
  334. // CodeGuard hangs in v*printf functions. But while it's possible to disable CodeGuard in vsprintf, it's not possible for vsnprintf.
  335. // We never want to distribute this version of the code, hence the IDE condition.
  336. // Put this into WinSCP.cgi along with WinSCP.exe
  337. // [vsprintf]
  338. // Disable=yes
  339. int len = vsprintf(buf + oldlen, fmt, aq);
  340. #else
  341. int len = vsnprintf(buf + oldlen, size - oldlen, fmt, aq);
  342. #endif
  343. va_end(aq);
  344. if (len >= 0 && len < size) {
  345. /* This is the C99-specified criterion for snprintf to have
  346. * been completely successful. */
  347. *sizeptr = size;
  348. return buf;
  349. } else if (len > 0) {
  350. /* This is the C99 error condition: the returned length is
  351. * the required buffer size not counting the NUL. */
  352. sgrowarrayn_nm(buf, size, oldlen + 1, len);
  353. } else {
  354. /* This is the pre-C99 glibc error condition: <0 means the
  355. * buffer wasn't big enough, so we enlarge it a bit and hope. */
  356. sgrowarray_nm(buf, size, size);
  357. }
  358. } // WINSCP
  359. }
  360. }
  361. char *dupvprintf(const char *fmt, va_list ap)
  362. {
  363. size_t size = 0;
  364. return dupvprintf_inner(NULL, 0, &size, fmt, ap);
  365. }
  366. char *dupprintf(const char *fmt, ...)
  367. {
  368. char *ret;
  369. va_list ap;
  370. va_start(ap, fmt);
  371. ret = dupvprintf(fmt, ap);
  372. va_end(ap);
  373. return ret;
  374. }
  375. struct strbuf_impl {
  376. size_t size;
  377. struct strbuf visible;
  378. bool nm; /* true if we insist on non-moving buffer resizes */
  379. };
  380. #define STRBUF_SET_UPTR(buf) \
  381. ((buf)->visible.u = (unsigned char *)(buf)->visible.s)
  382. #define STRBUF_SET_PTR(buf, ptr) \
  383. ((buf)->visible.s = (ptr), STRBUF_SET_UPTR(buf))
  384. void *strbuf_append(strbuf *buf_o, size_t len)
  385. {
  386. struct strbuf_impl *buf = container_of(buf_o, struct strbuf_impl, visible);
  387. char *toret;
  388. sgrowarray_general(
  389. buf->visible.s, buf->size, buf->visible.len + 1, len, buf->nm);
  390. STRBUF_SET_UPTR(buf);
  391. toret = buf->visible.s + buf->visible.len;
  392. buf->visible.len += len;
  393. buf->visible.s[buf->visible.len] = '\0';
  394. return toret;
  395. }
  396. static void strbuf_BinarySink_write(
  397. BinarySink *bs, const void *data, size_t len)
  398. {
  399. strbuf *buf_o = BinarySink_DOWNCAST(bs, strbuf);
  400. memcpy(strbuf_append(buf_o, len), data, len);
  401. }
  402. static strbuf *strbuf_new_general(bool nm)
  403. {
  404. struct strbuf_impl *buf = snew(struct strbuf_impl);
  405. BinarySink_INIT(&buf->visible, strbuf_BinarySink_write);
  406. buf->visible.len = 0;
  407. buf->size = 512;
  408. buf->nm = nm;
  409. STRBUF_SET_PTR(buf, snewn(buf->size, char));
  410. *buf->visible.s = '\0';
  411. return &buf->visible;
  412. }
  413. strbuf *strbuf_new(void) { return strbuf_new_general(false); }
  414. strbuf *strbuf_new_nm(void) { return strbuf_new_general(true); }
  415. void strbuf_free(strbuf *buf_o)
  416. {
  417. struct strbuf_impl *buf = container_of(buf_o, struct strbuf_impl, visible);
  418. if (buf->visible.s) {
  419. smemclr(buf->visible.s, buf->size);
  420. sfree(buf->visible.s);
  421. }
  422. sfree(buf);
  423. }
  424. char *strbuf_to_str(strbuf *buf_o)
  425. {
  426. struct strbuf_impl *buf = container_of(buf_o, struct strbuf_impl, visible);
  427. char *ret = buf->visible.s;
  428. sfree(buf);
  429. return ret;
  430. }
  431. void strbuf_catfv(strbuf *buf_o, const char *fmt, va_list ap)
  432. {
  433. struct strbuf_impl *buf = container_of(buf_o, struct strbuf_impl, visible);
  434. STRBUF_SET_PTR(buf, dupvprintf_inner(buf->visible.s, buf->visible.len,
  435. &buf->size, fmt, ap));
  436. buf->visible.len += strlen(buf->visible.s + buf->visible.len);
  437. }
  438. void strbuf_catf(strbuf *buf_o, const char *fmt, ...)
  439. {
  440. va_list ap;
  441. va_start(ap, fmt);
  442. strbuf_catfv(buf_o, fmt, ap);
  443. va_end(ap);
  444. }
  445. strbuf *strbuf_new_for_agent_query(void)
  446. {
  447. strbuf *buf = strbuf_new();
  448. strbuf_append(buf, 4);
  449. return buf;
  450. }
  451. void strbuf_finalise_agent_query(strbuf *buf_o)
  452. {
  453. struct strbuf_impl *buf = container_of(buf_o, struct strbuf_impl, visible);
  454. assert(buf->visible.len >= 5);
  455. PUT_32BIT_MSB_FIRST(buf->visible.u, buf->visible.len - 4);
  456. }
  457. /*
  458. * Read an entire line of text from a file. Return a buffer
  459. * malloced to be as big as necessary (caller must free).
  460. */
  461. char *fgetline(FILE *fp)
  462. {
  463. char *ret = snewn(512, char);
  464. size_t size = 512, len = 0;
  465. while (fgets(ret + len, size - len, fp)) {
  466. len += strlen(ret + len);
  467. if (len > 0 && ret[len-1] == '\n')
  468. break; /* got a newline, we're done */
  469. sgrowarrayn_nm(ret, size, len, 512);
  470. }
  471. if (len == 0) { /* first fgets returned NULL */
  472. sfree(ret);
  473. return NULL;
  474. }
  475. ret[len] = '\0';
  476. return ret;
  477. }
  478. /*
  479. * Perl-style 'chomp', for a line we just read with fgetline. Unlike
  480. * Perl chomp, however, we're deliberately forgiving of strange
  481. * line-ending conventions. Also we forgive NULL on input, so you can
  482. * just write 'line = chomp(fgetline(fp));' and not bother checking
  483. * for NULL until afterwards.
  484. */
  485. char *chomp(char *str)
  486. {
  487. if (str) {
  488. int len = strlen(str);
  489. while (len > 0 && (str[len-1] == '\r' || str[len-1] == '\n'))
  490. len--;
  491. str[len] = '\0';
  492. }
  493. return str;
  494. }
  495. /* ----------------------------------------------------------------------
  496. * Core base64 encoding and decoding routines.
  497. */
  498. void base64_encode_atom(const unsigned char *data, int n, char *out)
  499. {
  500. static const char base64_chars[] =
  501. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  502. unsigned word;
  503. word = data[0] << 16;
  504. if (n > 1)
  505. word |= data[1] << 8;
  506. if (n > 2)
  507. word |= data[2];
  508. out[0] = base64_chars[(word >> 18) & 0x3F];
  509. out[1] = base64_chars[(word >> 12) & 0x3F];
  510. if (n > 1)
  511. out[2] = base64_chars[(word >> 6) & 0x3F];
  512. else
  513. out[2] = '=';
  514. if (n > 2)
  515. out[3] = base64_chars[word & 0x3F];
  516. else
  517. out[3] = '=';
  518. }
  519. int base64_decode_atom(const char *atom, unsigned char *out)
  520. {
  521. int vals[4];
  522. int i, v, len;
  523. unsigned word;
  524. char c;
  525. for (i = 0; i < 4; i++) {
  526. c = atom[i];
  527. if (c >= 'A' && c <= 'Z')
  528. v = c - 'A';
  529. else if (c >= 'a' && c <= 'z')
  530. v = c - 'a' + 26;
  531. else if (c >= '0' && c <= '9')
  532. v = c - '0' + 52;
  533. else if (c == '+')
  534. v = 62;
  535. else if (c == '/')
  536. v = 63;
  537. else if (c == '=')
  538. v = -1;
  539. else
  540. return 0; /* invalid atom */
  541. vals[i] = v;
  542. }
  543. if (vals[0] == -1 || vals[1] == -1)
  544. return 0;
  545. if (vals[2] == -1 && vals[3] != -1)
  546. return 0;
  547. if (vals[3] != -1)
  548. len = 3;
  549. else if (vals[2] != -1)
  550. len = 2;
  551. else
  552. len = 1;
  553. word = ((vals[0] << 18) |
  554. (vals[1] << 12) | ((vals[2] & 0x3F) << 6) | (vals[3] & 0x3F));
  555. out[0] = (word >> 16) & 0xFF;
  556. if (len > 1)
  557. out[1] = (word >> 8) & 0xFF;
  558. if (len > 2)
  559. out[2] = word & 0xFF;
  560. return len;
  561. }
  562. /* ----------------------------------------------------------------------
  563. * Generic routines to deal with send buffers: a linked list of
  564. * smallish blocks, with the operations
  565. *
  566. * - add an arbitrary amount of data to the end of the list
  567. * - remove the first N bytes from the list
  568. * - return a (pointer,length) pair giving some initial data in
  569. * the list, suitable for passing to a send or write system
  570. * call
  571. * - retrieve a larger amount of initial data from the list
  572. * - return the current size of the buffer chain in bytes
  573. */
  574. /* WINSCP
  575. * Default granule of 512 leads to low performance.
  576. */
  577. #define BUFFER_MIN_GRANULE 512*2*32
  578. struct bufchain_granule {
  579. struct bufchain_granule *next;
  580. char *bufpos, *bufend, *bufmax;
  581. };
  582. static void uninitialised_queue_idempotent_callback(IdempotentCallback *ic)
  583. {
  584. unreachable("bufchain callback used while uninitialised");
  585. }
  586. void bufchain_init(bufchain *ch)
  587. {
  588. ch->head = ch->tail = NULL;
  589. ch->buffersize = 0;
  590. ch->ic = NULL;
  591. ch->queue_idempotent_callback = uninitialised_queue_idempotent_callback;
  592. }
  593. void bufchain_clear(bufchain *ch)
  594. {
  595. struct bufchain_granule *b;
  596. while (ch->head) {
  597. b = ch->head;
  598. ch->head = ch->head->next;
  599. smemclr(b, sizeof(*b));
  600. sfree(b);
  601. }
  602. ch->tail = NULL;
  603. ch->buffersize = 0;
  604. }
  605. size_t bufchain_size(bufchain *ch)
  606. {
  607. return ch->buffersize;
  608. }
  609. void bufchain_set_callback_inner(
  610. bufchain *ch, IdempotentCallback *ic,
  611. void (*queue_idempotent_callback)(IdempotentCallback *ic))
  612. {
  613. ch->queue_idempotent_callback = queue_idempotent_callback;
  614. ch->ic = ic;
  615. }
  616. void bufchain_add(bufchain *ch, const void *data, size_t len)
  617. {
  618. const char *buf = (const char *)data;
  619. if (len == 0) return;
  620. ch->buffersize += len;
  621. while (len > 0) {
  622. if (ch->tail && ch->tail->bufend < ch->tail->bufmax) {
  623. size_t copylen = min(len, ch->tail->bufmax - ch->tail->bufend);
  624. memcpy(ch->tail->bufend, buf, copylen);
  625. buf += copylen;
  626. len -= copylen;
  627. ch->tail->bufend += copylen;
  628. }
  629. if (len > 0) {
  630. size_t grainlen =
  631. max(sizeof(struct bufchain_granule) + len, BUFFER_MIN_GRANULE);
  632. struct bufchain_granule *newbuf;
  633. newbuf = smalloc(grainlen);
  634. newbuf->bufpos = newbuf->bufend =
  635. (char *)newbuf + sizeof(struct bufchain_granule);
  636. newbuf->bufmax = (char *)newbuf + grainlen;
  637. newbuf->next = NULL;
  638. if (ch->tail)
  639. ch->tail->next = newbuf;
  640. else
  641. ch->head = newbuf;
  642. ch->tail = newbuf;
  643. }
  644. }
  645. if (ch->ic)
  646. ch->queue_idempotent_callback(ch->ic);
  647. }
  648. void bufchain_consume(bufchain *ch, size_t len)
  649. {
  650. struct bufchain_granule *tmp;
  651. assert(ch->buffersize >= len);
  652. while (len > 0) {
  653. int remlen = len;
  654. assert(ch->head != NULL);
  655. if (remlen >= ch->head->bufend - ch->head->bufpos) {
  656. remlen = ch->head->bufend - ch->head->bufpos;
  657. tmp = ch->head;
  658. ch->head = tmp->next;
  659. if (!ch->head)
  660. ch->tail = NULL;
  661. smemclr(tmp, sizeof(*tmp));
  662. sfree(tmp);
  663. } else
  664. ch->head->bufpos += remlen;
  665. ch->buffersize -= remlen;
  666. len -= remlen;
  667. }
  668. }
  669. ptrlen bufchain_prefix(bufchain *ch)
  670. {
  671. return make_ptrlen(ch->head->bufpos, ch->head->bufend - ch->head->bufpos);
  672. }
  673. void bufchain_fetch(bufchain *ch, void *data, size_t len)
  674. {
  675. struct bufchain_granule *tmp;
  676. char *data_c = (char *)data;
  677. tmp = ch->head;
  678. assert(ch->buffersize >= len);
  679. while (len > 0) {
  680. int remlen = len;
  681. assert(tmp != NULL);
  682. if (remlen >= tmp->bufend - tmp->bufpos)
  683. remlen = tmp->bufend - tmp->bufpos;
  684. memcpy(data_c, tmp->bufpos, remlen);
  685. tmp = tmp->next;
  686. len -= remlen;
  687. data_c += remlen;
  688. }
  689. }
  690. void bufchain_fetch_consume(bufchain *ch, void *data, size_t len)
  691. {
  692. bufchain_fetch(ch, data, len);
  693. bufchain_consume(ch, len);
  694. }
  695. bool bufchain_try_fetch_consume(bufchain *ch, void *data, size_t len)
  696. {
  697. if (ch->buffersize >= len) {
  698. bufchain_fetch_consume(ch, data, len);
  699. return true;
  700. } else {
  701. return false;
  702. }
  703. }
  704. size_t bufchain_fetch_consume_up_to(bufchain *ch, void *data, size_t len)
  705. {
  706. if (len > ch->buffersize)
  707. len = ch->buffersize;
  708. if (len)
  709. bufchain_fetch_consume(ch, data, len);
  710. return len;
  711. }
  712. /* ----------------------------------------------------------------------
  713. * Debugging routines.
  714. */
  715. #ifdef DEBUG
  716. extern void dputs(const char *); /* defined in per-platform *misc.c */
  717. void debug_printf(const char *fmt, ...)
  718. {
  719. char *buf;
  720. va_list ap;
  721. va_start(ap, fmt);
  722. buf = dupvprintf(fmt, ap);
  723. dputs(buf);
  724. sfree(buf);
  725. va_end(ap);
  726. }
  727. void debug_memdump(const void *buf, int len, bool L)
  728. {
  729. int i;
  730. const unsigned char *p = buf;
  731. char foo[17];
  732. if (L) {
  733. int delta;
  734. debug_printf("\t%d (0x%x) bytes:\n", len, len);
  735. delta = 15 & (uintptr_t)p;
  736. p -= delta;
  737. len += delta;
  738. }
  739. for (; 0 < len; p += 16, len -= 16) {
  740. dputs(" ");
  741. if (L)
  742. debug_printf("%p: ", p);
  743. strcpy(foo, "................"); /* sixteen dots */
  744. for (i = 0; i < 16 && i < len; ++i) {
  745. if (&p[i] < (unsigned char *) buf) {
  746. dputs(" "); /* 3 spaces */
  747. foo[i] = ' ';
  748. } else {
  749. debug_printf("%c%02.2x",
  750. &p[i] != (unsigned char *) buf
  751. && i % 4 ? '.' : ' ', p[i]
  752. );
  753. if (p[i] >= ' ' && p[i] <= '~')
  754. foo[i] = (char) p[i];
  755. }
  756. }
  757. foo[i] = '\0';
  758. debug_printf("%*s%s\n", (16 - i) * 3 + 2, "", foo);
  759. }
  760. }
  761. #endif /* def DEBUG */
  762. #ifndef PLATFORM_HAS_SMEMCLR
  763. /*
  764. * Securely wipe memory.
  765. *
  766. * The actual wiping is no different from what memset would do: the
  767. * point of 'securely' is to try to be sure over-clever compilers
  768. * won't optimise away memsets on variables that are about to be freed
  769. * or go out of scope. See
  770. * https://buildsecurityin.us-cert.gov/bsi-rules/home/g1/771-BSI.html
  771. *
  772. * Some platforms (e.g. Windows) may provide their own version of this
  773. * function.
  774. */
  775. void smemclr(void *b, size_t n) {
  776. volatile char *vp;
  777. if (b && n > 0) {
  778. /*
  779. * Zero out the memory.
  780. */
  781. memset(b, 0, n);
  782. /*
  783. * Perform a volatile access to the object, forcing the
  784. * compiler to admit that the previous memset was important.
  785. *
  786. * This while loop should in practice run for zero iterations
  787. * (since we know we just zeroed the object out), but in
  788. * theory (as far as the compiler knows) it might range over
  789. * the whole object. (If we had just written, say, '*vp =
  790. * *vp;', a compiler could in principle have 'helpfully'
  791. * optimised the memset into only zeroing out the first byte.
  792. * This should be robust.)
  793. */
  794. vp = b;
  795. while (*vp) vp++;
  796. }
  797. }
  798. #endif
  799. bool smemeq(const void *av, const void *bv, size_t len)
  800. {
  801. const unsigned char *a = (const unsigned char *)av;
  802. const unsigned char *b = (const unsigned char *)bv;
  803. unsigned val = 0;
  804. while (len-- > 0) {
  805. val |= *a++ ^ *b++;
  806. }
  807. /* Now val is 0 iff we want to return 1, and in the range
  808. * 0x01..0xFF iff we want to return 0. So subtracting from 0x100
  809. * will clear bit 8 iff we want to return 0, and leave it set iff
  810. * we want to return 1, so then we can just shift down. */
  811. return (0x100 - val) >> 8;
  812. }
  813. int nullstrcmp(const char *a, const char *b)
  814. {
  815. if (a == NULL && b == NULL)
  816. return 0;
  817. if (a == NULL)
  818. return -1;
  819. if (b == NULL)
  820. return +1;
  821. return strcmp(a, b);
  822. }
  823. bool ptrlen_eq_string(ptrlen pl, const char *str)
  824. {
  825. size_t len = strlen(str);
  826. return (pl.len == len && !memcmp(pl.ptr, str, len));
  827. }
  828. bool ptrlen_eq_ptrlen(ptrlen pl1, ptrlen pl2)
  829. {
  830. return (pl1.len == pl2.len && !memcmp(pl1.ptr, pl2.ptr, pl1.len));
  831. }
  832. int ptrlen_strcmp(ptrlen pl1, ptrlen pl2)
  833. {
  834. size_t minlen = pl1.len < pl2.len ? pl1.len : pl2.len;
  835. if (minlen) { /* tolerate plX.ptr==NULL as long as plX.len==0 */
  836. int cmp = memcmp(pl1.ptr, pl2.ptr, minlen);
  837. if (cmp)
  838. return cmp;
  839. }
  840. return pl1.len < pl2.len ? -1 : pl1.len > pl2.len ? +1 : 0;
  841. }
  842. bool ptrlen_startswith(ptrlen whole, ptrlen prefix, ptrlen *tail)
  843. {
  844. if (whole.len >= prefix.len &&
  845. !memcmp(whole.ptr, prefix.ptr, prefix.len)) {
  846. if (tail) {
  847. tail->ptr = (const char *)whole.ptr + prefix.len;
  848. tail->len = whole.len - prefix.len;
  849. }
  850. return true;
  851. }
  852. return false;
  853. }
  854. bool ptrlen_endswith(ptrlen whole, ptrlen suffix, ptrlen *tail)
  855. {
  856. if (whole.len >= suffix.len &&
  857. !memcmp((char *)whole.ptr + (whole.len - suffix.len),
  858. suffix.ptr, suffix.len)) {
  859. if (tail) {
  860. tail->ptr = whole.ptr;
  861. tail->len = whole.len - suffix.len;
  862. }
  863. return true;
  864. }
  865. return false;
  866. }
  867. char *mkstr(ptrlen pl)
  868. {
  869. char *p = snewn(pl.len + 1, char);
  870. memcpy(p, pl.ptr, pl.len);
  871. p[pl.len] = '\0';
  872. return p;
  873. }
  874. bool strstartswith(const char *s, const char *t)
  875. {
  876. return !memcmp(s, t, strlen(t));
  877. }
  878. bool strendswith(const char *s, const char *t)
  879. {
  880. size_t slen = strlen(s), tlen = strlen(t);
  881. return slen >= tlen && !strcmp(s + (slen - tlen), t);
  882. }
  883. size_t encode_utf8(void *output, unsigned long ch)
  884. {
  885. unsigned char *start = (unsigned char *)output, *p = start;
  886. if (ch < 0x80) {
  887. *p++ = ch;
  888. } else if (ch < 0x800) {
  889. *p++ = 0xC0 | (ch >> 6);
  890. *p++ = 0x80 | (ch & 0x3F);
  891. } else if (ch < 0x10000) {
  892. *p++ = 0xE0 | (ch >> 12);
  893. *p++ = 0x80 | ((ch >> 6) & 0x3F);
  894. *p++ = 0x80 | (ch & 0x3F);
  895. } else {
  896. *p++ = 0xF0 | (ch >> 18);
  897. *p++ = 0x80 | ((ch >> 12) & 0x3F);
  898. *p++ = 0x80 | ((ch >> 6) & 0x3F);
  899. *p++ = 0x80 | (ch & 0x3F);
  900. }
  901. return p - start;
  902. }