]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - misc.c
New hostname-handling functions in 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  * Base64 encoding routine. This is required in public-key writing
477  * but also in HTTP proxy handling, so it's centralised here.
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 /* ----------------------------------------------------------------------
505  * Generic routines to deal with send buffers: a linked list of
506  * smallish blocks, with the operations
507  * 
508  *  - add an arbitrary amount of data to the end of the list
509  *  - remove the first N bytes from the list
510  *  - return a (pointer,length) pair giving some initial data in
511  *    the list, suitable for passing to a send or write system
512  *    call
513  *  - retrieve a larger amount of initial data from the list
514  *  - return the current size of the buffer chain in bytes
515  */
516
517 #define BUFFER_MIN_GRANULE  512
518
519 struct bufchain_granule {
520     struct bufchain_granule *next;
521     char *bufpos, *bufend, *bufmax;
522 };
523
524 void bufchain_init(bufchain *ch)
525 {
526     ch->head = ch->tail = NULL;
527     ch->buffersize = 0;
528 }
529
530 void bufchain_clear(bufchain *ch)
531 {
532     struct bufchain_granule *b;
533     while (ch->head) {
534         b = ch->head;
535         ch->head = ch->head->next;
536         sfree(b);
537     }
538     ch->tail = NULL;
539     ch->buffersize = 0;
540 }
541
542 int bufchain_size(bufchain *ch)
543 {
544     return ch->buffersize;
545 }
546
547 void bufchain_add(bufchain *ch, const void *data, int len)
548 {
549     const char *buf = (const char *)data;
550
551     if (len == 0) return;
552
553     ch->buffersize += len;
554
555     while (len > 0) {
556         if (ch->tail && ch->tail->bufend < ch->tail->bufmax) {
557             int copylen = min(len, ch->tail->bufmax - ch->tail->bufend);
558             memcpy(ch->tail->bufend, buf, copylen);
559             buf += copylen;
560             len -= copylen;
561             ch->tail->bufend += copylen;
562         }
563         if (len > 0) {
564             int grainlen =
565                 max(sizeof(struct bufchain_granule) + len, BUFFER_MIN_GRANULE);
566             struct bufchain_granule *newbuf;
567             newbuf = smalloc(grainlen);
568             newbuf->bufpos = newbuf->bufend =
569                 (char *)newbuf + sizeof(struct bufchain_granule);
570             newbuf->bufmax = (char *)newbuf + grainlen;
571             newbuf->next = NULL;
572             if (ch->tail)
573                 ch->tail->next = newbuf;
574             else
575                 ch->head = newbuf;
576             ch->tail = newbuf;
577         }
578     }
579 }
580
581 void bufchain_consume(bufchain *ch, int len)
582 {
583     struct bufchain_granule *tmp;
584
585     assert(ch->buffersize >= len);
586     while (len > 0) {
587         int remlen = len;
588         assert(ch->head != NULL);
589         if (remlen >= ch->head->bufend - ch->head->bufpos) {
590             remlen = ch->head->bufend - ch->head->bufpos;
591             tmp = ch->head;
592             ch->head = tmp->next;
593             if (!ch->head)
594                 ch->tail = NULL;
595             sfree(tmp);
596         } else
597             ch->head->bufpos += remlen;
598         ch->buffersize -= remlen;
599         len -= remlen;
600     }
601 }
602
603 void bufchain_prefix(bufchain *ch, void **data, int *len)
604 {
605     *len = ch->head->bufend - ch->head->bufpos;
606     *data = ch->head->bufpos;
607 }
608
609 void bufchain_fetch(bufchain *ch, void *data, int len)
610 {
611     struct bufchain_granule *tmp;
612     char *data_c = (char *)data;
613
614     tmp = ch->head;
615
616     assert(ch->buffersize >= len);
617     while (len > 0) {
618         int remlen = len;
619
620         assert(tmp != NULL);
621         if (remlen >= tmp->bufend - tmp->bufpos)
622             remlen = tmp->bufend - tmp->bufpos;
623         memcpy(data_c, tmp->bufpos, remlen);
624
625         tmp = tmp->next;
626         len -= remlen;
627         data_c += remlen;
628     }
629 }
630
631 /* ----------------------------------------------------------------------
632  * My own versions of malloc, realloc and free. Because I want
633  * malloc and realloc to bomb out and exit the program if they run
634  * out of memory, realloc to reliably call malloc if passed a NULL
635  * pointer, and free to reliably do nothing if passed a NULL
636  * pointer. We can also put trace printouts in, if we need to; and
637  * we can also replace the allocator with an ElectricFence-like
638  * one.
639  */
640
641 #ifdef MINEFIELD
642 void *minefield_c_malloc(size_t size);
643 void minefield_c_free(void *p);
644 void *minefield_c_realloc(void *p, size_t size);
645 #endif
646
647 #ifdef MALLOC_LOG
648 static FILE *fp = NULL;
649
650 static char *mlog_file = NULL;
651 static int mlog_line = 0;
652
653 void mlog(char *file, int line)
654 {
655     mlog_file = file;
656     mlog_line = line;
657     if (!fp) {
658         fp = fopen("putty_mem.log", "w");
659         setvbuf(fp, NULL, _IONBF, BUFSIZ);
660     }
661     if (fp)
662         fprintf(fp, "%s:%d: ", file, line);
663 }
664 #endif
665
666 void *safemalloc(size_t n, size_t size)
667 {
668     void *p;
669
670     if (n > INT_MAX / size) {
671         p = NULL;
672     } else {
673         size *= n;
674         if (size == 0) size = 1;
675 #ifdef MINEFIELD
676         p = minefield_c_malloc(size);
677 #else
678         p = malloc(size);
679 #endif
680     }
681
682     if (!p) {
683         char str[200];
684 #ifdef MALLOC_LOG
685         sprintf(str, "Out of memory! (%s:%d, size=%d)",
686                 mlog_file, mlog_line, size);
687         fprintf(fp, "*** %s\n", str);
688         fclose(fp);
689 #else
690         strcpy(str, "Out of memory!");
691 #endif
692         modalfatalbox(str);
693     }
694 #ifdef MALLOC_LOG
695     if (fp)
696         fprintf(fp, "malloc(%d) returns %p\n", size, p);
697 #endif
698     return p;
699 }
700
701 void *saferealloc(void *ptr, size_t n, size_t size)
702 {
703     void *p;
704
705     if (n > INT_MAX / size) {
706         p = NULL;
707     } else {
708         size *= n;
709         if (!ptr) {
710 #ifdef MINEFIELD
711             p = minefield_c_malloc(size);
712 #else
713             p = malloc(size);
714 #endif
715         } else {
716 #ifdef MINEFIELD
717             p = minefield_c_realloc(ptr, size);
718 #else
719             p = realloc(ptr, size);
720 #endif
721         }
722     }
723
724     if (!p) {
725         char str[200];
726 #ifdef MALLOC_LOG
727         sprintf(str, "Out of memory! (%s:%d, size=%d)",
728                 mlog_file, mlog_line, size);
729         fprintf(fp, "*** %s\n", str);
730         fclose(fp);
731 #else
732         strcpy(str, "Out of memory!");
733 #endif
734         modalfatalbox(str);
735     }
736 #ifdef MALLOC_LOG
737     if (fp)
738         fprintf(fp, "realloc(%p,%d) returns %p\n", ptr, size, p);
739 #endif
740     return p;
741 }
742
743 void safefree(void *ptr)
744 {
745     if (ptr) {
746 #ifdef MALLOC_LOG
747         if (fp)
748             fprintf(fp, "free(%p)\n", ptr);
749 #endif
750 #ifdef MINEFIELD
751         minefield_c_free(ptr);
752 #else
753         free(ptr);
754 #endif
755     }
756 #ifdef MALLOC_LOG
757     else if (fp)
758         fprintf(fp, "freeing null pointer - no action taken\n");
759 #endif
760 }
761
762 /* ----------------------------------------------------------------------
763  * Debugging routines.
764  */
765
766 #ifdef DEBUG
767 extern void dputs(char *);             /* defined in per-platform *misc.c */
768
769 void debug_printf(char *fmt, ...)
770 {
771     char *buf;
772     va_list ap;
773
774     va_start(ap, fmt);
775     buf = dupvprintf(fmt, ap);
776     dputs(buf);
777     sfree(buf);
778     va_end(ap);
779 }
780
781
782 void debug_memdump(void *buf, int len, int L)
783 {
784     int i;
785     unsigned char *p = buf;
786     char foo[17];
787     if (L) {
788         int delta;
789         debug_printf("\t%d (0x%x) bytes:\n", len, len);
790         delta = 15 & (unsigned long int) p;
791         p -= delta;
792         len += delta;
793     }
794     for (; 0 < len; p += 16, len -= 16) {
795         dputs("  ");
796         if (L)
797             debug_printf("%p: ", p);
798         strcpy(foo, "................");        /* sixteen dots */
799         for (i = 0; i < 16 && i < len; ++i) {
800             if (&p[i] < (unsigned char *) buf) {
801                 dputs("   ");          /* 3 spaces */
802                 foo[i] = ' ';
803             } else {
804                 debug_printf("%c%02.2x",
805                         &p[i] != (unsigned char *) buf
806                         && i % 4 ? '.' : ' ', p[i]
807                     );
808                 if (p[i] >= ' ' && p[i] <= '~')
809                     foo[i] = (char) p[i];
810             }
811         }
812         foo[i] = '\0';
813         debug_printf("%*s%s\n", (16 - i) * 3 + 2, "", foo);
814     }
815 }
816
817 #endif                          /* def DEBUG */
818
819 /*
820  * Determine whether or not a Conf represents a session which can
821  * sensibly be launched right now.
822  */
823 int conf_launchable(Conf *conf)
824 {
825     if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL)
826         return conf_get_str(conf, CONF_serline)[0] != 0;
827     else
828         return conf_get_str(conf, CONF_host)[0] != 0;
829 }
830
831 char const *conf_dest(Conf *conf)
832 {
833     if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL)
834         return conf_get_str(conf, CONF_serline);
835     else
836         return conf_get_str(conf, CONF_host);
837 }
838
839 #ifndef PLATFORM_HAS_SMEMCLR
840 /*
841  * Securely wipe memory.
842  *
843  * The actual wiping is no different from what memset would do: the
844  * point of 'securely' is to try to be sure over-clever compilers
845  * won't optimise away memsets on variables that are about to be freed
846  * or go out of scope. See
847  * https://buildsecurityin.us-cert.gov/bsi-rules/home/g1/771-BSI.html
848  *
849  * Some platforms (e.g. Windows) may provide their own version of this
850  * function.
851  */
852 void smemclr(void *b, size_t n) {
853     volatile char *vp;
854
855     if (b && n > 0) {
856         /*
857          * Zero out the memory.
858          */
859         memset(b, 0, n);
860
861         /*
862          * Perform a volatile access to the object, forcing the
863          * compiler to admit that the previous memset was important.
864          *
865          * This while loop should in practice run for zero iterations
866          * (since we know we just zeroed the object out), but in
867          * theory (as far as the compiler knows) it might range over
868          * the whole object. (If we had just written, say, '*vp =
869          * *vp;', a compiler could in principle have 'helpfully'
870          * optimised the memset into only zeroing out the first byte.
871          * This should be robust.)
872          */
873         vp = b;
874         while (*vp) vp++;
875     }
876 }
877 #endif