utils.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  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 == ']' && !p[1] && colons > 1) {
  198. /*
  199. * This looks like an IPv6 address literal (hex digits and
  200. * at least two colons, contained in square brackets).
  201. * Trim off the brackets.
  202. */
  203. return dupprintf("%.*s", (int)(p - (s+1)), s+1);
  204. }
  205. }
  206. /*
  207. * Any other shape of string is simply duplicated.
  208. */
  209. return dupstr(s);
  210. }
  211. /* ----------------------------------------------------------------------
  212. * String handling routines.
  213. */
  214. char *dupstr(const char *s)
  215. {
  216. char *p = NULL;
  217. if (s) {
  218. int len = strlen(s);
  219. p = snewn(len + 1, char);
  220. strcpy(p, s);
  221. }
  222. return p;
  223. }
  224. /* Allocate the concatenation of N strings. Terminate arg list with NULL. */
  225. char *dupcat(const char *s1, ...)
  226. {
  227. int len;
  228. char *p, *q, *sn;
  229. va_list ap;
  230. len = strlen(s1);
  231. va_start(ap, s1);
  232. while (1) {
  233. sn = va_arg(ap, char *);
  234. if (!sn)
  235. break;
  236. len += strlen(sn);
  237. }
  238. va_end(ap);
  239. p = snewn(len + 1, char);
  240. strcpy(p, s1);
  241. q = p + strlen(p);
  242. va_start(ap, s1);
  243. while (1) {
  244. sn = va_arg(ap, char *);
  245. if (!sn)
  246. break;
  247. strcpy(q, sn);
  248. q += strlen(q);
  249. }
  250. va_end(ap);
  251. return p;
  252. }
  253. void burnstr(char *string) /* sfree(str), only clear it first */
  254. {
  255. if (string) {
  256. smemclr(string, strlen(string));
  257. sfree(string);
  258. }
  259. }
  260. int string_length_for_printf(size_t s)
  261. {
  262. /* Truncate absurdly long strings (should one show up) to fit
  263. * within a positive 'int', which is what the "%.*s" format will
  264. * expect. */
  265. if (s > INT_MAX)
  266. return INT_MAX;
  267. return s;
  268. }
  269. /*
  270. * Do an sprintf(), but into a custom-allocated buffer.
  271. *
  272. * Currently I'm doing this via vsnprintf. This has worked so far,
  273. * but it's not good, because vsnprintf is not available on all
  274. * platforms. There's an ifdef to use `_vsnprintf', which seems
  275. * to be the local name for it on Windows. Other platforms may
  276. * lack it completely, in which case it'll be time to rewrite
  277. * this function in a totally different way.
  278. *
  279. * The only `properly' portable solution I can think of is to
  280. * implement my own format string scanner, which figures out an
  281. * upper bound for the length of each formatting directive,
  282. * allocates the buffer as it goes along, and calls sprintf() to
  283. * actually process each directive. If I ever need to actually do
  284. * this, some caveats:
  285. *
  286. * - It's very hard to find a reliable upper bound for
  287. * floating-point values. %f, in particular, when supplied with
  288. * a number near to the upper or lower limit of representable
  289. * numbers, could easily take several hundred characters. It's
  290. * probably feasible to predict this statically using the
  291. * constants in <float.h>, or even to predict it dynamically by
  292. * looking at the exponent of the specific float provided, but
  293. * it won't be fun.
  294. *
  295. * - Don't forget to _check_, after calling sprintf, that it's
  296. * used at most the amount of space we had available.
  297. *
  298. * - Fault any formatting directive we don't fully understand. The
  299. * aim here is to _guarantee_ that we never overflow the buffer,
  300. * because this is a security-critical function. If we see a
  301. * directive we don't know about, we should panic and die rather
  302. * than run any risk.
  303. */
  304. static char *dupvprintf_inner(char *buf, int oldlen, int *oldsize,
  305. const char *fmt, va_list ap)
  306. {
  307. int len, size, newsize;
  308. assert(*oldsize >= oldlen);
  309. size = *oldsize - oldlen;
  310. if (size == 0) {
  311. size = 512;
  312. newsize = oldlen + size;
  313. buf = sresize(buf, newsize, char);
  314. } else {
  315. newsize = *oldsize;
  316. }
  317. while (1) {
  318. #if defined _WINDOWS && !defined __WINE__ && _MSC_VER < 1900 /* 1900 == VS2015 has real snprintf */
  319. #define vsnprintf _vsnprintf
  320. #endif
  321. #ifdef va_copy
  322. /* Use the `va_copy' macro mandated by C99, if present.
  323. * XXX some environments may have this as __va_copy() */
  324. va_list aq;
  325. va_copy(aq, ap);
  326. len = vsnprintf(buf + oldlen, size, fmt, aq);
  327. va_end(aq);
  328. #else
  329. /* Ugh. No va_copy macro, so do something nasty.
  330. * Technically, you can't reuse a va_list like this: it is left
  331. * unspecified whether advancing a va_list pointer modifies its
  332. * value or something it points to, so on some platforms calling
  333. * vsnprintf twice on the same va_list might fail hideously
  334. * (indeed, it has been observed to).
  335. * XXX the autoconf manual suggests that using memcpy() will give
  336. * "maximum portability". */
  337. len = vsnprintf(buf + oldlen, size, fmt, ap);
  338. #endif
  339. if (len >= 0 && len < size) {
  340. /* This is the C99-specified criterion for snprintf to have
  341. * been completely successful. */
  342. *oldsize = newsize;
  343. return buf;
  344. } else if (len > 0) {
  345. /* This is the C99 error condition: the returned length is
  346. * the required buffer size not counting the NUL. */
  347. size = len + 1;
  348. } else {
  349. /* This is the pre-C99 glibc error condition: <0 means the
  350. * buffer wasn't big enough, so we enlarge it a bit and hope. */
  351. size += 512;
  352. }
  353. newsize = oldlen + size;
  354. buf = sresize(buf, newsize, char);
  355. }
  356. }
  357. char *dupvprintf(const char *fmt, va_list ap)
  358. {
  359. int size = 0;
  360. return dupvprintf_inner(NULL, 0, &size, fmt, ap);
  361. }
  362. char *dupprintf(const char *fmt, ...)
  363. {
  364. char *ret;
  365. va_list ap;
  366. va_start(ap, fmt);
  367. ret = dupvprintf(fmt, ap);
  368. va_end(ap);
  369. return ret;
  370. }
  371. struct strbuf_impl {
  372. int size;
  373. struct strbuf visible;
  374. };
  375. #define STRBUF_SET_PTR(buf, ptr) \
  376. ((buf)->visible.s = (ptr), \
  377. (buf)->visible.u = (unsigned char *)(buf)->visible.s)
  378. void *strbuf_append(strbuf *buf_o, size_t len)
  379. {
  380. struct strbuf_impl *buf = container_of(buf_o, struct strbuf_impl, visible);
  381. char *toret;
  382. if (buf->size < buf->visible.len + len + 1) {
  383. buf->size = (buf->visible.len + len + 1) * 5 / 4 + 512;
  384. STRBUF_SET_PTR(buf, sresize(buf->visible.s, buf->size, char));
  385. }
  386. toret = buf->visible.s + buf->visible.len;
  387. buf->visible.len += len;
  388. buf->visible.s[buf->visible.len] = '\0';
  389. return toret;
  390. }
  391. static void strbuf_BinarySink_write(
  392. BinarySink *bs, const void *data, size_t len)
  393. {
  394. strbuf *buf_o = BinarySink_DOWNCAST(bs, strbuf);
  395. memcpy(strbuf_append(buf_o, len), data, len);
  396. }
  397. strbuf *strbuf_new(void)
  398. {
  399. struct strbuf_impl *buf = snew(struct strbuf_impl);
  400. BinarySink_INIT(&buf->visible, strbuf_BinarySink_write);
  401. buf->visible.len = 0;
  402. buf->size = 512;
  403. STRBUF_SET_PTR(buf, snewn(buf->size, char));
  404. *buf->visible.s = '\0';
  405. return &buf->visible;
  406. }
  407. void strbuf_free(strbuf *buf_o)
  408. {
  409. struct strbuf_impl *buf = container_of(buf_o, struct strbuf_impl, visible);
  410. if (buf->visible.s) {
  411. smemclr(buf->visible.s, buf->size);
  412. sfree(buf->visible.s);
  413. }
  414. sfree(buf);
  415. }
  416. char *strbuf_to_str(strbuf *buf_o)
  417. {
  418. struct strbuf_impl *buf = container_of(buf_o, struct strbuf_impl, visible);
  419. char *ret = buf->visible.s;
  420. sfree(buf);
  421. return ret;
  422. }
  423. void strbuf_catfv(strbuf *buf_o, const char *fmt, va_list ap)
  424. {
  425. struct strbuf_impl *buf = container_of(buf_o, struct strbuf_impl, visible);
  426. STRBUF_SET_PTR(buf, dupvprintf_inner(buf->visible.s, buf->visible.len,
  427. &buf->size, fmt, ap));
  428. buf->visible.len += strlen(buf->visible.s + buf->visible.len);
  429. }
  430. void strbuf_catf(strbuf *buf_o, const char *fmt, ...)
  431. {
  432. va_list ap;
  433. va_start(ap, fmt);
  434. strbuf_catfv(buf_o, fmt, ap);
  435. va_end(ap);
  436. }
  437. strbuf *strbuf_new_for_agent_query(void)
  438. {
  439. strbuf *buf = strbuf_new();
  440. strbuf_append(buf, 4);
  441. return buf;
  442. }
  443. void strbuf_finalise_agent_query(strbuf *buf_o)
  444. {
  445. struct strbuf_impl *buf = container_of(buf_o, struct strbuf_impl, visible);
  446. assert(buf->visible.len >= 5);
  447. PUT_32BIT_MSB_FIRST(buf->visible.u, buf->visible.len - 4);
  448. }
  449. /*
  450. * Read an entire line of text from a file. Return a buffer
  451. * malloced to be as big as necessary (caller must free).
  452. */
  453. char *fgetline(FILE *fp)
  454. {
  455. char *ret = snewn(512, char);
  456. int size = 512, len = 0;
  457. while (fgets(ret + len, size - len, fp)) {
  458. len += strlen(ret + len);
  459. if (len > 0 && ret[len-1] == '\n')
  460. break; /* got a newline, we're done */
  461. size = len + 512;
  462. ret = sresize(ret, size, char);
  463. }
  464. if (len == 0) { /* first fgets returned NULL */
  465. sfree(ret);
  466. return NULL;
  467. }
  468. ret[len] = '\0';
  469. return ret;
  470. }
  471. /*
  472. * Perl-style 'chomp', for a line we just read with fgetline. Unlike
  473. * Perl chomp, however, we're deliberately forgiving of strange
  474. * line-ending conventions. Also we forgive NULL on input, so you can
  475. * just write 'line = chomp(fgetline(fp));' and not bother checking
  476. * for NULL until afterwards.
  477. */
  478. char *chomp(char *str)
  479. {
  480. if (str) {
  481. int len = strlen(str);
  482. while (len > 0 && (str[len-1] == '\r' || str[len-1] == '\n'))
  483. len--;
  484. str[len] = '\0';
  485. }
  486. return str;
  487. }
  488. /* ----------------------------------------------------------------------
  489. * Core base64 encoding and decoding routines.
  490. */
  491. void base64_encode_atom(const unsigned char *data, int n, char *out)
  492. {
  493. static const char base64_chars[] =
  494. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  495. unsigned word;
  496. word = data[0] << 16;
  497. if (n > 1)
  498. word |= data[1] << 8;
  499. if (n > 2)
  500. word |= data[2];
  501. out[0] = base64_chars[(word >> 18) & 0x3F];
  502. out[1] = base64_chars[(word >> 12) & 0x3F];
  503. if (n > 1)
  504. out[2] = base64_chars[(word >> 6) & 0x3F];
  505. else
  506. out[2] = '=';
  507. if (n > 2)
  508. out[3] = base64_chars[word & 0x3F];
  509. else
  510. out[3] = '=';
  511. }
  512. int base64_decode_atom(const char *atom, unsigned char *out)
  513. {
  514. int vals[4];
  515. int i, v, len;
  516. unsigned word;
  517. char c;
  518. for (i = 0; i < 4; i++) {
  519. c = atom[i];
  520. if (c >= 'A' && c <= 'Z')
  521. v = c - 'A';
  522. else if (c >= 'a' && c <= 'z')
  523. v = c - 'a' + 26;
  524. else if (c >= '0' && c <= '9')
  525. v = c - '0' + 52;
  526. else if (c == '+')
  527. v = 62;
  528. else if (c == '/')
  529. v = 63;
  530. else if (c == '=')
  531. v = -1;
  532. else
  533. return 0; /* invalid atom */
  534. vals[i] = v;
  535. }
  536. if (vals[0] == -1 || vals[1] == -1)
  537. return 0;
  538. if (vals[2] == -1 && vals[3] != -1)
  539. return 0;
  540. if (vals[3] != -1)
  541. len = 3;
  542. else if (vals[2] != -1)
  543. len = 2;
  544. else
  545. len = 1;
  546. word = ((vals[0] << 18) |
  547. (vals[1] << 12) | ((vals[2] & 0x3F) << 6) | (vals[3] & 0x3F));
  548. out[0] = (word >> 16) & 0xFF;
  549. if (len > 1)
  550. out[1] = (word >> 8) & 0xFF;
  551. if (len > 2)
  552. out[2] = word & 0xFF;
  553. return len;
  554. }
  555. /* ----------------------------------------------------------------------
  556. * Generic routines to deal with send buffers: a linked list of
  557. * smallish blocks, with the operations
  558. *
  559. * - add an arbitrary amount of data to the end of the list
  560. * - remove the first N bytes from the list
  561. * - return a (pointer,length) pair giving some initial data in
  562. * the list, suitable for passing to a send or write system
  563. * call
  564. * - retrieve a larger amount of initial data from the list
  565. * - return the current size of the buffer chain in bytes
  566. */
  567. #define BUFFER_MIN_GRANULE 512
  568. struct bufchain_granule {
  569. struct bufchain_granule *next;
  570. char *bufpos, *bufend, *bufmax;
  571. };
  572. static void uninitialised_queue_idempotent_callback(IdempotentCallback *ic)
  573. {
  574. unreachable("bufchain callback used while uninitialised");
  575. }
  576. void bufchain_init(bufchain *ch)
  577. {
  578. ch->head = ch->tail = NULL;
  579. ch->buffersize = 0;
  580. ch->ic = NULL;
  581. ch->queue_idempotent_callback = uninitialised_queue_idempotent_callback;
  582. }
  583. void bufchain_clear(bufchain *ch)
  584. {
  585. struct bufchain_granule *b;
  586. while (ch->head) {
  587. b = ch->head;
  588. ch->head = ch->head->next;
  589. sfree(b);
  590. }
  591. ch->tail = NULL;
  592. ch->buffersize = 0;
  593. }
  594. int bufchain_size(bufchain *ch)
  595. {
  596. return ch->buffersize;
  597. }
  598. void bufchain_set_callback_inner(
  599. bufchain *ch, IdempotentCallback *ic,
  600. void (*queue_idempotent_callback)(IdempotentCallback *ic))
  601. {
  602. ch->queue_idempotent_callback = queue_idempotent_callback;
  603. ch->ic = ic;
  604. }
  605. void bufchain_add(bufchain *ch, const void *data, int len)
  606. {
  607. const char *buf = (const char *)data;
  608. if (len == 0) return;
  609. ch->buffersize += len;
  610. while (len > 0) {
  611. if (ch->tail && ch->tail->bufend < ch->tail->bufmax) {
  612. int copylen = min(len, ch->tail->bufmax - ch->tail->bufend);
  613. memcpy(ch->tail->bufend, buf, copylen);
  614. buf += copylen;
  615. len -= copylen;
  616. ch->tail->bufend += copylen;
  617. }
  618. if (len > 0) {
  619. int grainlen =
  620. max(sizeof(struct bufchain_granule) + len, BUFFER_MIN_GRANULE);
  621. struct bufchain_granule *newbuf;
  622. newbuf = smalloc(grainlen);
  623. newbuf->bufpos = newbuf->bufend =
  624. (char *)newbuf + sizeof(struct bufchain_granule);
  625. newbuf->bufmax = (char *)newbuf + grainlen;
  626. newbuf->next = NULL;
  627. if (ch->tail)
  628. ch->tail->next = newbuf;
  629. else
  630. ch->head = newbuf;
  631. ch->tail = newbuf;
  632. }
  633. }
  634. if (ch->ic)
  635. ch->queue_idempotent_callback(ch->ic);
  636. }
  637. void bufchain_consume(bufchain *ch, int len)
  638. {
  639. struct bufchain_granule *tmp;
  640. assert(ch->buffersize >= len);
  641. while (len > 0) {
  642. int remlen = len;
  643. assert(ch->head != NULL);
  644. if (remlen >= ch->head->bufend - ch->head->bufpos) {
  645. remlen = ch->head->bufend - ch->head->bufpos;
  646. tmp = ch->head;
  647. ch->head = tmp->next;
  648. if (!ch->head)
  649. ch->tail = NULL;
  650. sfree(tmp);
  651. } else
  652. ch->head->bufpos += remlen;
  653. ch->buffersize -= remlen;
  654. len -= remlen;
  655. }
  656. }
  657. void bufchain_prefix(bufchain *ch, void **data, int *len)
  658. {
  659. *len = ch->head->bufend - ch->head->bufpos;
  660. *data = ch->head->bufpos;
  661. }
  662. void bufchain_fetch(bufchain *ch, void *data, int len)
  663. {
  664. struct bufchain_granule *tmp;
  665. char *data_c = (char *)data;
  666. tmp = ch->head;
  667. assert(ch->buffersize >= len);
  668. while (len > 0) {
  669. int remlen = len;
  670. assert(tmp != NULL);
  671. if (remlen >= tmp->bufend - tmp->bufpos)
  672. remlen = tmp->bufend - tmp->bufpos;
  673. memcpy(data_c, tmp->bufpos, remlen);
  674. tmp = tmp->next;
  675. len -= remlen;
  676. data_c += remlen;
  677. }
  678. }
  679. void bufchain_fetch_consume(bufchain *ch, void *data, int len)
  680. {
  681. bufchain_fetch(ch, data, len);
  682. bufchain_consume(ch, len);
  683. }
  684. bool bufchain_try_fetch_consume(bufchain *ch, void *data, int len)
  685. {
  686. if (ch->buffersize >= len) {
  687. bufchain_fetch_consume(ch, data, len);
  688. return true;
  689. } else {
  690. return false;
  691. }
  692. }
  693. int bufchain_fetch_consume_up_to(bufchain *ch, void *data, int len)
  694. {
  695. if (len > ch->buffersize)
  696. len = ch->buffersize;
  697. if (len)
  698. bufchain_fetch_consume(ch, data, len);
  699. return len;
  700. }
  701. /* ----------------------------------------------------------------------
  702. * Sanitise terminal output that we have reason not to trust, e.g.
  703. * because it appears in the login banner or password prompt from a
  704. * server, which we'd rather not permit to use arbitrary escape
  705. * sequences.
  706. */
  707. void sanitise_term_data(bufchain *out, const void *vdata, int len)
  708. {
  709. const char *data = (const char *)vdata;
  710. int i;
  711. /*
  712. * FIXME: this method of sanitisation is ASCII-centric. It would
  713. * be nice to permit SSH banners and the like to contain printable
  714. * Unicode, but that would need a lot more complicated code here
  715. * (not to mention knowing what character set it should interpret
  716. * the data as).
  717. */
  718. for (i = 0; i < len; i++) {
  719. if (data[i] == '\n')
  720. bufchain_add(out, "\r\n", 2);
  721. else if (data[i] >= ' ' && data[i] < 0x7F)
  722. bufchain_add(out, data + i, 1);
  723. }
  724. }
  725. /* ----------------------------------------------------------------------
  726. * Debugging routines.
  727. */
  728. #ifdef DEBUG
  729. extern void dputs(const char *); /* defined in per-platform *misc.c */
  730. void debug_printf(const char *fmt, ...)
  731. {
  732. char *buf;
  733. va_list ap;
  734. va_start(ap, fmt);
  735. buf = dupvprintf(fmt, ap);
  736. dputs(buf);
  737. sfree(buf);
  738. va_end(ap);
  739. }
  740. void debug_memdump(const void *buf, int len, bool L)
  741. {
  742. int i;
  743. const unsigned char *p = buf;
  744. char foo[17];
  745. if (L) {
  746. int delta;
  747. debug_printf("\t%d (0x%x) bytes:\n", len, len);
  748. delta = 15 & (uintptr_t)p;
  749. p -= delta;
  750. len += delta;
  751. }
  752. for (; 0 < len; p += 16, len -= 16) {
  753. dputs(" ");
  754. if (L)
  755. debug_printf("%p: ", p);
  756. strcpy(foo, "................"); /* sixteen dots */
  757. for (i = 0; i < 16 && i < len; ++i) {
  758. if (&p[i] < (unsigned char *) buf) {
  759. dputs(" "); /* 3 spaces */
  760. foo[i] = ' ';
  761. } else {
  762. debug_printf("%c%02.2x",
  763. &p[i] != (unsigned char *) buf
  764. && i % 4 ? '.' : ' ', p[i]
  765. );
  766. if (p[i] >= ' ' && p[i] <= '~')
  767. foo[i] = (char) p[i];
  768. }
  769. }
  770. foo[i] = '\0';
  771. debug_printf("%*s%s\n", (16 - i) * 3 + 2, "", foo);
  772. }
  773. }
  774. #endif /* def DEBUG */
  775. #ifndef PLATFORM_HAS_SMEMCLR
  776. /*
  777. * Securely wipe memory.
  778. *
  779. * The actual wiping is no different from what memset would do: the
  780. * point of 'securely' is to try to be sure over-clever compilers
  781. * won't optimise away memsets on variables that are about to be freed
  782. * or go out of scope. See
  783. * https://buildsecurityin.us-cert.gov/bsi-rules/home/g1/771-BSI.html
  784. *
  785. * Some platforms (e.g. Windows) may provide their own version of this
  786. * function.
  787. */
  788. void smemclr(void *b, size_t n) {
  789. volatile char *vp;
  790. if (b && n > 0) {
  791. /*
  792. * Zero out the memory.
  793. */
  794. memset(b, 0, n);
  795. /*
  796. * Perform a volatile access to the object, forcing the
  797. * compiler to admit that the previous memset was important.
  798. *
  799. * This while loop should in practice run for zero iterations
  800. * (since we know we just zeroed the object out), but in
  801. * theory (as far as the compiler knows) it might range over
  802. * the whole object. (If we had just written, say, '*vp =
  803. * *vp;', a compiler could in principle have 'helpfully'
  804. * optimised the memset into only zeroing out the first byte.
  805. * This should be robust.)
  806. */
  807. vp = b;
  808. while (*vp) vp++;
  809. }
  810. }
  811. #endif
  812. bool smemeq(const void *av, const void *bv, size_t len)
  813. {
  814. const unsigned char *a = (const unsigned char *)av;
  815. const unsigned char *b = (const unsigned char *)bv;
  816. unsigned val = 0;
  817. while (len-- > 0) {
  818. val |= *a++ ^ *b++;
  819. }
  820. /* Now val is 0 iff we want to return 1, and in the range
  821. * 0x01..0xFF iff we want to return 0. So subtracting from 0x100
  822. * will clear bit 8 iff we want to return 0, and leave it set iff
  823. * we want to return 1, so then we can just shift down. */
  824. return (0x100 - val) >> 8;
  825. }
  826. int nullstrcmp(const char *a, const char *b)
  827. {
  828. if (a == NULL && b == NULL)
  829. return 0;
  830. if (a == NULL)
  831. return -1;
  832. if (b == NULL)
  833. return +1;
  834. return strcmp(a, b);
  835. }
  836. bool ptrlen_eq_string(ptrlen pl, const char *str)
  837. {
  838. size_t len = strlen(str);
  839. return (pl.len == len && !memcmp(pl.ptr, str, len));
  840. }
  841. bool ptrlen_eq_ptrlen(ptrlen pl1, ptrlen pl2)
  842. {
  843. return (pl1.len == pl2.len && !memcmp(pl1.ptr, pl2.ptr, pl1.len));
  844. }
  845. bool ptrlen_startswith(ptrlen whole, ptrlen prefix, ptrlen *tail)
  846. {
  847. if (whole.len >= prefix.len &&
  848. !memcmp(whole.ptr, prefix.ptr, prefix.len)) {
  849. if (tail) {
  850. tail->ptr = (const char *)whole.ptr + prefix.len;
  851. tail->len = whole.len - prefix.len;
  852. }
  853. return true;
  854. }
  855. return false;
  856. }
  857. char *mkstr(ptrlen pl)
  858. {
  859. char *p = snewn(pl.len + 1, char);
  860. memcpy(p, pl.ptr, pl.len);
  861. p[pl.len] = '\0';
  862. return p;
  863. }
  864. bool strstartswith(const char *s, const char *t)
  865. {
  866. return !memcmp(s, t, strlen(t));
  867. }
  868. bool strendswith(const char *s, const char *t)
  869. {
  870. size_t slen = strlen(s), tlen = strlen(t);
  871. return slen >= tlen && !strcmp(s + (slen - tlen), t);
  872. }