utils.c 32 KB

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