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