misc.c 36 KB

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