utils.c 27 KB

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