utils.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980
  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 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. int len = vsnprintf(buf + oldlen, size - oldlen, fmt, aq);
  333. va_end(aq);
  334. if (len >= 0 && len < size) {
  335. /* This is the C99-specified criterion for snprintf to have
  336. * been completely successful. */
  337. *sizeptr = size;
  338. return buf;
  339. } else if (len > 0) {
  340. /* This is the C99 error condition: the returned length is
  341. * the required buffer size not counting the NUL. */
  342. sgrowarrayn_nm(buf, size, oldlen + 1, len);
  343. } else {
  344. /* This is the pre-C99 glibc error condition: <0 means the
  345. * buffer wasn't big enough, so we enlarge it a bit and hope. */
  346. sgrowarray_nm(buf, size, size);
  347. }
  348. }
  349. }
  350. char *dupvprintf(const char *fmt, va_list ap)
  351. {
  352. size_t size = 0;
  353. return dupvprintf_inner(NULL, 0, &size, fmt, ap);
  354. }
  355. char *dupprintf(const char *fmt, ...)
  356. {
  357. char *ret;
  358. va_list ap;
  359. va_start(ap, fmt);
  360. ret = dupvprintf(fmt, ap);
  361. va_end(ap);
  362. return ret;
  363. }
  364. struct strbuf_impl {
  365. size_t size;
  366. struct strbuf visible;
  367. bool nm; /* true if we insist on non-moving buffer resizes */
  368. };
  369. #define STRBUF_SET_UPTR(buf) \
  370. ((buf)->visible.u = (unsigned char *)(buf)->visible.s)
  371. #define STRBUF_SET_PTR(buf, ptr) \
  372. ((buf)->visible.s = (ptr), STRBUF_SET_UPTR(buf))
  373. void *strbuf_append(strbuf *buf_o, size_t len)
  374. {
  375. struct strbuf_impl *buf = container_of(buf_o, struct strbuf_impl, visible);
  376. char *toret;
  377. sgrowarray_general(
  378. buf->visible.s, buf->size, buf->visible.len + 1, len, buf->nm);
  379. STRBUF_SET_UPTR(buf);
  380. toret = buf->visible.s + buf->visible.len;
  381. buf->visible.len += len;
  382. buf->visible.s[buf->visible.len] = '\0';
  383. return toret;
  384. }
  385. static void strbuf_BinarySink_write(
  386. BinarySink *bs, const void *data, size_t len)
  387. {
  388. strbuf *buf_o = BinarySink_DOWNCAST(bs, strbuf);
  389. memcpy(strbuf_append(buf_o, len), data, len);
  390. }
  391. static strbuf *strbuf_new_general(bool nm)
  392. {
  393. struct strbuf_impl *buf = snew(struct strbuf_impl);
  394. BinarySink_INIT(&buf->visible, strbuf_BinarySink_write);
  395. buf->visible.len = 0;
  396. buf->size = 512;
  397. buf->nm = nm;
  398. STRBUF_SET_PTR(buf, snewn(buf->size, char));
  399. *buf->visible.s = '\0';
  400. return &buf->visible;
  401. }
  402. strbuf *strbuf_new(void) { return strbuf_new_general(false); }
  403. strbuf *strbuf_new_nm(void) { return strbuf_new_general(true); }
  404. void strbuf_free(strbuf *buf_o)
  405. {
  406. struct strbuf_impl *buf = container_of(buf_o, struct strbuf_impl, visible);
  407. if (buf->visible.s) {
  408. smemclr(buf->visible.s, buf->size);
  409. sfree(buf->visible.s);
  410. }
  411. sfree(buf);
  412. }
  413. char *strbuf_to_str(strbuf *buf_o)
  414. {
  415. struct strbuf_impl *buf = container_of(buf_o, struct strbuf_impl, visible);
  416. char *ret = buf->visible.s;
  417. sfree(buf);
  418. return ret;
  419. }
  420. void strbuf_catfv(strbuf *buf_o, const char *fmt, va_list ap)
  421. {
  422. struct strbuf_impl *buf = container_of(buf_o, struct strbuf_impl, visible);
  423. STRBUF_SET_PTR(buf, dupvprintf_inner(buf->visible.s, buf->visible.len,
  424. &buf->size, fmt, ap));
  425. buf->visible.len += strlen(buf->visible.s + buf->visible.len);
  426. }
  427. void strbuf_catf(strbuf *buf_o, const char *fmt, ...)
  428. {
  429. va_list ap;
  430. va_start(ap, fmt);
  431. strbuf_catfv(buf_o, fmt, ap);
  432. va_end(ap);
  433. }
  434. strbuf *strbuf_new_for_agent_query(void)
  435. {
  436. strbuf *buf = strbuf_new();
  437. strbuf_append(buf, 4);
  438. return buf;
  439. }
  440. void strbuf_finalise_agent_query(strbuf *buf_o)
  441. {
  442. struct strbuf_impl *buf = container_of(buf_o, struct strbuf_impl, visible);
  443. assert(buf->visible.len >= 5);
  444. PUT_32BIT_MSB_FIRST(buf->visible.u, buf->visible.len - 4);
  445. }
  446. /*
  447. * Read an entire line of text from a file. Return a buffer
  448. * malloced to be as big as necessary (caller must free).
  449. */
  450. char *fgetline(FILE *fp)
  451. {
  452. char *ret = snewn(512, char);
  453. size_t size = 512, len = 0;
  454. while (fgets(ret + len, size - len, fp)) {
  455. len += strlen(ret + len);
  456. if (len > 0 && ret[len-1] == '\n')
  457. break; /* got a newline, we're done */
  458. sgrowarrayn_nm(ret, size, len, 512);
  459. }
  460. if (len == 0) { /* first fgets returned NULL */
  461. sfree(ret);
  462. return NULL;
  463. }
  464. ret[len] = '\0';
  465. return ret;
  466. }
  467. /*
  468. * Perl-style 'chomp', for a line we just read with fgetline. Unlike
  469. * Perl chomp, however, we're deliberately forgiving of strange
  470. * line-ending conventions. Also we forgive NULL on input, so you can
  471. * just write 'line = chomp(fgetline(fp));' and not bother checking
  472. * for NULL until afterwards.
  473. */
  474. char *chomp(char *str)
  475. {
  476. if (str) {
  477. int len = strlen(str);
  478. while (len > 0 && (str[len-1] == '\r' || str[len-1] == '\n'))
  479. len--;
  480. str[len] = '\0';
  481. }
  482. return str;
  483. }
  484. /* ----------------------------------------------------------------------
  485. * Core base64 encoding and decoding routines.
  486. */
  487. void base64_encode_atom(const unsigned char *data, int n, char *out)
  488. {
  489. static const char base64_chars[] =
  490. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  491. unsigned word;
  492. word = data[0] << 16;
  493. if (n > 1)
  494. word |= data[1] << 8;
  495. if (n > 2)
  496. word |= data[2];
  497. out[0] = base64_chars[(word >> 18) & 0x3F];
  498. out[1] = base64_chars[(word >> 12) & 0x3F];
  499. if (n > 1)
  500. out[2] = base64_chars[(word >> 6) & 0x3F];
  501. else
  502. out[2] = '=';
  503. if (n > 2)
  504. out[3] = base64_chars[word & 0x3F];
  505. else
  506. out[3] = '=';
  507. }
  508. int base64_decode_atom(const char *atom, unsigned char *out)
  509. {
  510. int vals[4];
  511. int i, v, len;
  512. unsigned word;
  513. char c;
  514. for (i = 0; i < 4; i++) {
  515. c = atom[i];
  516. if (c >= 'A' && c <= 'Z')
  517. v = c - 'A';
  518. else if (c >= 'a' && c <= 'z')
  519. v = c - 'a' + 26;
  520. else if (c >= '0' && c <= '9')
  521. v = c - '0' + 52;
  522. else if (c == '+')
  523. v = 62;
  524. else if (c == '/')
  525. v = 63;
  526. else if (c == '=')
  527. v = -1;
  528. else
  529. return 0; /* invalid atom */
  530. vals[i] = v;
  531. }
  532. if (vals[0] == -1 || vals[1] == -1)
  533. return 0;
  534. if (vals[2] == -1 && vals[3] != -1)
  535. return 0;
  536. if (vals[3] != -1)
  537. len = 3;
  538. else if (vals[2] != -1)
  539. len = 2;
  540. else
  541. len = 1;
  542. word = ((vals[0] << 18) |
  543. (vals[1] << 12) | ((vals[2] & 0x3F) << 6) | (vals[3] & 0x3F));
  544. out[0] = (word >> 16) & 0xFF;
  545. if (len > 1)
  546. out[1] = (word >> 8) & 0xFF;
  547. if (len > 2)
  548. out[2] = word & 0xFF;
  549. return len;
  550. }
  551. /* ----------------------------------------------------------------------
  552. * Generic routines to deal with send buffers: a linked list of
  553. * smallish blocks, with the operations
  554. *
  555. * - add an arbitrary amount of data to the end of the list
  556. * - remove the first N bytes from the list
  557. * - return a (pointer,length) pair giving some initial data in
  558. * the list, suitable for passing to a send or write system
  559. * call
  560. * - retrieve a larger amount of initial data from the list
  561. * - return the current size of the buffer chain in bytes
  562. */
  563. #define BUFFER_MIN_GRANULE 512
  564. struct bufchain_granule {
  565. struct bufchain_granule *next;
  566. char *bufpos, *bufend, *bufmax;
  567. };
  568. static void uninitialised_queue_idempotent_callback(IdempotentCallback *ic)
  569. {
  570. unreachable("bufchain callback used while uninitialised");
  571. }
  572. void bufchain_init(bufchain *ch)
  573. {
  574. ch->head = ch->tail = NULL;
  575. ch->buffersize = 0;
  576. ch->ic = NULL;
  577. ch->queue_idempotent_callback = uninitialised_queue_idempotent_callback;
  578. }
  579. void bufchain_clear(bufchain *ch)
  580. {
  581. struct bufchain_granule *b;
  582. while (ch->head) {
  583. b = ch->head;
  584. ch->head = ch->head->next;
  585. smemclr(b, sizeof(*b));
  586. sfree(b);
  587. }
  588. ch->tail = NULL;
  589. ch->buffersize = 0;
  590. }
  591. size_t bufchain_size(bufchain *ch)
  592. {
  593. return ch->buffersize;
  594. }
  595. void bufchain_set_callback_inner(
  596. bufchain *ch, IdempotentCallback *ic,
  597. void (*queue_idempotent_callback)(IdempotentCallback *ic))
  598. {
  599. ch->queue_idempotent_callback = queue_idempotent_callback;
  600. ch->ic = ic;
  601. }
  602. void bufchain_add(bufchain *ch, const void *data, size_t len)
  603. {
  604. const char *buf = (const char *)data;
  605. if (len == 0) return;
  606. ch->buffersize += len;
  607. while (len > 0) {
  608. if (ch->tail && ch->tail->bufend < ch->tail->bufmax) {
  609. size_t copylen = min(len, ch->tail->bufmax - ch->tail->bufend);
  610. memcpy(ch->tail->bufend, buf, copylen);
  611. buf += copylen;
  612. len -= copylen;
  613. ch->tail->bufend += copylen;
  614. }
  615. if (len > 0) {
  616. size_t grainlen =
  617. max(sizeof(struct bufchain_granule) + len, BUFFER_MIN_GRANULE);
  618. struct bufchain_granule *newbuf;
  619. newbuf = smalloc(grainlen);
  620. newbuf->bufpos = newbuf->bufend =
  621. (char *)newbuf + sizeof(struct bufchain_granule);
  622. newbuf->bufmax = (char *)newbuf + grainlen;
  623. newbuf->next = NULL;
  624. if (ch->tail)
  625. ch->tail->next = newbuf;
  626. else
  627. ch->head = newbuf;
  628. ch->tail = newbuf;
  629. }
  630. }
  631. if (ch->ic)
  632. ch->queue_idempotent_callback(ch->ic);
  633. }
  634. void bufchain_consume(bufchain *ch, size_t len)
  635. {
  636. struct bufchain_granule *tmp;
  637. assert(ch->buffersize >= len);
  638. while (len > 0) {
  639. int remlen = len;
  640. assert(ch->head != NULL);
  641. if (remlen >= ch->head->bufend - ch->head->bufpos) {
  642. remlen = ch->head->bufend - ch->head->bufpos;
  643. tmp = ch->head;
  644. ch->head = tmp->next;
  645. if (!ch->head)
  646. ch->tail = NULL;
  647. smemclr(tmp, sizeof(*tmp));
  648. sfree(tmp);
  649. } else
  650. ch->head->bufpos += remlen;
  651. ch->buffersize -= remlen;
  652. len -= remlen;
  653. }
  654. }
  655. ptrlen bufchain_prefix(bufchain *ch)
  656. {
  657. return make_ptrlen(ch->head->bufpos, ch->head->bufend - ch->head->bufpos);
  658. }
  659. void bufchain_fetch(bufchain *ch, void *data, size_t len)
  660. {
  661. struct bufchain_granule *tmp;
  662. char *data_c = (char *)data;
  663. tmp = ch->head;
  664. assert(ch->buffersize >= len);
  665. while (len > 0) {
  666. int remlen = len;
  667. assert(tmp != NULL);
  668. if (remlen >= tmp->bufend - tmp->bufpos)
  669. remlen = tmp->bufend - tmp->bufpos;
  670. memcpy(data_c, tmp->bufpos, remlen);
  671. tmp = tmp->next;
  672. len -= remlen;
  673. data_c += remlen;
  674. }
  675. }
  676. void bufchain_fetch_consume(bufchain *ch, void *data, size_t len)
  677. {
  678. bufchain_fetch(ch, data, len);
  679. bufchain_consume(ch, len);
  680. }
  681. bool bufchain_try_fetch_consume(bufchain *ch, void *data, size_t len)
  682. {
  683. if (ch->buffersize >= len) {
  684. bufchain_fetch_consume(ch, data, len);
  685. return true;
  686. } else {
  687. return false;
  688. }
  689. }
  690. size_t bufchain_fetch_consume_up_to(bufchain *ch, void *data, size_t len)
  691. {
  692. if (len > ch->buffersize)
  693. len = ch->buffersize;
  694. if (len)
  695. bufchain_fetch_consume(ch, data, len);
  696. return len;
  697. }
  698. /* ----------------------------------------------------------------------
  699. * Debugging routines.
  700. */
  701. #ifdef DEBUG
  702. extern void dputs(const char *); /* defined in per-platform *misc.c */
  703. void debug_printf(const char *fmt, ...)
  704. {
  705. char *buf;
  706. va_list ap;
  707. va_start(ap, fmt);
  708. buf = dupvprintf(fmt, ap);
  709. dputs(buf);
  710. sfree(buf);
  711. va_end(ap);
  712. }
  713. void debug_memdump(const void *buf, int len, bool L)
  714. {
  715. int i;
  716. const unsigned char *p = buf;
  717. char foo[17];
  718. if (L) {
  719. int delta;
  720. debug_printf("\t%d (0x%x) bytes:\n", len, len);
  721. delta = 15 & (uintptr_t)p;
  722. p -= delta;
  723. len += delta;
  724. }
  725. for (; 0 < len; p += 16, len -= 16) {
  726. dputs(" ");
  727. if (L)
  728. debug_printf("%p: ", p);
  729. strcpy(foo, "................"); /* sixteen dots */
  730. for (i = 0; i < 16 && i < len; ++i) {
  731. if (&p[i] < (unsigned char *) buf) {
  732. dputs(" "); /* 3 spaces */
  733. foo[i] = ' ';
  734. } else {
  735. debug_printf("%c%02.2x",
  736. &p[i] != (unsigned char *) buf
  737. && i % 4 ? '.' : ' ', p[i]
  738. );
  739. if (p[i] >= ' ' && p[i] <= '~')
  740. foo[i] = (char) p[i];
  741. }
  742. }
  743. foo[i] = '\0';
  744. debug_printf("%*s%s\n", (16 - i) * 3 + 2, "", foo);
  745. }
  746. }
  747. #endif /* def DEBUG */
  748. #ifndef PLATFORM_HAS_SMEMCLR
  749. /*
  750. * Securely wipe memory.
  751. *
  752. * The actual wiping is no different from what memset would do: the
  753. * point of 'securely' is to try to be sure over-clever compilers
  754. * won't optimise away memsets on variables that are about to be freed
  755. * or go out of scope. See
  756. * https://buildsecurityin.us-cert.gov/bsi-rules/home/g1/771-BSI.html
  757. *
  758. * Some platforms (e.g. Windows) may provide their own version of this
  759. * function.
  760. */
  761. void smemclr(void *b, size_t n) {
  762. volatile char *vp;
  763. if (b && n > 0) {
  764. /*
  765. * Zero out the memory.
  766. */
  767. memset(b, 0, n);
  768. /*
  769. * Perform a volatile access to the object, forcing the
  770. * compiler to admit that the previous memset was important.
  771. *
  772. * This while loop should in practice run for zero iterations
  773. * (since we know we just zeroed the object out), but in
  774. * theory (as far as the compiler knows) it might range over
  775. * the whole object. (If we had just written, say, '*vp =
  776. * *vp;', a compiler could in principle have 'helpfully'
  777. * optimised the memset into only zeroing out the first byte.
  778. * This should be robust.)
  779. */
  780. vp = b;
  781. while (*vp) vp++;
  782. }
  783. }
  784. #endif
  785. bool smemeq(const void *av, const void *bv, size_t len)
  786. {
  787. const unsigned char *a = (const unsigned char *)av;
  788. const unsigned char *b = (const unsigned char *)bv;
  789. unsigned val = 0;
  790. while (len-- > 0) {
  791. val |= *a++ ^ *b++;
  792. }
  793. /* Now val is 0 iff we want to return 1, and in the range
  794. * 0x01..0xFF iff we want to return 0. So subtracting from 0x100
  795. * will clear bit 8 iff we want to return 0, and leave it set iff
  796. * we want to return 1, so then we can just shift down. */
  797. return (0x100 - val) >> 8;
  798. }
  799. int nullstrcmp(const char *a, const char *b)
  800. {
  801. if (a == NULL && b == NULL)
  802. return 0;
  803. if (a == NULL)
  804. return -1;
  805. if (b == NULL)
  806. return +1;
  807. return strcmp(a, b);
  808. }
  809. bool ptrlen_eq_string(ptrlen pl, const char *str)
  810. {
  811. size_t len = strlen(str);
  812. return (pl.len == len && !memcmp(pl.ptr, str, len));
  813. }
  814. bool ptrlen_eq_ptrlen(ptrlen pl1, ptrlen pl2)
  815. {
  816. return (pl1.len == pl2.len && !memcmp(pl1.ptr, pl2.ptr, pl1.len));
  817. }
  818. int ptrlen_strcmp(ptrlen pl1, ptrlen pl2)
  819. {
  820. size_t minlen = pl1.len < pl2.len ? pl1.len : pl2.len;
  821. if (minlen) { /* tolerate plX.ptr==NULL as long as plX.len==0 */
  822. int cmp = memcmp(pl1.ptr, pl2.ptr, minlen);
  823. if (cmp)
  824. return cmp;
  825. }
  826. return pl1.len < pl2.len ? -1 : pl1.len > pl2.len ? +1 : 0;
  827. }
  828. bool ptrlen_startswith(ptrlen whole, ptrlen prefix, ptrlen *tail)
  829. {
  830. if (whole.len >= prefix.len &&
  831. !memcmp(whole.ptr, prefix.ptr, prefix.len)) {
  832. if (tail) {
  833. tail->ptr = (const char *)whole.ptr + prefix.len;
  834. tail->len = whole.len - prefix.len;
  835. }
  836. return true;
  837. }
  838. return false;
  839. }
  840. bool ptrlen_endswith(ptrlen whole, ptrlen suffix, ptrlen *tail)
  841. {
  842. if (whole.len >= suffix.len &&
  843. !memcmp((char *)whole.ptr + (whole.len - suffix.len),
  844. suffix.ptr, suffix.len)) {
  845. if (tail) {
  846. tail->ptr = whole.ptr;
  847. tail->len = whole.len - suffix.len;
  848. }
  849. return true;
  850. }
  851. return false;
  852. }
  853. char *mkstr(ptrlen pl)
  854. {
  855. char *p = snewn(pl.len + 1, char);
  856. memcpy(p, pl.ptr, pl.len);
  857. p[pl.len] = '\0';
  858. return p;
  859. }
  860. bool strstartswith(const char *s, const char *t)
  861. {
  862. return !memcmp(s, t, strlen(t));
  863. }
  864. bool strendswith(const char *s, const char *t)
  865. {
  866. size_t slen = strlen(s), tlen = strlen(t);
  867. return slen >= tlen && !strcmp(s + (slen - tlen), t);
  868. }
  869. size_t encode_utf8(void *output, unsigned long ch)
  870. {
  871. unsigned char *start = (unsigned char *)output, *p = start;
  872. if (ch < 0x80) {
  873. *p++ = ch;
  874. } else if (ch < 0x800) {
  875. *p++ = 0xC0 | (ch >> 6);
  876. *p++ = 0x80 | (ch & 0x3F);
  877. } else if (ch < 0x10000) {
  878. *p++ = 0xE0 | (ch >> 12);
  879. *p++ = 0x80 | ((ch >> 6) & 0x3F);
  880. *p++ = 0x80 | (ch & 0x3F);
  881. } else {
  882. *p++ = 0xF0 | (ch >> 18);
  883. *p++ = 0x80 | ((ch >> 12) & 0x3F);
  884. *p++ = 0x80 | ((ch >> 6) & 0x3F);
  885. *p++ = 0x80 | (ch & 0x3F);
  886. }
  887. return p - start;
  888. }