misc.c 30 KB

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