misc.c 33 KB

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