utils.c 32 KB

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