]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - misc.c
first pass
[PuTTY.git] / misc.c
1 /*
2  * Platform-independent routines shared between all PuTTY programs.
3  */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <stdarg.h>
8 #include <limits.h>
9 #include <ctype.h>
10 #include <assert.h>
11 #include "putty.h"
12 #include "misc.h"
13
14 /*
15  * Parse a string block size specification. This is approximately a
16  * subset of the block size specs supported by GNU fileutils:
17  *  "nk" = n kilobytes
18  *  "nM" = n megabytes
19  *  "nG" = n gigabytes
20  * All numbers are decimal, and suffixes refer to powers of two.
21  * Case-insensitive.
22  */
23 unsigned long parse_blocksize(const char *bs)
24 {
25     char *suf;
26     unsigned long r = strtoul(bs, &suf, 10);
27     if (*suf != '\0') {
28         while (*suf && isspace((unsigned char)*suf)) suf++;
29         switch (*suf) {
30           case 'k': case 'K':
31             r *= 1024ul;
32             break;
33           case 'm': case 'M':
34             r *= 1024ul * 1024ul;
35             break;
36           case 'g': case 'G':
37             r *= 1024ul * 1024ul * 1024ul;
38             break;
39           case '\0':
40           default:
41             break;
42         }
43     }
44     return r;
45 }
46
47 /*
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:
54  *   ^?             127
55  *   ^@A-Z[\]^_     0-31
56  *   a-z            1-26
57  *   <num>          specified by number (decimal, 0octal, 0xHEX)
58  *   ~              ^ escape
59  */
60 char ctrlparse(char *s, char **next)
61 {
62     char c = 0;
63     if (*s != '^') {
64         *next = NULL;
65     } else {
66         s++;
67         if (*s == '\0') {
68             *next = NULL;
69         } else if (*s == '<') {
70             s++;
71             c = (char)strtol(s, next, 0);
72             if ((*next == s) || (**next != '>')) {
73                 c = 0;
74                 *next = NULL;
75             } else
76                 (*next)++;
77         } else if (*s >= 'a' && *s <= 'z') {
78             c = (*s - ('a' - 1));
79             *next = s+1;
80         } else if ((*s >= '@' && *s <= '_') || *s == '?' || (*s & 0x80)) {
81             c = ('@' ^ *s);
82             *next = s+1;
83         } else if (*s == '~') {
84             c = '^';
85             *next = s+1;
86         }
87     }
88     return c;
89 }
90
91 /*
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.
95  *
96  * We provide several variants of this function, with semantics like
97  * various standard string.h functions.
98  */
99 static const char *host_strchr_internal(const char *s, const char *set,
100                                         int first)
101 {
102     int brackets = 0;
103     const char *ret = NULL;
104
105     while (1) {
106         if (!*s)
107             return ret;
108
109         if (*s == '[')
110             brackets++;
111         else if (*s == ']' && brackets > 0)
112             brackets--;
113         else if (brackets && *s == ':')
114             /* never match */ ;
115         else if (strchr(set, *s)) {
116             ret = s;
117             if (first)
118                 return ret;
119         }
120
121         s++;
122     }
123 }
124 size_t host_strcspn(const char *s, const char *set)
125 {
126     const char *answer = host_strchr_internal(s, set, TRUE);
127     if (answer)
128         return answer - s;
129     else
130         return strlen(s);
131 }
132 char *host_strchr(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, TRUE);
138 }
139 char *host_strrchr(const char *s, int c)
140 {
141     char set[2];
142     set[0] = c;
143     set[1] = '\0';
144     return (char *) host_strchr_internal(s, set, FALSE);
145 }
146
147 #ifdef TEST_HOST_STRFOO
148 int main(void)
149 {
150     int passes = 0, fails = 0;
151
152 #define TEST1(func, string, arg2, suffix, result) do                    \
153     {                                                                   \
154         const char *str = string;                                       \
155         unsigned ret = func(string, arg2) suffix;                       \
156         if (ret == result) {                                            \
157             passes++;                                                   \
158         } else {                                                        \
159             printf("fail: %s(%s,%s)%s = %u, expected %u\n",             \
160                    #func, #string, #arg2, #suffix, ret, result);        \
161             fails++;                                                    \
162         }                                                               \
163 } while (0)
164
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);
173
174     printf("passed %d failed %d total %d\n", passes, fails, passes+fails);
175     return fails != 0 ? 1 : 0;
176 }
177 /* Stubs to stop the rest of this module causing compile failures. */
178 void modalfatalbox(const 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 */
182
183 /*
184  * Trim square brackets off the outside of an IPv6 address literal.
185  * Leave all other strings unchanged. Returns a fresh dynamically
186  * allocated string.
187  */
188 char *host_strduptrim(const char *s)
189 {
190     if (s[0] == '[') {
191         const char *p = s+1;
192         int colons = 0;
193         while (*p && *p != ']') {
194             if (isxdigit((unsigned char)*p))
195                 /* OK */;
196             else if (*p == ':')
197                 colons++;
198             else
199                 break;
200             p++;
201         }
202         if (*p == ']' && !p[1] && colons > 1) {
203             /*
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.
207              */
208             return dupprintf("%.*s", (int)(p - (s+1)), s+1);
209         }
210     }
211
212     /*
213      * Any other shape of string is simply duplicated.
214      */
215     return dupstr(s);
216 }
217
218 prompts_t *new_prompts(void *frontend)
219 {
220     prompts_t *p = snew(prompts_t);
221     p->prompts = NULL;
222     p->n_prompts = 0;
223     p->frontend = frontend;
224     p->data = NULL;
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;
228     return p;
229 }
230 void add_prompt(prompts_t *p, char *promptstr, int echo)
231 {
232     prompt_t *pr = snew(prompt_t);
233     pr->prompt = promptstr;
234     pr->echo = echo;
235     pr->result = NULL;
236     pr->resultsize = 0;
237     p->n_prompts++;
238     p->prompts = sresize(p->prompts, p->n_prompts, prompt_t *);
239     p->prompts[p->n_prompts-1] = pr;
240 }
241 void prompt_ensure_result_size(prompt_t *pr, int newlen)
242 {
243     if ((int)pr->resultsize < newlen) {
244         char *newbuf;
245         newlen = newlen * 5 / 4 + 512; /* avoid too many small allocs */
246
247         /*
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.
252          */
253         newbuf = snewn(newlen, char);
254         memcpy(newbuf, pr->result, pr->resultsize);
255         smemclr(pr->result, pr->resultsize);
256         sfree(pr->result);
257         pr->result = newbuf;
258         pr->resultsize = newlen;
259     }
260 }
261 void prompt_set_result(prompt_t *pr, const char *newstr)
262 {
263     prompt_ensure_result_size(pr, strlen(newstr) + 1);
264     strcpy(pr->result, newstr);
265 }
266 void free_prompts(prompts_t *p)
267 {
268     size_t i;
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 */
272         sfree(pr->result);
273         sfree(pr->prompt);
274         sfree(pr);
275     }
276     sfree(p->prompts);
277     sfree(p->name);
278     sfree(p->instruction);
279     sfree(p);
280 }
281
282 /* ----------------------------------------------------------------------
283  * String handling routines.
284  */
285
286 char *dupstr(const char *s)
287 {
288     char *p = NULL;
289     if (s) {
290         int len = strlen(s);
291         p = snewn(len + 1, char);
292         strcpy(p, s);
293     }
294     return p;
295 }
296
297 /* Allocate the concatenation of N strings. Terminate arg list with NULL. */
298 char *dupcat(const char *s1, ...)
299 {
300     int len;
301     char *p, *q, *sn;
302     va_list ap;
303
304     len = strlen(s1);
305     va_start(ap, s1);
306     while (1) {
307         sn = va_arg(ap, char *);
308         if (!sn)
309             break;
310         len += strlen(sn);
311     }
312     va_end(ap);
313
314     p = snewn(len + 1, char);
315     strcpy(p, s1);
316     q = p + strlen(p);
317
318     va_start(ap, s1);
319     while (1) {
320         sn = va_arg(ap, char *);
321         if (!sn)
322             break;
323         strcpy(q, sn);
324         q += strlen(q);
325     }
326     va_end(ap);
327
328     return p;
329 }
330
331 void burnstr(char *string)             /* sfree(str), only clear it first */
332 {
333     if (string) {
334         smemclr(string, strlen(string));
335         sfree(string);
336     }
337 }
338
339 int toint(unsigned u)
340 {
341     /*
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
349      * the cast.
350      *
351      * Sensible compilers ought of course to optimise this entire
352      * function into 'just return the input value'!
353      */
354     if (u <= (unsigned)INT_MAX)
355         return (int)u;
356     else if (u >= (unsigned)INT_MIN)   /* wrap in cast _to_ unsigned is OK */
357         return INT_MIN + (int)(u - (unsigned)INT_MIN);
358     else
359         return INT_MIN; /* fallback; should never occur on binary machines */
360 }
361
362 /*
363  * Do an sprintf(), but into a custom-allocated buffer.
364  * 
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.
371  * 
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:
378  * 
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
386  *    it won't be fun.
387  * 
388  *  - Don't forget to _check_, after calling sprintf, that it's
389  *    used at most the amount of space we had available.
390  * 
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
395  *    than run any risk.
396  */
397 static char *dupvprintf_inner(char *buf, int oldlen, int *oldsize,
398                               const char *fmt, va_list ap)
399 {
400     int len, size, newsize;
401
402     assert(*oldsize >= oldlen);
403     size = *oldsize - oldlen;
404     if (size == 0) {
405         size = 512;
406         newsize = oldlen + size;
407         buf = sresize(buf, newsize, char);
408     } else {
409         newsize = *oldsize;
410     }
411
412     while (1) {
413 #if defined _WINDOWS && !defined __WINE__ && _MSC_VER < 1900 /* 1900 == VS2015 has real snprintf */
414 #define vsnprintf _vsnprintf
415 #endif
416 #ifdef va_copy
417         /* Use the `va_copy' macro mandated by C99, if present.
418          * XXX some environments may have this as __va_copy() */
419         va_list aq;
420         va_copy(aq, ap);
421         len = vsnprintf(buf + oldlen, size, fmt, aq);
422         va_end(aq);
423 #else
424         /* Ugh. No va_copy macro, so do something nasty.
425          * Technically, you can't reuse a va_list like this: it is left
426          * unspecified whether advancing a va_list pointer modifies its
427          * value or something it points to, so on some platforms calling
428          * vsnprintf twice on the same va_list might fail hideously
429          * (indeed, it has been observed to).
430          * XXX the autoconf manual suggests that using memcpy() will give
431          *     "maximum portability". */
432         len = vsnprintf(buf + oldlen, size, fmt, ap);
433 #endif
434         if (len >= 0 && len < size) {
435             /* This is the C99-specified criterion for snprintf to have
436              * been completely successful. */
437             *oldsize = newsize;
438             return buf;
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. */
442             size = len + 1;
443         } else {
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. */
446             size += 512;
447         }
448         newsize = oldlen + size;
449         buf = sresize(buf, newsize, char);
450     }
451 }
452
453 char *dupvprintf(const char *fmt, va_list ap)
454 {
455     int size = 0;
456     return dupvprintf_inner(NULL, 0, &size, fmt, ap);
457 }
458 char *dupprintf(const char *fmt, ...)
459 {
460     char *ret;
461     va_list ap;
462     va_start(ap, fmt);
463     ret = dupvprintf(fmt, ap);
464     va_end(ap);
465     return ret;
466 }
467
468 struct strbuf {
469     char *s;
470     int len, size;
471 };
472 strbuf *strbuf_new(void)
473 {
474     strbuf *buf = snew(strbuf);
475     buf->len = 0;
476     buf->size = 512;
477     buf->s = snewn(buf->size, char);
478     *buf->s = '\0';
479     return buf;
480 }
481 void strbuf_free(strbuf *buf)
482 {
483     sfree(buf->s);
484     sfree(buf);
485 }
486 char *strbuf_str(strbuf *buf)
487 {
488     return buf->s;
489 }
490 char *strbuf_to_str(strbuf *buf)
491 {
492     char *ret = buf->s;
493     sfree(buf);
494     return ret;
495 }
496 void strbuf_catfv(strbuf *buf, const char *fmt, va_list ap)
497 {
498     buf->s = dupvprintf_inner(buf->s, buf->len, &buf->size, fmt, ap);
499     buf->len += strlen(buf->s + buf->len);
500 }
501 void strbuf_catf(strbuf *buf, const char *fmt, ...)
502 {
503     va_list ap;
504     va_start(ap, fmt);
505     strbuf_catfv(buf, fmt, ap);
506     va_end(ap);
507 }
508
509 /*
510  * Read an entire line of text from a file. Return a buffer
511  * malloced to be as big as necessary (caller must free).
512  */
513 char *fgetline(FILE *fp)
514 {
515     char *ret = snewn(512, char);
516     int size = 512, len = 0;
517     while (fgets(ret + len, size - len, fp)) {
518         len += strlen(ret + len);
519         if (len > 0 && ret[len-1] == '\n')
520             break;                     /* got a newline, we're done */
521         size = len + 512;
522         ret = sresize(ret, size, char);
523     }
524     if (len == 0) {                    /* first fgets returned NULL */
525         sfree(ret);
526         return NULL;
527     }
528     ret[len] = '\0';
529     return ret;
530 }
531
532 /*
533  * Perl-style 'chomp', for a line we just read with fgetline. Unlike
534  * Perl chomp, however, we're deliberately forgiving of strange
535  * line-ending conventions. Also we forgive NULL on input, so you can
536  * just write 'line = chomp(fgetline(fp));' and not bother checking
537  * for NULL until afterwards.
538  */
539 char *chomp(char *str)
540 {
541     if (str) {
542         int len = strlen(str);
543         while (len > 0 && (str[len-1] == '\r' || str[len-1] == '\n'))
544             len--;
545         str[len] = '\0';
546     }
547     return str;
548 }
549
550 /* ----------------------------------------------------------------------
551  * Core base64 encoding and decoding routines.
552  */
553
554 void base64_encode_atom(const unsigned char *data, int n, char *out)
555 {
556     static const char base64_chars[] =
557         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
558
559     unsigned word;
560
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
578 int base64_decode_atom(const char *atom, unsigned char *out)
579 {
580     int vals[4];
581     int i, v, len;
582     unsigned word;
583     char c;
584
585     for (i = 0; i < 4; i++) {
586         c = atom[i];
587         if (c >= 'A' && c <= 'Z')
588             v = c - 'A';
589         else if (c >= 'a' && c <= 'z')
590             v = c - 'a' + 26;
591         else if (c >= '0' && c <= '9')
592             v = c - '0' + 52;
593         else if (c == '+')
594             v = 62;
595         else if (c == '/')
596             v = 63;
597         else if (c == '=')
598             v = -1;
599         else
600             return 0;                  /* invalid atom */
601         vals[i] = v;
602     }
603
604     if (vals[0] == -1 || vals[1] == -1)
605         return 0;
606     if (vals[2] == -1 && vals[3] != -1)
607         return 0;
608
609     if (vals[3] != -1)
610         len = 3;
611     else if (vals[2] != -1)
612         len = 2;
613     else
614         len = 1;
615
616     word = ((vals[0] << 18) |
617             (vals[1] << 12) | ((vals[2] & 0x3F) << 6) | (vals[3] & 0x3F));
618     out[0] = (word >> 16) & 0xFF;
619     if (len > 1)
620         out[1] = (word >> 8) & 0xFF;
621     if (len > 2)
622         out[2] = word & 0xFF;
623     return len;
624 }
625
626 /* ----------------------------------------------------------------------
627  * Generic routines to deal with send buffers: a linked list of
628  * smallish blocks, with the operations
629  * 
630  *  - add an arbitrary amount of data to the end of the list
631  *  - remove the first N bytes from the list
632  *  - return a (pointer,length) pair giving some initial data in
633  *    the list, suitable for passing to a send or write system
634  *    call
635  *  - retrieve a larger amount of initial data from the list
636  *  - return the current size of the buffer chain in bytes
637  */
638
639 #define BUFFER_MIN_GRANULE  512
640
641 struct bufchain_granule {
642     struct bufchain_granule *next;
643     char *bufpos, *bufend, *bufmax;
644 };
645
646 void bufchain_init(bufchain *ch)
647 {
648     ch->head = ch->tail = NULL;
649     ch->buffersize = 0;
650 }
651
652 void bufchain_clear(bufchain *ch)
653 {
654     struct bufchain_granule *b;
655     while (ch->head) {
656         b = ch->head;
657         ch->head = ch->head->next;
658         sfree(b);
659     }
660     ch->tail = NULL;
661     ch->buffersize = 0;
662 }
663
664 int bufchain_size(bufchain *ch)
665 {
666     return ch->buffersize;
667 }
668
669 void bufchain_add(bufchain *ch, const void *data, int len)
670 {
671     const char *buf = (const char *)data;
672
673     if (len == 0) return;
674
675     ch->buffersize += len;
676
677     while (len > 0) {
678         if (ch->tail && ch->tail->bufend < ch->tail->bufmax) {
679             int copylen = min(len, ch->tail->bufmax - ch->tail->bufend);
680             memcpy(ch->tail->bufend, buf, copylen);
681             buf += copylen;
682             len -= copylen;
683             ch->tail->bufend += copylen;
684         }
685         if (len > 0) {
686             int grainlen =
687                 max(sizeof(struct bufchain_granule) + len, BUFFER_MIN_GRANULE);
688             struct bufchain_granule *newbuf;
689             newbuf = smalloc(grainlen);
690             newbuf->bufpos = newbuf->bufend =
691                 (char *)newbuf + sizeof(struct bufchain_granule);
692             newbuf->bufmax = (char *)newbuf + grainlen;
693             newbuf->next = NULL;
694             if (ch->tail)
695                 ch->tail->next = newbuf;
696             else
697                 ch->head = newbuf;
698             ch->tail = newbuf;
699         }
700     }
701 }
702
703 void bufchain_consume(bufchain *ch, int len)
704 {
705     struct bufchain_granule *tmp;
706
707     assert(ch->buffersize >= len);
708     while (len > 0) {
709         int remlen = len;
710         assert(ch->head != NULL);
711         if (remlen >= ch->head->bufend - ch->head->bufpos) {
712             remlen = ch->head->bufend - ch->head->bufpos;
713             tmp = ch->head;
714             ch->head = tmp->next;
715             if (!ch->head)
716                 ch->tail = NULL;
717             sfree(tmp);
718         } else
719             ch->head->bufpos += remlen;
720         ch->buffersize -= remlen;
721         len -= remlen;
722     }
723 }
724
725 void bufchain_prefix(bufchain *ch, void **data, int *len)
726 {
727     *len = ch->head->bufend - ch->head->bufpos;
728     *data = ch->head->bufpos;
729 }
730
731 void bufchain_fetch(bufchain *ch, void *data, int len)
732 {
733     struct bufchain_granule *tmp;
734     char *data_c = (char *)data;
735
736     tmp = ch->head;
737
738     assert(ch->buffersize >= len);
739     while (len > 0) {
740         int remlen = len;
741
742         assert(tmp != NULL);
743         if (remlen >= tmp->bufend - tmp->bufpos)
744             remlen = tmp->bufend - tmp->bufpos;
745         memcpy(data_c, tmp->bufpos, remlen);
746
747         tmp = tmp->next;
748         len -= remlen;
749         data_c += remlen;
750     }
751 }
752
753 /* ----------------------------------------------------------------------
754  * My own versions of malloc, realloc and free. Because I want
755  * malloc and realloc to bomb out and exit the program if they run
756  * out of memory, realloc to reliably call malloc if passed a NULL
757  * pointer, and free to reliably do nothing if passed a NULL
758  * pointer. We can also put trace printouts in, if we need to; and
759  * we can also replace the allocator with an ElectricFence-like
760  * one.
761  */
762
763 #ifdef MINEFIELD
764 void *minefield_c_malloc(size_t size);
765 void minefield_c_free(void *p);
766 void *minefield_c_realloc(void *p, size_t size);
767 #endif
768
769 #ifdef MALLOC_LOG
770 static FILE *fp = NULL;
771
772 static char *mlog_file = NULL;
773 static int mlog_line = 0;
774
775 void mlog(char *file, int line)
776 {
777     mlog_file = file;
778     mlog_line = line;
779     if (!fp) {
780         fp = fopen("putty_mem.log", "w");
781         setvbuf(fp, NULL, _IONBF, BUFSIZ);
782     }
783     if (fp)
784         fprintf(fp, "%s:%d: ", file, line);
785 }
786 #endif
787
788 void *safemalloc(size_t n, size_t size)
789 {
790     void *p;
791
792     if (n > INT_MAX / size) {
793         p = NULL;
794     } else {
795         size *= n;
796         if (size == 0) size = 1;
797 #ifdef MINEFIELD
798         p = minefield_c_malloc(size);
799 #else
800         p = malloc(size);
801 #endif
802     }
803
804     if (!p) {
805         char str[200];
806 #ifdef MALLOC_LOG
807         sprintf(str, "Out of memory! (%s:%d, size=%d)",
808                 mlog_file, mlog_line, size);
809         fprintf(fp, "*** %s\n", str);
810         fclose(fp);
811 #else
812         strcpy(str, "Out of memory!");
813 #endif
814         modalfatalbox("%s", str);
815     }
816 #ifdef MALLOC_LOG
817     if (fp)
818         fprintf(fp, "malloc(%d) returns %p\n", size, p);
819 #endif
820     return p;
821 }
822
823 void *saferealloc(void *ptr, size_t n, size_t size)
824 {
825     void *p;
826
827     if (n > INT_MAX / size) {
828         p = NULL;
829     } else {
830         size *= n;
831         if (!ptr) {
832 #ifdef MINEFIELD
833             p = minefield_c_malloc(size);
834 #else
835             p = malloc(size);
836 #endif
837         } else {
838 #ifdef MINEFIELD
839             p = minefield_c_realloc(ptr, size);
840 #else
841             p = realloc(ptr, size);
842 #endif
843         }
844     }
845
846     if (!p) {
847         char str[200];
848 #ifdef MALLOC_LOG
849         sprintf(str, "Out of memory! (%s:%d, size=%d)",
850                 mlog_file, mlog_line, size);
851         fprintf(fp, "*** %s\n", str);
852         fclose(fp);
853 #else
854         strcpy(str, "Out of memory!");
855 #endif
856         modalfatalbox("%s", str);
857     }
858 #ifdef MALLOC_LOG
859     if (fp)
860         fprintf(fp, "realloc(%p,%d) returns %p\n", ptr, size, p);
861 #endif
862     return p;
863 }
864
865 void safefree(void *ptr)
866 {
867     if (ptr) {
868 #ifdef MALLOC_LOG
869         if (fp)
870             fprintf(fp, "free(%p)\n", ptr);
871 #endif
872 #ifdef MINEFIELD
873         minefield_c_free(ptr);
874 #else
875         free(ptr);
876 #endif
877     }
878 #ifdef MALLOC_LOG
879     else if (fp)
880         fprintf(fp, "freeing null pointer - no action taken\n");
881 #endif
882 }
883
884 /* ----------------------------------------------------------------------
885  * Debugging routines.
886  */
887
888 #ifdef DEBUG
889 extern void dputs(const char *); /* defined in per-platform *misc.c */
890
891 void debug_printf(const char *fmt, ...)
892 {
893     char *buf;
894     va_list ap;
895
896     va_start(ap, fmt);
897     buf = dupvprintf(fmt, ap);
898     dputs(buf);
899     sfree(buf);
900     va_end(ap);
901 }
902
903
904 void debug_memdump(const void *buf, int len, int L)
905 {
906     int i;
907     const unsigned char *p = buf;
908     char foo[17];
909     if (L) {
910         int delta;
911         debug_printf("\t%d (0x%x) bytes:\n", len, len);
912         delta = 15 & (uintptr_t)p;
913         p -= delta;
914         len += delta;
915     }
916     for (; 0 < len; p += 16, len -= 16) {
917         dputs("  ");
918         if (L)
919             debug_printf("%p: ", p);
920         strcpy(foo, "................");        /* sixteen dots */
921         for (i = 0; i < 16 && i < len; ++i) {
922             if (&p[i] < (unsigned char *) buf) {
923                 dputs("   ");          /* 3 spaces */
924                 foo[i] = ' ';
925             } else {
926                 debug_printf("%c%02.2x",
927                         &p[i] != (unsigned char *) buf
928                         && i % 4 ? '.' : ' ', p[i]
929                     );
930                 if (p[i] >= ' ' && p[i] <= '~')
931                     foo[i] = (char) p[i];
932             }
933         }
934         foo[i] = '\0';
935         debug_printf("%*s%s\n", (16 - i) * 3 + 2, "", foo);
936     }
937 }
938
939 #endif                          /* def DEBUG */
940
941 /*
942  * Determine whether or not a Conf represents a session which can
943  * sensibly be launched right now.
944  */
945 int conf_launchable(Conf *conf)
946 {
947     if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL)
948         return conf_get_str(conf, CONF_serline)[0] != 0;
949     else
950         return conf_get_str(conf, CONF_host)[0] != 0;
951 }
952
953 char const *conf_dest(Conf *conf)
954 {
955     if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL)
956         return conf_get_str(conf, CONF_serline);
957     else
958         return conf_get_str(conf, CONF_host);
959 }
960
961 #ifndef PLATFORM_HAS_SMEMCLR
962 /*
963  * Securely wipe memory.
964  *
965  * The actual wiping is no different from what memset would do: the
966  * point of 'securely' is to try to be sure over-clever compilers
967  * won't optimise away memsets on variables that are about to be freed
968  * or go out of scope. See
969  * https://buildsecurityin.us-cert.gov/bsi-rules/home/g1/771-BSI.html
970  *
971  * Some platforms (e.g. Windows) may provide their own version of this
972  * function.
973  */
974 void smemclr(void *b, size_t n) {
975     volatile char *vp;
976
977     if (b && n > 0) {
978         /*
979          * Zero out the memory.
980          */
981         memset(b, 0, n);
982
983         /*
984          * Perform a volatile access to the object, forcing the
985          * compiler to admit that the previous memset was important.
986          *
987          * This while loop should in practice run for zero iterations
988          * (since we know we just zeroed the object out), but in
989          * theory (as far as the compiler knows) it might range over
990          * the whole object. (If we had just written, say, '*vp =
991          * *vp;', a compiler could in principle have 'helpfully'
992          * optimised the memset into only zeroing out the first byte.
993          * This should be robust.)
994          */
995         vp = b;
996         while (*vp) vp++;
997     }
998 }
999 #endif
1000
1001 /*
1002  * Validate a manual host key specification (either entered in the
1003  * GUI, or via -hostkey). If valid, we return TRUE, and update 'key'
1004  * to contain a canonicalised version of the key string in 'key'
1005  * (which is guaranteed to take up at most as much space as the
1006  * original version), suitable for putting into the Conf. If not
1007  * valid, we return FALSE.
1008  */
1009 int validate_manual_hostkey(char *key)
1010 {
1011     char *p, *q, *r, *s;
1012
1013     /*
1014      * Step through the string word by word, looking for a word that's
1015      * in one of the formats we like.
1016      */
1017     p = key;
1018     while ((p += strspn(p, " \t"))[0]) {
1019         q = p;
1020         p += strcspn(p, " \t");
1021         if (*p) *p++ = '\0';
1022
1023         /*
1024          * Now q is our word.
1025          */
1026
1027         if (strlen(q) == 16*3 - 1 &&
1028             q[strspn(q, "0123456789abcdefABCDEF:")] == 0) {
1029             /*
1030              * Might be a key fingerprint. Check the colons are in the
1031              * right places, and if so, return the same fingerprint
1032              * canonicalised into lowercase.
1033              */
1034             int i;
1035             for (i = 0; i < 16; i++)
1036                 if (q[3*i] == ':' || q[3*i+1] == ':')
1037                     goto not_fingerprint; /* sorry */
1038             for (i = 0; i < 15; i++)
1039                 if (q[3*i+2] != ':')
1040                     goto not_fingerprint; /* sorry */
1041             for (i = 0; i < 16*3 - 1; i++)
1042                 key[i] = tolower(q[i]);
1043             key[16*3 - 1] = '\0';
1044             return TRUE;
1045         }
1046       not_fingerprint:;
1047
1048         /*
1049          * Before we check for a public-key blob, trim newlines out of
1050          * the middle of the word, in case someone's managed to paste
1051          * in a public-key blob _with_ them.
1052          */
1053         for (r = s = q; *r; r++)
1054             if (*r != '\n' && *r != '\r')
1055                 *s++ = *r;
1056         *s = '\0';
1057
1058         if (strlen(q) % 4 == 0 && strlen(q) > 2*4 &&
1059             q[strspn(q, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1060                      "abcdefghijklmnopqrstuvwxyz+/=")] == 0) {
1061             /*
1062              * Might be a base64-encoded SSH-2 public key blob. Check
1063              * that it starts with a sensible algorithm string. No
1064              * canonicalisation is necessary for this string type.
1065              *
1066              * The algorithm string must be at most 64 characters long
1067              * (RFC 4251 section 6).
1068              */
1069             unsigned char decoded[6];
1070             unsigned alglen;
1071             int minlen;
1072             int len = 0;
1073
1074             len += base64_decode_atom(q, decoded+len);
1075             if (len < 3)
1076                 goto not_ssh2_blob;    /* sorry */
1077             len += base64_decode_atom(q+4, decoded+len);
1078             if (len < 4)
1079                 goto not_ssh2_blob;    /* sorry */
1080
1081             alglen = GET_32BIT_MSB_FIRST(decoded);
1082             if (alglen > 64)
1083                 goto not_ssh2_blob;    /* sorry */
1084
1085             minlen = ((alglen + 4) + 2) / 3;
1086             if (strlen(q) < minlen)
1087                 goto not_ssh2_blob;    /* sorry */
1088
1089             strcpy(key, q);
1090             return TRUE;
1091         }
1092       not_ssh2_blob:;
1093     }
1094
1095     return FALSE;
1096 }
1097
1098 int smemeq(const void *av, const void *bv, size_t len)
1099 {
1100     const unsigned char *a = (const unsigned char *)av;
1101     const unsigned char *b = (const unsigned char *)bv;
1102     unsigned val = 0;
1103
1104     while (len-- > 0) {
1105         val |= *a++ ^ *b++;
1106     }
1107     /* Now val is 0 iff we want to return 1, and in the range
1108      * 0x01..0xFF iff we want to return 0. So subtracting from 0x100
1109      * will clear bit 8 iff we want to return 0, and leave it set iff
1110      * we want to return 1, so then we can just shift down. */
1111     return (0x100 - val) >> 8;
1112 }
1113
1114 int match_ssh_id(int stringlen, const void *string, const char *id)
1115 {
1116     int idlen = strlen(id);
1117     return (idlen == stringlen && !memcmp(string, id, idlen));
1118 }
1119
1120 void *get_ssh_string(int *datalen, const void **data, int *stringlen)
1121 {
1122     void *ret;
1123     unsigned int len;
1124
1125     if (*datalen < 4)
1126         return NULL;
1127     len = GET_32BIT_MSB_FIRST((const unsigned char *)*data);
1128     if (*datalen - 4 < len)
1129         return NULL;
1130     ret = (void *)((const char *)*data + 4);
1131     *datalen -= len + 4;
1132     *data = (const char *)*data + len + 4;
1133     *stringlen = len;
1134     return ret;
1135 }
1136
1137 int get_ssh_uint32(int *datalen, const void **data, unsigned *ret)
1138 {
1139     if (*datalen < 4)
1140         return FALSE;
1141     *ret = GET_32BIT_MSB_FIRST((const unsigned char *)*data);
1142     *datalen -= 4;
1143     *data = (const char *)*data + 4;
1144     return TRUE;
1145 }
1146
1147 int strstartswith(const char *s, const char *t)
1148 {
1149     return !memcmp(s, t, strlen(t));
1150 }
1151
1152 int strendswith(const char *s, const char *t)
1153 {
1154     size_t slen = strlen(s), tlen = strlen(t);
1155     return slen >= tlen && !strcmp(s + (slen - tlen), t);
1156 }
1157
1158 char *buildinfo(const char *newline)
1159 {
1160     strbuf *buf = strbuf_new();
1161     extern const char commitid[];      /* in commitid.c */
1162
1163     strbuf_catf(buf, "Build platform: %d-bit %s",
1164                 (int)(CHAR_BIT * sizeof(void *)),
1165                 BUILDINFO_PLATFORM);
1166
1167 #ifdef __clang_version__
1168     strbuf_catf(buf, "%sCompiler: clang %s", newline, __clang_version__);
1169 #elif defined __GNUC__ && defined __VERSION__
1170     strbuf_catf(buf, "%sCompiler: gcc %s", newline, __VERSION__);
1171 #elif defined _MSC_VER
1172     strbuf_catf(buf, "%sCompiler: Visual Studio", newline);
1173 #if _MSC_VER == 1900
1174     strbuf_catf(buf, " 2015 / MSVC++ 14.0");
1175 #elif _MSC_VER == 1800
1176     strbuf_catf(buf, " 2013 / MSVC++ 12.0");
1177 #elif _MSC_VER == 1700
1178     strbuf_catf(buf, " 2012 / MSVC++ 11.0");
1179 #elif _MSC_VER == 1600
1180     strbuf_catf(buf, " 2010 / MSVC++ 10.0");
1181 #elif  _MSC_VER == 1500
1182     strbuf_catf(buf, " 2008 / MSVC++ 9.0");
1183 #elif  _MSC_VER == 1400
1184     strbuf_catf(buf, " 2005 / MSVC++ 8.0");
1185 #elif  _MSC_VER == 1310
1186     strbuf_catf(buf, " 2003 / MSVC++ 7.1");
1187 #else
1188     strbuf_catf(buf, ", unrecognised version");
1189 #endif
1190     strbuf_catf(buf, " (_MSC_VER=%d)", (int)_MSC_VER);
1191 #endif
1192
1193 #ifdef BUILDINFO_GTK
1194     {
1195         char *gtk_buildinfo = buildinfo_gtk_version();
1196         if (gtk_buildinfo) {
1197             strbuf_catf(buf, "%sCompiled against GTK version %s",
1198                         newline, gtk_buildinfo);
1199             sfree(gtk_buildinfo);
1200         }
1201     }
1202 #endif
1203
1204 #ifdef NO_SECURITY
1205     strbuf_catf(buf, "%sBuild option: NO_SECURITY", newline);
1206 #endif
1207 #ifdef NO_SECUREZEROMEMORY
1208     strbuf_catf(buf, "%sBuild option: NO_SECUREZEROMEMORY", newline);
1209 #endif
1210 #ifdef NO_IPV6
1211     strbuf_catf(buf, "%sBuild option: NO_IPV6", newline);
1212 #endif
1213 #ifdef NO_GSSAPI
1214     strbuf_catf(buf, "%sBuild option: NO_GSSAPI", newline);
1215 #endif
1216 #ifdef STATIC_GSSAPI
1217     strbuf_catf(buf, "%sBuild option: STATIC_GSSAPI", newline);
1218 #endif
1219 #ifdef UNPROTECT
1220     strbuf_catf(buf, "%sBuild option: UNPROTECT", newline);
1221 #endif
1222 #ifdef FUZZING
1223     strbuf_catf(buf, "%sBuild option: FUZZING", newline);
1224 #endif
1225 #ifdef DEBUG
1226     strbuf_catf(buf, "%sBuild option: DEBUG", newline);
1227 #endif
1228
1229     strbuf_catf(buf, "%sSource commit: %s", newline, commitid);
1230
1231     return strbuf_to_str(buf);
1232 }