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 * Base64 encoding routine. This is required in public-key writing
477 * but also in HTTP proxy handling, so it's centralised here.
480 void base64_encode_atom(unsigned char *data, int n, char *out)
482 static const char base64_chars[] =
483 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
487 word = data[0] << 16;
489 word |= data[1] << 8;
492 out[0] = base64_chars[(word >> 18) & 0x3F];
493 out[1] = base64_chars[(word >> 12) & 0x3F];
495 out[2] = base64_chars[(word >> 6) & 0x3F];
499 out[3] = base64_chars[word & 0x3F];
504 /* ----------------------------------------------------------------------
505 * Generic routines to deal with send buffers: a linked list of
506 * smallish blocks, with the operations
508 * - add an arbitrary amount of data to the end of the list
509 * - remove the first N bytes from the list
510 * - return a (pointer,length) pair giving some initial data in
511 * the list, suitable for passing to a send or write system
513 * - retrieve a larger amount of initial data from the list
514 * - return the current size of the buffer chain in bytes
517 #define BUFFER_MIN_GRANULE 512
519 struct bufchain_granule {
520 struct bufchain_granule *next;
521 char *bufpos, *bufend, *bufmax;
524 void bufchain_init(bufchain *ch)
526 ch->head = ch->tail = NULL;
530 void bufchain_clear(bufchain *ch)
532 struct bufchain_granule *b;
535 ch->head = ch->head->next;
542 int bufchain_size(bufchain *ch)
544 return ch->buffersize;
547 void bufchain_add(bufchain *ch, const void *data, int len)
549 const char *buf = (const char *)data;
551 if (len == 0) return;
553 ch->buffersize += len;
556 if (ch->tail && ch->tail->bufend < ch->tail->bufmax) {
557 int copylen = min(len, ch->tail->bufmax - ch->tail->bufend);
558 memcpy(ch->tail->bufend, buf, copylen);
561 ch->tail->bufend += copylen;
565 max(sizeof(struct bufchain_granule) + len, BUFFER_MIN_GRANULE);
566 struct bufchain_granule *newbuf;
567 newbuf = smalloc(grainlen);
568 newbuf->bufpos = newbuf->bufend =
569 (char *)newbuf + sizeof(struct bufchain_granule);
570 newbuf->bufmax = (char *)newbuf + grainlen;
573 ch->tail->next = newbuf;
581 void bufchain_consume(bufchain *ch, int len)
583 struct bufchain_granule *tmp;
585 assert(ch->buffersize >= len);
588 assert(ch->head != NULL);
589 if (remlen >= ch->head->bufend - ch->head->bufpos) {
590 remlen = ch->head->bufend - ch->head->bufpos;
592 ch->head = tmp->next;
597 ch->head->bufpos += remlen;
598 ch->buffersize -= remlen;
603 void bufchain_prefix(bufchain *ch, void **data, int *len)
605 *len = ch->head->bufend - ch->head->bufpos;
606 *data = ch->head->bufpos;
609 void bufchain_fetch(bufchain *ch, void *data, int len)
611 struct bufchain_granule *tmp;
612 char *data_c = (char *)data;
616 assert(ch->buffersize >= len);
621 if (remlen >= tmp->bufend - tmp->bufpos)
622 remlen = tmp->bufend - tmp->bufpos;
623 memcpy(data_c, tmp->bufpos, remlen);
631 /* ----------------------------------------------------------------------
632 * My own versions of malloc, realloc and free. Because I want
633 * malloc and realloc to bomb out and exit the program if they run
634 * out of memory, realloc to reliably call malloc if passed a NULL
635 * pointer, and free to reliably do nothing if passed a NULL
636 * pointer. We can also put trace printouts in, if we need to; and
637 * we can also replace the allocator with an ElectricFence-like
642 void *minefield_c_malloc(size_t size);
643 void minefield_c_free(void *p);
644 void *minefield_c_realloc(void *p, size_t size);
648 static FILE *fp = NULL;
650 static char *mlog_file = NULL;
651 static int mlog_line = 0;
653 void mlog(char *file, int line)
658 fp = fopen("putty_mem.log", "w");
659 setvbuf(fp, NULL, _IONBF, BUFSIZ);
662 fprintf(fp, "%s:%d: ", file, line);
666 void *safemalloc(size_t n, size_t size)
670 if (n > INT_MAX / size) {
674 if (size == 0) size = 1;
676 p = minefield_c_malloc(size);
685 sprintf(str, "Out of memory! (%s:%d, size=%d)",
686 mlog_file, mlog_line, size);
687 fprintf(fp, "*** %s\n", str);
690 strcpy(str, "Out of memory!");
696 fprintf(fp, "malloc(%d) returns %p\n", size, p);
701 void *saferealloc(void *ptr, size_t n, size_t size)
705 if (n > INT_MAX / size) {
711 p = minefield_c_malloc(size);
717 p = minefield_c_realloc(ptr, size);
719 p = realloc(ptr, size);
727 sprintf(str, "Out of memory! (%s:%d, size=%d)",
728 mlog_file, mlog_line, size);
729 fprintf(fp, "*** %s\n", str);
732 strcpy(str, "Out of memory!");
738 fprintf(fp, "realloc(%p,%d) returns %p\n", ptr, size, p);
743 void safefree(void *ptr)
748 fprintf(fp, "free(%p)\n", ptr);
751 minefield_c_free(ptr);
758 fprintf(fp, "freeing null pointer - no action taken\n");
762 /* ----------------------------------------------------------------------
763 * Debugging routines.
767 extern void dputs(char *); /* defined in per-platform *misc.c */
769 void debug_printf(char *fmt, ...)
775 buf = dupvprintf(fmt, ap);
782 void debug_memdump(void *buf, int len, int L)
785 unsigned char *p = buf;
789 debug_printf("\t%d (0x%x) bytes:\n", len, len);
790 delta = 15 & (unsigned long int) p;
794 for (; 0 < len; p += 16, len -= 16) {
797 debug_printf("%p: ", p);
798 strcpy(foo, "................"); /* sixteen dots */
799 for (i = 0; i < 16 && i < len; ++i) {
800 if (&p[i] < (unsigned char *) buf) {
801 dputs(" "); /* 3 spaces */
804 debug_printf("%c%02.2x",
805 &p[i] != (unsigned char *) buf
806 && i % 4 ? '.' : ' ', p[i]
808 if (p[i] >= ' ' && p[i] <= '~')
809 foo[i] = (char) p[i];
813 debug_printf("%*s%s\n", (16 - i) * 3 + 2, "", foo);
817 #endif /* def DEBUG */
820 * Determine whether or not a Conf represents a session which can
821 * sensibly be launched right now.
823 int conf_launchable(Conf *conf)
825 if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL)
826 return conf_get_str(conf, CONF_serline)[0] != 0;
828 return conf_get_str(conf, CONF_host)[0] != 0;
831 char const *conf_dest(Conf *conf)
833 if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL)
834 return conf_get_str(conf, CONF_serline);
836 return conf_get_str(conf, CONF_host);
839 #ifndef PLATFORM_HAS_SMEMCLR
841 * Securely wipe memory.
843 * The actual wiping is no different from what memset would do: the
844 * point of 'securely' is to try to be sure over-clever compilers
845 * won't optimise away memsets on variables that are about to be freed
846 * or go out of scope. See
847 * https://buildsecurityin.us-cert.gov/bsi-rules/home/g1/771-BSI.html
849 * Some platforms (e.g. Windows) may provide their own version of this
852 void smemclr(void *b, size_t n) {
857 * Zero out the memory.
862 * Perform a volatile access to the object, forcing the
863 * compiler to admit that the previous memset was important.
865 * This while loop should in practice run for zero iterations
866 * (since we know we just zeroed the object out), but in
867 * theory (as far as the compiler knows) it might range over
868 * the whole object. (If we had just written, say, '*vp =
869 * *vp;', a compiler could in principle have 'helpfully'
870 * optimised the memset into only zeroing out the first byte.
871 * This should be robust.)