misc.c 33 KB

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