misc.c 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333
  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(Frontend *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. int string_length_for_printf(size_t s)
  339. {
  340. /* Truncate absurdly long strings (should one show up) to fit
  341. * within a positive 'int', which is what the "%.*s" format will
  342. * expect. */
  343. if (s > INT_MAX)
  344. return INT_MAX;
  345. return s;
  346. }
  347. /*
  348. * Do an sprintf(), but into a custom-allocated buffer.
  349. *
  350. * Currently I'm doing this via vsnprintf. This has worked so far,
  351. * but it's not good, because vsnprintf is not available on all
  352. * platforms. There's an ifdef to use `_vsnprintf', which seems
  353. * to be the local name for it on Windows. Other platforms may
  354. * lack it completely, in which case it'll be time to rewrite
  355. * this function in a totally different way.
  356. *
  357. * The only `properly' portable solution I can think of is to
  358. * implement my own format string scanner, which figures out an
  359. * upper bound for the length of each formatting directive,
  360. * allocates the buffer as it goes along, and calls sprintf() to
  361. * actually process each directive. If I ever need to actually do
  362. * this, some caveats:
  363. *
  364. * - It's very hard to find a reliable upper bound for
  365. * floating-point values. %f, in particular, when supplied with
  366. * a number near to the upper or lower limit of representable
  367. * numbers, could easily take several hundred characters. It's
  368. * probably feasible to predict this statically using the
  369. * constants in <float.h>, or even to predict it dynamically by
  370. * looking at the exponent of the specific float provided, but
  371. * it won't be fun.
  372. *
  373. * - Don't forget to _check_, after calling sprintf, that it's
  374. * used at most the amount of space we had available.
  375. *
  376. * - Fault any formatting directive we don't fully understand. The
  377. * aim here is to _guarantee_ that we never overflow the buffer,
  378. * because this is a security-critical function. If we see a
  379. * directive we don't know about, we should panic and die rather
  380. * than run any risk.
  381. */
  382. static char *dupvprintf_inner(char *buf, int oldlen, int *oldsize,
  383. const char *fmt, va_list ap)
  384. {
  385. int len, size, newsize;
  386. assert(*oldsize >= oldlen);
  387. size = *oldsize - oldlen;
  388. if (size == 0) {
  389. size = 512;
  390. newsize = oldlen + size;
  391. buf = sresize(buf, newsize, char);
  392. } else {
  393. newsize = *oldsize;
  394. }
  395. while (1) {
  396. #if defined _WINDOWS && !defined __WINE__ && _MSC_VER < 1900 /* 1900 == VS2015 has real snprintf */
  397. #define vsnprintf _vsnprintf
  398. #endif
  399. #ifdef va_copy
  400. /* Use the `va_copy' macro mandated by C99, if present.
  401. * XXX some environments may have this as __va_copy() */
  402. va_list aq;
  403. va_copy(aq, ap);
  404. len = vsnprintf(buf + oldlen, size, fmt, aq);
  405. va_end(aq);
  406. #else
  407. /* Ugh. No va_copy macro, so do something nasty.
  408. * Technically, you can't reuse a va_list like this: it is left
  409. * unspecified whether advancing a va_list pointer modifies its
  410. * value or something it points to, so on some platforms calling
  411. * vsnprintf twice on the same va_list might fail hideously
  412. * (indeed, it has been observed to).
  413. * XXX the autoconf manual suggests that using memcpy() will give
  414. * "maximum portability". */
  415. len = vsnprintf(buf + oldlen, size, fmt, ap);
  416. #endif
  417. if (len >= 0 && len < size) {
  418. /* This is the C99-specified criterion for snprintf to have
  419. * been completely successful. */
  420. *oldsize = newsize;
  421. return buf;
  422. } else if (len > 0) {
  423. /* This is the C99 error condition: the returned length is
  424. * the required buffer size not counting the NUL. */
  425. size = len + 1;
  426. } else {
  427. /* This is the pre-C99 glibc error condition: <0 means the
  428. * buffer wasn't big enough, so we enlarge it a bit and hope. */
  429. size += 512;
  430. }
  431. newsize = oldlen + size;
  432. buf = sresize(buf, newsize, char);
  433. }
  434. }
  435. char *dupvprintf(const char *fmt, va_list ap)
  436. {
  437. int size = 0;
  438. return dupvprintf_inner(NULL, 0, &size, fmt, ap);
  439. }
  440. char *dupprintf(const char *fmt, ...)
  441. {
  442. char *ret;
  443. va_list ap;
  444. va_start(ap, fmt);
  445. ret = dupvprintf(fmt, ap);
  446. va_end(ap);
  447. return ret;
  448. }
  449. struct strbuf_impl {
  450. int size;
  451. struct strbuf visible;
  452. };
  453. #define STRBUF_SET_PTR(buf, ptr) \
  454. ((buf)->visible.s = (ptr), \
  455. (buf)->visible.u = (unsigned char *)(buf)->visible.s)
  456. void *strbuf_append(strbuf *buf_o, size_t len)
  457. {
  458. struct strbuf_impl *buf = FROMFIELD(buf_o, struct strbuf_impl, visible);
  459. char *toret;
  460. if (buf->size < buf->visible.len + len + 1) {
  461. buf->size = (buf->visible.len + len + 1) * 5 / 4 + 512;
  462. STRBUF_SET_PTR(buf, sresize(buf->visible.s, buf->size, char));
  463. }
  464. toret = buf->visible.s + buf->visible.len;
  465. buf->visible.len += len;
  466. buf->visible.s[buf->visible.len] = '\0';
  467. return toret;
  468. }
  469. static void strbuf_BinarySink_write(
  470. BinarySink *bs, const void *data, size_t len)
  471. {
  472. strbuf *buf_o = BinarySink_DOWNCAST(bs, strbuf);
  473. memcpy(strbuf_append(buf_o, len), data, len);
  474. }
  475. strbuf *strbuf_new(void)
  476. {
  477. struct strbuf_impl *buf = snew(struct strbuf_impl);
  478. BinarySink_INIT(&buf->visible, strbuf_BinarySink_write);
  479. buf->visible.len = 0;
  480. buf->size = 512;
  481. STRBUF_SET_PTR(buf, snewn(buf->size, char));
  482. *buf->visible.s = '\0';
  483. return &buf->visible;
  484. }
  485. void strbuf_free(strbuf *buf_o)
  486. {
  487. struct strbuf_impl *buf = FROMFIELD(buf_o, struct strbuf_impl, visible);
  488. if (buf->visible.s) {
  489. smemclr(buf->visible.s, buf->size);
  490. sfree(buf->visible.s);
  491. }
  492. sfree(buf);
  493. }
  494. char *strbuf_to_str(strbuf *buf_o)
  495. {
  496. struct strbuf_impl *buf = FROMFIELD(buf_o, struct strbuf_impl, visible);
  497. char *ret = buf->visible.s;
  498. sfree(buf);
  499. return ret;
  500. }
  501. void strbuf_catfv(strbuf *buf_o, const char *fmt, va_list ap)
  502. {
  503. struct strbuf_impl *buf = FROMFIELD(buf_o, struct strbuf_impl, visible);
  504. STRBUF_SET_PTR(buf, dupvprintf_inner(buf->visible.s, buf->visible.len,
  505. &buf->size, fmt, ap));
  506. buf->visible.len += strlen(buf->visible.s + buf->visible.len);
  507. }
  508. void strbuf_catf(strbuf *buf_o, const char *fmt, ...)
  509. {
  510. va_list ap;
  511. va_start(ap, fmt);
  512. strbuf_catfv(buf_o, fmt, ap);
  513. va_end(ap);
  514. }
  515. strbuf *strbuf_new_for_agent_query(void)
  516. {
  517. strbuf *buf = strbuf_new();
  518. put_uint32(buf, 0); /* reserve space for length field */
  519. return buf;
  520. }
  521. void strbuf_finalise_agent_query(strbuf *buf_o)
  522. {
  523. struct strbuf_impl *buf = FROMFIELD(buf_o, struct strbuf_impl, visible);
  524. assert(buf->visible.len >= 5);
  525. PUT_32BIT_MSB_FIRST(buf->visible.u, buf->visible.len - 4);
  526. }
  527. /*
  528. * Read an entire line of text from a file. Return a buffer
  529. * malloced to be as big as necessary (caller must free).
  530. */
  531. char *fgetline(FILE *fp)
  532. {
  533. char *ret = snewn(512, char);
  534. int size = 512, len = 0;
  535. while (fgets(ret + len, size - len, fp)) {
  536. len += strlen(ret + len);
  537. if (len > 0 && ret[len-1] == '\n')
  538. break; /* got a newline, we're done */
  539. size = len + 512;
  540. ret = sresize(ret, size, char);
  541. }
  542. if (len == 0) { /* first fgets returned NULL */
  543. sfree(ret);
  544. return NULL;
  545. }
  546. ret[len] = '\0';
  547. return ret;
  548. }
  549. /*
  550. * Perl-style 'chomp', for a line we just read with fgetline. Unlike
  551. * Perl chomp, however, we're deliberately forgiving of strange
  552. * line-ending conventions. Also we forgive NULL on input, so you can
  553. * just write 'line = chomp(fgetline(fp));' and not bother checking
  554. * for NULL until afterwards.
  555. */
  556. char *chomp(char *str)
  557. {
  558. if (str) {
  559. int len = strlen(str);
  560. while (len > 0 && (str[len-1] == '\r' || str[len-1] == '\n'))
  561. len--;
  562. str[len] = '\0';
  563. }
  564. return str;
  565. }
  566. /* ----------------------------------------------------------------------
  567. * Core base64 encoding and decoding routines.
  568. */
  569. void base64_encode_atom(const unsigned char *data, int n, char *out)
  570. {
  571. static const char base64_chars[] =
  572. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  573. unsigned word;
  574. word = data[0] << 16;
  575. if (n > 1)
  576. word |= data[1] << 8;
  577. if (n > 2)
  578. word |= data[2];
  579. out[0] = base64_chars[(word >> 18) & 0x3F];
  580. out[1] = base64_chars[(word >> 12) & 0x3F];
  581. if (n > 1)
  582. out[2] = base64_chars[(word >> 6) & 0x3F];
  583. else
  584. out[2] = '=';
  585. if (n > 2)
  586. out[3] = base64_chars[word & 0x3F];
  587. else
  588. out[3] = '=';
  589. }
  590. int base64_decode_atom(const char *atom, unsigned char *out)
  591. {
  592. int vals[4];
  593. int i, v, len;
  594. unsigned word;
  595. char c;
  596. for (i = 0; i < 4; i++) {
  597. c = atom[i];
  598. if (c >= 'A' && c <= 'Z')
  599. v = c - 'A';
  600. else if (c >= 'a' && c <= 'z')
  601. v = c - 'a' + 26;
  602. else if (c >= '0' && c <= '9')
  603. v = c - '0' + 52;
  604. else if (c == '+')
  605. v = 62;
  606. else if (c == '/')
  607. v = 63;
  608. else if (c == '=')
  609. v = -1;
  610. else
  611. return 0; /* invalid atom */
  612. vals[i] = v;
  613. }
  614. if (vals[0] == -1 || vals[1] == -1)
  615. return 0;
  616. if (vals[2] == -1 && vals[3] != -1)
  617. return 0;
  618. if (vals[3] != -1)
  619. len = 3;
  620. else if (vals[2] != -1)
  621. len = 2;
  622. else
  623. len = 1;
  624. word = ((vals[0] << 18) |
  625. (vals[1] << 12) | ((vals[2] & 0x3F) << 6) | (vals[3] & 0x3F));
  626. out[0] = (word >> 16) & 0xFF;
  627. if (len > 1)
  628. out[1] = (word >> 8) & 0xFF;
  629. if (len > 2)
  630. out[2] = word & 0xFF;
  631. return len;
  632. }
  633. /* ----------------------------------------------------------------------
  634. * Generic routines to deal with send buffers: a linked list of
  635. * smallish blocks, with the operations
  636. *
  637. * - add an arbitrary amount of data to the end of the list
  638. * - remove the first N bytes from the list
  639. * - return a (pointer,length) pair giving some initial data in
  640. * the list, suitable for passing to a send or write system
  641. * call
  642. * - retrieve a larger amount of initial data from the list
  643. * - return the current size of the buffer chain in bytes
  644. */
  645. /* MP:
  646. * Default granule of 512 leads to low performance.
  647. */
  648. #define BUFFER_MIN_GRANULE 512*2*32
  649. struct bufchain_granule {
  650. struct bufchain_granule *next;
  651. char *bufpos, *bufend, *bufmax;
  652. };
  653. void bufchain_init(bufchain *ch)
  654. {
  655. ch->head = ch->tail = NULL;
  656. ch->buffersize = 0;
  657. }
  658. void bufchain_clear(bufchain *ch)
  659. {
  660. struct bufchain_granule *b;
  661. while (ch->head) {
  662. b = ch->head;
  663. ch->head = ch->head->next;
  664. sfree(b);
  665. }
  666. ch->tail = NULL;
  667. ch->buffersize = 0;
  668. }
  669. int bufchain_size(bufchain *ch)
  670. {
  671. return ch->buffersize;
  672. }
  673. void bufchain_add(bufchain *ch, const void *data, int len)
  674. {
  675. const char *buf = (const char *)data;
  676. if (len == 0) return;
  677. ch->buffersize += len;
  678. while (len > 0) {
  679. if (ch->tail && ch->tail->bufend < ch->tail->bufmax) {
  680. int copylen = min(len, ch->tail->bufmax - ch->tail->bufend);
  681. memcpy(ch->tail->bufend, buf, copylen);
  682. buf += copylen;
  683. len -= copylen;
  684. ch->tail->bufend += copylen;
  685. }
  686. if (len > 0) {
  687. int grainlen =
  688. max(sizeof(struct bufchain_granule) + len, BUFFER_MIN_GRANULE);
  689. struct bufchain_granule *newbuf;
  690. newbuf = smalloc(grainlen);
  691. newbuf->bufpos = newbuf->bufend =
  692. (char *)newbuf + sizeof(struct bufchain_granule);
  693. newbuf->bufmax = (char *)newbuf + grainlen;
  694. newbuf->next = NULL;
  695. if (ch->tail)
  696. ch->tail->next = newbuf;
  697. else
  698. ch->head = newbuf;
  699. ch->tail = newbuf;
  700. }
  701. }
  702. }
  703. void bufchain_consume(bufchain *ch, int len)
  704. {
  705. struct bufchain_granule *tmp;
  706. assert(ch->buffersize >= len);
  707. while (len > 0) {
  708. int remlen = len;
  709. assert(ch->head != NULL);
  710. if (remlen >= ch->head->bufend - ch->head->bufpos) {
  711. remlen = ch->head->bufend - ch->head->bufpos;
  712. tmp = ch->head;
  713. ch->head = tmp->next;
  714. if (!ch->head)
  715. ch->tail = NULL;
  716. sfree(tmp);
  717. } else
  718. ch->head->bufpos += remlen;
  719. ch->buffersize -= remlen;
  720. len -= remlen;
  721. }
  722. }
  723. void bufchain_prefix(bufchain *ch, void **data, int *len)
  724. {
  725. *len = ch->head->bufend - ch->head->bufpos;
  726. *data = ch->head->bufpos;
  727. }
  728. void bufchain_fetch(bufchain *ch, void *data, int len)
  729. {
  730. struct bufchain_granule *tmp;
  731. char *data_c = (char *)data;
  732. tmp = ch->head;
  733. assert(ch->buffersize >= len);
  734. while (len > 0) {
  735. int remlen = len;
  736. assert(tmp != NULL);
  737. if (remlen >= tmp->bufend - tmp->bufpos)
  738. remlen = tmp->bufend - tmp->bufpos;
  739. memcpy(data_c, tmp->bufpos, remlen);
  740. tmp = tmp->next;
  741. len -= remlen;
  742. data_c += remlen;
  743. }
  744. }
  745. void bufchain_fetch_consume(bufchain *ch, void *data, int len)
  746. {
  747. bufchain_fetch(ch, data, len);
  748. bufchain_consume(ch, len);
  749. }
  750. int bufchain_try_fetch_consume(bufchain *ch, void *data, int len)
  751. {
  752. if (ch->buffersize >= len) {
  753. bufchain_fetch_consume(ch, data, len);
  754. return TRUE;
  755. } else {
  756. return FALSE;
  757. }
  758. }
  759. /* ----------------------------------------------------------------------
  760. * My own versions of malloc, realloc and free. Because I want
  761. * malloc and realloc to bomb out and exit the program if they run
  762. * out of memory, realloc to reliably call malloc if passed a NULL
  763. * pointer, and free to reliably do nothing if passed a NULL
  764. * pointer. We can also put trace printouts in, if we need to; and
  765. * we can also replace the allocator with an ElectricFence-like
  766. * one.
  767. */
  768. #ifdef MINEFIELD
  769. void *minefield_c_malloc(size_t size);
  770. void minefield_c_free(void *p);
  771. void *minefield_c_realloc(void *p, size_t size);
  772. #endif
  773. #ifdef MALLOC_LOG
  774. static FILE *fp = NULL;
  775. static char *mlog_file = NULL;
  776. static int mlog_line = 0;
  777. void mlog(char *file, int line)
  778. {
  779. mlog_file = file;
  780. mlog_line = line;
  781. if (!fp) {
  782. fp = fopen("putty_mem.log", "w");
  783. setvbuf(fp, NULL, _IONBF, BUFSIZ);
  784. }
  785. if (fp)
  786. fprintf(fp, "%s:%d: ", file, line);
  787. }
  788. #endif
  789. void *safemalloc(size_t n, size_t size)
  790. {
  791. void *p;
  792. if (n > INT_MAX / size) {
  793. p = NULL;
  794. } else {
  795. size *= n;
  796. if (size == 0) size = 1;
  797. #ifdef MINEFIELD
  798. p = minefield_c_malloc(size);
  799. #else
  800. p = malloc(size);
  801. #endif
  802. }
  803. if (!p) {
  804. char str[200];
  805. #ifdef MALLOC_LOG
  806. sprintf(str, "Out of memory! (%s:%d, size=%d)",
  807. mlog_file, mlog_line, size);
  808. fprintf(fp, "*** %s\n", str);
  809. fclose(fp);
  810. #else
  811. strcpy(str, "Out of memory!");
  812. #endif
  813. modalfatalbox("%s", str);
  814. }
  815. #ifdef MALLOC_LOG
  816. if (fp)
  817. fprintf(fp, "malloc(%d) returns %p\n", size, p);
  818. #endif
  819. return p;
  820. }
  821. void *saferealloc(void *ptr, size_t n, size_t size)
  822. {
  823. void *p;
  824. if (n > INT_MAX / size) {
  825. p = NULL;
  826. } else {
  827. size *= n;
  828. if (!ptr) {
  829. #ifdef MINEFIELD
  830. p = minefield_c_malloc(size);
  831. #else
  832. p = malloc(size);
  833. #endif
  834. } else {
  835. #ifdef MINEFIELD
  836. p = minefield_c_realloc(ptr, size);
  837. #else
  838. p = realloc(ptr, size);
  839. #endif
  840. }
  841. }
  842. if (!p) {
  843. char str[200];
  844. #ifdef MALLOC_LOG
  845. sprintf(str, "Out of memory! (%s:%d, size=%d)",
  846. mlog_file, mlog_line, size);
  847. fprintf(fp, "*** %s\n", str);
  848. fclose(fp);
  849. #else
  850. strcpy(str, "Out of memory!");
  851. #endif
  852. modalfatalbox("%s", str);
  853. }
  854. #ifdef MALLOC_LOG
  855. if (fp)
  856. fprintf(fp, "realloc(%p,%d) returns %p\n", ptr, size, p);
  857. #endif
  858. return p;
  859. }
  860. void safefree(void *ptr)
  861. {
  862. if (ptr) {
  863. #ifdef MALLOC_LOG
  864. if (fp)
  865. fprintf(fp, "free(%p)\n", ptr);
  866. #endif
  867. #ifdef MINEFIELD
  868. minefield_c_free(ptr);
  869. #else
  870. free(ptr);
  871. #endif
  872. }
  873. #ifdef MALLOC_LOG
  874. else if (fp)
  875. fprintf(fp, "freeing null pointer - no action taken\n");
  876. #endif
  877. }
  878. /* ----------------------------------------------------------------------
  879. * Debugging routines.
  880. */
  881. #ifdef DEBUG
  882. extern void dputs(const char *); /* defined in per-platform *misc.c */
  883. void debug_printf(const char *fmt, ...)
  884. {
  885. char *buf;
  886. va_list ap;
  887. va_start(ap, fmt);
  888. buf = dupvprintf(fmt, ap);
  889. dputs(buf);
  890. sfree(buf);
  891. va_end(ap);
  892. }
  893. void debug_memdump(const void *buf, int len, int L)
  894. {
  895. int i;
  896. const unsigned char *p = buf;
  897. char foo[17];
  898. if (L) {
  899. int delta;
  900. debug_printf("\t%d (0x%x) bytes:\n", len, len);
  901. delta = 15 & (uintptr_t)p;
  902. p -= delta;
  903. len += delta;
  904. }
  905. for (; 0 < len; p += 16, len -= 16) {
  906. dputs(" ");
  907. if (L)
  908. debug_printf("%p: ", p);
  909. strcpy(foo, "................"); /* sixteen dots */
  910. for (i = 0; i < 16 && i < len; ++i) {
  911. if (&p[i] < (unsigned char *) buf) {
  912. dputs(" "); /* 3 spaces */
  913. foo[i] = ' ';
  914. } else {
  915. debug_printf("%c%02.2x",
  916. &p[i] != (unsigned char *) buf
  917. && i % 4 ? '.' : ' ', p[i]
  918. );
  919. if (p[i] >= ' ' && p[i] <= '~')
  920. foo[i] = (char) p[i];
  921. }
  922. }
  923. foo[i] = '\0';
  924. debug_printf("%*s%s\n", (16 - i) * 3 + 2, "", foo);
  925. }
  926. }
  927. #endif /* def DEBUG */
  928. /*
  929. * Determine whether or not a Conf represents a session which can
  930. * sensibly be launched right now.
  931. */
  932. int conf_launchable(Conf *conf)
  933. {
  934. if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL)
  935. return conf_get_str(conf, CONF_serline)[0] != 0;
  936. else
  937. return conf_get_str(conf, CONF_host)[0] != 0;
  938. }
  939. char const *conf_dest(Conf *conf)
  940. {
  941. if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL)
  942. return conf_get_str(conf, CONF_serline);
  943. else
  944. return conf_get_str(conf, CONF_host);
  945. }
  946. #ifndef PLATFORM_HAS_SMEMCLR
  947. /*
  948. * Securely wipe memory.
  949. *
  950. * The actual wiping is no different from what memset would do: the
  951. * point of 'securely' is to try to be sure over-clever compilers
  952. * won't optimise away memsets on variables that are about to be freed
  953. * or go out of scope. See
  954. * https://buildsecurityin.us-cert.gov/bsi-rules/home/g1/771-BSI.html
  955. *
  956. * Some platforms (e.g. Windows) may provide their own version of this
  957. * function.
  958. */
  959. void smemclr(void *b, size_t n) {
  960. volatile char *vp;
  961. if (b && n > 0) {
  962. /*
  963. * Zero out the memory.
  964. */
  965. memset(b, 0, n);
  966. /*
  967. * Perform a volatile access to the object, forcing the
  968. * compiler to admit that the previous memset was important.
  969. *
  970. * This while loop should in practice run for zero iterations
  971. * (since we know we just zeroed the object out), but in
  972. * theory (as far as the compiler knows) it might range over
  973. * the whole object. (If we had just written, say, '*vp =
  974. * *vp;', a compiler could in principle have 'helpfully'
  975. * optimised the memset into only zeroing out the first byte.
  976. * This should be robust.)
  977. */
  978. vp = b;
  979. while (*vp) vp++;
  980. }
  981. }
  982. #endif
  983. /*
  984. * Validate a manual host key specification (either entered in the
  985. * GUI, or via -hostkey). If valid, we return TRUE, and update 'key'
  986. * to contain a canonicalised version of the key string in 'key'
  987. * (which is guaranteed to take up at most as much space as the
  988. * original version), suitable for putting into the Conf. If not
  989. * valid, we return FALSE.
  990. */
  991. int validate_manual_hostkey(char *key)
  992. {
  993. char *p, *q, *r, *s;
  994. /*
  995. * Step through the string word by word, looking for a word that's
  996. * in one of the formats we like.
  997. */
  998. p = key;
  999. while ((p += strspn(p, " \t"))[0]) {
  1000. q = p;
  1001. p += strcspn(p, " \t");
  1002. if (*p) *p++ = '\0';
  1003. /*
  1004. * Now q is our word.
  1005. */
  1006. if (strlen(q) == 16*3 - 1 &&
  1007. q[strspn(q, "0123456789abcdefABCDEF:")] == 0) {
  1008. /*
  1009. * Might be a key fingerprint. Check the colons are in the
  1010. * right places, and if so, return the same fingerprint
  1011. * canonicalised into lowercase.
  1012. */
  1013. int i;
  1014. for (i = 0; i < 16; i++)
  1015. if (q[3*i] == ':' || q[3*i+1] == ':')
  1016. goto not_fingerprint; /* sorry */
  1017. for (i = 0; i < 15; i++)
  1018. if (q[3*i+2] != ':')
  1019. goto not_fingerprint; /* sorry */
  1020. for (i = 0; i < 16*3 - 1; i++)
  1021. key[i] = tolower(q[i]);
  1022. key[16*3 - 1] = '\0';
  1023. return TRUE;
  1024. }
  1025. not_fingerprint:;
  1026. /*
  1027. * Before we check for a public-key blob, trim newlines out of
  1028. * the middle of the word, in case someone's managed to paste
  1029. * in a public-key blob _with_ them.
  1030. */
  1031. for (r = s = q; *r; r++)
  1032. if (*r != '\n' && *r != '\r')
  1033. *s++ = *r;
  1034. *s = '\0';
  1035. if (strlen(q) % 4 == 0 && strlen(q) > 2*4 &&
  1036. q[strspn(q, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  1037. "abcdefghijklmnopqrstuvwxyz+/=")] == 0) {
  1038. /*
  1039. * Might be a base64-encoded SSH-2 public key blob. Check
  1040. * that it starts with a sensible algorithm string. No
  1041. * canonicalisation is necessary for this string type.
  1042. *
  1043. * The algorithm string must be at most 64 characters long
  1044. * (RFC 4251 section 6).
  1045. */
  1046. unsigned char decoded[6];
  1047. unsigned alglen;
  1048. int minlen;
  1049. int len = 0;
  1050. len += base64_decode_atom(q, decoded+len);
  1051. if (len < 3)
  1052. goto not_ssh2_blob; /* sorry */
  1053. len += base64_decode_atom(q+4, decoded+len);
  1054. if (len < 4)
  1055. goto not_ssh2_blob; /* sorry */
  1056. alglen = GET_32BIT_MSB_FIRST(decoded);
  1057. if (alglen > 64)
  1058. goto not_ssh2_blob; /* sorry */
  1059. minlen = ((alglen + 4) + 2) / 3;
  1060. if (strlen(q) < minlen)
  1061. goto not_ssh2_blob; /* sorry */
  1062. strcpy(key, q);
  1063. return TRUE;
  1064. }
  1065. not_ssh2_blob:;
  1066. }
  1067. return FALSE;
  1068. }
  1069. int smemeq(const void *av, const void *bv, size_t len)
  1070. {
  1071. const unsigned char *a = (const unsigned char *)av;
  1072. const unsigned char *b = (const unsigned char *)bv;
  1073. unsigned val = 0;
  1074. while (len-- > 0) {
  1075. val |= *a++ ^ *b++;
  1076. }
  1077. /* Now val is 0 iff we want to return 1, and in the range
  1078. * 0x01..0xFF iff we want to return 0. So subtracting from 0x100
  1079. * will clear bit 8 iff we want to return 0, and leave it set iff
  1080. * we want to return 1, so then we can just shift down. */
  1081. return (0x100 - val) >> 8;
  1082. }
  1083. int nullstrcmp(const char *a, const char *b)
  1084. {
  1085. if (a == NULL && b == NULL)
  1086. return 0;
  1087. if (a == NULL)
  1088. return -1;
  1089. if (b == NULL)
  1090. return +1;
  1091. return strcmp(a, b);
  1092. }
  1093. ptrlen make_ptrlen(const void *ptr, size_t len)
  1094. {
  1095. ptrlen pl;
  1096. pl.ptr = ptr;
  1097. pl.len = len;
  1098. return pl;
  1099. }
  1100. int ptrlen_eq_string(ptrlen pl, const char *str)
  1101. {
  1102. size_t len = strlen(str);
  1103. return (pl.len == len && !memcmp(pl.ptr, str, len));
  1104. }
  1105. char *mkstr(ptrlen pl)
  1106. {
  1107. char *p = snewn(pl.len + 1, char);
  1108. memcpy(p, pl.ptr, pl.len);
  1109. p[pl.len] = '\0';
  1110. return p;
  1111. }
  1112. int strstartswith(const char *s, const char *t)
  1113. {
  1114. return !memcmp(s, t, strlen(t));
  1115. }
  1116. int strendswith(const char *s, const char *t)
  1117. {
  1118. size_t slen = strlen(s), tlen = strlen(t);
  1119. return slen >= tlen && !strcmp(s + (slen - tlen), t);
  1120. }
  1121. char *buildinfo(const char *newline)
  1122. {
  1123. strbuf *buf = strbuf_new();
  1124. extern const char commitid[]; /* in commitid.c */
  1125. strbuf_catf(buf, "Build platform: %d-bit %s",
  1126. (int)(CHAR_BIT * sizeof(void *)),
  1127. BUILDINFO_PLATFORM);
  1128. #ifdef __clang_version__
  1129. #define FOUND_COMPILER
  1130. strbuf_catf(buf, "%sCompiler: clang %s", newline, __clang_version__);
  1131. #elif defined __GNUC__ && defined __VERSION__
  1132. #define FOUND_COMPILER
  1133. strbuf_catf(buf, "%sCompiler: gcc %s", newline, __VERSION__);
  1134. #endif
  1135. #if defined _MSC_VER
  1136. #ifndef FOUND_COMPILER
  1137. #define FOUND_COMPILER
  1138. strbuf_catf(buf, "%sCompiler: ", newline);
  1139. #else
  1140. strbuf_catf(buf, ", emulating ");
  1141. #endif
  1142. strbuf_catf(buf, "Visual Studio", newline);
  1143. #if _MSC_VER == 1900
  1144. strbuf_catf(buf, " 2015 / MSVC++ 14.0");
  1145. #elif _MSC_VER == 1912
  1146. strbuf_catf(buf, " 2017 / MSVC++ 14.12");
  1147. #elif _MSC_VER == 1800
  1148. strbuf_catf(buf, " 2013 / MSVC++ 12.0");
  1149. #elif _MSC_VER == 1700
  1150. strbuf_catf(buf, " 2012 / MSVC++ 11.0");
  1151. #elif _MSC_VER == 1600
  1152. strbuf_catf(buf, " 2010 / MSVC++ 10.0");
  1153. #elif _MSC_VER == 1500
  1154. strbuf_catf(buf, " 2008 / MSVC++ 9.0");
  1155. #elif _MSC_VER == 1400
  1156. strbuf_catf(buf, " 2005 / MSVC++ 8.0");
  1157. #elif _MSC_VER == 1310
  1158. strbuf_catf(buf, " 2003 / MSVC++ 7.1");
  1159. #elif _MSC_VER == 1300
  1160. strbuf_catf(buf, " 2003 / MSVC++ 7.0");
  1161. #else
  1162. strbuf_catf(buf, ", unrecognised version");
  1163. #endif
  1164. strbuf_catf(buf, " (_MSC_VER=%d)", (int)_MSC_VER);
  1165. #endif
  1166. #ifdef BUILDINFO_GTK
  1167. {
  1168. char *gtk_buildinfo = buildinfo_gtk_version();
  1169. if (gtk_buildinfo) {
  1170. strbuf_catf(buf, "%sCompiled against GTK version %s",
  1171. newline, gtk_buildinfo);
  1172. sfree(gtk_buildinfo);
  1173. }
  1174. }
  1175. #endif
  1176. #if defined _WINDOWS && defined MINEFIELD
  1177. strbuf_catf(buf, "%sBuild option: MINEFIELD", newline);
  1178. #endif
  1179. #ifdef NO_SECURITY
  1180. strbuf_catf(buf, "%sBuild option: NO_SECURITY", newline);
  1181. #endif
  1182. #ifdef NO_SECUREZEROMEMORY
  1183. strbuf_catf(buf, "%sBuild option: NO_SECUREZEROMEMORY", newline);
  1184. #endif
  1185. #ifdef NO_IPV6
  1186. strbuf_catf(buf, "%sBuild option: NO_IPV6", newline);
  1187. #endif
  1188. #ifdef NO_GSSAPI
  1189. strbuf_catf(buf, "%sBuild option: NO_GSSAPI", newline);
  1190. #endif
  1191. #ifdef STATIC_GSSAPI
  1192. strbuf_catf(buf, "%sBuild option: STATIC_GSSAPI", newline);
  1193. #endif
  1194. #ifdef UNPROTECT
  1195. strbuf_catf(buf, "%sBuild option: UNPROTECT", newline);
  1196. #endif
  1197. #ifdef FUZZING
  1198. strbuf_catf(buf, "%sBuild option: FUZZING", newline);
  1199. #endif
  1200. #ifdef DEBUG
  1201. strbuf_catf(buf, "%sBuild option: DEBUG", newline);
  1202. #endif
  1203. strbuf_catf(buf, "%sSource commit: %s", newline, commitid);
  1204. return strbuf_to_str(buf);
  1205. }
  1206. #ifdef MPEXT
  1207. #include "version.h"
  1208. const char * get_putty_version()
  1209. {
  1210. return TEXTVER;
  1211. }
  1212. #endif