misc.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101
  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. char *dupprintf(const char *fmt, ...)
  373. {
  374. char *ret;
  375. va_list ap;
  376. va_start(ap, fmt);
  377. ret = dupvprintf(fmt, ap);
  378. va_end(ap);
  379. return ret;
  380. }
  381. char *dupvprintf(const char *fmt, va_list ap)
  382. {
  383. char *buf;
  384. int len, size;
  385. buf = snewn(512, char);
  386. size = 512;
  387. while (1) {
  388. #if defined _WINDOWS && _MSC_VER < 1900 /* 1900 == VS2015 has real snprintf */
  389. #define vsnprintf _vsnprintf
  390. #endif
  391. #ifdef va_copy
  392. /* Use the `va_copy' macro mandated by C99, if present.
  393. * XXX some environments may have this as __va_copy() */
  394. va_list aq;
  395. va_copy(aq, ap);
  396. len = vsnprintf(buf, size, fmt, aq);
  397. va_end(aq);
  398. #else
  399. /* Ugh. No va_copy macro, so do something nasty.
  400. * Technically, you can't reuse a va_list like this: it is left
  401. * unspecified whether advancing a va_list pointer modifies its
  402. * value or something it points to, so on some platforms calling
  403. * vsnprintf twice on the same va_list might fail hideously
  404. * (indeed, it has been observed to).
  405. * XXX the autoconf manual suggests that using memcpy() will give
  406. * "maximum portability". */
  407. len = vsnprintf(buf, size, fmt, ap);
  408. #endif
  409. if (len >= 0 && len < size) {
  410. /* This is the C99-specified criterion for snprintf to have
  411. * been completely successful. */
  412. return buf;
  413. } else if (len > 0) {
  414. /* This is the C99 error condition: the returned length is
  415. * the required buffer size not counting the NUL. */
  416. size = len + 1;
  417. } else {
  418. /* This is the pre-C99 glibc error condition: <0 means the
  419. * buffer wasn't big enough, so we enlarge it a bit and hope. */
  420. size += 512;
  421. }
  422. buf = sresize(buf, size, char);
  423. }
  424. }
  425. /*
  426. * Read an entire line of text from a file. Return a buffer
  427. * malloced to be as big as necessary (caller must free).
  428. */
  429. char *fgetline(FILE *fp)
  430. {
  431. char *ret = snewn(512, char);
  432. int size = 512, len = 0;
  433. while (fgets(ret + len, size - len, fp)) {
  434. len += strlen(ret + len);
  435. if (len > 0 && ret[len-1] == '\n')
  436. break; /* got a newline, we're done */
  437. size = len + 512;
  438. ret = sresize(ret, size, char);
  439. }
  440. if (len == 0) { /* first fgets returned NULL */
  441. sfree(ret);
  442. return NULL;
  443. }
  444. ret[len] = '\0';
  445. return ret;
  446. }
  447. /*
  448. * Perl-style 'chomp', for a line we just read with fgetline. Unlike
  449. * Perl chomp, however, we're deliberately forgiving of strange
  450. * line-ending conventions. Also we forgive NULL on input, so you can
  451. * just write 'line = chomp(fgetline(fp));' and not bother checking
  452. * for NULL until afterwards.
  453. */
  454. char *chomp(char *str)
  455. {
  456. if (str) {
  457. int len = strlen(str);
  458. while (len > 0 && (str[len-1] == '\r' || str[len-1] == '\n'))
  459. len--;
  460. str[len] = '\0';
  461. }
  462. return str;
  463. }
  464. /* ----------------------------------------------------------------------
  465. * Core base64 encoding and decoding routines.
  466. */
  467. void base64_encode_atom(const unsigned char *data, int n, char *out)
  468. {
  469. static const char base64_chars[] =
  470. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  471. unsigned word;
  472. word = data[0] << 16;
  473. if (n > 1)
  474. word |= data[1] << 8;
  475. if (n > 2)
  476. word |= data[2];
  477. out[0] = base64_chars[(word >> 18) & 0x3F];
  478. out[1] = base64_chars[(word >> 12) & 0x3F];
  479. if (n > 1)
  480. out[2] = base64_chars[(word >> 6) & 0x3F];
  481. else
  482. out[2] = '=';
  483. if (n > 2)
  484. out[3] = base64_chars[word & 0x3F];
  485. else
  486. out[3] = '=';
  487. }
  488. int base64_decode_atom(const char *atom, unsigned char *out)
  489. {
  490. int vals[4];
  491. int i, v, len;
  492. unsigned word;
  493. char c;
  494. for (i = 0; i < 4; i++) {
  495. c = atom[i];
  496. if (c >= 'A' && c <= 'Z')
  497. v = c - 'A';
  498. else if (c >= 'a' && c <= 'z')
  499. v = c - 'a' + 26;
  500. else if (c >= '0' && c <= '9')
  501. v = c - '0' + 52;
  502. else if (c == '+')
  503. v = 62;
  504. else if (c == '/')
  505. v = 63;
  506. else if (c == '=')
  507. v = -1;
  508. else
  509. return 0; /* invalid atom */
  510. vals[i] = v;
  511. }
  512. if (vals[0] == -1 || vals[1] == -1)
  513. return 0;
  514. if (vals[2] == -1 && vals[3] != -1)
  515. return 0;
  516. if (vals[3] != -1)
  517. len = 3;
  518. else if (vals[2] != -1)
  519. len = 2;
  520. else
  521. len = 1;
  522. word = ((vals[0] << 18) |
  523. (vals[1] << 12) | ((vals[2] & 0x3F) << 6) | (vals[3] & 0x3F));
  524. out[0] = (word >> 16) & 0xFF;
  525. if (len > 1)
  526. out[1] = (word >> 8) & 0xFF;
  527. if (len > 2)
  528. out[2] = word & 0xFF;
  529. return len;
  530. }
  531. /* ----------------------------------------------------------------------
  532. * Generic routines to deal with send buffers: a linked list of
  533. * smallish blocks, with the operations
  534. *
  535. * - add an arbitrary amount of data to the end of the list
  536. * - remove the first N bytes from the list
  537. * - return a (pointer,length) pair giving some initial data in
  538. * the list, suitable for passing to a send or write system
  539. * call
  540. * - retrieve a larger amount of initial data from the list
  541. * - return the current size of the buffer chain in bytes
  542. */
  543. #define BUFFER_MIN_GRANULE 512
  544. struct bufchain_granule {
  545. struct bufchain_granule *next;
  546. char *bufpos, *bufend, *bufmax;
  547. };
  548. void bufchain_init(bufchain *ch)
  549. {
  550. ch->head = ch->tail = NULL;
  551. ch->buffersize = 0;
  552. }
  553. void bufchain_clear(bufchain *ch)
  554. {
  555. struct bufchain_granule *b;
  556. while (ch->head) {
  557. b = ch->head;
  558. ch->head = ch->head->next;
  559. sfree(b);
  560. }
  561. ch->tail = NULL;
  562. ch->buffersize = 0;
  563. }
  564. int bufchain_size(bufchain *ch)
  565. {
  566. return ch->buffersize;
  567. }
  568. void bufchain_add(bufchain *ch, const void *data, int len)
  569. {
  570. const char *buf = (const char *)data;
  571. if (len == 0) return;
  572. ch->buffersize += len;
  573. while (len > 0) {
  574. if (ch->tail && ch->tail->bufend < ch->tail->bufmax) {
  575. int copylen = min(len, ch->tail->bufmax - ch->tail->bufend);
  576. memcpy(ch->tail->bufend, buf, copylen);
  577. buf += copylen;
  578. len -= copylen;
  579. ch->tail->bufend += copylen;
  580. }
  581. if (len > 0) {
  582. int grainlen =
  583. max(sizeof(struct bufchain_granule) + len, BUFFER_MIN_GRANULE);
  584. struct bufchain_granule *newbuf;
  585. newbuf = smalloc(grainlen);
  586. newbuf->bufpos = newbuf->bufend =
  587. (char *)newbuf + sizeof(struct bufchain_granule);
  588. newbuf->bufmax = (char *)newbuf + grainlen;
  589. newbuf->next = NULL;
  590. if (ch->tail)
  591. ch->tail->next = newbuf;
  592. else
  593. ch->head = newbuf;
  594. ch->tail = newbuf;
  595. }
  596. }
  597. }
  598. void bufchain_consume(bufchain *ch, int len)
  599. {
  600. struct bufchain_granule *tmp;
  601. assert(ch->buffersize >= len);
  602. while (len > 0) {
  603. int remlen = len;
  604. assert(ch->head != NULL);
  605. if (remlen >= ch->head->bufend - ch->head->bufpos) {
  606. remlen = ch->head->bufend - ch->head->bufpos;
  607. tmp = ch->head;
  608. ch->head = tmp->next;
  609. if (!ch->head)
  610. ch->tail = NULL;
  611. sfree(tmp);
  612. } else
  613. ch->head->bufpos += remlen;
  614. ch->buffersize -= remlen;
  615. len -= remlen;
  616. }
  617. }
  618. void bufchain_prefix(bufchain *ch, void **data, int *len)
  619. {
  620. *len = ch->head->bufend - ch->head->bufpos;
  621. *data = ch->head->bufpos;
  622. }
  623. void bufchain_fetch(bufchain *ch, void *data, int len)
  624. {
  625. struct bufchain_granule *tmp;
  626. char *data_c = (char *)data;
  627. tmp = ch->head;
  628. assert(ch->buffersize >= len);
  629. while (len > 0) {
  630. int remlen = len;
  631. assert(tmp != NULL);
  632. if (remlen >= tmp->bufend - tmp->bufpos)
  633. remlen = tmp->bufend - tmp->bufpos;
  634. memcpy(data_c, tmp->bufpos, remlen);
  635. tmp = tmp->next;
  636. len -= remlen;
  637. data_c += remlen;
  638. }
  639. }
  640. /* ----------------------------------------------------------------------
  641. * My own versions of malloc, realloc and free. Because I want
  642. * malloc and realloc to bomb out and exit the program if they run
  643. * out of memory, realloc to reliably call malloc if passed a NULL
  644. * pointer, and free to reliably do nothing if passed a NULL
  645. * pointer. We can also put trace printouts in, if we need to; and
  646. * we can also replace the allocator with an ElectricFence-like
  647. * one.
  648. */
  649. #ifdef MINEFIELD
  650. void *minefield_c_malloc(size_t size);
  651. void minefield_c_free(void *p);
  652. void *minefield_c_realloc(void *p, size_t size);
  653. #endif
  654. #ifdef MALLOC_LOG
  655. static FILE *fp = NULL;
  656. static char *mlog_file = NULL;
  657. static int mlog_line = 0;
  658. void mlog(char *file, int line)
  659. {
  660. mlog_file = file;
  661. mlog_line = line;
  662. if (!fp) {
  663. fp = fopen("putty_mem.log", "w");
  664. setvbuf(fp, NULL, _IONBF, BUFSIZ);
  665. }
  666. if (fp)
  667. fprintf(fp, "%s:%d: ", file, line);
  668. }
  669. #endif
  670. void *safemalloc(size_t n, size_t size)
  671. {
  672. void *p;
  673. if (n > INT_MAX / size) {
  674. p = NULL;
  675. } else {
  676. size *= n;
  677. if (size == 0) size = 1;
  678. #ifdef MINEFIELD
  679. p = minefield_c_malloc(size);
  680. #else
  681. p = malloc(size);
  682. #endif
  683. }
  684. if (!p) {
  685. char str[200];
  686. #ifdef MALLOC_LOG
  687. sprintf(str, "Out of memory! (%s:%d, size=%d)",
  688. mlog_file, mlog_line, size);
  689. fprintf(fp, "*** %s\n", str);
  690. fclose(fp);
  691. #else
  692. strcpy(str, "Out of memory!");
  693. #endif
  694. modalfatalbox("%s", str);
  695. }
  696. #ifdef MALLOC_LOG
  697. if (fp)
  698. fprintf(fp, "malloc(%d) returns %p\n", size, p);
  699. #endif
  700. return p;
  701. }
  702. void *saferealloc(void *ptr, size_t n, size_t size)
  703. {
  704. void *p;
  705. if (n > INT_MAX / size) {
  706. p = NULL;
  707. } else {
  708. size *= n;
  709. if (!ptr) {
  710. #ifdef MINEFIELD
  711. p = minefield_c_malloc(size);
  712. #else
  713. p = malloc(size);
  714. #endif
  715. } else {
  716. #ifdef MINEFIELD
  717. p = minefield_c_realloc(ptr, size);
  718. #else
  719. p = realloc(ptr, size);
  720. #endif
  721. }
  722. }
  723. if (!p) {
  724. char str[200];
  725. #ifdef MALLOC_LOG
  726. sprintf(str, "Out of memory! (%s:%d, size=%d)",
  727. mlog_file, mlog_line, size);
  728. fprintf(fp, "*** %s\n", str);
  729. fclose(fp);
  730. #else
  731. strcpy(str, "Out of memory!");
  732. #endif
  733. modalfatalbox("%s", str);
  734. }
  735. #ifdef MALLOC_LOG
  736. if (fp)
  737. fprintf(fp, "realloc(%p,%d) returns %p\n", ptr, size, p);
  738. #endif
  739. return p;
  740. }
  741. void safefree(void *ptr)
  742. {
  743. if (ptr) {
  744. #ifdef MALLOC_LOG
  745. if (fp)
  746. fprintf(fp, "free(%p)\n", ptr);
  747. #endif
  748. #ifdef MINEFIELD
  749. minefield_c_free(ptr);
  750. #else
  751. free(ptr);
  752. #endif
  753. }
  754. #ifdef MALLOC_LOG
  755. else if (fp)
  756. fprintf(fp, "freeing null pointer - no action taken\n");
  757. #endif
  758. }
  759. /* ----------------------------------------------------------------------
  760. * Debugging routines.
  761. */
  762. #ifdef DEBUG
  763. extern void dputs(const char *); /* defined in per-platform *misc.c */
  764. void debug_printf(const char *fmt, ...)
  765. {
  766. char *buf;
  767. va_list ap;
  768. va_start(ap, fmt);
  769. buf = dupvprintf(fmt, ap);
  770. dputs(buf);
  771. sfree(buf);
  772. va_end(ap);
  773. }
  774. void debug_memdump(const void *buf, int len, int L)
  775. {
  776. int i;
  777. const unsigned char *p = buf;
  778. char foo[17];
  779. if (L) {
  780. int delta;
  781. debug_printf("\t%d (0x%x) bytes:\n", len, len);
  782. delta = 15 & (uintptr_t)p;
  783. p -= delta;
  784. len += delta;
  785. }
  786. for (; 0 < len; p += 16, len -= 16) {
  787. dputs(" ");
  788. if (L)
  789. debug_printf("%p: ", p);
  790. strcpy(foo, "................"); /* sixteen dots */
  791. for (i = 0; i < 16 && i < len; ++i) {
  792. if (&p[i] < (unsigned char *) buf) {
  793. dputs(" "); /* 3 spaces */
  794. foo[i] = ' ';
  795. } else {
  796. debug_printf("%c%02.2x",
  797. &p[i] != (unsigned char *) buf
  798. && i % 4 ? '.' : ' ', p[i]
  799. );
  800. if (p[i] >= ' ' && p[i] <= '~')
  801. foo[i] = (char) p[i];
  802. }
  803. }
  804. foo[i] = '\0';
  805. debug_printf("%*s%s\n", (16 - i) * 3 + 2, "", foo);
  806. }
  807. }
  808. #endif /* def DEBUG */
  809. /*
  810. * Determine whether or not a Conf represents a session which can
  811. * sensibly be launched right now.
  812. */
  813. int conf_launchable(Conf *conf)
  814. {
  815. if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL)
  816. return conf_get_str(conf, CONF_serline)[0] != 0;
  817. else
  818. return conf_get_str(conf, CONF_host)[0] != 0;
  819. }
  820. char const *conf_dest(Conf *conf)
  821. {
  822. if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL)
  823. return conf_get_str(conf, CONF_serline);
  824. else
  825. return conf_get_str(conf, CONF_host);
  826. }
  827. #ifndef PLATFORM_HAS_SMEMCLR
  828. /*
  829. * Securely wipe memory.
  830. *
  831. * The actual wiping is no different from what memset would do: the
  832. * point of 'securely' is to try to be sure over-clever compilers
  833. * won't optimise away memsets on variables that are about to be freed
  834. * or go out of scope. See
  835. * https://buildsecurityin.us-cert.gov/bsi-rules/home/g1/771-BSI.html
  836. *
  837. * Some platforms (e.g. Windows) may provide their own version of this
  838. * function.
  839. */
  840. void smemclr(void *b, size_t n) {
  841. volatile char *vp;
  842. if (b && n > 0) {
  843. /*
  844. * Zero out the memory.
  845. */
  846. memset(b, 0, n);
  847. /*
  848. * Perform a volatile access to the object, forcing the
  849. * compiler to admit that the previous memset was important.
  850. *
  851. * This while loop should in practice run for zero iterations
  852. * (since we know we just zeroed the object out), but in
  853. * theory (as far as the compiler knows) it might range over
  854. * the whole object. (If we had just written, say, '*vp =
  855. * *vp;', a compiler could in principle have 'helpfully'
  856. * optimised the memset into only zeroing out the first byte.
  857. * This should be robust.)
  858. */
  859. vp = b;
  860. while (*vp) vp++;
  861. }
  862. }
  863. #endif
  864. /*
  865. * Validate a manual host key specification (either entered in the
  866. * GUI, or via -hostkey). If valid, we return TRUE, and update 'key'
  867. * to contain a canonicalised version of the key string in 'key'
  868. * (which is guaranteed to take up at most as much space as the
  869. * original version), suitable for putting into the Conf. If not
  870. * valid, we return FALSE.
  871. */
  872. int validate_manual_hostkey(char *key)
  873. {
  874. char *p, *q, *r, *s;
  875. /*
  876. * Step through the string word by word, looking for a word that's
  877. * in one of the formats we like.
  878. */
  879. p = key;
  880. while ((p += strspn(p, " \t"))[0]) {
  881. q = p;
  882. p += strcspn(p, " \t");
  883. if (*p) *p++ = '\0';
  884. /*
  885. * Now q is our word.
  886. */
  887. if (strlen(q) == 16*3 - 1 &&
  888. q[strspn(q, "0123456789abcdefABCDEF:")] == 0) {
  889. /*
  890. * Might be a key fingerprint. Check the colons are in the
  891. * right places, and if so, return the same fingerprint
  892. * canonicalised into lowercase.
  893. */
  894. int i;
  895. for (i = 0; i < 16; i++)
  896. if (q[3*i] == ':' || q[3*i+1] == ':')
  897. goto not_fingerprint; /* sorry */
  898. for (i = 0; i < 15; i++)
  899. if (q[3*i+2] != ':')
  900. goto not_fingerprint; /* sorry */
  901. for (i = 0; i < 16*3 - 1; i++)
  902. key[i] = tolower(q[i]);
  903. key[16*3 - 1] = '\0';
  904. return TRUE;
  905. }
  906. not_fingerprint:;
  907. /*
  908. * Before we check for a public-key blob, trim newlines out of
  909. * the middle of the word, in case someone's managed to paste
  910. * in a public-key blob _with_ them.
  911. */
  912. for (r = s = q; *r; r++)
  913. if (*r != '\n' && *r != '\r')
  914. *s++ = *r;
  915. *s = '\0';
  916. if (strlen(q) % 4 == 0 && strlen(q) > 2*4 &&
  917. q[strspn(q, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  918. "abcdefghijklmnopqrstuvwxyz+/=")] == 0) {
  919. /*
  920. * Might be a base64-encoded SSH-2 public key blob. Check
  921. * that it starts with a sensible algorithm string. No
  922. * canonicalisation is necessary for this string type.
  923. *
  924. * The algorithm string must be at most 64 characters long
  925. * (RFC 4251 section 6).
  926. */
  927. unsigned char decoded[6];
  928. unsigned alglen;
  929. int minlen;
  930. int len = 0;
  931. len += base64_decode_atom(q, decoded+len);
  932. if (len < 3)
  933. goto not_ssh2_blob; /* sorry */
  934. len += base64_decode_atom(q+4, decoded+len);
  935. if (len < 4)
  936. goto not_ssh2_blob; /* sorry */
  937. alglen = GET_32BIT_MSB_FIRST(decoded);
  938. if (alglen > 64)
  939. goto not_ssh2_blob; /* sorry */
  940. minlen = ((alglen + 4) + 2) / 3;
  941. if (strlen(q) < minlen)
  942. goto not_ssh2_blob; /* sorry */
  943. strcpy(key, q);
  944. return TRUE;
  945. }
  946. not_ssh2_blob:;
  947. }
  948. return FALSE;
  949. }
  950. int smemeq(const void *av, const void *bv, size_t len)
  951. {
  952. const unsigned char *a = (const unsigned char *)av;
  953. const unsigned char *b = (const unsigned char *)bv;
  954. unsigned val = 0;
  955. while (len-- > 0) {
  956. val |= *a++ ^ *b++;
  957. }
  958. /* Now val is 0 iff we want to return 1, and in the range
  959. * 0x01..0xFF iff we want to return 0. So subtracting from 0x100
  960. * will clear bit 8 iff we want to return 0, and leave it set iff
  961. * we want to return 1, so then we can just shift down. */
  962. return (0x100 - val) >> 8;
  963. }
  964. int match_ssh_id(int stringlen, const void *string, const char *id)
  965. {
  966. int idlen = strlen(id);
  967. return (idlen == stringlen && !memcmp(string, id, idlen));
  968. }
  969. void *get_ssh_string(int *datalen, const void **data, int *stringlen)
  970. {
  971. void *ret;
  972. unsigned int len;
  973. if (*datalen < 4)
  974. return NULL;
  975. len = GET_32BIT_MSB_FIRST((const unsigned char *)*data);
  976. if (*datalen < len+4)
  977. return NULL;
  978. ret = (void *)((const char *)*data + 4);
  979. *datalen -= len + 4;
  980. *data = (const char *)*data + len + 4;
  981. *stringlen = len;
  982. return ret;
  983. }
  984. int get_ssh_uint32(int *datalen, const void **data, unsigned *ret)
  985. {
  986. if (*datalen < 4)
  987. return FALSE;
  988. *ret = GET_32BIT_MSB_FIRST((const unsigned char *)*data);
  989. *datalen -= 4;
  990. *data = (const char *)*data + 4;
  991. return TRUE;
  992. }
  993. int strstartswith(const char *s, const char *t)
  994. {
  995. return !memcmp(s, t, strlen(t));
  996. }
  997. int strendswith(const char *s, const char *t)
  998. {
  999. size_t slen = strlen(s), tlen = strlen(t);
  1000. return slen >= tlen && !strcmp(s + (slen - tlen), t);
  1001. }