]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - misc.c
636ca9f39f003a60901ea4f2495c0cdf027775af
[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 prompts_t *new_prompts(void *frontend)
91 {
92     prompts_t *p = snew(prompts_t);
93     p->prompts = NULL;
94     p->n_prompts = 0;
95     p->frontend = frontend;
96     p->data = NULL;
97     p->to_server = TRUE; /* to be on the safe side */
98     p->name = p->instruction = NULL;
99     p->name_reqd = p->instr_reqd = FALSE;
100     return p;
101 }
102 void add_prompt(prompts_t *p, char *promptstr, int echo)
103 {
104     prompt_t *pr = snew(prompt_t);
105     pr->prompt = promptstr;
106     pr->echo = echo;
107     pr->result = NULL;
108     pr->resultsize = 0;
109     p->n_prompts++;
110     p->prompts = sresize(p->prompts, p->n_prompts, prompt_t *);
111     p->prompts[p->n_prompts-1] = pr;
112 }
113 void prompt_ensure_result_size(prompt_t *pr, int newlen)
114 {
115     if ((int)pr->resultsize < newlen) {
116         char *newbuf;
117         newlen = newlen * 5 / 4 + 512; /* avoid too many small allocs */
118
119         /*
120          * We don't use sresize / realloc here, because we will be
121          * storing sensitive stuff like passwords in here, and we want
122          * to make sure that the data doesn't get copied around in
123          * memory without the old copy being destroyed.
124          */
125         newbuf = snewn(newlen, char);
126         memcpy(newbuf, pr->result, pr->resultsize);
127         memset(pr->result, '\0', pr->resultsize);
128         sfree(pr->result);
129         pr->result = newbuf;
130         pr->resultsize = newlen;
131     }
132 }
133 void prompt_set_result(prompt_t *pr, const char *newstr)
134 {
135     prompt_ensure_result_size(pr, strlen(newstr) + 1);
136     strcpy(pr->result, newstr);
137 }
138 void free_prompts(prompts_t *p)
139 {
140     size_t i;
141     for (i=0; i < p->n_prompts; i++) {
142         prompt_t *pr = p->prompts[i];
143         memset(pr->result, 0, pr->resultsize); /* burn the evidence */
144         sfree(pr->result);
145         sfree(pr->prompt);
146         sfree(pr);
147     }
148     sfree(p->prompts);
149     sfree(p->name);
150     sfree(p->instruction);
151     sfree(p);
152 }
153
154 /* ----------------------------------------------------------------------
155  * String handling routines.
156  */
157
158 char *dupstr(const char *s)
159 {
160     char *p = NULL;
161     if (s) {
162         int len = strlen(s);
163         p = snewn(len + 1, char);
164         strcpy(p, s);
165     }
166     return p;
167 }
168
169 /* Allocate the concatenation of N strings. Terminate arg list with NULL. */
170 char *dupcat(const char *s1, ...)
171 {
172     int len;
173     char *p, *q, *sn;
174     va_list ap;
175
176     len = strlen(s1);
177     va_start(ap, s1);
178     while (1) {
179         sn = va_arg(ap, char *);
180         if (!sn)
181             break;
182         len += strlen(sn);
183     }
184     va_end(ap);
185
186     p = snewn(len + 1, char);
187     strcpy(p, s1);
188     q = p + strlen(p);
189
190     va_start(ap, s1);
191     while (1) {
192         sn = va_arg(ap, char *);
193         if (!sn)
194             break;
195         strcpy(q, sn);
196         q += strlen(q);
197     }
198     va_end(ap);
199
200     return p;
201 }
202
203 void burnstr(char *string)             /* sfree(str), only clear it first */
204 {
205     if (string) {
206         memset(string, 0, strlen(string));
207         sfree(string);
208     }
209 }
210
211 /*
212  * Do an sprintf(), but into a custom-allocated buffer.
213  * 
214  * Currently I'm doing this via vsnprintf. This has worked so far,
215  * but it's not good, because vsnprintf is not available on all
216  * platforms. There's an ifdef to use `_vsnprintf', which seems
217  * to be the local name for it on Windows. Other platforms may
218  * lack it completely, in which case it'll be time to rewrite
219  * this function in a totally different way.
220  * 
221  * The only `properly' portable solution I can think of is to
222  * implement my own format string scanner, which figures out an
223  * upper bound for the length of each formatting directive,
224  * allocates the buffer as it goes along, and calls sprintf() to
225  * actually process each directive. If I ever need to actually do
226  * this, some caveats:
227  * 
228  *  - It's very hard to find a reliable upper bound for
229  *    floating-point values. %f, in particular, when supplied with
230  *    a number near to the upper or lower limit of representable
231  *    numbers, could easily take several hundred characters. It's
232  *    probably feasible to predict this statically using the
233  *    constants in <float.h>, or even to predict it dynamically by
234  *    looking at the exponent of the specific float provided, but
235  *    it won't be fun.
236  * 
237  *  - Don't forget to _check_, after calling sprintf, that it's
238  *    used at most the amount of space we had available.
239  * 
240  *  - Fault any formatting directive we don't fully understand. The
241  *    aim here is to _guarantee_ that we never overflow the buffer,
242  *    because this is a security-critical function. If we see a
243  *    directive we don't know about, we should panic and die rather
244  *    than run any risk.
245  */
246 char *dupprintf(const char *fmt, ...)
247 {
248     char *ret;
249     va_list ap;
250     va_start(ap, fmt);
251     ret = dupvprintf(fmt, ap);
252     va_end(ap);
253     return ret;
254 }
255 char *dupvprintf(const char *fmt, va_list ap)
256 {
257     char *buf;
258     int len, size;
259
260     buf = snewn(512, char);
261     size = 512;
262
263     while (1) {
264 #ifdef _WINDOWS
265 #define vsnprintf _vsnprintf
266 #endif
267 #ifdef va_copy
268         /* Use the `va_copy' macro mandated by C99, if present.
269          * XXX some environments may have this as __va_copy() */
270         va_list aq;
271         va_copy(aq, ap);
272         len = vsnprintf(buf, size, fmt, aq);
273         va_end(aq);
274 #else
275         /* Ugh. No va_copy macro, so do something nasty.
276          * Technically, you can't reuse a va_list like this: it is left
277          * unspecified whether advancing a va_list pointer modifies its
278          * value or something it points to, so on some platforms calling
279          * vsnprintf twice on the same va_list might fail hideously
280          * (indeed, it has been observed to).
281          * XXX the autoconf manual suggests that using memcpy() will give
282          *     "maximum portability". */
283         len = vsnprintf(buf, size, fmt, ap);
284 #endif
285         if (len >= 0 && len < size) {
286             /* This is the C99-specified criterion for snprintf to have
287              * been completely successful. */
288             return buf;
289         } else if (len > 0) {
290             /* This is the C99 error condition: the returned length is
291              * the required buffer size not counting the NUL. */
292             size = len + 1;
293         } else {
294             /* This is the pre-C99 glibc error condition: <0 means the
295              * buffer wasn't big enough, so we enlarge it a bit and hope. */
296             size += 512;
297         }
298         buf = sresize(buf, size, char);
299     }
300 }
301
302 /*
303  * Read an entire line of text from a file. Return a buffer
304  * malloced to be as big as necessary (caller must free).
305  */
306 char *fgetline(FILE *fp)
307 {
308     char *ret = snewn(512, char);
309     int size = 512, len = 0;
310     while (fgets(ret + len, size - len, fp)) {
311         len += strlen(ret + len);
312         if (ret[len-1] == '\n')
313             break;                     /* got a newline, we're done */
314         size = len + 512;
315         ret = sresize(ret, size, char);
316     }
317     if (len == 0) {                    /* first fgets returned NULL */
318         sfree(ret);
319         return NULL;
320     }
321     ret[len] = '\0';
322     return ret;
323 }
324
325 /* ----------------------------------------------------------------------
326  * Base64 encoding routine. This is required in public-key writing
327  * but also in HTTP proxy handling, so it's centralised here.
328  */
329
330 void base64_encode_atom(unsigned char *data, int n, char *out)
331 {
332     static const char base64_chars[] =
333         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
334
335     unsigned word;
336
337     word = data[0] << 16;
338     if (n > 1)
339         word |= data[1] << 8;
340     if (n > 2)
341         word |= data[2];
342     out[0] = base64_chars[(word >> 18) & 0x3F];
343     out[1] = base64_chars[(word >> 12) & 0x3F];
344     if (n > 1)
345         out[2] = base64_chars[(word >> 6) & 0x3F];
346     else
347         out[2] = '=';
348     if (n > 2)
349         out[3] = base64_chars[word & 0x3F];
350     else
351         out[3] = '=';
352 }
353
354 /* ----------------------------------------------------------------------
355  * Generic routines to deal with send buffers: a linked list of
356  * smallish blocks, with the operations
357  * 
358  *  - add an arbitrary amount of data to the end of the list
359  *  - remove the first N bytes from the list
360  *  - return a (pointer,length) pair giving some initial data in
361  *    the list, suitable for passing to a send or write system
362  *    call
363  *  - retrieve a larger amount of initial data from the list
364  *  - return the current size of the buffer chain in bytes
365  */
366
367 #define BUFFER_GRANULE  512
368
369 struct bufchain_granule {
370     struct bufchain_granule *next;
371     int buflen, bufpos;
372     char buf[BUFFER_GRANULE];
373 };
374
375 void bufchain_init(bufchain *ch)
376 {
377     ch->head = ch->tail = NULL;
378     ch->buffersize = 0;
379 }
380
381 void bufchain_clear(bufchain *ch)
382 {
383     struct bufchain_granule *b;
384     while (ch->head) {
385         b = ch->head;
386         ch->head = ch->head->next;
387         sfree(b);
388     }
389     ch->tail = NULL;
390     ch->buffersize = 0;
391 }
392
393 int bufchain_size(bufchain *ch)
394 {
395     return ch->buffersize;
396 }
397
398 void bufchain_add(bufchain *ch, const void *data, int len)
399 {
400     const char *buf = (const char *)data;
401
402     if (len == 0) return;
403
404     ch->buffersize += len;
405
406     if (ch->tail && ch->tail->buflen < BUFFER_GRANULE) {
407         int copylen = min(len, BUFFER_GRANULE - ch->tail->buflen);
408         memcpy(ch->tail->buf + ch->tail->buflen, buf, copylen);
409         buf += copylen;
410         len -= copylen;
411         ch->tail->buflen += copylen;
412     }
413     while (len > 0) {
414         int grainlen = min(len, BUFFER_GRANULE);
415         struct bufchain_granule *newbuf;
416         newbuf = snew(struct bufchain_granule);
417         newbuf->bufpos = 0;
418         newbuf->buflen = grainlen;
419         memcpy(newbuf->buf, buf, grainlen);
420         buf += grainlen;
421         len -= grainlen;
422         if (ch->tail)
423             ch->tail->next = newbuf;
424         else
425             ch->head = ch->tail = newbuf;
426         newbuf->next = NULL;
427         ch->tail = newbuf;
428     }
429 }
430
431 void bufchain_consume(bufchain *ch, int len)
432 {
433     struct bufchain_granule *tmp;
434
435     assert(ch->buffersize >= len);
436     while (len > 0) {
437         int remlen = len;
438         assert(ch->head != NULL);
439         if (remlen >= ch->head->buflen - ch->head->bufpos) {
440             remlen = ch->head->buflen - ch->head->bufpos;
441             tmp = ch->head;
442             ch->head = tmp->next;
443             sfree(tmp);
444             if (!ch->head)
445                 ch->tail = NULL;
446         } else
447             ch->head->bufpos += remlen;
448         ch->buffersize -= remlen;
449         len -= remlen;
450     }
451 }
452
453 void bufchain_prefix(bufchain *ch, void **data, int *len)
454 {
455     *len = ch->head->buflen - ch->head->bufpos;
456     *data = ch->head->buf + ch->head->bufpos;
457 }
458
459 void bufchain_fetch(bufchain *ch, void *data, int len)
460 {
461     struct bufchain_granule *tmp;
462     char *data_c = (char *)data;
463
464     tmp = ch->head;
465
466     assert(ch->buffersize >= len);
467     while (len > 0) {
468         int remlen = len;
469
470         assert(tmp != NULL);
471         if (remlen >= tmp->buflen - tmp->bufpos)
472             remlen = tmp->buflen - tmp->bufpos;
473         memcpy(data_c, tmp->buf + tmp->bufpos, remlen);
474
475         tmp = tmp->next;
476         len -= remlen;
477         data_c += remlen;
478     }
479 }
480
481 /* ----------------------------------------------------------------------
482  * My own versions of malloc, realloc and free. Because I want
483  * malloc and realloc to bomb out and exit the program if they run
484  * out of memory, realloc to reliably call malloc if passed a NULL
485  * pointer, and free to reliably do nothing if passed a NULL
486  * pointer. We can also put trace printouts in, if we need to; and
487  * we can also replace the allocator with an ElectricFence-like
488  * one.
489  */
490
491 #ifdef MINEFIELD
492 void *minefield_c_malloc(size_t size);
493 void minefield_c_free(void *p);
494 void *minefield_c_realloc(void *p, size_t size);
495 #endif
496
497 #ifdef MALLOC_LOG
498 static FILE *fp = NULL;
499
500 static char *mlog_file = NULL;
501 static int mlog_line = 0;
502
503 void mlog(char *file, int line)
504 {
505     mlog_file = file;
506     mlog_line = line;
507     if (!fp) {
508         fp = fopen("putty_mem.log", "w");
509         setvbuf(fp, NULL, _IONBF, BUFSIZ);
510     }
511     if (fp)
512         fprintf(fp, "%s:%d: ", file, line);
513 }
514 #endif
515
516 void *safemalloc(size_t n, size_t size)
517 {
518     void *p;
519
520     if (n > INT_MAX / size) {
521         p = NULL;
522     } else {
523         size *= n;
524         if (size == 0) size = 1;
525 #ifdef MINEFIELD
526         p = minefield_c_malloc(size);
527 #else
528         p = malloc(size);
529 #endif
530     }
531
532     if (!p) {
533         char str[200];
534 #ifdef MALLOC_LOG
535         sprintf(str, "Out of memory! (%s:%d, size=%d)",
536                 mlog_file, mlog_line, size);
537         fprintf(fp, "*** %s\n", str);
538         fclose(fp);
539 #else
540         strcpy(str, "Out of memory!");
541 #endif
542         modalfatalbox(str);
543     }
544 #ifdef MALLOC_LOG
545     if (fp)
546         fprintf(fp, "malloc(%d) returns %p\n", size, p);
547 #endif
548     return p;
549 }
550
551 void *saferealloc(void *ptr, size_t n, size_t size)
552 {
553     void *p;
554
555     if (n > INT_MAX / size) {
556         p = NULL;
557     } else {
558         size *= n;
559         if (!ptr) {
560 #ifdef MINEFIELD
561             p = minefield_c_malloc(size);
562 #else
563             p = malloc(size);
564 #endif
565         } else {
566 #ifdef MINEFIELD
567             p = minefield_c_realloc(ptr, size);
568 #else
569             p = realloc(ptr, size);
570 #endif
571         }
572     }
573
574     if (!p) {
575         char str[200];
576 #ifdef MALLOC_LOG
577         sprintf(str, "Out of memory! (%s:%d, size=%d)",
578                 mlog_file, mlog_line, size);
579         fprintf(fp, "*** %s\n", str);
580         fclose(fp);
581 #else
582         strcpy(str, "Out of memory!");
583 #endif
584         modalfatalbox(str);
585     }
586 #ifdef MALLOC_LOG
587     if (fp)
588         fprintf(fp, "realloc(%p,%d) returns %p\n", ptr, size, p);
589 #endif
590     return p;
591 }
592
593 void safefree(void *ptr)
594 {
595     if (ptr) {
596 #ifdef MALLOC_LOG
597         if (fp)
598             fprintf(fp, "free(%p)\n", ptr);
599 #endif
600 #ifdef MINEFIELD
601         minefield_c_free(ptr);
602 #else
603         free(ptr);
604 #endif
605     }
606 #ifdef MALLOC_LOG
607     else if (fp)
608         fprintf(fp, "freeing null pointer - no action taken\n");
609 #endif
610 }
611
612 /* ----------------------------------------------------------------------
613  * Debugging routines.
614  */
615
616 #ifdef DEBUG
617 extern void dputs(char *);             /* defined in per-platform *misc.c */
618
619 void debug_printf(char *fmt, ...)
620 {
621     char *buf;
622     va_list ap;
623
624     va_start(ap, fmt);
625     buf = dupvprintf(fmt, ap);
626     dputs(buf);
627     sfree(buf);
628     va_end(ap);
629 }
630
631
632 void debug_memdump(void *buf, int len, int L)
633 {
634     int i;
635     unsigned char *p = buf;
636     char foo[17];
637     if (L) {
638         int delta;
639         debug_printf("\t%d (0x%x) bytes:\n", len, len);
640         delta = 15 & (unsigned long int) p;
641         p -= delta;
642         len += delta;
643     }
644     for (; 0 < len; p += 16, len -= 16) {
645         dputs("  ");
646         if (L)
647             debug_printf("%p: ", p);
648         strcpy(foo, "................");        /* sixteen dots */
649         for (i = 0; i < 16 && i < len; ++i) {
650             if (&p[i] < (unsigned char *) buf) {
651                 dputs("   ");          /* 3 spaces */
652                 foo[i] = ' ';
653             } else {
654                 debug_printf("%c%02.2x",
655                         &p[i] != (unsigned char *) buf
656                         && i % 4 ? '.' : ' ', p[i]
657                     );
658                 if (p[i] >= ' ' && p[i] <= '~')
659                     foo[i] = (char) p[i];
660             }
661         }
662         foo[i] = '\0';
663         debug_printf("%*s%s\n", (16 - i) * 3 + 2, "", foo);
664     }
665 }
666
667 #endif                          /* def DEBUG */
668
669 /*
670  * Determine whether or not a Conf represents a session which can
671  * sensibly be launched right now.
672  */
673 int conf_launchable(Conf *conf)
674 {
675     if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL)
676         return conf_get_str(conf, CONF_serline)[0] != 0;
677     else
678         return conf_get_str(conf, CONF_host)[0] != 0;
679 }
680
681 char const *conf_dest(Conf *conf)
682 {
683     if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL)
684         return conf_get_str(conf, CONF_serline);
685     else
686         return conf_get_str(conf, CONF_host);
687 }