2 * Platform-independent routines shared between all PuTTY programs.
15 * Parse a string block size specification. This is approximately a
16 * subset of the block size specs supported by GNU fileutils:
20 * All numbers are decimal, and suffixes refer to powers of two.
23 unsigned long parse_blocksize(const char *bs)
26 unsigned long r = strtoul(bs, &suf, 10);
28 while (*suf && isspace((unsigned char)*suf)) suf++;
37 r *= 1024ul * 1024ul * 1024ul;
48 * Parse a ^C style character specification.
49 * Returns NULL in `next' if we didn't recognise it as a control character,
50 * in which case `c' should be ignored.
51 * The precise current parsing is an oddity inherited from the terminal
52 * answerback-string parsing code. All sequences start with ^; all except
53 * ^<123> are two characters. The ones that are worth keeping are probably:
57 * <num> specified by number (decimal, 0octal, 0xHEX)
60 char ctrlparse(char *s, char **next)
69 } else if (*s == '<') {
71 c = (char)strtol(s, next, 0);
72 if ((*next == s) || (**next != '>')) {
77 } else if (*s >= 'a' && *s <= 'z') {
80 } else if ((*s >= '@' && *s <= '_') || *s == '?' || (*s & 0x80)) {
83 } else if (*s == '~') {
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.
96 * We provide several variants of this function, with semantics like
97 * various standard string.h functions.
99 static const char *host_strchr_internal(const char *s, const char *set,
103 const char *ret = NULL;
111 else if (*s == ']' && brackets > 0)
113 else if (brackets && *s == ':')
115 else if (strchr(set, *s)) {
124 size_t host_strcspn(const char *s, const char *set)
126 const char *answer = host_strchr_internal(s, set, TRUE);
132 char *host_strchr(const char *s, int c)
137 return (char *) host_strchr_internal(s, set, TRUE);
139 char *host_strrchr(const char *s, int c)
144 return (char *) host_strchr_internal(s, set, FALSE);
147 #ifdef TEST_HOST_STRFOO
150 int passes = 0, fails = 0;
152 #define TEST1(func, string, arg2, suffix, result) do \
154 const char *str = string; \
155 unsigned ret = func(string, arg2) suffix; \
156 if (ret == result) { \
159 printf("fail: %s(%s,%s)%s = %u, expected %u\n", \
160 #func, #string, #arg2, #suffix, ret, result); \
165 TEST1(host_strchr, "[1:2:3]:4:5", ':', -str, 7);
166 TEST1(host_strrchr, "[1:2:3]:4:5", ':', -str, 9);
167 TEST1(host_strcspn, "[1:2:3]:4:5", "/:",, 7);
168 TEST1(host_strchr, "[1:2:3]", ':', == NULL, 1);
169 TEST1(host_strrchr, "[1:2:3]", ':', == NULL, 1);
170 TEST1(host_strcspn, "[1:2:3]", "/:",, 7);
171 TEST1(host_strcspn, "[1:2/3]", "/:",, 4);
172 TEST1(host_strcspn, "[1:2:3]/", "/:",, 7);
174 printf("passed %d failed %d total %d\n", passes, fails, passes+fails);
175 return fails != 0 ? 1 : 0;
177 /* Stubs to stop the rest of this module causing compile failures. */
178 void modalfatalbox(char *fmt, ...) {}
179 int conf_get_int(Conf *conf, int primary) { return 0; }
180 char *conf_get_str(Conf *conf, int primary) { return NULL; }
181 #endif /* TEST_HOST_STRFOO */
184 * Trim square brackets off the outside of an IPv6 address literal.
185 * Leave all other strings unchanged. Returns a fresh dynamically
188 char *host_strduptrim(const char *s)
193 while (*p && *p != ']') {
194 if (isxdigit((unsigned char)*p))
202 if (*p == ']' && !p[1] && colons > 1) {
204 * This looks like an IPv6 address literal (hex digits and
205 * at least two colons, contained in square brackets).
206 * Trim off the brackets.
208 return dupprintf("%.*s", (int)(p - (s+1)), s+1);
213 * Any other shape of string is simply duplicated.
218 prompts_t *new_prompts(void *frontend)
220 prompts_t *p = snew(prompts_t);
223 p->frontend = frontend;
225 p->to_server = TRUE; /* to be on the safe side */
226 p->name = p->instruction = NULL;
227 p->name_reqd = p->instr_reqd = FALSE;
230 void add_prompt(prompts_t *p, char *promptstr, int echo)
232 prompt_t *pr = snew(prompt_t);
233 pr->prompt = promptstr;
238 p->prompts = sresize(p->prompts, p->n_prompts, prompt_t *);
239 p->prompts[p->n_prompts-1] = pr;
241 void prompt_ensure_result_size(prompt_t *pr, int newlen)
243 if ((int)pr->resultsize < newlen) {
245 newlen = newlen * 5 / 4 + 512; /* avoid too many small allocs */
248 * We don't use sresize / realloc here, because we will be
249 * storing sensitive stuff like passwords in here, and we want
250 * to make sure that the data doesn't get copied around in
251 * memory without the old copy being destroyed.
253 newbuf = snewn(newlen, char);
254 memcpy(newbuf, pr->result, pr->resultsize);
255 smemclr(pr->result, pr->resultsize);
258 pr->resultsize = newlen;
261 void prompt_set_result(prompt_t *pr, const char *newstr)
263 prompt_ensure_result_size(pr, strlen(newstr) + 1);
264 strcpy(pr->result, newstr);
266 void free_prompts(prompts_t *p)
269 for (i=0; i < p->n_prompts; i++) {
270 prompt_t *pr = p->prompts[i];
271 smemclr(pr->result, pr->resultsize); /* burn the evidence */
278 sfree(p->instruction);
282 /* ----------------------------------------------------------------------
283 * String handling routines.
286 char *dupstr(const char *s)
291 p = snewn(len + 1, char);
297 /* Allocate the concatenation of N strings. Terminate arg list with NULL. */
298 char *dupcat(const char *s1, ...)
307 sn = va_arg(ap, char *);
314 p = snewn(len + 1, char);
320 sn = va_arg(ap, char *);
331 void burnstr(char *string) /* sfree(str), only clear it first */
334 smemclr(string, strlen(string));
339 int toint(unsigned u)
342 * Convert an unsigned to an int, without running into the
343 * undefined behaviour which happens by the strict C standard if
344 * the value overflows. You'd hope that sensible compilers would
345 * do the sensible thing in response to a cast, but actually I
346 * don't trust modern compilers not to do silly things like
347 * assuming that _obviously_ you wouldn't have caused an overflow
348 * and so they can elide an 'if (i < 0)' test immediately after
351 * Sensible compilers ought of course to optimise this entire
352 * function into 'just return the input value'!
354 if (u <= (unsigned)INT_MAX)
356 else if (u >= (unsigned)INT_MIN) /* wrap in cast _to_ unsigned is OK */
357 return INT_MIN + (int)(u - (unsigned)INT_MIN);
359 return INT_MIN; /* fallback; should never occur on binary machines */
363 * Do an sprintf(), but into a custom-allocated buffer.
365 * Currently I'm doing this via vsnprintf. This has worked so far,
366 * but it's not good, because vsnprintf is not available on all
367 * platforms. There's an ifdef to use `_vsnprintf', which seems
368 * to be the local name for it on Windows. Other platforms may
369 * lack it completely, in which case it'll be time to rewrite
370 * this function in a totally different way.
372 * The only `properly' portable solution I can think of is to
373 * implement my own format string scanner, which figures out an
374 * upper bound for the length of each formatting directive,
375 * allocates the buffer as it goes along, and calls sprintf() to
376 * actually process each directive. If I ever need to actually do
377 * this, some caveats:
379 * - It's very hard to find a reliable upper bound for
380 * floating-point values. %f, in particular, when supplied with
381 * a number near to the upper or lower limit of representable
382 * numbers, could easily take several hundred characters. It's
383 * probably feasible to predict this statically using the
384 * constants in <float.h>, or even to predict it dynamically by
385 * looking at the exponent of the specific float provided, but
388 * - Don't forget to _check_, after calling sprintf, that it's
389 * used at most the amount of space we had available.
391 * - Fault any formatting directive we don't fully understand. The
392 * aim here is to _guarantee_ that we never overflow the buffer,
393 * because this is a security-critical function. If we see a
394 * directive we don't know about, we should panic and die rather
397 char *dupprintf(const char *fmt, ...)
402 ret = dupvprintf(fmt, ap);
406 char *dupvprintf(const char *fmt, va_list ap)
411 buf = snewn(512, char);
416 #define vsnprintf _vsnprintf
419 /* Use the `va_copy' macro mandated by C99, if present.
420 * XXX some environments may have this as __va_copy() */
423 len = vsnprintf(buf, size, fmt, aq);
426 /* Ugh. No va_copy macro, so do something nasty.
427 * Technically, you can't reuse a va_list like this: it is left
428 * unspecified whether advancing a va_list pointer modifies its
429 * value or something it points to, so on some platforms calling
430 * vsnprintf twice on the same va_list might fail hideously
431 * (indeed, it has been observed to).
432 * XXX the autoconf manual suggests that using memcpy() will give
433 * "maximum portability". */
434 len = vsnprintf(buf, size, fmt, ap);
436 if (len >= 0 && len < size) {
437 /* This is the C99-specified criterion for snprintf to have
438 * been completely successful. */
440 } else if (len > 0) {
441 /* This is the C99 error condition: the returned length is
442 * the required buffer size not counting the NUL. */
445 /* This is the pre-C99 glibc error condition: <0 means the
446 * buffer wasn't big enough, so we enlarge it a bit and hope. */
449 buf = sresize(buf, size, char);
454 * Read an entire line of text from a file. Return a buffer
455 * malloced to be as big as necessary (caller must free).
457 char *fgetline(FILE *fp)
459 char *ret = snewn(512, char);
460 int size = 512, len = 0;
461 while (fgets(ret + len, size - len, fp)) {
462 len += strlen(ret + len);
463 if (ret[len-1] == '\n')
464 break; /* got a newline, we're done */
466 ret = sresize(ret, size, char);
468 if (len == 0) { /* first fgets returned NULL */
477 * Perl-style 'chomp', for a line we just read with fgetline. Unlike
478 * Perl chomp, however, we're deliberately forgiving of strange
479 * line-ending conventions. Also we forgive NULL on input, so you can
480 * just write 'line = chomp(fgetline(fp));' and not bother checking
481 * for NULL until afterwards.
483 char *chomp(char *str)
486 int len = strlen(str);
487 while (len > 0 && (str[len-1] == '\r' || str[len-1] == '\n'))
494 /* ----------------------------------------------------------------------
495 * Core base64 encoding and decoding routines.
498 void base64_encode_atom(const unsigned char *data, int n, char *out)
500 static const char base64_chars[] =
501 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
505 word = data[0] << 16;
507 word |= data[1] << 8;
510 out[0] = base64_chars[(word >> 18) & 0x3F];
511 out[1] = base64_chars[(word >> 12) & 0x3F];
513 out[2] = base64_chars[(word >> 6) & 0x3F];
517 out[3] = base64_chars[word & 0x3F];
522 int base64_decode_atom(const char *atom, unsigned char *out)
529 for (i = 0; i < 4; i++) {
531 if (c >= 'A' && c <= 'Z')
533 else if (c >= 'a' && c <= 'z')
535 else if (c >= '0' && c <= '9')
544 return 0; /* invalid atom */
548 if (vals[0] == -1 || vals[1] == -1)
550 if (vals[2] == -1 && vals[3] != -1)
555 else if (vals[2] != -1)
560 word = ((vals[0] << 18) |
561 (vals[1] << 12) | ((vals[2] & 0x3F) << 6) | (vals[3] & 0x3F));
562 out[0] = (word >> 16) & 0xFF;
564 out[1] = (word >> 8) & 0xFF;
566 out[2] = word & 0xFF;
570 /* ----------------------------------------------------------------------
571 * Generic routines to deal with send buffers: a linked list of
572 * smallish blocks, with the operations
574 * - add an arbitrary amount of data to the end of the list
575 * - remove the first N bytes from the list
576 * - return a (pointer,length) pair giving some initial data in
577 * the list, suitable for passing to a send or write system
579 * - retrieve a larger amount of initial data from the list
580 * - return the current size of the buffer chain in bytes
583 #define BUFFER_MIN_GRANULE 512
585 struct bufchain_granule {
586 struct bufchain_granule *next;
587 char *bufpos, *bufend, *bufmax;
590 void bufchain_init(bufchain *ch)
592 ch->head = ch->tail = NULL;
596 void bufchain_clear(bufchain *ch)
598 struct bufchain_granule *b;
601 ch->head = ch->head->next;
608 int bufchain_size(bufchain *ch)
610 return ch->buffersize;
613 void bufchain_add(bufchain *ch, const void *data, int len)
615 const char *buf = (const char *)data;
617 if (len == 0) return;
619 ch->buffersize += len;
622 if (ch->tail && ch->tail->bufend < ch->tail->bufmax) {
623 int copylen = min(len, ch->tail->bufmax - ch->tail->bufend);
624 memcpy(ch->tail->bufend, buf, copylen);
627 ch->tail->bufend += copylen;
631 max(sizeof(struct bufchain_granule) + len, BUFFER_MIN_GRANULE);
632 struct bufchain_granule *newbuf;
633 newbuf = smalloc(grainlen);
634 newbuf->bufpos = newbuf->bufend =
635 (char *)newbuf + sizeof(struct bufchain_granule);
636 newbuf->bufmax = (char *)newbuf + grainlen;
639 ch->tail->next = newbuf;
647 void bufchain_consume(bufchain *ch, int len)
649 struct bufchain_granule *tmp;
651 assert(ch->buffersize >= len);
654 assert(ch->head != NULL);
655 if (remlen >= ch->head->bufend - ch->head->bufpos) {
656 remlen = ch->head->bufend - ch->head->bufpos;
658 ch->head = tmp->next;
663 ch->head->bufpos += remlen;
664 ch->buffersize -= remlen;
669 void bufchain_prefix(bufchain *ch, void **data, int *len)
671 *len = ch->head->bufend - ch->head->bufpos;
672 *data = ch->head->bufpos;
675 void bufchain_fetch(bufchain *ch, void *data, int len)
677 struct bufchain_granule *tmp;
678 char *data_c = (char *)data;
682 assert(ch->buffersize >= len);
687 if (remlen >= tmp->bufend - tmp->bufpos)
688 remlen = tmp->bufend - tmp->bufpos;
689 memcpy(data_c, tmp->bufpos, remlen);
697 /* ----------------------------------------------------------------------
698 * My own versions of malloc, realloc and free. Because I want
699 * malloc and realloc to bomb out and exit the program if they run
700 * out of memory, realloc to reliably call malloc if passed a NULL
701 * pointer, and free to reliably do nothing if passed a NULL
702 * pointer. We can also put trace printouts in, if we need to; and
703 * we can also replace the allocator with an ElectricFence-like
708 void *minefield_c_malloc(size_t size);
709 void minefield_c_free(void *p);
710 void *minefield_c_realloc(void *p, size_t size);
714 static FILE *fp = NULL;
716 static char *mlog_file = NULL;
717 static int mlog_line = 0;
719 void mlog(char *file, int line)
724 fp = fopen("putty_mem.log", "w");
725 setvbuf(fp, NULL, _IONBF, BUFSIZ);
728 fprintf(fp, "%s:%d: ", file, line);
732 void *safemalloc(size_t n, size_t size)
736 if (n > INT_MAX / size) {
740 if (size == 0) size = 1;
742 p = minefield_c_malloc(size);
751 sprintf(str, "Out of memory! (%s:%d, size=%d)",
752 mlog_file, mlog_line, size);
753 fprintf(fp, "*** %s\n", str);
756 strcpy(str, "Out of memory!");
762 fprintf(fp, "malloc(%d) returns %p\n", size, p);
767 void *saferealloc(void *ptr, size_t n, size_t size)
771 if (n > INT_MAX / size) {
777 p = minefield_c_malloc(size);
783 p = minefield_c_realloc(ptr, size);
785 p = realloc(ptr, size);
793 sprintf(str, "Out of memory! (%s:%d, size=%d)",
794 mlog_file, mlog_line, size);
795 fprintf(fp, "*** %s\n", str);
798 strcpy(str, "Out of memory!");
804 fprintf(fp, "realloc(%p,%d) returns %p\n", ptr, size, p);
809 void safefree(void *ptr)
814 fprintf(fp, "free(%p)\n", ptr);
817 minefield_c_free(ptr);
824 fprintf(fp, "freeing null pointer - no action taken\n");
828 /* ----------------------------------------------------------------------
829 * Debugging routines.
833 extern void dputs(char *); /* defined in per-platform *misc.c */
835 void debug_printf(const char *fmt, ...)
841 buf = dupvprintf(fmt, ap);
848 void debug_memdump(const void *buf, int len, int L)
851 const unsigned char *p = buf;
855 debug_printf("\t%d (0x%x) bytes:\n", len, len);
856 delta = 15 & (unsigned long int) p;
860 for (; 0 < len; p += 16, len -= 16) {
863 debug_printf("%p: ", p);
864 strcpy(foo, "................"); /* sixteen dots */
865 for (i = 0; i < 16 && i < len; ++i) {
866 if (&p[i] < (unsigned char *) buf) {
867 dputs(" "); /* 3 spaces */
870 debug_printf("%c%02.2x",
871 &p[i] != (unsigned char *) buf
872 && i % 4 ? '.' : ' ', p[i]
874 if (p[i] >= ' ' && p[i] <= '~')
875 foo[i] = (char) p[i];
879 debug_printf("%*s%s\n", (16 - i) * 3 + 2, "", foo);
883 #endif /* def DEBUG */
886 * Determine whether or not a Conf represents a session which can
887 * sensibly be launched right now.
889 int conf_launchable(Conf *conf)
891 if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL)
892 return conf_get_str(conf, CONF_serline)[0] != 0;
894 return conf_get_str(conf, CONF_host)[0] != 0;
897 char const *conf_dest(Conf *conf)
899 if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL)
900 return conf_get_str(conf, CONF_serline);
902 return conf_get_str(conf, CONF_host);
905 #ifndef PLATFORM_HAS_SMEMCLR
907 * Securely wipe memory.
909 * The actual wiping is no different from what memset would do: the
910 * point of 'securely' is to try to be sure over-clever compilers
911 * won't optimise away memsets on variables that are about to be freed
912 * or go out of scope. See
913 * https://buildsecurityin.us-cert.gov/bsi-rules/home/g1/771-BSI.html
915 * Some platforms (e.g. Windows) may provide their own version of this
918 void smemclr(void *b, size_t n) {
923 * Zero out the memory.
928 * Perform a volatile access to the object, forcing the
929 * compiler to admit that the previous memset was important.
931 * This while loop should in practice run for zero iterations
932 * (since we know we just zeroed the object out), but in
933 * theory (as far as the compiler knows) it might range over
934 * the whole object. (If we had just written, say, '*vp =
935 * *vp;', a compiler could in principle have 'helpfully'
936 * optimised the memset into only zeroing out the first byte.
937 * This should be robust.)
946 * Validate a manual host key specification (either entered in the
947 * GUI, or via -hostkey). If valid, we return TRUE, and update 'key'
948 * to contain a canonicalised version of the key string in 'key'
949 * (which is guaranteed to take up at most as much space as the
950 * original version), suitable for putting into the Conf. If not
951 * valid, we return FALSE.
953 int validate_manual_hostkey(char *key)
958 * Step through the string word by word, looking for a word that's
959 * in one of the formats we like.
962 while ((p += strspn(p, " \t"))[0]) {
964 p += strcspn(p, " \t");
971 if (strlen(q) == 16*3 - 1 &&
972 q[strspn(q, "0123456789abcdefABCDEF:")] == 0) {
974 * Might be a key fingerprint. Check the colons are in the
975 * right places, and if so, return the same fingerprint
976 * canonicalised into lowercase.
979 for (i = 0; i < 16; i++)
980 if (q[3*i] == ':' || q[3*i+1] == ':')
981 goto not_fingerprint; /* sorry */
982 for (i = 0; i < 15; i++)
984 goto not_fingerprint; /* sorry */
985 for (i = 0; i < 16*3 - 1; i++)
986 key[i] = tolower(q[i]);
987 key[16*3 - 1] = '\0';
993 * Before we check for a public-key blob, trim newlines out of
994 * the middle of the word, in case someone's managed to paste
995 * in a public-key blob _with_ them.
997 for (r = s = q; *r; r++)
998 if (*r != '\n' && *r != '\r')
1002 if (strlen(q) % 4 == 0 && strlen(q) > 2*4 &&
1003 q[strspn(q, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1004 "abcdefghijklmnopqrstuvwxyz+/=")] == 0) {
1006 * Might be a base64-encoded SSH-2 public key blob. Check
1007 * that it starts with a sensible algorithm string. No
1008 * canonicalisation is necessary for this string type.
1010 * The algorithm string must be at most 64 characters long
1011 * (RFC 4251 section 6).
1013 unsigned char decoded[6];
1018 len += base64_decode_atom(q, decoded+len);
1020 goto not_ssh2_blob; /* sorry */
1021 len += base64_decode_atom(q+4, decoded+len);
1023 goto not_ssh2_blob; /* sorry */
1025 alglen = GET_32BIT_MSB_FIRST(decoded);
1027 goto not_ssh2_blob; /* sorry */
1029 minlen = ((alglen + 4) + 2) / 3;
1030 if (strlen(q) < minlen)
1031 goto not_ssh2_blob; /* sorry */
1042 int smemeq(const void *av, const void *bv, size_t len)
1044 const unsigned char *a = (const unsigned char *)av;
1045 const unsigned char *b = (const unsigned char *)bv;
1051 /* Now val is 0 iff we want to return 1, and in the range
1052 * 0x01..0xFF iff we want to return 0. So subtracting from 0x100
1053 * will clear bit 8 iff we want to return 0, and leave it set iff
1054 * we want to return 1, so then we can just shift down. */
1055 return (0x100 - val) >> 8;
1058 int match_ssh_id(int stringlen, const void *string, const char *id)
1060 int idlen = strlen(id);
1061 return (idlen == stringlen && !memcmp(string, id, idlen));
1064 void *get_ssh_string(int *datalen, const void **data, int *stringlen)
1071 len = GET_32BIT_MSB_FIRST((const unsigned char *)*data);
1072 if (*datalen < len+4)
1074 ret = (void *)((const char *)*data + 4);
1075 *datalen -= len + 4;
1076 *data = (const char *)*data + len + 4;
1081 int get_ssh_uint32(int *datalen, const void **data, unsigned *ret)
1085 *ret = GET_32BIT_MSB_FIRST((const unsigned char *)*data);
1087 *data = (const char *)*data + 4;