]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - misc.c
Fix the '--without-gtk' mode in configure.
[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;
401
402     size = oldsize - oldlen;
403     if (size == 0) {
404         size = 512;
405         buf = sresize(buf, oldlen + size, char);
406     }
407
408     while (1) {
409 #if defined _WINDOWS && !defined __WINE__ && _MSC_VER < 1900 /* 1900 == VS2015 has real snprintf */
410 #define vsnprintf _vsnprintf
411 #endif
412 #ifdef va_copy
413         /* Use the `va_copy' macro mandated by C99, if present.
414          * XXX some environments may have this as __va_copy() */
415         va_list aq;
416         va_copy(aq, ap);
417         len = vsnprintf(buf + oldlen, size, fmt, aq);
418         va_end(aq);
419 #else
420         /* Ugh. No va_copy macro, so do something nasty.
421          * Technically, you can't reuse a va_list like this: it is left
422          * unspecified whether advancing a va_list pointer modifies its
423          * value or something it points to, so on some platforms calling
424          * vsnprintf twice on the same va_list might fail hideously
425          * (indeed, it has been observed to).
426          * XXX the autoconf manual suggests that using memcpy() will give
427          *     "maximum portability". */
428         len = vsnprintf(buf + oldlen, size, fmt, ap);
429 #endif
430         if (len >= 0 && len < size) {
431             /* This is the C99-specified criterion for snprintf to have
432              * been completely successful. */
433             return buf;
434         } else if (len > 0) {
435             /* This is the C99 error condition: the returned length is
436              * the required buffer size not counting the NUL. */
437             size = len + 1;
438         } else {
439             /* This is the pre-C99 glibc error condition: <0 means the
440              * buffer wasn't big enough, so we enlarge it a bit and hope. */
441             size += 512;
442         }
443         buf = sresize(buf, oldlen + size, char);
444     }
445 }
446
447 char *dupvprintf(const char *fmt, va_list ap)
448 {
449     return dupvprintf_inner(NULL, 0, 0, fmt, ap);
450 }
451 char *dupprintf(const char *fmt, ...)
452 {
453     char *ret;
454     va_list ap;
455     va_start(ap, fmt);
456     ret = dupvprintf(fmt, ap);
457     va_end(ap);
458     return ret;
459 }
460
461 struct strbuf {
462     char *s;
463     int len, size;
464 };
465 strbuf *strbuf_new(void)
466 {
467     strbuf *buf = snew(strbuf);
468     buf->len = 0;
469     buf->size = 512;
470     buf->s = snewn(buf->size, char);
471     *buf->s = '\0';
472     return buf;
473 }
474 void strbuf_free(strbuf *buf)
475 {
476     sfree(buf->s);
477     sfree(buf);
478 }
479 char *strbuf_str(strbuf *buf)
480 {
481     return buf->s;
482 }
483 char *strbuf_to_str(strbuf *buf)
484 {
485     char *ret = buf->s;
486     sfree(buf);
487     return ret;
488 }
489 void strbuf_catfv(strbuf *buf, const char *fmt, va_list ap)
490 {
491     buf->s = dupvprintf_inner(buf->s, buf->len, buf->size, fmt, ap);
492     buf->len += strlen(buf->s + buf->len);
493 }
494 void strbuf_catf(strbuf *buf, const char *fmt, ...)
495 {
496     va_list ap;
497     va_start(ap, fmt);
498     strbuf_catfv(buf, fmt, ap);
499     va_end(ap);
500 }
501
502 /*
503  * Read an entire line of text from a file. Return a buffer
504  * malloced to be as big as necessary (caller must free).
505  */
506 char *fgetline(FILE *fp)
507 {
508     char *ret = snewn(512, char);
509     int size = 512, len = 0;
510     while (fgets(ret + len, size - len, fp)) {
511         len += strlen(ret + len);
512         if (len > 0 && ret[len-1] == '\n')
513             break;                     /* got a newline, we're done */
514         size = len + 512;
515         ret = sresize(ret, size, char);
516     }
517     if (len == 0) {                    /* first fgets returned NULL */
518         sfree(ret);
519         return NULL;
520     }
521     ret[len] = '\0';
522     return ret;
523 }
524
525 /*
526  * Perl-style 'chomp', for a line we just read with fgetline. Unlike
527  * Perl chomp, however, we're deliberately forgiving of strange
528  * line-ending conventions. Also we forgive NULL on input, so you can
529  * just write 'line = chomp(fgetline(fp));' and not bother checking
530  * for NULL until afterwards.
531  */
532 char *chomp(char *str)
533 {
534     if (str) {
535         int len = strlen(str);
536         while (len > 0 && (str[len-1] == '\r' || str[len-1] == '\n'))
537             len--;
538         str[len] = '\0';
539     }
540     return str;
541 }
542
543 /* ----------------------------------------------------------------------
544  * Core base64 encoding and decoding routines.
545  */
546
547 void base64_encode_atom(const unsigned char *data, int n, char *out)
548 {
549     static const char base64_chars[] =
550         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
551
552     unsigned word;
553
554     word = data[0] << 16;
555     if (n > 1)
556         word |= data[1] << 8;
557     if (n > 2)
558         word |= data[2];
559     out[0] = base64_chars[(word >> 18) & 0x3F];
560     out[1] = base64_chars[(word >> 12) & 0x3F];
561     if (n > 1)
562         out[2] = base64_chars[(word >> 6) & 0x3F];
563     else
564         out[2] = '=';
565     if (n > 2)
566         out[3] = base64_chars[word & 0x3F];
567     else
568         out[3] = '=';
569 }
570
571 int base64_decode_atom(const char *atom, unsigned char *out)
572 {
573     int vals[4];
574     int i, v, len;
575     unsigned word;
576     char c;
577
578     for (i = 0; i < 4; i++) {
579         c = atom[i];
580         if (c >= 'A' && c <= 'Z')
581             v = c - 'A';
582         else if (c >= 'a' && c <= 'z')
583             v = c - 'a' + 26;
584         else if (c >= '0' && c <= '9')
585             v = c - '0' + 52;
586         else if (c == '+')
587             v = 62;
588         else if (c == '/')
589             v = 63;
590         else if (c == '=')
591             v = -1;
592         else
593             return 0;                  /* invalid atom */
594         vals[i] = v;
595     }
596
597     if (vals[0] == -1 || vals[1] == -1)
598         return 0;
599     if (vals[2] == -1 && vals[3] != -1)
600         return 0;
601
602     if (vals[3] != -1)
603         len = 3;
604     else if (vals[2] != -1)
605         len = 2;
606     else
607         len = 1;
608
609     word = ((vals[0] << 18) |
610             (vals[1] << 12) | ((vals[2] & 0x3F) << 6) | (vals[3] & 0x3F));
611     out[0] = (word >> 16) & 0xFF;
612     if (len > 1)
613         out[1] = (word >> 8) & 0xFF;
614     if (len > 2)
615         out[2] = word & 0xFF;
616     return len;
617 }
618
619 /* ----------------------------------------------------------------------
620  * Generic routines to deal with send buffers: a linked list of
621  * smallish blocks, with the operations
622  * 
623  *  - add an arbitrary amount of data to the end of the list
624  *  - remove the first N bytes from the list
625  *  - return a (pointer,length) pair giving some initial data in
626  *    the list, suitable for passing to a send or write system
627  *    call
628  *  - retrieve a larger amount of initial data from the list
629  *  - return the current size of the buffer chain in bytes
630  */
631
632 #define BUFFER_MIN_GRANULE  512
633
634 struct bufchain_granule {
635     struct bufchain_granule *next;
636     char *bufpos, *bufend, *bufmax;
637 };
638
639 void bufchain_init(bufchain *ch)
640 {
641     ch->head = ch->tail = NULL;
642     ch->buffersize = 0;
643 }
644
645 void bufchain_clear(bufchain *ch)
646 {
647     struct bufchain_granule *b;
648     while (ch->head) {
649         b = ch->head;
650         ch->head = ch->head->next;
651         sfree(b);
652     }
653     ch->tail = NULL;
654     ch->buffersize = 0;
655 }
656
657 int bufchain_size(bufchain *ch)
658 {
659     return ch->buffersize;
660 }
661
662 void bufchain_add(bufchain *ch, const void *data, int len)
663 {
664     const char *buf = (const char *)data;
665
666     if (len == 0) return;
667
668     ch->buffersize += len;
669
670     while (len > 0) {
671         if (ch->tail && ch->tail->bufend < ch->tail->bufmax) {
672             int copylen = min(len, ch->tail->bufmax - ch->tail->bufend);
673             memcpy(ch->tail->bufend, buf, copylen);
674             buf += copylen;
675             len -= copylen;
676             ch->tail->bufend += copylen;
677         }
678         if (len > 0) {
679             int grainlen =
680                 max(sizeof(struct bufchain_granule) + len, BUFFER_MIN_GRANULE);
681             struct bufchain_granule *newbuf;
682             newbuf = smalloc(grainlen);
683             newbuf->bufpos = newbuf->bufend =
684                 (char *)newbuf + sizeof(struct bufchain_granule);
685             newbuf->bufmax = (char *)newbuf + grainlen;
686             newbuf->next = NULL;
687             if (ch->tail)
688                 ch->tail->next = newbuf;
689             else
690                 ch->head = newbuf;
691             ch->tail = newbuf;
692         }
693     }
694 }
695
696 void bufchain_consume(bufchain *ch, int len)
697 {
698     struct bufchain_granule *tmp;
699
700     assert(ch->buffersize >= len);
701     while (len > 0) {
702         int remlen = len;
703         assert(ch->head != NULL);
704         if (remlen >= ch->head->bufend - ch->head->bufpos) {
705             remlen = ch->head->bufend - ch->head->bufpos;
706             tmp = ch->head;
707             ch->head = tmp->next;
708             if (!ch->head)
709                 ch->tail = NULL;
710             sfree(tmp);
711         } else
712             ch->head->bufpos += remlen;
713         ch->buffersize -= remlen;
714         len -= remlen;
715     }
716 }
717
718 void bufchain_prefix(bufchain *ch, void **data, int *len)
719 {
720     *len = ch->head->bufend - ch->head->bufpos;
721     *data = ch->head->bufpos;
722 }
723
724 void bufchain_fetch(bufchain *ch, void *data, int len)
725 {
726     struct bufchain_granule *tmp;
727     char *data_c = (char *)data;
728
729     tmp = ch->head;
730
731     assert(ch->buffersize >= len);
732     while (len > 0) {
733         int remlen = len;
734
735         assert(tmp != NULL);
736         if (remlen >= tmp->bufend - tmp->bufpos)
737             remlen = tmp->bufend - tmp->bufpos;
738         memcpy(data_c, tmp->bufpos, remlen);
739
740         tmp = tmp->next;
741         len -= remlen;
742         data_c += remlen;
743     }
744 }
745
746 /* ----------------------------------------------------------------------
747  * My own versions of malloc, realloc and free. Because I want
748  * malloc and realloc to bomb out and exit the program if they run
749  * out of memory, realloc to reliably call malloc if passed a NULL
750  * pointer, and free to reliably do nothing if passed a NULL
751  * pointer. We can also put trace printouts in, if we need to; and
752  * we can also replace the allocator with an ElectricFence-like
753  * one.
754  */
755
756 #ifdef MINEFIELD
757 void *minefield_c_malloc(size_t size);
758 void minefield_c_free(void *p);
759 void *minefield_c_realloc(void *p, size_t size);
760 #endif
761
762 #ifdef MALLOC_LOG
763 static FILE *fp = NULL;
764
765 static char *mlog_file = NULL;
766 static int mlog_line = 0;
767
768 void mlog(char *file, int line)
769 {
770     mlog_file = file;
771     mlog_line = line;
772     if (!fp) {
773         fp = fopen("putty_mem.log", "w");
774         setvbuf(fp, NULL, _IONBF, BUFSIZ);
775     }
776     if (fp)
777         fprintf(fp, "%s:%d: ", file, line);
778 }
779 #endif
780
781 void *safemalloc(size_t n, size_t size)
782 {
783     void *p;
784
785     if (n > INT_MAX / size) {
786         p = NULL;
787     } else {
788         size *= n;
789         if (size == 0) size = 1;
790 #ifdef MINEFIELD
791         p = minefield_c_malloc(size);
792 #else
793         p = malloc(size);
794 #endif
795     }
796
797     if (!p) {
798         char str[200];
799 #ifdef MALLOC_LOG
800         sprintf(str, "Out of memory! (%s:%d, size=%d)",
801                 mlog_file, mlog_line, size);
802         fprintf(fp, "*** %s\n", str);
803         fclose(fp);
804 #else
805         strcpy(str, "Out of memory!");
806 #endif
807         modalfatalbox("%s", str);
808     }
809 #ifdef MALLOC_LOG
810     if (fp)
811         fprintf(fp, "malloc(%d) returns %p\n", size, p);
812 #endif
813     return p;
814 }
815
816 void *saferealloc(void *ptr, size_t n, size_t size)
817 {
818     void *p;
819
820     if (n > INT_MAX / size) {
821         p = NULL;
822     } else {
823         size *= n;
824         if (!ptr) {
825 #ifdef MINEFIELD
826             p = minefield_c_malloc(size);
827 #else
828             p = malloc(size);
829 #endif
830         } else {
831 #ifdef MINEFIELD
832             p = minefield_c_realloc(ptr, size);
833 #else
834             p = realloc(ptr, size);
835 #endif
836         }
837     }
838
839     if (!p) {
840         char str[200];
841 #ifdef MALLOC_LOG
842         sprintf(str, "Out of memory! (%s:%d, size=%d)",
843                 mlog_file, mlog_line, size);
844         fprintf(fp, "*** %s\n", str);
845         fclose(fp);
846 #else
847         strcpy(str, "Out of memory!");
848 #endif
849         modalfatalbox("%s", str);
850     }
851 #ifdef MALLOC_LOG
852     if (fp)
853         fprintf(fp, "realloc(%p,%d) returns %p\n", ptr, size, p);
854 #endif
855     return p;
856 }
857
858 void safefree(void *ptr)
859 {
860     if (ptr) {
861 #ifdef MALLOC_LOG
862         if (fp)
863             fprintf(fp, "free(%p)\n", ptr);
864 #endif
865 #ifdef MINEFIELD
866         minefield_c_free(ptr);
867 #else
868         free(ptr);
869 #endif
870     }
871 #ifdef MALLOC_LOG
872     else if (fp)
873         fprintf(fp, "freeing null pointer - no action taken\n");
874 #endif
875 }
876
877 /* ----------------------------------------------------------------------
878  * Debugging routines.
879  */
880
881 #ifdef DEBUG
882 extern void dputs(const char *); /* defined in per-platform *misc.c */
883
884 void debug_printf(const char *fmt, ...)
885 {
886     char *buf;
887     va_list ap;
888
889     va_start(ap, fmt);
890     buf = dupvprintf(fmt, ap);
891     dputs(buf);
892     sfree(buf);
893     va_end(ap);
894 }
895
896
897 void debug_memdump(const void *buf, int len, int L)
898 {
899     int i;
900     const unsigned char *p = buf;
901     char foo[17];
902     if (L) {
903         int delta;
904         debug_printf("\t%d (0x%x) bytes:\n", len, len);
905         delta = 15 & (uintptr_t)p;
906         p -= delta;
907         len += delta;
908     }
909     for (; 0 < len; p += 16, len -= 16) {
910         dputs("  ");
911         if (L)
912             debug_printf("%p: ", p);
913         strcpy(foo, "................");        /* sixteen dots */
914         for (i = 0; i < 16 && i < len; ++i) {
915             if (&p[i] < (unsigned char *) buf) {
916                 dputs("   ");          /* 3 spaces */
917                 foo[i] = ' ';
918             } else {
919                 debug_printf("%c%02.2x",
920                         &p[i] != (unsigned char *) buf
921                         && i % 4 ? '.' : ' ', p[i]
922                     );
923                 if (p[i] >= ' ' && p[i] <= '~')
924                     foo[i] = (char) p[i];
925             }
926         }
927         foo[i] = '\0';
928         debug_printf("%*s%s\n", (16 - i) * 3 + 2, "", foo);
929     }
930 }
931
932 #endif                          /* def DEBUG */
933
934 /*
935  * Determine whether or not a Conf represents a session which can
936  * sensibly be launched right now.
937  */
938 int conf_launchable(Conf *conf)
939 {
940     if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL)
941         return conf_get_str(conf, CONF_serline)[0] != 0;
942     else
943         return conf_get_str(conf, CONF_host)[0] != 0;
944 }
945
946 char const *conf_dest(Conf *conf)
947 {
948     if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL)
949         return conf_get_str(conf, CONF_serline);
950     else
951         return conf_get_str(conf, CONF_host);
952 }
953
954 #ifndef PLATFORM_HAS_SMEMCLR
955 /*
956  * Securely wipe memory.
957  *
958  * The actual wiping is no different from what memset would do: the
959  * point of 'securely' is to try to be sure over-clever compilers
960  * won't optimise away memsets on variables that are about to be freed
961  * or go out of scope. See
962  * https://buildsecurityin.us-cert.gov/bsi-rules/home/g1/771-BSI.html
963  *
964  * Some platforms (e.g. Windows) may provide their own version of this
965  * function.
966  */
967 void smemclr(void *b, size_t n) {
968     volatile char *vp;
969
970     if (b && n > 0) {
971         /*
972          * Zero out the memory.
973          */
974         memset(b, 0, n);
975
976         /*
977          * Perform a volatile access to the object, forcing the
978          * compiler to admit that the previous memset was important.
979          *
980          * This while loop should in practice run for zero iterations
981          * (since we know we just zeroed the object out), but in
982          * theory (as far as the compiler knows) it might range over
983          * the whole object. (If we had just written, say, '*vp =
984          * *vp;', a compiler could in principle have 'helpfully'
985          * optimised the memset into only zeroing out the first byte.
986          * This should be robust.)
987          */
988         vp = b;
989         while (*vp) vp++;
990     }
991 }
992 #endif
993
994 /*
995  * Validate a manual host key specification (either entered in the
996  * GUI, or via -hostkey). If valid, we return TRUE, and update 'key'
997  * to contain a canonicalised version of the key string in 'key'
998  * (which is guaranteed to take up at most as much space as the
999  * original version), suitable for putting into the Conf. If not
1000  * valid, we return FALSE.
1001  */
1002 int validate_manual_hostkey(char *key)
1003 {
1004     char *p, *q, *r, *s;
1005
1006     /*
1007      * Step through the string word by word, looking for a word that's
1008      * in one of the formats we like.
1009      */
1010     p = key;
1011     while ((p += strspn(p, " \t"))[0]) {
1012         q = p;
1013         p += strcspn(p, " \t");
1014         if (*p) *p++ = '\0';
1015
1016         /*
1017          * Now q is our word.
1018          */
1019
1020         if (strlen(q) == 16*3 - 1 &&
1021             q[strspn(q, "0123456789abcdefABCDEF:")] == 0) {
1022             /*
1023              * Might be a key fingerprint. Check the colons are in the
1024              * right places, and if so, return the same fingerprint
1025              * canonicalised into lowercase.
1026              */
1027             int i;
1028             for (i = 0; i < 16; i++)
1029                 if (q[3*i] == ':' || q[3*i+1] == ':')
1030                     goto not_fingerprint; /* sorry */
1031             for (i = 0; i < 15; i++)
1032                 if (q[3*i+2] != ':')
1033                     goto not_fingerprint; /* sorry */
1034             for (i = 0; i < 16*3 - 1; i++)
1035                 key[i] = tolower(q[i]);
1036             key[16*3 - 1] = '\0';
1037             return TRUE;
1038         }
1039       not_fingerprint:;
1040
1041         /*
1042          * Before we check for a public-key blob, trim newlines out of
1043          * the middle of the word, in case someone's managed to paste
1044          * in a public-key blob _with_ them.
1045          */
1046         for (r = s = q; *r; r++)
1047             if (*r != '\n' && *r != '\r')
1048                 *s++ = *r;
1049         *s = '\0';
1050
1051         if (strlen(q) % 4 == 0 && strlen(q) > 2*4 &&
1052             q[strspn(q, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1053                      "abcdefghijklmnopqrstuvwxyz+/=")] == 0) {
1054             /*
1055              * Might be a base64-encoded SSH-2 public key blob. Check
1056              * that it starts with a sensible algorithm string. No
1057              * canonicalisation is necessary for this string type.
1058              *
1059              * The algorithm string must be at most 64 characters long
1060              * (RFC 4251 section 6).
1061              */
1062             unsigned char decoded[6];
1063             unsigned alglen;
1064             int minlen;
1065             int len = 0;
1066
1067             len += base64_decode_atom(q, decoded+len);
1068             if (len < 3)
1069                 goto not_ssh2_blob;    /* sorry */
1070             len += base64_decode_atom(q+4, decoded+len);
1071             if (len < 4)
1072                 goto not_ssh2_blob;    /* sorry */
1073
1074             alglen = GET_32BIT_MSB_FIRST(decoded);
1075             if (alglen > 64)
1076                 goto not_ssh2_blob;    /* sorry */
1077
1078             minlen = ((alglen + 4) + 2) / 3;
1079             if (strlen(q) < minlen)
1080                 goto not_ssh2_blob;    /* sorry */
1081
1082             strcpy(key, q);
1083             return TRUE;
1084         }
1085       not_ssh2_blob:;
1086     }
1087
1088     return FALSE;
1089 }
1090
1091 int smemeq(const void *av, const void *bv, size_t len)
1092 {
1093     const unsigned char *a = (const unsigned char *)av;
1094     const unsigned char *b = (const unsigned char *)bv;
1095     unsigned val = 0;
1096
1097     while (len-- > 0) {
1098         val |= *a++ ^ *b++;
1099     }
1100     /* Now val is 0 iff we want to return 1, and in the range
1101      * 0x01..0xFF iff we want to return 0. So subtracting from 0x100
1102      * will clear bit 8 iff we want to return 0, and leave it set iff
1103      * we want to return 1, so then we can just shift down. */
1104     return (0x100 - val) >> 8;
1105 }
1106
1107 int match_ssh_id(int stringlen, const void *string, const char *id)
1108 {
1109     int idlen = strlen(id);
1110     return (idlen == stringlen && !memcmp(string, id, idlen));
1111 }
1112
1113 void *get_ssh_string(int *datalen, const void **data, int *stringlen)
1114 {
1115     void *ret;
1116     unsigned int len;
1117
1118     if (*datalen < 4)
1119         return NULL;
1120     len = GET_32BIT_MSB_FIRST((const unsigned char *)*data);
1121     if (*datalen - 4 < len)
1122         return NULL;
1123     ret = (void *)((const char *)*data + 4);
1124     *datalen -= len + 4;
1125     *data = (const char *)*data + len + 4;
1126     *stringlen = len;
1127     return ret;
1128 }
1129
1130 int get_ssh_uint32(int *datalen, const void **data, unsigned *ret)
1131 {
1132     if (*datalen < 4)
1133         return FALSE;
1134     *ret = GET_32BIT_MSB_FIRST((const unsigned char *)*data);
1135     *datalen -= 4;
1136     *data = (const char *)*data + 4;
1137     return TRUE;
1138 }
1139
1140 int strstartswith(const char *s, const char *t)
1141 {
1142     return !memcmp(s, t, strlen(t));
1143 }
1144
1145 int strendswith(const char *s, const char *t)
1146 {
1147     size_t slen = strlen(s), tlen = strlen(t);
1148     return slen >= tlen && !strcmp(s + (slen - tlen), t);
1149 }
1150
1151 char *buildinfo(const char *newline)
1152 {
1153     strbuf *buf = strbuf_new();
1154     extern const char commitid[];      /* in commitid.c */
1155
1156     strbuf_catf(buf, "Build platform: %d-bit %s",
1157                 (int)(CHAR_BIT * sizeof(void *)),
1158                 BUILDINFO_PLATFORM);
1159
1160 #ifdef __clang_version__
1161     strbuf_catf(buf, "%sCompiler: clang %s", newline, __clang_version__);
1162 #elif defined __GNUC__ && defined __VERSION__
1163     strbuf_catf(buf, "%sCompiler: gcc %s", newline, __VERSION__);
1164 #elif defined _MSC_VER
1165     strbuf_catf(buf, "%sCompiler: Visual Studio", newline);
1166 #if _MSC_VER == 1900
1167     strbuf_catf(buf, " 2015 / MSVC++ 14.0");
1168 #elif _MSC_VER == 1800
1169     strbuf_catf(buf, " 2013 / MSVC++ 12.0");
1170 #elif _MSC_VER == 1700
1171     strbuf_catf(buf, " 2012 / MSVC++ 11.0");
1172 #elif _MSC_VER == 1600
1173     strbuf_catf(buf, " 2010 / MSVC++ 10.0");
1174 #elif  _MSC_VER == 1500
1175     strbuf_catf(buf, " 2008 / MSVC++ 9.0");
1176 #elif  _MSC_VER == 1400
1177     strbuf_catf(buf, " 2005 / MSVC++ 8.0");
1178 #elif  _MSC_VER == 1310
1179     strbuf_catf(buf, " 2003 / MSVC++ 7.1");
1180 #else
1181     strbuf_catf(buf, ", unrecognised version");
1182 #endif
1183     strbuf_catf(buf, " (_MSC_VER=%d)", (int)_MSC_VER);
1184 #endif
1185
1186 #ifdef BUILDINFO_GTK
1187     {
1188         char *gtk_buildinfo = buildinfo_gtk_version();
1189         if (gtk_buildinfo) {
1190             strbuf_catf(buf, "%sCompiled against GTK version %s",
1191                         newline, gtk_buildinfo);
1192             sfree(gtk_buildinfo);
1193         }
1194     }
1195 #endif
1196
1197 #ifdef NO_SECURITY
1198     strbuf_catf(buf, "%sBuild option: NO_SECURITY", newline);
1199 #endif
1200 #ifdef NO_SECUREZEROMEMORY
1201     strbuf_catf(buf, "%sBuild option: NO_SECUREZEROMEMORY", newline);
1202 #endif
1203 #ifdef NO_IPV6
1204     strbuf_catf(buf, "%sBuild option: NO_IPV6", newline);
1205 #endif
1206 #ifdef NO_GSSAPI
1207     strbuf_catf(buf, "%sBuild option: NO_GSSAPI", newline);
1208 #endif
1209 #ifdef STATIC_GSSAPI
1210     strbuf_catf(buf, "%sBuild option: STATIC_GSSAPI", newline);
1211 #endif
1212 #ifdef UNPROTECT
1213     strbuf_catf(buf, "%sBuild option: UNPROTECT", newline);
1214 #endif
1215 #ifdef FUZZING
1216     strbuf_catf(buf, "%sBuild option: FUZZING", newline);
1217 #endif
1218 #ifdef DEBUG
1219     strbuf_catf(buf, "%sBuild option: DEBUG", newline);
1220 #endif
1221
1222     strbuf_catf(buf, "%sSource commit: %s", newline, commitid);
1223
1224     return strbuf_to_str(buf);
1225 }