2 * Platform-independent routines shared between all PuTTY programs.
14 * Parse a string block size specification. This is approximately a
15 * subset of the block size specs supported by GNU fileutils:
19 * All numbers are decimal, and suffixes refer to powers of two.
22 unsigned long parse_blocksize(const char *bs)
25 unsigned long r = strtoul(bs, &suf, 10);
27 while (*suf && isspace((unsigned char)*suf)) suf++;
36 r *= 1024ul * 1024ul * 1024ul;
47 * Parse a ^C style character specification.
48 * Returns NULL in `next' if we didn't recognise it as a control character,
49 * in which case `c' should be ignored.
50 * The precise current parsing is an oddity inherited from the terminal
51 * answerback-string parsing code. All sequences start with ^; all except
52 * ^<123> are two characters. The ones that are worth keeping are probably:
56 * <num> specified by number (decimal, 0octal, 0xHEX)
59 char ctrlparse(char *s, char **next)
68 } else if (*s == '<') {
70 c = (char)strtol(s, next, 0);
71 if ((*next == s) || (**next != '>')) {
76 } else if (*s >= 'a' && *s <= 'z') {
79 } else if ((*s >= '@' && *s <= '_') || *s == '?' || (*s & 0x80)) {
82 } else if (*s == '~') {
91 * Find a character in a string, unless it's a colon contained within
92 * square brackets. Used for untangling strings of the form
93 * 'host:port', where host can be an IPv6 literal.
95 * We provide several variants of this function, with semantics like
96 * various standard string.h functions.
98 static const char *host_strchr_internal(const char *s, const char *set,
102 const char *ret = NULL;
110 else if (*s == ']' && brackets > 0)
112 else if (brackets && *s == ':')
114 else if (strchr(set, *s)) {
123 size_t host_strcspn(const char *s, const char *set)
125 const char *answer = host_strchr_internal(s, set, TRUE);
131 char *host_strchr(const char *s, int c)
136 return (char *) host_strchr_internal(s, set, TRUE);
138 char *host_strrchr(const char *s, int c)
143 return (char *) host_strchr_internal(s, set, FALSE);
146 #ifdef TEST_HOST_STRFOO
149 int passes = 0, fails = 0;
151 #define TEST1(func, string, arg2, suffix, result) do \
153 const char *str = string; \
154 unsigned ret = func(string, arg2) suffix; \
155 if (ret == result) { \
158 printf("fail: %s(%s,%s)%s = %u, expected %u\n", \
159 #func, #string, #arg2, #suffix, ret, result); \
164 TEST1(host_strchr, "[1:2:3]:4:5", ':', -str, 7);
165 TEST1(host_strrchr, "[1:2:3]:4:5", ':', -str, 9);
166 TEST1(host_strcspn, "[1:2:3]:4:5", "/:",, 7);
167 TEST1(host_strchr, "[1:2:3]", ':', == NULL, 1);
168 TEST1(host_strrchr, "[1:2:3]", ':', == NULL, 1);
169 TEST1(host_strcspn, "[1:2:3]", "/:",, 7);
170 TEST1(host_strcspn, "[1:2/3]", "/:",, 4);
171 TEST1(host_strcspn, "[1:2:3]/", "/:",, 7);
173 printf("passed %d failed %d total %d\n", passes, fails, passes+fails);
174 return fails != 0 ? 1 : 0;
176 /* Stubs to stop the rest of this module causing compile failures. */
177 void modalfatalbox(char *fmt, ...) {}
178 int conf_get_int(Conf *conf, int primary) { return 0; }
179 char *conf_get_str(Conf *conf, int primary) { return NULL; }
180 #endif /* TEST_HOST_STRFOO */
183 * Trim square brackets off the outside of an IPv6 address literal.
184 * Leave all other strings unchanged. Returns a fresh dynamically
187 char *host_strduptrim(const char *s)
192 while (*p && *p != ']') {
193 if (isxdigit((unsigned char)*p))
201 if (*p == ']' && !p[1] && colons > 1) {
203 * This looks like an IPv6 address literal (hex digits and
204 * at least two colons, contained in square brackets).
205 * Trim off the brackets.
207 return dupprintf("%.*s", (int)(p - (s+1)), s+1);
212 * Any other shape of string is simply duplicated.
217 prompts_t *new_prompts(void *frontend)
219 prompts_t *p = snew(prompts_t);
222 p->frontend = frontend;
224 p->to_server = TRUE; /* to be on the safe side */
225 p->name = p->instruction = NULL;
226 p->name_reqd = p->instr_reqd = FALSE;
229 void add_prompt(prompts_t *p, char *promptstr, int echo)
231 prompt_t *pr = snew(prompt_t);
232 pr->prompt = promptstr;
237 p->prompts = sresize(p->prompts, p->n_prompts, prompt_t *);
238 p->prompts[p->n_prompts-1] = pr;
240 void prompt_ensure_result_size(prompt_t *pr, int newlen)
242 if ((int)pr->resultsize < newlen) {
244 newlen = newlen * 5 / 4 + 512; /* avoid too many small allocs */
247 * We don't use sresize / realloc here, because we will be
248 * storing sensitive stuff like passwords in here, and we want
249 * to make sure that the data doesn't get copied around in
250 * memory without the old copy being destroyed.
252 newbuf = snewn(newlen, char);
253 memcpy(newbuf, pr->result, pr->resultsize);
254 smemclr(pr->result, pr->resultsize);
257 pr->resultsize = newlen;
260 void prompt_set_result(prompt_t *pr, const char *newstr)
262 prompt_ensure_result_size(pr, strlen(newstr) + 1);
263 strcpy(pr->result, newstr);
265 void free_prompts(prompts_t *p)
268 for (i=0; i < p->n_prompts; i++) {
269 prompt_t *pr = p->prompts[i];
270 smemclr(pr->result, pr->resultsize); /* burn the evidence */
277 sfree(p->instruction);
281 /* ----------------------------------------------------------------------
282 * String handling routines.
285 char *dupstr(const char *s)
290 p = snewn(len + 1, char);
296 /* Allocate the concatenation of N strings. Terminate arg list with NULL. */
297 char *dupcat(const char *s1, ...)
306 sn = va_arg(ap, char *);
313 p = snewn(len + 1, char);
319 sn = va_arg(ap, char *);
330 void burnstr(char *string) /* sfree(str), only clear it first */
333 smemclr(string, strlen(string));
338 int toint(unsigned u)
341 * Convert an unsigned to an int, without running into the
342 * undefined behaviour which happens by the strict C standard if
343 * the value overflows. You'd hope that sensible compilers would
344 * do the sensible thing in response to a cast, but actually I
345 * don't trust modern compilers not to do silly things like
346 * assuming that _obviously_ you wouldn't have caused an overflow
347 * and so they can elide an 'if (i < 0)' test immediately after
350 * Sensible compilers ought of course to optimise this entire
351 * function into 'just return the input value'!
353 if (u <= (unsigned)INT_MAX)
355 else if (u >= (unsigned)INT_MIN) /* wrap in cast _to_ unsigned is OK */
356 return INT_MIN + (int)(u - (unsigned)INT_MIN);
358 return INT_MIN; /* fallback; should never occur on binary machines */
362 * Do an sprintf(), but into a custom-allocated buffer.
364 * Currently I'm doing this via vsnprintf. This has worked so far,
365 * but it's not good, because vsnprintf is not available on all
366 * platforms. There's an ifdef to use `_vsnprintf', which seems
367 * to be the local name for it on Windows. Other platforms may
368 * lack it completely, in which case it'll be time to rewrite
369 * this function in a totally different way.
371 * The only `properly' portable solution I can think of is to
372 * implement my own format string scanner, which figures out an
373 * upper bound for the length of each formatting directive,
374 * allocates the buffer as it goes along, and calls sprintf() to
375 * actually process each directive. If I ever need to actually do
376 * this, some caveats:
378 * - It's very hard to find a reliable upper bound for
379 * floating-point values. %f, in particular, when supplied with
380 * a number near to the upper or lower limit of representable
381 * numbers, could easily take several hundred characters. It's
382 * probably feasible to predict this statically using the
383 * constants in <float.h>, or even to predict it dynamically by
384 * looking at the exponent of the specific float provided, but
387 * - Don't forget to _check_, after calling sprintf, that it's
388 * used at most the amount of space we had available.
390 * - Fault any formatting directive we don't fully understand. The
391 * aim here is to _guarantee_ that we never overflow the buffer,
392 * because this is a security-critical function. If we see a
393 * directive we don't know about, we should panic and die rather
396 char *dupprintf(const char *fmt, ...)
401 ret = dupvprintf(fmt, ap);
405 char *dupvprintf(const char *fmt, va_list ap)
410 buf = snewn(512, char);
415 #define vsnprintf _vsnprintf
418 /* Use the `va_copy' macro mandated by C99, if present.
419 * XXX some environments may have this as __va_copy() */
422 len = vsnprintf(buf, size, fmt, aq);
425 /* Ugh. No va_copy macro, so do something nasty.
426 * Technically, you can't reuse a va_list like this: it is left
427 * unspecified whether advancing a va_list pointer modifies its
428 * value or something it points to, so on some platforms calling
429 * vsnprintf twice on the same va_list might fail hideously
430 * (indeed, it has been observed to).
431 * XXX the autoconf manual suggests that using memcpy() will give
432 * "maximum portability". */
433 len = vsnprintf(buf, size, fmt, ap);
435 if (len >= 0 && len < size) {
436 /* This is the C99-specified criterion for snprintf to have
437 * been completely successful. */
439 } else if (len > 0) {
440 /* This is the C99 error condition: the returned length is
441 * the required buffer size not counting the NUL. */
444 /* This is the pre-C99 glibc error condition: <0 means the
445 * buffer wasn't big enough, so we enlarge it a bit and hope. */
448 buf = sresize(buf, size, char);
453 * Read an entire line of text from a file. Return a buffer
454 * malloced to be as big as necessary (caller must free).
456 char *fgetline(FILE *fp)
458 char *ret = snewn(512, char);
459 int size = 512, len = 0;
460 while (fgets(ret + len, size - len, fp)) {
461 len += strlen(ret + len);
462 if (ret[len-1] == '\n')
463 break; /* got a newline, we're done */
465 ret = sresize(ret, size, char);
467 if (len == 0) { /* first fgets returned NULL */
475 /* ----------------------------------------------------------------------
476 * Core base64 encoding and decoding routines.
479 void base64_encode_atom(unsigned char *data, int n, char *out)
481 static const char base64_chars[] =
482 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
486 word = data[0] << 16;
488 word |= data[1] << 8;
491 out[0] = base64_chars[(word >> 18) & 0x3F];
492 out[1] = base64_chars[(word >> 12) & 0x3F];
494 out[2] = base64_chars[(word >> 6) & 0x3F];
498 out[3] = base64_chars[word & 0x3F];
503 int base64_decode_atom(char *atom, unsigned char *out)
510 for (i = 0; i < 4; i++) {
512 if (c >= 'A' && c <= 'Z')
514 else if (c >= 'a' && c <= 'z')
516 else if (c >= '0' && c <= '9')
525 return 0; /* invalid atom */
529 if (vals[0] == -1 || vals[1] == -1)
531 if (vals[2] == -1 && vals[3] != -1)
536 else if (vals[2] != -1)
541 word = ((vals[0] << 18) |
542 (vals[1] << 12) | ((vals[2] & 0x3F) << 6) | (vals[3] & 0x3F));
543 out[0] = (word >> 16) & 0xFF;
545 out[1] = (word >> 8) & 0xFF;
547 out[2] = word & 0xFF;
551 /* ----------------------------------------------------------------------
552 * Generic routines to deal with send buffers: a linked list of
553 * smallish blocks, with the operations
555 * - add an arbitrary amount of data to the end of the list
556 * - remove the first N bytes from the list
557 * - return a (pointer,length) pair giving some initial data in
558 * the list, suitable for passing to a send or write system
560 * - retrieve a larger amount of initial data from the list
561 * - return the current size of the buffer chain in bytes
564 #define BUFFER_MIN_GRANULE 512
566 struct bufchain_granule {
567 struct bufchain_granule *next;
568 char *bufpos, *bufend, *bufmax;
571 void bufchain_init(bufchain *ch)
573 ch->head = ch->tail = NULL;
577 void bufchain_clear(bufchain *ch)
579 struct bufchain_granule *b;
582 ch->head = ch->head->next;
589 int bufchain_size(bufchain *ch)
591 return ch->buffersize;
594 void bufchain_add(bufchain *ch, const void *data, int len)
596 const char *buf = (const char *)data;
598 if (len == 0) return;
600 ch->buffersize += len;
603 if (ch->tail && ch->tail->bufend < ch->tail->bufmax) {
604 int copylen = min(len, ch->tail->bufmax - ch->tail->bufend);
605 memcpy(ch->tail->bufend, buf, copylen);
608 ch->tail->bufend += copylen;
612 max(sizeof(struct bufchain_granule) + len, BUFFER_MIN_GRANULE);
613 struct bufchain_granule *newbuf;
614 newbuf = smalloc(grainlen);
615 newbuf->bufpos = newbuf->bufend =
616 (char *)newbuf + sizeof(struct bufchain_granule);
617 newbuf->bufmax = (char *)newbuf + grainlen;
620 ch->tail->next = newbuf;
628 void bufchain_consume(bufchain *ch, int len)
630 struct bufchain_granule *tmp;
632 assert(ch->buffersize >= len);
635 assert(ch->head != NULL);
636 if (remlen >= ch->head->bufend - ch->head->bufpos) {
637 remlen = ch->head->bufend - ch->head->bufpos;
639 ch->head = tmp->next;
644 ch->head->bufpos += remlen;
645 ch->buffersize -= remlen;
650 void bufchain_prefix(bufchain *ch, void **data, int *len)
652 *len = ch->head->bufend - ch->head->bufpos;
653 *data = ch->head->bufpos;
656 void bufchain_fetch(bufchain *ch, void *data, int len)
658 struct bufchain_granule *tmp;
659 char *data_c = (char *)data;
663 assert(ch->buffersize >= len);
668 if (remlen >= tmp->bufend - tmp->bufpos)
669 remlen = tmp->bufend - tmp->bufpos;
670 memcpy(data_c, tmp->bufpos, remlen);
678 /* ----------------------------------------------------------------------
679 * My own versions of malloc, realloc and free. Because I want
680 * malloc and realloc to bomb out and exit the program if they run
681 * out of memory, realloc to reliably call malloc if passed a NULL
682 * pointer, and free to reliably do nothing if passed a NULL
683 * pointer. We can also put trace printouts in, if we need to; and
684 * we can also replace the allocator with an ElectricFence-like
689 void *minefield_c_malloc(size_t size);
690 void minefield_c_free(void *p);
691 void *minefield_c_realloc(void *p, size_t size);
695 static FILE *fp = NULL;
697 static char *mlog_file = NULL;
698 static int mlog_line = 0;
700 void mlog(char *file, int line)
705 fp = fopen("putty_mem.log", "w");
706 setvbuf(fp, NULL, _IONBF, BUFSIZ);
709 fprintf(fp, "%s:%d: ", file, line);
713 void *safemalloc(size_t n, size_t size)
717 if (n > INT_MAX / size) {
721 if (size == 0) size = 1;
723 p = minefield_c_malloc(size);
732 sprintf(str, "Out of memory! (%s:%d, size=%d)",
733 mlog_file, mlog_line, size);
734 fprintf(fp, "*** %s\n", str);
737 strcpy(str, "Out of memory!");
743 fprintf(fp, "malloc(%d) returns %p\n", size, p);
748 void *saferealloc(void *ptr, size_t n, size_t size)
752 if (n > INT_MAX / size) {
758 p = minefield_c_malloc(size);
764 p = minefield_c_realloc(ptr, size);
766 p = realloc(ptr, size);
774 sprintf(str, "Out of memory! (%s:%d, size=%d)",
775 mlog_file, mlog_line, size);
776 fprintf(fp, "*** %s\n", str);
779 strcpy(str, "Out of memory!");
785 fprintf(fp, "realloc(%p,%d) returns %p\n", ptr, size, p);
790 void safefree(void *ptr)
795 fprintf(fp, "free(%p)\n", ptr);
798 minefield_c_free(ptr);
805 fprintf(fp, "freeing null pointer - no action taken\n");
809 /* ----------------------------------------------------------------------
810 * Debugging routines.
814 extern void dputs(char *); /* defined in per-platform *misc.c */
816 void debug_printf(char *fmt, ...)
822 buf = dupvprintf(fmt, ap);
829 void debug_memdump(void *buf, int len, int L)
832 unsigned char *p = buf;
836 debug_printf("\t%d (0x%x) bytes:\n", len, len);
837 delta = 15 & (unsigned long int) p;
841 for (; 0 < len; p += 16, len -= 16) {
844 debug_printf("%p: ", p);
845 strcpy(foo, "................"); /* sixteen dots */
846 for (i = 0; i < 16 && i < len; ++i) {
847 if (&p[i] < (unsigned char *) buf) {
848 dputs(" "); /* 3 spaces */
851 debug_printf("%c%02.2x",
852 &p[i] != (unsigned char *) buf
853 && i % 4 ? '.' : ' ', p[i]
855 if (p[i] >= ' ' && p[i] <= '~')
856 foo[i] = (char) p[i];
860 debug_printf("%*s%s\n", (16 - i) * 3 + 2, "", foo);
864 #endif /* def DEBUG */
867 * Determine whether or not a Conf represents a session which can
868 * sensibly be launched right now.
870 int conf_launchable(Conf *conf)
872 if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL)
873 return conf_get_str(conf, CONF_serline)[0] != 0;
875 return conf_get_str(conf, CONF_host)[0] != 0;
878 char const *conf_dest(Conf *conf)
880 if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL)
881 return conf_get_str(conf, CONF_serline);
883 return conf_get_str(conf, CONF_host);
886 #ifndef PLATFORM_HAS_SMEMCLR
888 * Securely wipe memory.
890 * The actual wiping is no different from what memset would do: the
891 * point of 'securely' is to try to be sure over-clever compilers
892 * won't optimise away memsets on variables that are about to be freed
893 * or go out of scope. See
894 * https://buildsecurityin.us-cert.gov/bsi-rules/home/g1/771-BSI.html
896 * Some platforms (e.g. Windows) may provide their own version of this
899 void smemclr(void *b, size_t n) {
904 * Zero out the memory.
909 * Perform a volatile access to the object, forcing the
910 * compiler to admit that the previous memset was important.
912 * This while loop should in practice run for zero iterations
913 * (since we know we just zeroed the object out), but in
914 * theory (as far as the compiler knows) it might range over
915 * the whole object. (If we had just written, say, '*vp =
916 * *vp;', a compiler could in principle have 'helpfully'
917 * optimised the memset into only zeroing out the first byte.
918 * This should be robust.)
927 * Validate a manual host key specification (either entered in the
928 * GUI, or via -hostkey). If valid, we return TRUE, and update 'key'
929 * to contain a canonicalised version of the key string in 'key'
930 * (which is guaranteed to take up at most as much space as the
931 * original version), suitable for putting into the Conf. If not
932 * valid, we return FALSE.
934 int validate_manual_hostkey(char *key)
939 * Step through the string word by word, looking for a word that's
940 * in one of the formats we like.
943 while ((p += strspn(p, " \t"))[0]) {
945 p += strcspn(p, " \t");
952 if (strlen(q) == 16*3 - 1 &&
953 q[strspn(q, "0123456789abcdefABCDEF:")] == 0) {
955 * Might be a key fingerprint. Check the colons are in the
956 * right places, and if so, return the same fingerprint
957 * canonicalised into lowercase.
960 for (i = 0; i < 16; i++)
961 if (q[3*i] == ':' || q[3*i+1] == ':')
962 goto not_fingerprint; /* sorry */
963 for (i = 0; i < 15; i++)
965 goto not_fingerprint; /* sorry */
966 for (i = 0; i < 16*3 - 1; i++)
967 key[i] = tolower(q[i]);
968 key[16*3 - 1] = '\0';
974 * Before we check for a public-key blob, trim newlines out of
975 * the middle of the word, in case someone's managed to paste
976 * in a public-key blob _with_ them.
978 for (r = s = q; *r; r++)
979 if (*r != '\n' && *r != '\r')
983 if (strlen(q) % 4 == 0 && strlen(q) > 2*4 &&
984 q[strspn(q, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
985 "abcdefghijklmnopqrstuvwxyz+/=")] == 0) {
987 * Might be a base64-encoded SSH-2 public key blob. Check
988 * that it starts with a sensible algorithm string. No
989 * canonicalisation is necessary for this string type.
991 * The algorithm string must be at most 64 characters long
992 * (RFC 4251 section 6).
994 unsigned char decoded[6];
999 len += base64_decode_atom(q, decoded+len);
1001 goto not_ssh2_blob; /* sorry */
1002 len += base64_decode_atom(q+4, decoded+len);
1004 goto not_ssh2_blob; /* sorry */
1006 alglen = GET_32BIT_MSB_FIRST(decoded);
1008 goto not_ssh2_blob; /* sorry */
1010 minlen = ((alglen + 4) + 2) / 3;
1011 if (strlen(q) < minlen)
1012 goto not_ssh2_blob; /* sorry */