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