misc.c 33 KB

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