misc.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248
  1. /*
  2. * Platform-independent routines shared between all PuTTY programs.
  3. */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <stdarg.h>
  7. #include <limits.h>
  8. #include <ctype.h>
  9. #include <assert.h>
  10. #include "putty.h"
  11. #include "misc.h"
  12. /*
  13. * Parse a string block size specification. This is approximately a
  14. * subset of the block size specs supported by GNU fileutils:
  15. * "nk" = n kilobytes
  16. * "nM" = n megabytes
  17. * "nG" = n gigabytes
  18. * All numbers are decimal, and suffixes refer to powers of two.
  19. * Case-insensitive.
  20. */
  21. unsigned long parse_blocksize(const char *bs)
  22. {
  23. char *suf;
  24. unsigned long r = strtoul(bs, &suf, 10);
  25. if (*suf != '\0') {
  26. while (*suf && isspace((unsigned char)*suf)) suf++;
  27. switch (*suf) {
  28. case 'k': case 'K':
  29. r *= 1024ul;
  30. break;
  31. case 'm': case 'M':
  32. r *= 1024ul * 1024ul;
  33. break;
  34. case 'g': case 'G':
  35. r *= 1024ul * 1024ul * 1024ul;
  36. break;
  37. case '\0':
  38. default:
  39. break;
  40. }
  41. }
  42. return r;
  43. }
  44. /*
  45. * Parse a ^C style character specification.
  46. * Returns NULL in `next' if we didn't recognise it as a control character,
  47. * in which case `c' should be ignored.
  48. * The precise current parsing is an oddity inherited from the terminal
  49. * answerback-string parsing code. All sequences start with ^; all except
  50. * ^<123> are two characters. The ones that are worth keeping are probably:
  51. * ^? 127
  52. * ^@A-Z[\]^_ 0-31
  53. * a-z 1-26
  54. * <num> specified by number (decimal, 0octal, 0xHEX)
  55. * ~ ^ escape
  56. */
  57. char ctrlparse(char *s, char **next)
  58. {
  59. char c = 0;
  60. if (*s != '^') {
  61. *next = NULL;
  62. } else {
  63. s++;
  64. if (*s == '\0') {
  65. *next = NULL;
  66. } else if (*s == '<') {
  67. s++;
  68. c = (char)strtol(s, next, 0);
  69. if ((*next == s) || (**next != '>')) {
  70. c = 0;
  71. *next = NULL;
  72. } else
  73. (*next)++;
  74. } else if (*s >= 'a' && *s <= 'z') {
  75. c = (*s - ('a' - 1));
  76. *next = s+1;
  77. } else if ((*s >= '@' && *s <= '_') || *s == '?' || (*s & 0x80)) {
  78. c = ('@' ^ *s);
  79. *next = s+1;
  80. } else if (*s == '~') {
  81. c = '^';
  82. *next = s+1;
  83. }
  84. }
  85. return c;
  86. }
  87. /*
  88. * Find a character in a string, unless it's a colon contained within
  89. * square brackets. Used for untangling strings of the form
  90. * 'host:port', where host can be an IPv6 literal.
  91. *
  92. * We provide several variants of this function, with semantics like
  93. * various standard string.h functions.
  94. */
  95. static const char *host_strchr_internal(const char *s, const char *set,
  96. int first)
  97. {
  98. int brackets = 0;
  99. const char *ret = NULL;
  100. while (1) {
  101. if (!*s)
  102. return ret;
  103. if (*s == '[')
  104. brackets++;
  105. else if (*s == ']' && brackets > 0)
  106. brackets--;
  107. else if (brackets && *s == ':')
  108. /* never match */ ;
  109. else if (strchr(set, *s)) {
  110. ret = s;
  111. if (first)
  112. return ret;
  113. }
  114. s++;
  115. }
  116. }
  117. size_t host_strcspn(const char *s, const char *set)
  118. {
  119. const char *answer = host_strchr_internal(s, set, TRUE);
  120. if (answer)
  121. return answer - s;
  122. else
  123. return strlen(s);
  124. }
  125. char *host_strchr(const char *s, int c)
  126. {
  127. char set[2];
  128. set[0] = c;
  129. set[1] = '\0';
  130. return (char *) host_strchr_internal(s, set, TRUE);
  131. }
  132. char *host_strrchr(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, FALSE);
  138. }
  139. #ifdef TEST_HOST_STRFOO
  140. int main(void)
  141. {
  142. int passes = 0, fails = 0;
  143. #define TEST1(func, string, arg2, suffix, result) do \
  144. { \
  145. const char *str = string; \
  146. unsigned ret = func(string, arg2) suffix; \
  147. if (ret == result) { \
  148. passes++; \
  149. } else { \
  150. printf("fail: %s(%s,%s)%s = %u, expected %u\n", \
  151. #func, #string, #arg2, #suffix, ret, \
  152. (unsigned)result); \
  153. fails++; \
  154. } \
  155. } while (0)
  156. TEST1(host_strchr, "[1:2:3]:4:5", ':', -str, 7);
  157. TEST1(host_strrchr, "[1:2:3]:4:5", ':', -str, 9);
  158. TEST1(host_strcspn, "[1:2:3]:4:5", "/:",, 7);
  159. TEST1(host_strchr, "[1:2:3]", ':', == NULL, 1);
  160. TEST1(host_strrchr, "[1:2:3]", ':', == NULL, 1);
  161. TEST1(host_strcspn, "[1:2:3]", "/:",, 7);
  162. TEST1(host_strcspn, "[1:2/3]", "/:",, 4);
  163. TEST1(host_strcspn, "[1:2:3]/", "/:",, 7);
  164. printf("passed %d failed %d total %d\n", passes, fails, passes+fails);
  165. return fails != 0 ? 1 : 0;
  166. }
  167. /* Stubs to stop the rest of this module causing compile failures. */
  168. void modalfatalbox(const char *fmt, ...) {}
  169. int conf_get_int(Conf *conf, int primary) { return 0; }
  170. char *conf_get_str(Conf *conf, int primary) { return NULL; }
  171. #endif /* TEST_HOST_STRFOO */
  172. /*
  173. * Trim square brackets off the outside of an IPv6 address literal.
  174. * Leave all other strings unchanged. Returns a fresh dynamically
  175. * allocated string.
  176. */
  177. char *host_strduptrim(const char *s)
  178. {
  179. if (s[0] == '[') {
  180. const char *p = s+1;
  181. int colons = 0;
  182. while (*p && *p != ']') {
  183. if (isxdigit((unsigned char)*p))
  184. /* OK */;
  185. else if (*p == ':')
  186. colons++;
  187. else
  188. break;
  189. p++;
  190. }
  191. if (*p == ']' && !p[1] && colons > 1) {
  192. /*
  193. * This looks like an IPv6 address literal (hex digits and
  194. * at least two colons, contained in square brackets).
  195. * Trim off the brackets.
  196. */
  197. return dupprintf("%.*s", (int)(p - (s+1)), s+1);
  198. }
  199. }
  200. /*
  201. * Any other shape of string is simply duplicated.
  202. */
  203. return dupstr(s);
  204. }
  205. prompts_t *new_prompts(void *frontend)
  206. {
  207. prompts_t *p = snew(prompts_t);
  208. p->prompts = NULL;
  209. p->n_prompts = 0;
  210. p->frontend = frontend;
  211. p->data = NULL;
  212. p->to_server = TRUE; /* to be on the safe side */
  213. p->name = p->instruction = NULL;
  214. p->name_reqd = p->instr_reqd = FALSE;
  215. return p;
  216. }
  217. void add_prompt(prompts_t *p, char *promptstr, int echo)
  218. {
  219. prompt_t *pr = snew(prompt_t);
  220. pr->prompt = promptstr;
  221. pr->echo = echo;
  222. pr->result = NULL;
  223. pr->resultsize = 0;
  224. p->n_prompts++;
  225. p->prompts = sresize(p->prompts, p->n_prompts, prompt_t *);
  226. p->prompts[p->n_prompts-1] = pr;
  227. }
  228. void prompt_ensure_result_size(prompt_t *pr, int newlen)
  229. {
  230. if ((int)pr->resultsize < newlen) {
  231. char *newbuf;
  232. newlen = newlen * 5 / 4 + 512; /* avoid too many small allocs */
  233. /*
  234. * We don't use sresize / realloc here, because we will be
  235. * storing sensitive stuff like passwords in here, and we want
  236. * to make sure that the data doesn't get copied around in
  237. * memory without the old copy being destroyed.
  238. */
  239. newbuf = snewn(newlen, char);
  240. memcpy(newbuf, pr->result, pr->resultsize);
  241. smemclr(pr->result, pr->resultsize);
  242. sfree(pr->result);
  243. pr->result = newbuf;
  244. pr->resultsize = newlen;
  245. }
  246. }
  247. void prompt_set_result(prompt_t *pr, const char *newstr)
  248. {
  249. prompt_ensure_result_size(pr, strlen(newstr) + 1);
  250. strcpy(pr->result, newstr);
  251. }
  252. void free_prompts(prompts_t *p)
  253. {
  254. size_t i;
  255. for (i=0; i < p->n_prompts; i++) {
  256. prompt_t *pr = p->prompts[i];
  257. smemclr(pr->result, pr->resultsize); /* burn the evidence */
  258. sfree(pr->result);
  259. sfree(pr->prompt);
  260. sfree(pr);
  261. }
  262. sfree(p->prompts);
  263. sfree(p->name);
  264. sfree(p->instruction);
  265. sfree(p);
  266. }
  267. /* ----------------------------------------------------------------------
  268. * String handling routines.
  269. */
  270. char *dupstr(const char *s)
  271. {
  272. char *p = NULL;
  273. if (s) {
  274. int len = strlen(s);
  275. p = snewn(len + 1, char);
  276. strcpy(p, s);
  277. }
  278. return p;
  279. }
  280. /* Allocate the concatenation of N strings. Terminate arg list with NULL. */
  281. char *dupcat(const char *s1, ...)
  282. {
  283. int len;
  284. char *p, *q, *sn;
  285. va_list ap;
  286. len = strlen(s1);
  287. va_start(ap, s1);
  288. while (1) {
  289. sn = va_arg(ap, char *);
  290. if (!sn)
  291. break;
  292. len += strlen(sn);
  293. }
  294. va_end(ap);
  295. p = snewn(len + 1, char);
  296. strcpy(p, s1);
  297. q = p + strlen(p);
  298. va_start(ap, s1);
  299. while (1) {
  300. sn = va_arg(ap, char *);
  301. if (!sn)
  302. break;
  303. strcpy(q, sn);
  304. q += strlen(q);
  305. }
  306. va_end(ap);
  307. return p;
  308. }
  309. void burnstr(char *string) /* sfree(str), only clear it first */
  310. {
  311. if (string) {
  312. smemclr(string, strlen(string));
  313. sfree(string);
  314. }
  315. }
  316. int toint(unsigned u)
  317. {
  318. /*
  319. * Convert an unsigned to an int, without running into the
  320. * undefined behaviour which happens by the strict C standard if
  321. * the value overflows. You'd hope that sensible compilers would
  322. * do the sensible thing in response to a cast, but actually I
  323. * don't trust modern compilers not to do silly things like
  324. * assuming that _obviously_ you wouldn't have caused an overflow
  325. * and so they can elide an 'if (i < 0)' test immediately after
  326. * the cast.
  327. *
  328. * Sensible compilers ought of course to optimise this entire
  329. * function into 'just return the input value'!
  330. */
  331. if (u <= (unsigned)INT_MAX)
  332. return (int)u;
  333. else if (u >= (unsigned)INT_MIN) /* wrap in cast _to_ unsigned is OK */
  334. return INT_MIN + (int)(u - (unsigned)INT_MIN);
  335. else
  336. return INT_MIN; /* fallback; should never occur on binary machines */
  337. }
  338. /*
  339. * Do an sprintf(), but into a custom-allocated buffer.
  340. *
  341. * Currently I'm doing this via vsnprintf. This has worked so far,
  342. * but it's not good, because vsnprintf is not available on all
  343. * platforms. There's an ifdef to use `_vsnprintf', which seems
  344. * to be the local name for it on Windows. Other platforms may
  345. * lack it completely, in which case it'll be time to rewrite
  346. * this function in a totally different way.
  347. *
  348. * The only `properly' portable solution I can think of is to
  349. * implement my own format string scanner, which figures out an
  350. * upper bound for the length of each formatting directive,
  351. * allocates the buffer as it goes along, and calls sprintf() to
  352. * actually process each directive. If I ever need to actually do
  353. * this, some caveats:
  354. *
  355. * - It's very hard to find a reliable upper bound for
  356. * floating-point values. %f, in particular, when supplied with
  357. * a number near to the upper or lower limit of representable
  358. * numbers, could easily take several hundred characters. It's
  359. * probably feasible to predict this statically using the
  360. * constants in <float.h>, or even to predict it dynamically by
  361. * looking at the exponent of the specific float provided, but
  362. * it won't be fun.
  363. *
  364. * - Don't forget to _check_, after calling sprintf, that it's
  365. * used at most the amount of space we had available.
  366. *
  367. * - Fault any formatting directive we don't fully understand. The
  368. * aim here is to _guarantee_ that we never overflow the buffer,
  369. * because this is a security-critical function. If we see a
  370. * directive we don't know about, we should panic and die rather
  371. * than run any risk.
  372. */
  373. static char *dupvprintf_inner(char *buf, int oldlen, int *oldsize,
  374. const char *fmt, va_list ap)
  375. {
  376. int len, size, newsize;
  377. assert(*oldsize >= oldlen);
  378. size = *oldsize - oldlen;
  379. if (size == 0) {
  380. size = 512;
  381. newsize = oldlen + size;
  382. buf = sresize(buf, newsize, char);
  383. } else {
  384. newsize = *oldsize;
  385. }
  386. while (1) {
  387. #if defined _WINDOWS && !defined __WINE__ && _MSC_VER < 1900 /* 1900 == VS2015 has real snprintf */
  388. #define vsnprintf _vsnprintf
  389. #endif
  390. #ifdef va_copy
  391. /* Use the `va_copy' macro mandated by C99, if present.
  392. * XXX some environments may have this as __va_copy() */
  393. va_list aq;
  394. va_copy(aq, ap);
  395. len = vsnprintf(buf + oldlen, size, fmt, aq);
  396. va_end(aq);
  397. #else
  398. /* Ugh. No va_copy macro, so do something nasty.
  399. * Technically, you can't reuse a va_list like this: it is left
  400. * unspecified whether advancing a va_list pointer modifies its
  401. * value or something it points to, so on some platforms calling
  402. * vsnprintf twice on the same va_list might fail hideously
  403. * (indeed, it has been observed to).
  404. * XXX the autoconf manual suggests that using memcpy() will give
  405. * "maximum portability". */
  406. len = vsnprintf(buf + oldlen, size, fmt, ap);
  407. #endif
  408. if (len >= 0 && len < size) {
  409. /* This is the C99-specified criterion for snprintf to have
  410. * been completely successful. */
  411. *oldsize = newsize;
  412. return buf;
  413. } else if (len > 0) {
  414. /* This is the C99 error condition: the returned length is
  415. * the required buffer size not counting the NUL. */
  416. size = len + 1;
  417. } else {
  418. /* This is the pre-C99 glibc error condition: <0 means the
  419. * buffer wasn't big enough, so we enlarge it a bit and hope. */
  420. size += 512;
  421. }
  422. newsize = oldlen + size;
  423. buf = sresize(buf, newsize, char);
  424. }
  425. }
  426. char *dupvprintf(const char *fmt, va_list ap)
  427. {
  428. int size = 0;
  429. return dupvprintf_inner(NULL, 0, &size, fmt, ap);
  430. }
  431. char *dupprintf(const char *fmt, ...)
  432. {
  433. char *ret;
  434. va_list ap;
  435. va_start(ap, fmt);
  436. ret = dupvprintf(fmt, ap);
  437. va_end(ap);
  438. return ret;
  439. }
  440. struct strbuf {
  441. char *s;
  442. int len, size;
  443. };
  444. strbuf *strbuf_new(void)
  445. {
  446. strbuf *buf = snew(strbuf);
  447. buf->len = 0;
  448. buf->size = 512;
  449. buf->s = snewn(buf->size, char);
  450. *buf->s = '\0';
  451. return buf;
  452. }
  453. void strbuf_free(strbuf *buf)
  454. {
  455. sfree(buf->s);
  456. sfree(buf);
  457. }
  458. char *strbuf_str(strbuf *buf)
  459. {
  460. return buf->s;
  461. }
  462. char *strbuf_to_str(strbuf *buf)
  463. {
  464. char *ret = buf->s;
  465. sfree(buf);
  466. return ret;
  467. }
  468. void strbuf_catfv(strbuf *buf, const char *fmt, va_list ap)
  469. {
  470. buf->s = dupvprintf_inner(buf->s, buf->len, &buf->size, fmt, ap);
  471. buf->len += strlen(buf->s + buf->len);
  472. }
  473. void strbuf_catf(strbuf *buf, const char *fmt, ...)
  474. {
  475. va_list ap;
  476. va_start(ap, fmt);
  477. strbuf_catfv(buf, fmt, ap);
  478. va_end(ap);
  479. }
  480. /*
  481. * Read an entire line of text from a file. Return a buffer
  482. * malloced to be as big as necessary (caller must free).
  483. */
  484. char *fgetline(FILE *fp)
  485. {
  486. char *ret = snewn(512, char);
  487. int size = 512, len = 0;
  488. while (fgets(ret + len, size - len, fp)) {
  489. len += strlen(ret + len);
  490. if (len > 0 && ret[len-1] == '\n')
  491. break; /* got a newline, we're done */
  492. size = len + 512;
  493. ret = sresize(ret, size, char);
  494. }
  495. if (len == 0) { /* first fgets returned NULL */
  496. sfree(ret);
  497. return NULL;
  498. }
  499. ret[len] = '\0';
  500. return ret;
  501. }
  502. /*
  503. * Perl-style 'chomp', for a line we just read with fgetline. Unlike
  504. * Perl chomp, however, we're deliberately forgiving of strange
  505. * line-ending conventions. Also we forgive NULL on input, so you can
  506. * just write 'line = chomp(fgetline(fp));' and not bother checking
  507. * for NULL until afterwards.
  508. */
  509. char *chomp(char *str)
  510. {
  511. if (str) {
  512. int len = strlen(str);
  513. while (len > 0 && (str[len-1] == '\r' || str[len-1] == '\n'))
  514. len--;
  515. str[len] = '\0';
  516. }
  517. return str;
  518. }
  519. /* ----------------------------------------------------------------------
  520. * Core base64 encoding and decoding routines.
  521. */
  522. void base64_encode_atom(const unsigned char *data, int n, char *out)
  523. {
  524. static const char base64_chars[] =
  525. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  526. unsigned word;
  527. word = data[0] << 16;
  528. if (n > 1)
  529. word |= data[1] << 8;
  530. if (n > 2)
  531. word |= data[2];
  532. out[0] = base64_chars[(word >> 18) & 0x3F];
  533. out[1] = base64_chars[(word >> 12) & 0x3F];
  534. if (n > 1)
  535. out[2] = base64_chars[(word >> 6) & 0x3F];
  536. else
  537. out[2] = '=';
  538. if (n > 2)
  539. out[3] = base64_chars[word & 0x3F];
  540. else
  541. out[3] = '=';
  542. }
  543. int base64_decode_atom(const char *atom, unsigned char *out)
  544. {
  545. int vals[4];
  546. int i, v, len;
  547. unsigned word;
  548. char c;
  549. for (i = 0; i < 4; i++) {
  550. c = atom[i];
  551. if (c >= 'A' && c <= 'Z')
  552. v = c - 'A';
  553. else if (c >= 'a' && c <= 'z')
  554. v = c - 'a' + 26;
  555. else if (c >= '0' && c <= '9')
  556. v = c - '0' + 52;
  557. else if (c == '+')
  558. v = 62;
  559. else if (c == '/')
  560. v = 63;
  561. else if (c == '=')
  562. v = -1;
  563. else
  564. return 0; /* invalid atom */
  565. vals[i] = v;
  566. }
  567. if (vals[0] == -1 || vals[1] == -1)
  568. return 0;
  569. if (vals[2] == -1 && vals[3] != -1)
  570. return 0;
  571. if (vals[3] != -1)
  572. len = 3;
  573. else if (vals[2] != -1)
  574. len = 2;
  575. else
  576. len = 1;
  577. word = ((vals[0] << 18) |
  578. (vals[1] << 12) | ((vals[2] & 0x3F) << 6) | (vals[3] & 0x3F));
  579. out[0] = (word >> 16) & 0xFF;
  580. if (len > 1)
  581. out[1] = (word >> 8) & 0xFF;
  582. if (len > 2)
  583. out[2] = word & 0xFF;
  584. return len;
  585. }
  586. /* ----------------------------------------------------------------------
  587. * Generic routines to deal with send buffers: a linked list of
  588. * smallish blocks, with the operations
  589. *
  590. * - add an arbitrary amount of data to the end of the list
  591. * - remove the first N bytes from the list
  592. * - return a (pointer,length) pair giving some initial data in
  593. * the list, suitable for passing to a send or write system
  594. * call
  595. * - retrieve a larger amount of initial data from the list
  596. * - return the current size of the buffer chain in bytes
  597. */
  598. #define BUFFER_MIN_GRANULE 512
  599. struct bufchain_granule {
  600. struct bufchain_granule *next;
  601. char *bufpos, *bufend, *bufmax;
  602. };
  603. void bufchain_init(bufchain *ch)
  604. {
  605. ch->head = ch->tail = NULL;
  606. ch->buffersize = 0;
  607. }
  608. void bufchain_clear(bufchain *ch)
  609. {
  610. struct bufchain_granule *b;
  611. while (ch->head) {
  612. b = ch->head;
  613. ch->head = ch->head->next;
  614. sfree(b);
  615. }
  616. ch->tail = NULL;
  617. ch->buffersize = 0;
  618. }
  619. int bufchain_size(bufchain *ch)
  620. {
  621. return ch->buffersize;
  622. }
  623. void bufchain_add(bufchain *ch, const void *data, int len)
  624. {
  625. const char *buf = (const char *)data;
  626. if (len == 0) return;
  627. ch->buffersize += len;
  628. while (len > 0) {
  629. if (ch->tail && ch->tail->bufend < ch->tail->bufmax) {
  630. int copylen = min(len, ch->tail->bufmax - ch->tail->bufend);
  631. memcpy(ch->tail->bufend, buf, copylen);
  632. buf += copylen;
  633. len -= copylen;
  634. ch->tail->bufend += copylen;
  635. }
  636. if (len > 0) {
  637. int grainlen =
  638. max(sizeof(struct bufchain_granule) + len, BUFFER_MIN_GRANULE);
  639. struct bufchain_granule *newbuf;
  640. newbuf = smalloc(grainlen);
  641. newbuf->bufpos = newbuf->bufend =
  642. (char *)newbuf + sizeof(struct bufchain_granule);
  643. newbuf->bufmax = (char *)newbuf + grainlen;
  644. newbuf->next = NULL;
  645. if (ch->tail)
  646. ch->tail->next = newbuf;
  647. else
  648. ch->head = newbuf;
  649. ch->tail = newbuf;
  650. }
  651. }
  652. }
  653. void bufchain_consume(bufchain *ch, int len)
  654. {
  655. struct bufchain_granule *tmp;
  656. assert(ch->buffersize >= len);
  657. while (len > 0) {
  658. int remlen = len;
  659. assert(ch->head != NULL);
  660. if (remlen >= ch->head->bufend - ch->head->bufpos) {
  661. remlen = ch->head->bufend - ch->head->bufpos;
  662. tmp = ch->head;
  663. ch->head = tmp->next;
  664. if (!ch->head)
  665. ch->tail = NULL;
  666. sfree(tmp);
  667. } else
  668. ch->head->bufpos += remlen;
  669. ch->buffersize -= remlen;
  670. len -= remlen;
  671. }
  672. }
  673. void bufchain_prefix(bufchain *ch, void **data, int *len)
  674. {
  675. *len = ch->head->bufend - ch->head->bufpos;
  676. *data = ch->head->bufpos;
  677. }
  678. void bufchain_fetch(bufchain *ch, void *data, int len)
  679. {
  680. struct bufchain_granule *tmp;
  681. char *data_c = (char *)data;
  682. tmp = ch->head;
  683. assert(ch->buffersize >= len);
  684. while (len > 0) {
  685. int remlen = len;
  686. assert(tmp != NULL);
  687. if (remlen >= tmp->bufend - tmp->bufpos)
  688. remlen = tmp->bufend - tmp->bufpos;
  689. memcpy(data_c, tmp->bufpos, remlen);
  690. tmp = tmp->next;
  691. len -= remlen;
  692. data_c += remlen;
  693. }
  694. }
  695. /* ----------------------------------------------------------------------
  696. * My own versions of malloc, realloc and free. Because I want
  697. * malloc and realloc to bomb out and exit the program if they run
  698. * out of memory, realloc to reliably call malloc if passed a NULL
  699. * pointer, and free to reliably do nothing if passed a NULL
  700. * pointer. We can also put trace printouts in, if we need to; and
  701. * we can also replace the allocator with an ElectricFence-like
  702. * one.
  703. */
  704. #ifdef MINEFIELD
  705. void *minefield_c_malloc(size_t size);
  706. void minefield_c_free(void *p);
  707. void *minefield_c_realloc(void *p, size_t size);
  708. #endif
  709. #ifdef MALLOC_LOG
  710. static FILE *fp = NULL;
  711. static char *mlog_file = NULL;
  712. static int mlog_line = 0;
  713. void mlog(char *file, int line)
  714. {
  715. mlog_file = file;
  716. mlog_line = line;
  717. if (!fp) {
  718. fp = fopen("putty_mem.log", "w");
  719. setvbuf(fp, NULL, _IONBF, BUFSIZ);
  720. }
  721. if (fp)
  722. fprintf(fp, "%s:%d: ", file, line);
  723. }
  724. #endif
  725. void *safemalloc(size_t n, size_t size)
  726. {
  727. void *p;
  728. if (n > INT_MAX / size) {
  729. p = NULL;
  730. } else {
  731. size *= n;
  732. if (size == 0) size = 1;
  733. #ifdef MINEFIELD
  734. p = minefield_c_malloc(size);
  735. #else
  736. p = malloc(size);
  737. #endif
  738. }
  739. if (!p) {
  740. char str[200];
  741. #ifdef MALLOC_LOG
  742. sprintf(str, "Out of memory! (%s:%d, size=%d)",
  743. mlog_file, mlog_line, size);
  744. fprintf(fp, "*** %s\n", str);
  745. fclose(fp);
  746. #else
  747. strcpy(str, "Out of memory!");
  748. #endif
  749. modalfatalbox("%s", str);
  750. }
  751. #ifdef MALLOC_LOG
  752. if (fp)
  753. fprintf(fp, "malloc(%d) returns %p\n", size, p);
  754. #endif
  755. return p;
  756. }
  757. void *saferealloc(void *ptr, size_t n, size_t size)
  758. {
  759. void *p;
  760. if (n > INT_MAX / size) {
  761. p = NULL;
  762. } else {
  763. size *= n;
  764. if (!ptr) {
  765. #ifdef MINEFIELD
  766. p = minefield_c_malloc(size);
  767. #else
  768. p = malloc(size);
  769. #endif
  770. } else {
  771. #ifdef MINEFIELD
  772. p = minefield_c_realloc(ptr, size);
  773. #else
  774. p = realloc(ptr, size);
  775. #endif
  776. }
  777. }
  778. if (!p) {
  779. char str[200];
  780. #ifdef MALLOC_LOG
  781. sprintf(str, "Out of memory! (%s:%d, size=%d)",
  782. mlog_file, mlog_line, size);
  783. fprintf(fp, "*** %s\n", str);
  784. fclose(fp);
  785. #else
  786. strcpy(str, "Out of memory!");
  787. #endif
  788. modalfatalbox("%s", str);
  789. }
  790. #ifdef MALLOC_LOG
  791. if (fp)
  792. fprintf(fp, "realloc(%p,%d) returns %p\n", ptr, size, p);
  793. #endif
  794. return p;
  795. }
  796. void safefree(void *ptr)
  797. {
  798. if (ptr) {
  799. #ifdef MALLOC_LOG
  800. if (fp)
  801. fprintf(fp, "free(%p)\n", ptr);
  802. #endif
  803. #ifdef MINEFIELD
  804. minefield_c_free(ptr);
  805. #else
  806. free(ptr);
  807. #endif
  808. }
  809. #ifdef MALLOC_LOG
  810. else if (fp)
  811. fprintf(fp, "freeing null pointer - no action taken\n");
  812. #endif
  813. }
  814. /* ----------------------------------------------------------------------
  815. * Debugging routines.
  816. */
  817. #ifdef DEBUG
  818. extern void dputs(const char *); /* defined in per-platform *misc.c */
  819. void debug_printf(const char *fmt, ...)
  820. {
  821. char *buf;
  822. va_list ap;
  823. va_start(ap, fmt);
  824. buf = dupvprintf(fmt, ap);
  825. dputs(buf);
  826. sfree(buf);
  827. va_end(ap);
  828. }
  829. void debug_memdump(const void *buf, int len, int L)
  830. {
  831. int i;
  832. const unsigned char *p = buf;
  833. char foo[17];
  834. if (L) {
  835. int delta;
  836. debug_printf("\t%d (0x%x) bytes:\n", len, len);
  837. delta = 15 & (uintptr_t)p;
  838. p -= delta;
  839. len += delta;
  840. }
  841. for (; 0 < len; p += 16, len -= 16) {
  842. dputs(" ");
  843. if (L)
  844. debug_printf("%p: ", p);
  845. strcpy(foo, "................"); /* sixteen dots */
  846. for (i = 0; i < 16 && i < len; ++i) {
  847. if (&p[i] < (unsigned char *) buf) {
  848. dputs(" "); /* 3 spaces */
  849. foo[i] = ' ';
  850. } else {
  851. debug_printf("%c%02.2x",
  852. &p[i] != (unsigned char *) buf
  853. && i % 4 ? '.' : ' ', p[i]
  854. );
  855. if (p[i] >= ' ' && p[i] <= '~')
  856. foo[i] = (char) p[i];
  857. }
  858. }
  859. foo[i] = '\0';
  860. debug_printf("%*s%s\n", (16 - i) * 3 + 2, "", foo);
  861. }
  862. }
  863. #endif /* def DEBUG */
  864. /*
  865. * Determine whether or not a Conf represents a session which can
  866. * sensibly be launched right now.
  867. */
  868. int conf_launchable(Conf *conf)
  869. {
  870. if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL)
  871. return conf_get_str(conf, CONF_serline)[0] != 0;
  872. else
  873. return conf_get_str(conf, CONF_host)[0] != 0;
  874. }
  875. char const *conf_dest(Conf *conf)
  876. {
  877. if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL)
  878. return conf_get_str(conf, CONF_serline);
  879. else
  880. return conf_get_str(conf, CONF_host);
  881. }
  882. #ifndef PLATFORM_HAS_SMEMCLR
  883. /*
  884. * Securely wipe memory.
  885. *
  886. * The actual wiping is no different from what memset would do: the
  887. * point of 'securely' is to try to be sure over-clever compilers
  888. * won't optimise away memsets on variables that are about to be freed
  889. * or go out of scope. See
  890. * https://buildsecurityin.us-cert.gov/bsi-rules/home/g1/771-BSI.html
  891. *
  892. * Some platforms (e.g. Windows) may provide their own version of this
  893. * function.
  894. */
  895. void smemclr(void *b, size_t n) {
  896. volatile char *vp;
  897. if (b && n > 0) {
  898. /*
  899. * Zero out the memory.
  900. */
  901. memset(b, 0, n);
  902. /*
  903. * Perform a volatile access to the object, forcing the
  904. * compiler to admit that the previous memset was important.
  905. *
  906. * This while loop should in practice run for zero iterations
  907. * (since we know we just zeroed the object out), but in
  908. * theory (as far as the compiler knows) it might range over
  909. * the whole object. (If we had just written, say, '*vp =
  910. * *vp;', a compiler could in principle have 'helpfully'
  911. * optimised the memset into only zeroing out the first byte.
  912. * This should be robust.)
  913. */
  914. vp = b;
  915. while (*vp) vp++;
  916. }
  917. }
  918. #endif
  919. /*
  920. * Validate a manual host key specification (either entered in the
  921. * GUI, or via -hostkey). If valid, we return TRUE, and update 'key'
  922. * to contain a canonicalised version of the key string in 'key'
  923. * (which is guaranteed to take up at most as much space as the
  924. * original version), suitable for putting into the Conf. If not
  925. * valid, we return FALSE.
  926. */
  927. int validate_manual_hostkey(char *key)
  928. {
  929. char *p, *q, *r, *s;
  930. /*
  931. * Step through the string word by word, looking for a word that's
  932. * in one of the formats we like.
  933. */
  934. p = key;
  935. while ((p += strspn(p, " \t"))[0]) {
  936. q = p;
  937. p += strcspn(p, " \t");
  938. if (*p) *p++ = '\0';
  939. /*
  940. * Now q is our word.
  941. */
  942. if (strlen(q) == 16*3 - 1 &&
  943. q[strspn(q, "0123456789abcdefABCDEF:")] == 0) {
  944. /*
  945. * Might be a key fingerprint. Check the colons are in the
  946. * right places, and if so, return the same fingerprint
  947. * canonicalised into lowercase.
  948. */
  949. int i;
  950. for (i = 0; i < 16; i++)
  951. if (q[3*i] == ':' || q[3*i+1] == ':')
  952. goto not_fingerprint; /* sorry */
  953. for (i = 0; i < 15; i++)
  954. if (q[3*i+2] != ':')
  955. goto not_fingerprint; /* sorry */
  956. for (i = 0; i < 16*3 - 1; i++)
  957. key[i] = tolower(q[i]);
  958. key[16*3 - 1] = '\0';
  959. return TRUE;
  960. }
  961. not_fingerprint:;
  962. /*
  963. * Before we check for a public-key blob, trim newlines out of
  964. * the middle of the word, in case someone's managed to paste
  965. * in a public-key blob _with_ them.
  966. */
  967. for (r = s = q; *r; r++)
  968. if (*r != '\n' && *r != '\r')
  969. *s++ = *r;
  970. *s = '\0';
  971. if (strlen(q) % 4 == 0 && strlen(q) > 2*4 &&
  972. q[strspn(q, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  973. "abcdefghijklmnopqrstuvwxyz+/=")] == 0) {
  974. /*
  975. * Might be a base64-encoded SSH-2 public key blob. Check
  976. * that it starts with a sensible algorithm string. No
  977. * canonicalisation is necessary for this string type.
  978. *
  979. * The algorithm string must be at most 64 characters long
  980. * (RFC 4251 section 6).
  981. */
  982. unsigned char decoded[6];
  983. unsigned alglen;
  984. int minlen;
  985. int len = 0;
  986. len += base64_decode_atom(q, decoded+len);
  987. if (len < 3)
  988. goto not_ssh2_blob; /* sorry */
  989. len += base64_decode_atom(q+4, decoded+len);
  990. if (len < 4)
  991. goto not_ssh2_blob; /* sorry */
  992. alglen = GET_32BIT_MSB_FIRST(decoded);
  993. if (alglen > 64)
  994. goto not_ssh2_blob; /* sorry */
  995. minlen = ((alglen + 4) + 2) / 3;
  996. if (strlen(q) < minlen)
  997. goto not_ssh2_blob; /* sorry */
  998. strcpy(key, q);
  999. return TRUE;
  1000. }
  1001. not_ssh2_blob:;
  1002. }
  1003. return FALSE;
  1004. }
  1005. int smemeq(const void *av, const void *bv, size_t len)
  1006. {
  1007. const unsigned char *a = (const unsigned char *)av;
  1008. const unsigned char *b = (const unsigned char *)bv;
  1009. unsigned val = 0;
  1010. while (len-- > 0) {
  1011. val |= *a++ ^ *b++;
  1012. }
  1013. /* Now val is 0 iff we want to return 1, and in the range
  1014. * 0x01..0xFF iff we want to return 0. So subtracting from 0x100
  1015. * will clear bit 8 iff we want to return 0, and leave it set iff
  1016. * we want to return 1, so then we can just shift down. */
  1017. return (0x100 - val) >> 8;
  1018. }
  1019. int match_ssh_id(int stringlen, const void *string, const char *id)
  1020. {
  1021. int idlen = strlen(id);
  1022. return (idlen == stringlen && !memcmp(string, id, idlen));
  1023. }
  1024. void *get_ssh_string(int *datalen, const void **data, int *stringlen)
  1025. {
  1026. void *ret;
  1027. unsigned int len;
  1028. if (*datalen < 4)
  1029. return NULL;
  1030. len = GET_32BIT_MSB_FIRST((const unsigned char *)*data);
  1031. if (*datalen - 4 < len)
  1032. return NULL;
  1033. ret = (void *)((const char *)*data + 4);
  1034. *datalen -= len + 4;
  1035. *data = (const char *)*data + len + 4;
  1036. *stringlen = len;
  1037. return ret;
  1038. }
  1039. int get_ssh_uint32(int *datalen, const void **data, unsigned *ret)
  1040. {
  1041. if (*datalen < 4)
  1042. return FALSE;
  1043. *ret = GET_32BIT_MSB_FIRST((const unsigned char *)*data);
  1044. *datalen -= 4;
  1045. *data = (const char *)*data + 4;
  1046. return TRUE;
  1047. }
  1048. int strstartswith(const char *s, const char *t)
  1049. {
  1050. return !memcmp(s, t, strlen(t));
  1051. }
  1052. int strendswith(const char *s, const char *t)
  1053. {
  1054. size_t slen = strlen(s), tlen = strlen(t);
  1055. return slen >= tlen && !strcmp(s + (slen - tlen), t);
  1056. }
  1057. char *buildinfo(const char *newline)
  1058. {
  1059. strbuf *buf = strbuf_new();
  1060. extern const char commitid[]; /* in commitid.c */
  1061. strbuf_catf(buf, "Build platform: %d-bit %s",
  1062. (int)(CHAR_BIT * sizeof(void *)),
  1063. BUILDINFO_PLATFORM);
  1064. #ifdef __clang_version__
  1065. #define FOUND_COMPILER
  1066. strbuf_catf(buf, "%sCompiler: clang %s", newline, __clang_version__);
  1067. #elif defined __GNUC__ && defined __VERSION__
  1068. #define FOUND_COMPILER
  1069. strbuf_catf(buf, "%sCompiler: gcc %s", newline, __VERSION__);
  1070. #endif
  1071. #if defined _MSC_VER
  1072. #ifndef FOUND_COMPILER
  1073. #define FOUND_COMPILER
  1074. strbuf_catf(buf, "%sCompiler: ", newline);
  1075. #else
  1076. strbuf_catf(buf, ", emulating ");
  1077. #endif
  1078. strbuf_catf(buf, "Visual Studio", newline);
  1079. #if _MSC_VER == 1900
  1080. strbuf_catf(buf, " 2015 / MSVC++ 14.0");
  1081. #elif _MSC_VER == 1800
  1082. strbuf_catf(buf, " 2013 / MSVC++ 12.0");
  1083. #elif _MSC_VER == 1700
  1084. strbuf_catf(buf, " 2012 / MSVC++ 11.0");
  1085. #elif _MSC_VER == 1600
  1086. strbuf_catf(buf, " 2010 / MSVC++ 10.0");
  1087. #elif _MSC_VER == 1500
  1088. strbuf_catf(buf, " 2008 / MSVC++ 9.0");
  1089. #elif _MSC_VER == 1400
  1090. strbuf_catf(buf, " 2005 / MSVC++ 8.0");
  1091. #elif _MSC_VER == 1310
  1092. strbuf_catf(buf, " 2003 / MSVC++ 7.1");
  1093. #elif _MSC_VER == 1300
  1094. strbuf_catf(buf, " 2003 / MSVC++ 7.0");
  1095. #else
  1096. strbuf_catf(buf, ", unrecognised version");
  1097. #endif
  1098. strbuf_catf(buf, " (_MSC_VER=%d)", (int)_MSC_VER);
  1099. #endif
  1100. #ifdef BUILDINFO_GTK
  1101. {
  1102. char *gtk_buildinfo = buildinfo_gtk_version();
  1103. if (gtk_buildinfo) {
  1104. strbuf_catf(buf, "%sCompiled against GTK version %s",
  1105. newline, gtk_buildinfo);
  1106. sfree(gtk_buildinfo);
  1107. }
  1108. }
  1109. #endif
  1110. #if defined _WINDOWS && defined MINEFIELD
  1111. strbuf_catf(buf, "%sBuild option: MINEFIELD", newline);
  1112. #endif
  1113. #ifdef NO_SECURITY
  1114. strbuf_catf(buf, "%sBuild option: NO_SECURITY", newline);
  1115. #endif
  1116. #ifdef NO_SECUREZEROMEMORY
  1117. strbuf_catf(buf, "%sBuild option: NO_SECUREZEROMEMORY", newline);
  1118. #endif
  1119. #ifdef NO_IPV6
  1120. strbuf_catf(buf, "%sBuild option: NO_IPV6", newline);
  1121. #endif
  1122. #ifdef NO_GSSAPI
  1123. strbuf_catf(buf, "%sBuild option: NO_GSSAPI", newline);
  1124. #endif
  1125. #ifdef STATIC_GSSAPI
  1126. strbuf_catf(buf, "%sBuild option: STATIC_GSSAPI", newline);
  1127. #endif
  1128. #ifdef UNPROTECT
  1129. strbuf_catf(buf, "%sBuild option: UNPROTECT", newline);
  1130. #endif
  1131. #ifdef FUZZING
  1132. strbuf_catf(buf, "%sBuild option: FUZZING", newline);
  1133. #endif
  1134. #ifdef DEBUG
  1135. strbuf_catf(buf, "%sBuild option: DEBUG", newline);
  1136. #endif
  1137. strbuf_catf(buf, "%sSource commit: %s", newline, commitid);
  1138. return strbuf_to_str(buf);
  1139. }