MISC.C 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  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. /*
  12. * Parse a string block size specification. This is approximately a
  13. * subset of the block size specs supported by GNU fileutils:
  14. * "nk" = n kilobytes
  15. * "nM" = n megabytes
  16. * "nG" = n gigabytes
  17. * All numbers are decimal, and suffixes refer to powers of two.
  18. * Case-insensitive.
  19. */
  20. unsigned long parse_blocksize(const char *bs)
  21. {
  22. char *suf;
  23. unsigned long r = strtoul(bs, &suf, 10);
  24. if (*suf != '\0') {
  25. while (*suf && isspace((unsigned char)*suf)) suf++;
  26. switch (*suf) {
  27. case 'k': case 'K':
  28. r *= 1024ul;
  29. break;
  30. case 'm': case 'M':
  31. r *= 1024ul * 1024ul;
  32. break;
  33. case 'g': case 'G':
  34. r *= 1024ul * 1024ul * 1024ul;
  35. break;
  36. case '\0':
  37. default:
  38. break;
  39. }
  40. }
  41. return r;
  42. }
  43. /*
  44. * Parse a ^C style character specification.
  45. * Returns NULL in `next' if we didn't recognise it as a control character,
  46. * in which case `c' should be ignored.
  47. * The precise current parsing is an oddity inherited from the terminal
  48. * answerback-string parsing code. All sequences start with ^; all except
  49. * ^<123> are two characters. The ones that are worth keeping are probably:
  50. * ^? 127
  51. * ^@A-Z[\]^_ 0-31
  52. * a-z 1-26
  53. * <num> specified by number (decimal, 0octal, 0xHEX)
  54. * ~ ^ escape
  55. */
  56. char ctrlparse(char *s, char **next)
  57. {
  58. char c = 0;
  59. if (*s != '^') {
  60. *next = NULL;
  61. } else {
  62. s++;
  63. if (*s == '\0') {
  64. *next = NULL;
  65. } else if (*s == '<') {
  66. s++;
  67. c = (char)strtol(s, next, 0);
  68. if ((*next == s) || (**next != '>')) {
  69. c = 0;
  70. *next = NULL;
  71. } else
  72. (*next)++;
  73. } else if (*s >= 'a' && *s <= 'z') {
  74. c = (*s - ('a' - 1));
  75. *next = s+1;
  76. } else if ((*s >= '@' && *s <= '_') || *s == '?' || (*s & 0x80)) {
  77. c = ('@' ^ *s);
  78. *next = s+1;
  79. } else if (*s == '~') {
  80. c = '^';
  81. *next = s+1;
  82. }
  83. }
  84. return c;
  85. }
  86. prompts_t *new_prompts(void *frontend)
  87. {
  88. prompts_t *p = snew(prompts_t);
  89. p->prompts = NULL;
  90. p->n_prompts = 0;
  91. p->frontend = frontend;
  92. p->data = NULL;
  93. p->to_server = TRUE; /* to be on the safe side */
  94. p->name = p->instruction = NULL;
  95. p->name_reqd = p->instr_reqd = FALSE;
  96. return p;
  97. }
  98. void add_prompt(prompts_t *p, char *promptstr, int echo, size_t len)
  99. {
  100. prompt_t *pr = snew(prompt_t);
  101. char *result = snewn(len, char);
  102. pr->prompt = promptstr;
  103. pr->echo = echo;
  104. pr->result = result;
  105. pr->result_len = len;
  106. p->n_prompts++;
  107. p->prompts = sresize(p->prompts, p->n_prompts, prompt_t *);
  108. p->prompts[p->n_prompts-1] = pr;
  109. }
  110. void free_prompts(prompts_t *p)
  111. {
  112. size_t i;
  113. for (i=0; i < p->n_prompts; i++) {
  114. prompt_t *pr = p->prompts[i];
  115. memset(pr->result, 0, pr->result_len); /* burn the evidence */
  116. sfree(pr->result);
  117. sfree(pr->prompt);
  118. sfree(pr);
  119. }
  120. sfree(p->prompts);
  121. sfree(p->name);
  122. sfree(p->instruction);
  123. sfree(p);
  124. }
  125. /* ----------------------------------------------------------------------
  126. * String handling routines.
  127. */
  128. char *dupstr(const char *s)
  129. {
  130. char *p = NULL;
  131. if (s) {
  132. int len = strlen(s);
  133. p = snewn(len + 1, char);
  134. strcpy(p, s);
  135. }
  136. return p;
  137. }
  138. /* Allocate the concatenation of N strings. Terminate arg list with NULL. */
  139. char *dupcat(const char *s1, ...)
  140. {
  141. int len;
  142. char *p, *q, *sn;
  143. va_list ap;
  144. len = strlen(s1);
  145. va_start(ap, s1);
  146. while (1) {
  147. sn = va_arg(ap, char *);
  148. if (!sn)
  149. break;
  150. len += strlen(sn);
  151. }
  152. va_end(ap);
  153. p = snewn(len + 1, char);
  154. strcpy(p, s1);
  155. q = p + strlen(p);
  156. va_start(ap, s1);
  157. while (1) {
  158. sn = va_arg(ap, char *);
  159. if (!sn)
  160. break;
  161. strcpy(q, sn);
  162. q += strlen(q);
  163. }
  164. va_end(ap);
  165. return p;
  166. }
  167. /*
  168. * Do an sprintf(), but into a custom-allocated buffer.
  169. *
  170. * Currently I'm doing this via vsnprintf. This has worked so far,
  171. * but it's not good, because vsnprintf is not available on all
  172. * platforms. There's an ifdef to use `_vsnprintf', which seems
  173. * to be the local name for it on Windows. Other platforms may
  174. * lack it completely, in which case it'll be time to rewrite
  175. * this function in a totally different way.
  176. *
  177. * The only `properly' portable solution I can think of is to
  178. * implement my own format string scanner, which figures out an
  179. * upper bound for the length of each formatting directive,
  180. * allocates the buffer as it goes along, and calls sprintf() to
  181. * actually process each directive. If I ever need to actually do
  182. * this, some caveats:
  183. *
  184. * - It's very hard to find a reliable upper bound for
  185. * floating-point values. %f, in particular, when supplied with
  186. * a number near to the upper or lower limit of representable
  187. * numbers, could easily take several hundred characters. It's
  188. * probably feasible to predict this statically using the
  189. * constants in <float.h>, or even to predict it dynamically by
  190. * looking at the exponent of the specific float provided, but
  191. * it won't be fun.
  192. *
  193. * - Don't forget to _check_, after calling sprintf, that it's
  194. * used at most the amount of space we had available.
  195. *
  196. * - Fault any formatting directive we don't fully understand. The
  197. * aim here is to _guarantee_ that we never overflow the buffer,
  198. * because this is a security-critical function. If we see a
  199. * directive we don't know about, we should panic and die rather
  200. * than run any risk.
  201. */
  202. char *dupprintf(const char *fmt, ...)
  203. {
  204. char *ret;
  205. va_list ap;
  206. va_start(ap, fmt);
  207. ret = dupvprintf(fmt, ap);
  208. va_end(ap);
  209. return ret;
  210. }
  211. char *dupvprintf(const char *fmt, va_list ap)
  212. {
  213. char *buf;
  214. int len, size;
  215. buf = snewn(512, char);
  216. size = 512;
  217. while (1) {
  218. #ifdef _WINDOWS
  219. #define vsnprintf _vsnprintf
  220. #endif
  221. #ifdef va_copy
  222. /* Use the `va_copy' macro mandated by C99, if present.
  223. * XXX some environments may have this as __va_copy() */
  224. va_list aq;
  225. va_copy(aq, ap);
  226. len = vsnprintf(buf, size, fmt, aq);
  227. va_end(aq);
  228. #else
  229. /* Ugh. No va_copy macro, so do something nasty.
  230. * Technically, you can't reuse a va_list like this: it is left
  231. * unspecified whether advancing a va_list pointer modifies its
  232. * value or something it points to, so on some platforms calling
  233. * vsnprintf twice on the same va_list might fail hideously
  234. * (indeed, it has been observed to).
  235. * XXX the autoconf manual suggests that using memcpy() will give
  236. * "maximum portability". */
  237. len = vsnprintf(buf, size, fmt, ap);
  238. #endif
  239. if (len >= 0 && len < size) {
  240. /* This is the C99-specified criterion for snprintf to have
  241. * been completely successful. */
  242. return buf;
  243. } else if (len > 0) {
  244. /* This is the C99 error condition: the returned length is
  245. * the required buffer size not counting the NUL. */
  246. size = len + 1;
  247. } else {
  248. /* This is the pre-C99 glibc error condition: <0 means the
  249. * buffer wasn't big enough, so we enlarge it a bit and hope. */
  250. size += 512;
  251. }
  252. buf = sresize(buf, size, char);
  253. }
  254. }
  255. /*
  256. * Read an entire line of text from a file. Return a buffer
  257. * malloced to be as big as necessary (caller must free).
  258. */
  259. char *fgetline(FILE *fp)
  260. {
  261. char *ret = snewn(512, char);
  262. int size = 512, len = 0;
  263. while (fgets(ret + len, size - len, fp)) {
  264. len += strlen(ret + len);
  265. if (ret[len-1] == '\n')
  266. break; /* got a newline, we're done */
  267. size = len + 512;
  268. ret = sresize(ret, size, char);
  269. }
  270. if (len == 0) { /* first fgets returned NULL */
  271. sfree(ret);
  272. return NULL;
  273. }
  274. ret[len] = '\0';
  275. return ret;
  276. }
  277. /* ----------------------------------------------------------------------
  278. * Base64 encoding routine. This is required in public-key writing
  279. * but also in HTTP proxy handling, so it's centralised here.
  280. */
  281. void base64_encode_atom(unsigned char *data, int n, char *out)
  282. {
  283. static const char base64_chars[] =
  284. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  285. unsigned word;
  286. word = data[0] << 16;
  287. if (n > 1)
  288. word |= data[1] << 8;
  289. if (n > 2)
  290. word |= data[2];
  291. out[0] = base64_chars[(word >> 18) & 0x3F];
  292. out[1] = base64_chars[(word >> 12) & 0x3F];
  293. if (n > 1)
  294. out[2] = base64_chars[(word >> 6) & 0x3F];
  295. else
  296. out[2] = '=';
  297. if (n > 2)
  298. out[3] = base64_chars[word & 0x3F];
  299. else
  300. out[3] = '=';
  301. }
  302. /* ----------------------------------------------------------------------
  303. * Generic routines to deal with send buffers: a linked list of
  304. * smallish blocks, with the operations
  305. *
  306. * - add an arbitrary amount of data to the end of the list
  307. * - remove the first N bytes from the list
  308. * - return a (pointer,length) pair giving some initial data in
  309. * the list, suitable for passing to a send or write system
  310. * call
  311. * - retrieve a larger amount of initial data from the list
  312. * - return the current size of the buffer chain in bytes
  313. */
  314. #define BUFFER_GRANULE 512
  315. struct bufchain_granule {
  316. struct bufchain_granule *next;
  317. int buflen, bufpos;
  318. char buf[BUFFER_GRANULE];
  319. };
  320. void bufchain_init(bufchain *ch)
  321. {
  322. ch->head = ch->tail = NULL;
  323. ch->buffersize = 0;
  324. }
  325. void bufchain_clear(bufchain *ch)
  326. {
  327. struct bufchain_granule *b;
  328. while (ch->head) {
  329. b = ch->head;
  330. ch->head = ch->head->next;
  331. sfree(b);
  332. }
  333. ch->tail = NULL;
  334. ch->buffersize = 0;
  335. }
  336. int bufchain_size(bufchain *ch)
  337. {
  338. return ch->buffersize;
  339. }
  340. void bufchain_add(bufchain *ch, const void *data, int len)
  341. {
  342. const char *buf = (const char *)data;
  343. if (len == 0) return;
  344. ch->buffersize += len;
  345. if (ch->tail && ch->tail->buflen < BUFFER_GRANULE) {
  346. int copylen = min(len, BUFFER_GRANULE - ch->tail->buflen);
  347. memcpy(ch->tail->buf + ch->tail->buflen, buf, copylen);
  348. buf += copylen;
  349. len -= copylen;
  350. ch->tail->buflen += copylen;
  351. }
  352. while (len > 0) {
  353. int grainlen = min(len, BUFFER_GRANULE);
  354. struct bufchain_granule *newbuf;
  355. newbuf = snew(struct bufchain_granule);
  356. newbuf->bufpos = 0;
  357. newbuf->buflen = grainlen;
  358. memcpy(newbuf->buf, buf, grainlen);
  359. buf += grainlen;
  360. len -= grainlen;
  361. if (ch->tail)
  362. ch->tail->next = newbuf;
  363. else
  364. ch->head = ch->tail = newbuf;
  365. newbuf->next = NULL;
  366. ch->tail = newbuf;
  367. }
  368. }
  369. void bufchain_consume(bufchain *ch, int len)
  370. {
  371. struct bufchain_granule *tmp;
  372. assert(ch->buffersize >= len);
  373. while (len > 0) {
  374. int remlen = len;
  375. assert(ch->head != NULL);
  376. if (remlen >= ch->head->buflen - ch->head->bufpos) {
  377. remlen = ch->head->buflen - ch->head->bufpos;
  378. tmp = ch->head;
  379. ch->head = tmp->next;
  380. sfree(tmp);
  381. if (!ch->head)
  382. ch->tail = NULL;
  383. } else
  384. ch->head->bufpos += remlen;
  385. ch->buffersize -= remlen;
  386. len -= remlen;
  387. }
  388. }
  389. void bufchain_prefix(bufchain *ch, void **data, int *len)
  390. {
  391. *len = ch->head->buflen - ch->head->bufpos;
  392. *data = ch->head->buf + ch->head->bufpos;
  393. }
  394. void bufchain_fetch(bufchain *ch, void *data, int len)
  395. {
  396. struct bufchain_granule *tmp;
  397. char *data_c = (char *)data;
  398. tmp = ch->head;
  399. assert(ch->buffersize >= len);
  400. while (len > 0) {
  401. int remlen = len;
  402. assert(tmp != NULL);
  403. if (remlen >= tmp->buflen - tmp->bufpos)
  404. remlen = tmp->buflen - tmp->bufpos;
  405. memcpy(data_c, tmp->buf + tmp->bufpos, remlen);
  406. tmp = tmp->next;
  407. len -= remlen;
  408. data_c += remlen;
  409. }
  410. }
  411. /* ----------------------------------------------------------------------
  412. * My own versions of malloc, realloc and free. Because I want
  413. * malloc and realloc to bomb out and exit the program if they run
  414. * out of memory, realloc to reliably call malloc if passed a NULL
  415. * pointer, and free to reliably do nothing if passed a NULL
  416. * pointer. We can also put trace printouts in, if we need to; and
  417. * we can also replace the allocator with an ElectricFence-like
  418. * one.
  419. */
  420. #ifdef MINEFIELD
  421. void *minefield_c_malloc(size_t size);
  422. void minefield_c_free(void *p);
  423. void *minefield_c_realloc(void *p, size_t size);
  424. #endif
  425. #ifdef MALLOC_LOG
  426. static FILE *fp = NULL;
  427. static char *mlog_file = NULL;
  428. static int mlog_line = 0;
  429. void mlog(char *file, int line)
  430. {
  431. mlog_file = file;
  432. mlog_line = line;
  433. if (!fp) {
  434. fp = fopen("putty_mem.log", "w");
  435. setvbuf(fp, NULL, _IONBF, BUFSIZ);
  436. }
  437. if (fp)
  438. fprintf(fp, "%s:%d: ", file, line);
  439. }
  440. #endif
  441. void *safemalloc(size_t n, size_t size)
  442. {
  443. void *p;
  444. if (n > INT_MAX / size) {
  445. p = NULL;
  446. } else {
  447. size *= n;
  448. if (size == 0) size = 1;
  449. #ifdef MINEFIELD
  450. p = minefield_c_malloc(size);
  451. #else
  452. p = malloc(size);
  453. #endif
  454. }
  455. if (!p) {
  456. char str[200];
  457. #ifdef MALLOC_LOG
  458. sprintf(str, "Out of memory! (%s:%d, size=%d)",
  459. mlog_file, mlog_line, size);
  460. fprintf(fp, "*** %s\n", str);
  461. fclose(fp);
  462. #else
  463. strcpy(str, "Out of memory!");
  464. #endif
  465. modalfatalbox(str);
  466. }
  467. #ifdef MALLOC_LOG
  468. if (fp)
  469. fprintf(fp, "malloc(%d) returns %p\n", size, p);
  470. #endif
  471. return p;
  472. }
  473. void *saferealloc(void *ptr, size_t n, size_t size)
  474. {
  475. void *p;
  476. if (n > INT_MAX / size) {
  477. p = NULL;
  478. } else {
  479. size *= n;
  480. if (!ptr) {
  481. #ifdef MINEFIELD
  482. p = minefield_c_malloc(size);
  483. #else
  484. p = malloc(size);
  485. #endif
  486. } else {
  487. #ifdef MINEFIELD
  488. p = minefield_c_realloc(ptr, size);
  489. #else
  490. p = realloc(ptr, size);
  491. #endif
  492. }
  493. }
  494. if (!p) {
  495. char str[200];
  496. #ifdef MALLOC_LOG
  497. sprintf(str, "Out of memory! (%s:%d, size=%d)",
  498. mlog_file, mlog_line, size);
  499. fprintf(fp, "*** %s\n", str);
  500. fclose(fp);
  501. #else
  502. strcpy(str, "Out of memory!");
  503. #endif
  504. modalfatalbox(str);
  505. }
  506. #ifdef MALLOC_LOG
  507. if (fp)
  508. fprintf(fp, "realloc(%p,%d) returns %p\n", ptr, size, p);
  509. #endif
  510. return p;
  511. }
  512. void safefree(void *ptr)
  513. {
  514. if (ptr) {
  515. #ifdef MALLOC_LOG
  516. if (fp)
  517. fprintf(fp, "free(%p)\n", ptr);
  518. #endif
  519. #ifdef MINEFIELD
  520. minefield_c_free(ptr);
  521. #else
  522. free(ptr);
  523. #endif
  524. }
  525. #ifdef MALLOC_LOG
  526. else if (fp)
  527. fprintf(fp, "freeing null pointer - no action taken\n");
  528. #endif
  529. }
  530. /* ----------------------------------------------------------------------
  531. * Debugging routines.
  532. */
  533. #ifdef DEBUG
  534. extern void dputs(char *); /* defined in per-platform *misc.c */
  535. void debug_printf(char *fmt, ...)
  536. {
  537. char *buf;
  538. va_list ap;
  539. va_start(ap, fmt);
  540. buf = dupvprintf(fmt, ap);
  541. dputs(buf);
  542. sfree(buf);
  543. va_end(ap);
  544. }
  545. void debug_memdump(void *buf, int len, int L)
  546. {
  547. int i;
  548. unsigned char *p = buf;
  549. char foo[17];
  550. if (L) {
  551. int delta;
  552. debug_printf("\t%d (0x%x) bytes:\n", len, len);
  553. delta = 15 & (int) p;
  554. p -= delta;
  555. len += delta;
  556. }
  557. for (; 0 < len; p += 16, len -= 16) {
  558. dputs(" ");
  559. if (L)
  560. debug_printf("%p: ", p);
  561. strcpy(foo, "................"); /* sixteen dots */
  562. for (i = 0; i < 16 && i < len; ++i) {
  563. if (&p[i] < (unsigned char *) buf) {
  564. dputs(" "); /* 3 spaces */
  565. foo[i] = ' ';
  566. } else {
  567. debug_printf("%c%02.2x",
  568. &p[i] != (unsigned char *) buf
  569. && i % 4 ? '.' : ' ', p[i]
  570. );
  571. if (p[i] >= ' ' && p[i] <= '~')
  572. foo[i] = (char) p[i];
  573. }
  574. }
  575. foo[i] = '\0';
  576. debug_printf("%*s%s\n", (16 - i) * 3 + 2, "", foo);
  577. }
  578. }
  579. #endif /* def DEBUG */
  580. /*
  581. * Determine whether or not a Config structure represents a session
  582. * which can sensibly be launched right now.
  583. */
  584. int cfg_launchable(const Config *cfg)
  585. {
  586. if (cfg->protocol == PROT_SERIAL)
  587. return cfg->serline[0] != 0;
  588. else
  589. return cfg->host[0] != 0;
  590. }
  591. char const *cfg_dest(const Config *cfg)
  592. {
  593. if (cfg->protocol == PROT_SERIAL)
  594. return cfg->serline;
  595. else
  596. return cfg->host;
  597. }