]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - misc.c
Move base64_decode_atom into misc.c.
[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
13 /*
14  * Parse a string block size specification. This is approximately a
15  * subset of the block size specs supported by GNU fileutils:
16  *  "nk" = n kilobytes
17  *  "nM" = n megabytes
18  *  "nG" = n gigabytes
19  * All numbers are decimal, and suffixes refer to powers of two.
20  * Case-insensitive.
21  */
22 unsigned long parse_blocksize(const char *bs)
23 {
24     char *suf;
25     unsigned long r = strtoul(bs, &suf, 10);
26     if (*suf != '\0') {
27         while (*suf && isspace((unsigned char)*suf)) suf++;
28         switch (*suf) {
29           case 'k': case 'K':
30             r *= 1024ul;
31             break;
32           case 'm': case 'M':
33             r *= 1024ul * 1024ul;
34             break;
35           case 'g': case 'G':
36             r *= 1024ul * 1024ul * 1024ul;
37             break;
38           case '\0':
39           default:
40             break;
41         }
42     }
43     return r;
44 }
45
46 /*
47  * Parse a ^C style character specification.
48  * Returns NULL in `next' if we didn't recognise it as a control character,
49  * in which case `c' should be ignored.
50  * The precise current parsing is an oddity inherited from the terminal
51  * answerback-string parsing code. All sequences start with ^; all except
52  * ^<123> are two characters. The ones that are worth keeping are probably:
53  *   ^?             127
54  *   ^@A-Z[\]^_     0-31
55  *   a-z            1-26
56  *   <num>          specified by number (decimal, 0octal, 0xHEX)
57  *   ~              ^ escape
58  */
59 char ctrlparse(char *s, char **next)
60 {
61     char c = 0;
62     if (*s != '^') {
63         *next = NULL;
64     } else {
65         s++;
66         if (*s == '\0') {
67             *next = NULL;
68         } else if (*s == '<') {
69             s++;
70             c = (char)strtol(s, next, 0);
71             if ((*next == s) || (**next != '>')) {
72                 c = 0;
73                 *next = NULL;
74             } else
75                 (*next)++;
76         } else if (*s >= 'a' && *s <= 'z') {
77             c = (*s - ('a' - 1));
78             *next = s+1;
79         } else if ((*s >= '@' && *s <= '_') || *s == '?' || (*s & 0x80)) {
80             c = ('@' ^ *s);
81             *next = s+1;
82         } else if (*s == '~') {
83             c = '^';
84             *next = s+1;
85         }
86     }
87     return c;
88 }
89
90 /*
91  * Find a character in a string, unless it's a colon contained within
92  * square brackets. Used for untangling strings of the form
93  * 'host:port', where host can be an IPv6 literal.
94  *
95  * We provide several variants of this function, with semantics like
96  * various standard string.h functions.
97  */
98 static const char *host_strchr_internal(const char *s, const char *set,
99                                         int first)
100 {
101     int brackets = 0;
102     const char *ret = NULL;
103
104     while (1) {
105         if (!*s)
106             return ret;
107
108         if (*s == '[')
109             brackets++;
110         else if (*s == ']' && brackets > 0)
111             brackets--;
112         else if (brackets && *s == ':')
113             /* never match */ ;
114         else if (strchr(set, *s)) {
115             ret = s;
116             if (first)
117                 return ret;
118         }
119
120         s++;
121     }
122 }
123 size_t host_strcspn(const char *s, const char *set)
124 {
125     const char *answer = host_strchr_internal(s, set, TRUE);
126     if (answer)
127         return answer - s;
128     else
129         return strlen(s);
130 }
131 char *host_strchr(const char *s, int c)
132 {
133     char set[2];
134     set[0] = c;
135     set[1] = '\0';
136     return (char *) host_strchr_internal(s, set, TRUE);
137 }
138 char *host_strrchr(const char *s, int c)
139 {
140     char set[2];
141     set[0] = c;
142     set[1] = '\0';
143     return (char *) host_strchr_internal(s, set, FALSE);
144 }
145
146 #ifdef TEST_HOST_STRFOO
147 int main(void)
148 {
149     int passes = 0, fails = 0;
150
151 #define TEST1(func, string, arg2, suffix, result) do                    \
152     {                                                                   \
153         const char *str = string;                                       \
154         unsigned ret = func(string, arg2) suffix;                       \
155         if (ret == result) {                                            \
156             passes++;                                                   \
157         } else {                                                        \
158             printf("fail: %s(%s,%s)%s = %u, expected %u\n",             \
159                    #func, #string, #arg2, #suffix, ret, result);        \
160             fails++;                                                    \
161         }                                                               \
162 } while (0)
163
164     TEST1(host_strchr, "[1:2:3]:4:5", ':', -str, 7);
165     TEST1(host_strrchr, "[1:2:3]:4:5", ':', -str, 9);
166     TEST1(host_strcspn, "[1:2:3]:4:5", "/:",, 7);
167     TEST1(host_strchr, "[1:2:3]", ':', == NULL, 1);
168     TEST1(host_strrchr, "[1:2:3]", ':', == NULL, 1);
169     TEST1(host_strcspn, "[1:2:3]", "/:",, 7);
170     TEST1(host_strcspn, "[1:2/3]", "/:",, 4);
171     TEST1(host_strcspn, "[1:2:3]/", "/:",, 7);
172
173     printf("passed %d failed %d total %d\n", passes, fails, passes+fails);
174     return fails != 0 ? 1 : 0;
175 }
176 /* Stubs to stop the rest of this module causing compile failures. */
177 void modalfatalbox(char *fmt, ...) {}
178 int conf_get_int(Conf *conf, int primary) { return 0; }
179 char *conf_get_str(Conf *conf, int primary) { return NULL; }
180 #endif /* TEST_HOST_STRFOO */
181
182 /*
183  * Trim square brackets off the outside of an IPv6 address literal.
184  * Leave all other strings unchanged. Returns a fresh dynamically
185  * allocated string.
186  */
187 char *host_strduptrim(const char *s)
188 {
189     if (s[0] == '[') {
190         const char *p = s+1;
191         int colons = 0;
192         while (*p && *p != ']') {
193             if (isxdigit((unsigned char)*p))
194                 /* OK */;
195             else if (*p == ':')
196                 colons++;
197             else
198                 break;
199             p++;
200         }
201         if (*p == ']' && !p[1] && colons > 1) {
202             /*
203              * This looks like an IPv6 address literal (hex digits and
204              * at least two colons, contained in square brackets).
205              * Trim off the brackets.
206              */
207             return dupprintf("%.*s", (int)(p - (s+1)), s+1);
208         }
209     }
210
211     /*
212      * Any other shape of string is simply duplicated.
213      */
214     return dupstr(s);
215 }
216
217 prompts_t *new_prompts(void *frontend)
218 {
219     prompts_t *p = snew(prompts_t);
220     p->prompts = NULL;
221     p->n_prompts = 0;
222     p->frontend = frontend;
223     p->data = NULL;
224     p->to_server = TRUE; /* to be on the safe side */
225     p->name = p->instruction = NULL;
226     p->name_reqd = p->instr_reqd = FALSE;
227     return p;
228 }
229 void add_prompt(prompts_t *p, char *promptstr, int echo)
230 {
231     prompt_t *pr = snew(prompt_t);
232     pr->prompt = promptstr;
233     pr->echo = echo;
234     pr->result = NULL;
235     pr->resultsize = 0;
236     p->n_prompts++;
237     p->prompts = sresize(p->prompts, p->n_prompts, prompt_t *);
238     p->prompts[p->n_prompts-1] = pr;
239 }
240 void prompt_ensure_result_size(prompt_t *pr, int newlen)
241 {
242     if ((int)pr->resultsize < newlen) {
243         char *newbuf;
244         newlen = newlen * 5 / 4 + 512; /* avoid too many small allocs */
245
246         /*
247          * We don't use sresize / realloc here, because we will be
248          * storing sensitive stuff like passwords in here, and we want
249          * to make sure that the data doesn't get copied around in
250          * memory without the old copy being destroyed.
251          */
252         newbuf = snewn(newlen, char);
253         memcpy(newbuf, pr->result, pr->resultsize);
254         smemclr(pr->result, pr->resultsize);
255         sfree(pr->result);
256         pr->result = newbuf;
257         pr->resultsize = newlen;
258     }
259 }
260 void prompt_set_result(prompt_t *pr, const char *newstr)
261 {
262     prompt_ensure_result_size(pr, strlen(newstr) + 1);
263     strcpy(pr->result, newstr);
264 }
265 void free_prompts(prompts_t *p)
266 {
267     size_t i;
268     for (i=0; i < p->n_prompts; i++) {
269         prompt_t *pr = p->prompts[i];
270         smemclr(pr->result, pr->resultsize); /* burn the evidence */
271         sfree(pr->result);
272         sfree(pr->prompt);
273         sfree(pr);
274     }
275     sfree(p->prompts);
276     sfree(p->name);
277     sfree(p->instruction);
278     sfree(p);
279 }
280
281 /* ----------------------------------------------------------------------
282  * String handling routines.
283  */
284
285 char *dupstr(const char *s)
286 {
287     char *p = NULL;
288     if (s) {
289         int len = strlen(s);
290         p = snewn(len + 1, char);
291         strcpy(p, s);
292     }
293     return p;
294 }
295
296 /* Allocate the concatenation of N strings. Terminate arg list with NULL. */
297 char *dupcat(const char *s1, ...)
298 {
299     int len;
300     char *p, *q, *sn;
301     va_list ap;
302
303     len = strlen(s1);
304     va_start(ap, s1);
305     while (1) {
306         sn = va_arg(ap, char *);
307         if (!sn)
308             break;
309         len += strlen(sn);
310     }
311     va_end(ap);
312
313     p = snewn(len + 1, char);
314     strcpy(p, s1);
315     q = p + strlen(p);
316
317     va_start(ap, s1);
318     while (1) {
319         sn = va_arg(ap, char *);
320         if (!sn)
321             break;
322         strcpy(q, sn);
323         q += strlen(q);
324     }
325     va_end(ap);
326
327     return p;
328 }
329
330 void burnstr(char *string)             /* sfree(str), only clear it first */
331 {
332     if (string) {
333         smemclr(string, strlen(string));
334         sfree(string);
335     }
336 }
337
338 int toint(unsigned u)
339 {
340     /*
341      * Convert an unsigned to an int, without running into the
342      * undefined behaviour which happens by the strict C standard if
343      * the value overflows. You'd hope that sensible compilers would
344      * do the sensible thing in response to a cast, but actually I
345      * don't trust modern compilers not to do silly things like
346      * assuming that _obviously_ you wouldn't have caused an overflow
347      * and so they can elide an 'if (i < 0)' test immediately after
348      * the cast.
349      *
350      * Sensible compilers ought of course to optimise this entire
351      * function into 'just return the input value'!
352      */
353     if (u <= (unsigned)INT_MAX)
354         return (int)u;
355     else if (u >= (unsigned)INT_MIN)   /* wrap in cast _to_ unsigned is OK */
356         return INT_MIN + (int)(u - (unsigned)INT_MIN);
357     else
358         return INT_MIN; /* fallback; should never occur on binary machines */
359 }
360
361 /*
362  * Do an sprintf(), but into a custom-allocated buffer.
363  * 
364  * Currently I'm doing this via vsnprintf. This has worked so far,
365  * but it's not good, because vsnprintf is not available on all
366  * platforms. There's an ifdef to use `_vsnprintf', which seems
367  * to be the local name for it on Windows. Other platforms may
368  * lack it completely, in which case it'll be time to rewrite
369  * this function in a totally different way.
370  * 
371  * The only `properly' portable solution I can think of is to
372  * implement my own format string scanner, which figures out an
373  * upper bound for the length of each formatting directive,
374  * allocates the buffer as it goes along, and calls sprintf() to
375  * actually process each directive. If I ever need to actually do
376  * this, some caveats:
377  * 
378  *  - It's very hard to find a reliable upper bound for
379  *    floating-point values. %f, in particular, when supplied with
380  *    a number near to the upper or lower limit of representable
381  *    numbers, could easily take several hundred characters. It's
382  *    probably feasible to predict this statically using the
383  *    constants in <float.h>, or even to predict it dynamically by
384  *    looking at the exponent of the specific float provided, but
385  *    it won't be fun.
386  * 
387  *  - Don't forget to _check_, after calling sprintf, that it's
388  *    used at most the amount of space we had available.
389  * 
390  *  - Fault any formatting directive we don't fully understand. The
391  *    aim here is to _guarantee_ that we never overflow the buffer,
392  *    because this is a security-critical function. If we see a
393  *    directive we don't know about, we should panic and die rather
394  *    than run any risk.
395  */
396 char *dupprintf(const char *fmt, ...)
397 {
398     char *ret;
399     va_list ap;
400     va_start(ap, fmt);
401     ret = dupvprintf(fmt, ap);
402     va_end(ap);
403     return ret;
404 }
405 char *dupvprintf(const char *fmt, va_list ap)
406 {
407     char *buf;
408     int len, size;
409
410     buf = snewn(512, char);
411     size = 512;
412
413     while (1) {
414 #ifdef _WINDOWS
415 #define vsnprintf _vsnprintf
416 #endif
417 #ifdef va_copy
418         /* Use the `va_copy' macro mandated by C99, if present.
419          * XXX some environments may have this as __va_copy() */
420         va_list aq;
421         va_copy(aq, ap);
422         len = vsnprintf(buf, size, fmt, aq);
423         va_end(aq);
424 #else
425         /* Ugh. No va_copy macro, so do something nasty.
426          * Technically, you can't reuse a va_list like this: it is left
427          * unspecified whether advancing a va_list pointer modifies its
428          * value or something it points to, so on some platforms calling
429          * vsnprintf twice on the same va_list might fail hideously
430          * (indeed, it has been observed to).
431          * XXX the autoconf manual suggests that using memcpy() will give
432          *     "maximum portability". */
433         len = vsnprintf(buf, size, fmt, ap);
434 #endif
435         if (len >= 0 && len < size) {
436             /* This is the C99-specified criterion for snprintf to have
437              * been completely successful. */
438             return buf;
439         } else if (len > 0) {
440             /* This is the C99 error condition: the returned length is
441              * the required buffer size not counting the NUL. */
442             size = len + 1;
443         } else {
444             /* This is the pre-C99 glibc error condition: <0 means the
445              * buffer wasn't big enough, so we enlarge it a bit and hope. */
446             size += 512;
447         }
448         buf = sresize(buf, size, char);
449     }
450 }
451
452 /*
453  * Read an entire line of text from a file. Return a buffer
454  * malloced to be as big as necessary (caller must free).
455  */
456 char *fgetline(FILE *fp)
457 {
458     char *ret = snewn(512, char);
459     int size = 512, len = 0;
460     while (fgets(ret + len, size - len, fp)) {
461         len += strlen(ret + len);
462         if (ret[len-1] == '\n')
463             break;                     /* got a newline, we're done */
464         size = len + 512;
465         ret = sresize(ret, size, char);
466     }
467     if (len == 0) {                    /* first fgets returned NULL */
468         sfree(ret);
469         return NULL;
470     }
471     ret[len] = '\0';
472     return ret;
473 }
474
475 /* ----------------------------------------------------------------------
476  * Core base64 encoding and decoding routines.
477  */
478
479 void base64_encode_atom(unsigned char *data, int n, char *out)
480 {
481     static const char base64_chars[] =
482         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
483
484     unsigned word;
485
486     word = data[0] << 16;
487     if (n > 1)
488         word |= data[1] << 8;
489     if (n > 2)
490         word |= data[2];
491     out[0] = base64_chars[(word >> 18) & 0x3F];
492     out[1] = base64_chars[(word >> 12) & 0x3F];
493     if (n > 1)
494         out[2] = base64_chars[(word >> 6) & 0x3F];
495     else
496         out[2] = '=';
497     if (n > 2)
498         out[3] = base64_chars[word & 0x3F];
499     else
500         out[3] = '=';
501 }
502
503 int base64_decode_atom(char *atom, unsigned char *out)
504 {
505     int vals[4];
506     int i, v, len;
507     unsigned word;
508     char c;
509
510     for (i = 0; i < 4; i++) {
511         c = atom[i];
512         if (c >= 'A' && c <= 'Z')
513             v = c - 'A';
514         else if (c >= 'a' && c <= 'z')
515             v = c - 'a' + 26;
516         else if (c >= '0' && c <= '9')
517             v = c - '0' + 52;
518         else if (c == '+')
519             v = 62;
520         else if (c == '/')
521             v = 63;
522         else if (c == '=')
523             v = -1;
524         else
525             return 0;                  /* invalid atom */
526         vals[i] = v;
527     }
528
529     if (vals[0] == -1 || vals[1] == -1)
530         return 0;
531     if (vals[2] == -1 && vals[3] != -1)
532         return 0;
533
534     if (vals[3] != -1)
535         len = 3;
536     else if (vals[2] != -1)
537         len = 2;
538     else
539         len = 1;
540
541     word = ((vals[0] << 18) |
542             (vals[1] << 12) | ((vals[2] & 0x3F) << 6) | (vals[3] & 0x3F));
543     out[0] = (word >> 16) & 0xFF;
544     if (len > 1)
545         out[1] = (word >> 8) & 0xFF;
546     if (len > 2)
547         out[2] = word & 0xFF;
548     return len;
549 }
550
551 /* ----------------------------------------------------------------------
552  * Generic routines to deal with send buffers: a linked list of
553  * smallish blocks, with the operations
554  * 
555  *  - add an arbitrary amount of data to the end of the list
556  *  - remove the first N bytes from the list
557  *  - return a (pointer,length) pair giving some initial data in
558  *    the list, suitable for passing to a send or write system
559  *    call
560  *  - retrieve a larger amount of initial data from the list
561  *  - return the current size of the buffer chain in bytes
562  */
563
564 #define BUFFER_MIN_GRANULE  512
565
566 struct bufchain_granule {
567     struct bufchain_granule *next;
568     char *bufpos, *bufend, *bufmax;
569 };
570
571 void bufchain_init(bufchain *ch)
572 {
573     ch->head = ch->tail = NULL;
574     ch->buffersize = 0;
575 }
576
577 void bufchain_clear(bufchain *ch)
578 {
579     struct bufchain_granule *b;
580     while (ch->head) {
581         b = ch->head;
582         ch->head = ch->head->next;
583         sfree(b);
584     }
585     ch->tail = NULL;
586     ch->buffersize = 0;
587 }
588
589 int bufchain_size(bufchain *ch)
590 {
591     return ch->buffersize;
592 }
593
594 void bufchain_add(bufchain *ch, const void *data, int len)
595 {
596     const char *buf = (const char *)data;
597
598     if (len == 0) return;
599
600     ch->buffersize += len;
601
602     while (len > 0) {
603         if (ch->tail && ch->tail->bufend < ch->tail->bufmax) {
604             int copylen = min(len, ch->tail->bufmax - ch->tail->bufend);
605             memcpy(ch->tail->bufend, buf, copylen);
606             buf += copylen;
607             len -= copylen;
608             ch->tail->bufend += copylen;
609         }
610         if (len > 0) {
611             int grainlen =
612                 max(sizeof(struct bufchain_granule) + len, BUFFER_MIN_GRANULE);
613             struct bufchain_granule *newbuf;
614             newbuf = smalloc(grainlen);
615             newbuf->bufpos = newbuf->bufend =
616                 (char *)newbuf + sizeof(struct bufchain_granule);
617             newbuf->bufmax = (char *)newbuf + grainlen;
618             newbuf->next = NULL;
619             if (ch->tail)
620                 ch->tail->next = newbuf;
621             else
622                 ch->head = newbuf;
623             ch->tail = newbuf;
624         }
625     }
626 }
627
628 void bufchain_consume(bufchain *ch, int len)
629 {
630     struct bufchain_granule *tmp;
631
632     assert(ch->buffersize >= len);
633     while (len > 0) {
634         int remlen = len;
635         assert(ch->head != NULL);
636         if (remlen >= ch->head->bufend - ch->head->bufpos) {
637             remlen = ch->head->bufend - ch->head->bufpos;
638             tmp = ch->head;
639             ch->head = tmp->next;
640             if (!ch->head)
641                 ch->tail = NULL;
642             sfree(tmp);
643         } else
644             ch->head->bufpos += remlen;
645         ch->buffersize -= remlen;
646         len -= remlen;
647     }
648 }
649
650 void bufchain_prefix(bufchain *ch, void **data, int *len)
651 {
652     *len = ch->head->bufend - ch->head->bufpos;
653     *data = ch->head->bufpos;
654 }
655
656 void bufchain_fetch(bufchain *ch, void *data, int len)
657 {
658     struct bufchain_granule *tmp;
659     char *data_c = (char *)data;
660
661     tmp = ch->head;
662
663     assert(ch->buffersize >= len);
664     while (len > 0) {
665         int remlen = len;
666
667         assert(tmp != NULL);
668         if (remlen >= tmp->bufend - tmp->bufpos)
669             remlen = tmp->bufend - tmp->bufpos;
670         memcpy(data_c, tmp->bufpos, remlen);
671
672         tmp = tmp->next;
673         len -= remlen;
674         data_c += remlen;
675     }
676 }
677
678 /* ----------------------------------------------------------------------
679  * My own versions of malloc, realloc and free. Because I want
680  * malloc and realloc to bomb out and exit the program if they run
681  * out of memory, realloc to reliably call malloc if passed a NULL
682  * pointer, and free to reliably do nothing if passed a NULL
683  * pointer. We can also put trace printouts in, if we need to; and
684  * we can also replace the allocator with an ElectricFence-like
685  * one.
686  */
687
688 #ifdef MINEFIELD
689 void *minefield_c_malloc(size_t size);
690 void minefield_c_free(void *p);
691 void *minefield_c_realloc(void *p, size_t size);
692 #endif
693
694 #ifdef MALLOC_LOG
695 static FILE *fp = NULL;
696
697 static char *mlog_file = NULL;
698 static int mlog_line = 0;
699
700 void mlog(char *file, int line)
701 {
702     mlog_file = file;
703     mlog_line = line;
704     if (!fp) {
705         fp = fopen("putty_mem.log", "w");
706         setvbuf(fp, NULL, _IONBF, BUFSIZ);
707     }
708     if (fp)
709         fprintf(fp, "%s:%d: ", file, line);
710 }
711 #endif
712
713 void *safemalloc(size_t n, size_t size)
714 {
715     void *p;
716
717     if (n > INT_MAX / size) {
718         p = NULL;
719     } else {
720         size *= n;
721         if (size == 0) size = 1;
722 #ifdef MINEFIELD
723         p = minefield_c_malloc(size);
724 #else
725         p = malloc(size);
726 #endif
727     }
728
729     if (!p) {
730         char str[200];
731 #ifdef MALLOC_LOG
732         sprintf(str, "Out of memory! (%s:%d, size=%d)",
733                 mlog_file, mlog_line, size);
734         fprintf(fp, "*** %s\n", str);
735         fclose(fp);
736 #else
737         strcpy(str, "Out of memory!");
738 #endif
739         modalfatalbox(str);
740     }
741 #ifdef MALLOC_LOG
742     if (fp)
743         fprintf(fp, "malloc(%d) returns %p\n", size, p);
744 #endif
745     return p;
746 }
747
748 void *saferealloc(void *ptr, size_t n, size_t size)
749 {
750     void *p;
751
752     if (n > INT_MAX / size) {
753         p = NULL;
754     } else {
755         size *= n;
756         if (!ptr) {
757 #ifdef MINEFIELD
758             p = minefield_c_malloc(size);
759 #else
760             p = malloc(size);
761 #endif
762         } else {
763 #ifdef MINEFIELD
764             p = minefield_c_realloc(ptr, size);
765 #else
766             p = realloc(ptr, size);
767 #endif
768         }
769     }
770
771     if (!p) {
772         char str[200];
773 #ifdef MALLOC_LOG
774         sprintf(str, "Out of memory! (%s:%d, size=%d)",
775                 mlog_file, mlog_line, size);
776         fprintf(fp, "*** %s\n", str);
777         fclose(fp);
778 #else
779         strcpy(str, "Out of memory!");
780 #endif
781         modalfatalbox(str);
782     }
783 #ifdef MALLOC_LOG
784     if (fp)
785         fprintf(fp, "realloc(%p,%d) returns %p\n", ptr, size, p);
786 #endif
787     return p;
788 }
789
790 void safefree(void *ptr)
791 {
792     if (ptr) {
793 #ifdef MALLOC_LOG
794         if (fp)
795             fprintf(fp, "free(%p)\n", ptr);
796 #endif
797 #ifdef MINEFIELD
798         minefield_c_free(ptr);
799 #else
800         free(ptr);
801 #endif
802     }
803 #ifdef MALLOC_LOG
804     else if (fp)
805         fprintf(fp, "freeing null pointer - no action taken\n");
806 #endif
807 }
808
809 /* ----------------------------------------------------------------------
810  * Debugging routines.
811  */
812
813 #ifdef DEBUG
814 extern void dputs(char *);             /* defined in per-platform *misc.c */
815
816 void debug_printf(char *fmt, ...)
817 {
818     char *buf;
819     va_list ap;
820
821     va_start(ap, fmt);
822     buf = dupvprintf(fmt, ap);
823     dputs(buf);
824     sfree(buf);
825     va_end(ap);
826 }
827
828
829 void debug_memdump(void *buf, int len, int L)
830 {
831     int i;
832     unsigned char *p = buf;
833     char foo[17];
834     if (L) {
835         int delta;
836         debug_printf("\t%d (0x%x) bytes:\n", len, len);
837         delta = 15 & (unsigned long int) p;
838         p -= delta;
839         len += delta;
840     }
841     for (; 0 < len; p += 16, len -= 16) {
842         dputs("  ");
843         if (L)
844             debug_printf("%p: ", p);
845         strcpy(foo, "................");        /* sixteen dots */
846         for (i = 0; i < 16 && i < len; ++i) {
847             if (&p[i] < (unsigned char *) buf) {
848                 dputs("   ");          /* 3 spaces */
849                 foo[i] = ' ';
850             } else {
851                 debug_printf("%c%02.2x",
852                         &p[i] != (unsigned char *) buf
853                         && i % 4 ? '.' : ' ', p[i]
854                     );
855                 if (p[i] >= ' ' && p[i] <= '~')
856                     foo[i] = (char) p[i];
857             }
858         }
859         foo[i] = '\0';
860         debug_printf("%*s%s\n", (16 - i) * 3 + 2, "", foo);
861     }
862 }
863
864 #endif                          /* def DEBUG */
865
866 /*
867  * Determine whether or not a Conf represents a session which can
868  * sensibly be launched right now.
869  */
870 int conf_launchable(Conf *conf)
871 {
872     if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL)
873         return conf_get_str(conf, CONF_serline)[0] != 0;
874     else
875         return conf_get_str(conf, CONF_host)[0] != 0;
876 }
877
878 char const *conf_dest(Conf *conf)
879 {
880     if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL)
881         return conf_get_str(conf, CONF_serline);
882     else
883         return conf_get_str(conf, CONF_host);
884 }
885
886 #ifndef PLATFORM_HAS_SMEMCLR
887 /*
888  * Securely wipe memory.
889  *
890  * The actual wiping is no different from what memset would do: the
891  * point of 'securely' is to try to be sure over-clever compilers
892  * won't optimise away memsets on variables that are about to be freed
893  * or go out of scope. See
894  * https://buildsecurityin.us-cert.gov/bsi-rules/home/g1/771-BSI.html
895  *
896  * Some platforms (e.g. Windows) may provide their own version of this
897  * function.
898  */
899 void smemclr(void *b, size_t n) {
900     volatile char *vp;
901
902     if (b && n > 0) {
903         /*
904          * Zero out the memory.
905          */
906         memset(b, 0, n);
907
908         /*
909          * Perform a volatile access to the object, forcing the
910          * compiler to admit that the previous memset was important.
911          *
912          * This while loop should in practice run for zero iterations
913          * (since we know we just zeroed the object out), but in
914          * theory (as far as the compiler knows) it might range over
915          * the whole object. (If we had just written, say, '*vp =
916          * *vp;', a compiler could in principle have 'helpfully'
917          * optimised the memset into only zeroing out the first byte.
918          * This should be robust.)
919          */
920         vp = b;
921         while (*vp) vp++;
922     }
923 }
924 #endif