]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - misc.c
Basic configurability for client-initiated rekeys.
[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 <ctype.h>
9 #include <assert.h>
10 #include "putty.h"
11
12 /*
13  * Parse a string block size specification. This is approximately a
14  * subset of the block size specs supported by GNU fileutils:
15  *  "nk" = n kilobytes
16  *  "nM" = n megabytes
17  *  "nG" = n gigabytes
18  * All numbers are decimal, and suffixes refer to powers of two.
19  * Case-insensitive.
20  */
21 unsigned long parse_blocksize(const char *bs)
22 {
23     char *suf;
24     unsigned long r = strtoul(bs, &suf, 10);
25     if (*suf != '\0') {
26         while (isspace(*suf)) suf++;
27         switch (*suf) {
28           case 'k': case 'K':
29             r *= 1024ul;
30             break;
31           case 'm': case 'M':
32             r *= 1024ul * 1024ul;
33             break;
34           case 'g': case 'G':
35             r *= 1024ul * 1024ul * 1024ul;
36             break;
37           case '\0':
38           default:
39             break;
40         }
41     }
42     return r;
43 }
44
45 /* ----------------------------------------------------------------------
46  * String handling routines.
47  */
48
49 char *dupstr(const char *s)
50 {
51     char *p = NULL;
52     if (s) {
53         int len = strlen(s);
54         p = snewn(len + 1, char);
55         strcpy(p, s);
56     }
57     return p;
58 }
59
60 /* Allocate the concatenation of N strings. Terminate arg list with NULL. */
61 char *dupcat(const char *s1, ...)
62 {
63     int len;
64     char *p, *q, *sn;
65     va_list ap;
66
67     len = strlen(s1);
68     va_start(ap, s1);
69     while (1) {
70         sn = va_arg(ap, char *);
71         if (!sn)
72             break;
73         len += strlen(sn);
74     }
75     va_end(ap);
76
77     p = snewn(len + 1, char);
78     strcpy(p, s1);
79     q = p + strlen(p);
80
81     va_start(ap, s1);
82     while (1) {
83         sn = va_arg(ap, char *);
84         if (!sn)
85             break;
86         strcpy(q, sn);
87         q += strlen(q);
88     }
89     va_end(ap);
90
91     return p;
92 }
93
94 /*
95  * Do an sprintf(), but into a custom-allocated buffer.
96  * 
97  * Currently I'm doing this via vsnprintf. This has worked so far,
98  * but it's not good, because:
99  * 
100  *  - vsnprintf is not available on all platforms. There's an ifdef
101  *    to use `_vsnprintf', which seems to be the local name for it
102  *    on Windows. Other platforms may lack it completely, in which
103  *    case it'll be time to rewrite this function in a totally
104  *    different way.
105  * 
106  *  - technically you can't reuse a va_list like this: it is left
107  *    unspecified whether advancing a va_list pointer modifies its
108  *    value or something it points to, so on some platforms calling
109  *    vsnprintf twice on the same va_list might fail hideously. It
110  *    would be better to use the `va_copy' macro mandated by C99,
111  *    but that too is not yet ubiquitous.
112  * 
113  * The only `properly' portable solution I can think of is to
114  * implement my own format string scanner, which figures out an
115  * upper bound for the length of each formatting directive,
116  * allocates the buffer as it goes along, and calls sprintf() to
117  * actually process each directive. If I ever need to actually do
118  * this, some caveats:
119  * 
120  *  - It's very hard to find a reliable upper bound for
121  *    floating-point values. %f, in particular, when supplied with
122  *    a number near to the upper or lower limit of representable
123  *    numbers, could easily take several hundred characters. It's
124  *    probably feasible to predict this statically using the
125  *    constants in <float.h>, or even to predict it dynamically by
126  *    looking at the exponent of the specific float provided, but
127  *    it won't be fun.
128  * 
129  *  - Don't forget to _check_, after calling sprintf, that it's
130  *    used at most the amount of space we had available.
131  * 
132  *  - Fault any formatting directive we don't fully understand. The
133  *    aim here is to _guarantee_ that we never overflow the buffer,
134  *    because this is a security-critical function. If we see a
135  *    directive we don't know about, we should panic and die rather
136  *    than run any risk.
137  */
138 char *dupprintf(const char *fmt, ...)
139 {
140     char *ret;
141     va_list ap;
142     va_start(ap, fmt);
143     ret = dupvprintf(fmt, ap);
144     va_end(ap);
145     return ret;
146 }
147 char *dupvprintf(const char *fmt, va_list ap)
148 {
149     char *buf;
150     int len, size;
151
152     buf = snewn(512, char);
153     size = 512;
154
155     while (1) {
156 #ifdef _WINDOWS
157 #define vsnprintf _vsnprintf
158 #endif
159         len = vsnprintf(buf, size, fmt, ap);
160         if (len >= 0 && len < size) {
161             /* This is the C99-specified criterion for snprintf to have
162              * been completely successful. */
163             return buf;
164         } else if (len > 0) {
165             /* This is the C99 error condition: the returned length is
166              * the required buffer size not counting the NUL. */
167             size = len + 1;
168         } else {
169             /* This is the pre-C99 glibc error condition: <0 means the
170              * buffer wasn't big enough, so we enlarge it a bit and hope. */
171             size += 512;
172         }
173         buf = sresize(buf, size, char);
174     }
175 }
176
177 /*
178  * Read an entire line of text from a file. Return a buffer
179  * malloced to be as big as necessary (caller must free).
180  */
181 char *fgetline(FILE *fp)
182 {
183     char *ret = snewn(512, char);
184     int size = 512, len = 0;
185     while (fgets(ret + len, size - len, fp)) {
186         len += strlen(ret + len);
187         if (ret[len-1] == '\n')
188             break;                     /* got a newline, we're done */
189         size = len + 512;
190         ret = sresize(ret, size, char);
191     }
192     if (len == 0) {                    /* first fgets returned NULL */
193         sfree(ret);
194         return NULL;
195     }
196     ret[len] = '\0';
197     return ret;
198 }
199
200 /* ----------------------------------------------------------------------
201  * Base64 encoding routine. This is required in public-key writing
202  * but also in HTTP proxy handling, so it's centralised here.
203  */
204
205 void base64_encode_atom(unsigned char *data, int n, char *out)
206 {
207     static const char base64_chars[] =
208         "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
209
210     unsigned word;
211
212     word = data[0] << 16;
213     if (n > 1)
214         word |= data[1] << 8;
215     if (n > 2)
216         word |= data[2];
217     out[0] = base64_chars[(word >> 18) & 0x3F];
218     out[1] = base64_chars[(word >> 12) & 0x3F];
219     if (n > 1)
220         out[2] = base64_chars[(word >> 6) & 0x3F];
221     else
222         out[2] = '=';
223     if (n > 2)
224         out[3] = base64_chars[word & 0x3F];
225     else
226         out[3] = '=';
227 }
228
229 /* ----------------------------------------------------------------------
230  * Generic routines to deal with send buffers: a linked list of
231  * smallish blocks, with the operations
232  * 
233  *  - add an arbitrary amount of data to the end of the list
234  *  - remove the first N bytes from the list
235  *  - return a (pointer,length) pair giving some initial data in
236  *    the list, suitable for passing to a send or write system
237  *    call
238  *  - retrieve a larger amount of initial data from the list
239  *  - return the current size of the buffer chain in bytes
240  */
241
242 #define BUFFER_GRANULE  512
243
244 struct bufchain_granule {
245     struct bufchain_granule *next;
246     int buflen, bufpos;
247     char buf[BUFFER_GRANULE];
248 };
249
250 void bufchain_init(bufchain *ch)
251 {
252     ch->head = ch->tail = NULL;
253     ch->buffersize = 0;
254 }
255
256 void bufchain_clear(bufchain *ch)
257 {
258     struct bufchain_granule *b;
259     while (ch->head) {
260         b = ch->head;
261         ch->head = ch->head->next;
262         sfree(b);
263     }
264     ch->tail = NULL;
265     ch->buffersize = 0;
266 }
267
268 int bufchain_size(bufchain *ch)
269 {
270     return ch->buffersize;
271 }
272
273 void bufchain_add(bufchain *ch, const void *data, int len)
274 {
275     const char *buf = (const char *)data;
276
277     if (len == 0) return;
278
279     ch->buffersize += len;
280
281     if (ch->tail && ch->tail->buflen < BUFFER_GRANULE) {
282         int copylen = min(len, BUFFER_GRANULE - ch->tail->buflen);
283         memcpy(ch->tail->buf + ch->tail->buflen, buf, copylen);
284         buf += copylen;
285         len -= copylen;
286         ch->tail->buflen += copylen;
287     }
288     while (len > 0) {
289         int grainlen = min(len, BUFFER_GRANULE);
290         struct bufchain_granule *newbuf;
291         newbuf = snew(struct bufchain_granule);
292         newbuf->bufpos = 0;
293         newbuf->buflen = grainlen;
294         memcpy(newbuf->buf, buf, grainlen);
295         buf += grainlen;
296         len -= grainlen;
297         if (ch->tail)
298             ch->tail->next = newbuf;
299         else
300             ch->head = ch->tail = newbuf;
301         newbuf->next = NULL;
302         ch->tail = newbuf;
303     }
304 }
305
306 void bufchain_consume(bufchain *ch, int len)
307 {
308     struct bufchain_granule *tmp;
309
310     assert(ch->buffersize >= len);
311     while (len > 0) {
312         int remlen = len;
313         assert(ch->head != NULL);
314         if (remlen >= ch->head->buflen - ch->head->bufpos) {
315             remlen = ch->head->buflen - ch->head->bufpos;
316             tmp = ch->head;
317             ch->head = tmp->next;
318             sfree(tmp);
319             if (!ch->head)
320                 ch->tail = NULL;
321         } else
322             ch->head->bufpos += remlen;
323         ch->buffersize -= remlen;
324         len -= remlen;
325     }
326 }
327
328 void bufchain_prefix(bufchain *ch, void **data, int *len)
329 {
330     *len = ch->head->buflen - ch->head->bufpos;
331     *data = ch->head->buf + ch->head->bufpos;
332 }
333
334 void bufchain_fetch(bufchain *ch, void *data, int len)
335 {
336     struct bufchain_granule *tmp;
337     char *data_c = (char *)data;
338
339     tmp = ch->head;
340
341     assert(ch->buffersize >= len);
342     while (len > 0) {
343         int remlen = len;
344
345         assert(tmp != NULL);
346         if (remlen >= tmp->buflen - tmp->bufpos)
347             remlen = tmp->buflen - tmp->bufpos;
348         memcpy(data_c, tmp->buf + tmp->bufpos, remlen);
349
350         tmp = tmp->next;
351         len -= remlen;
352         data_c += remlen;
353     }
354 }
355
356 /* ----------------------------------------------------------------------
357  * My own versions of malloc, realloc and free. Because I want
358  * malloc and realloc to bomb out and exit the program if they run
359  * out of memory, realloc to reliably call malloc if passed a NULL
360  * pointer, and free to reliably do nothing if passed a NULL
361  * pointer. We can also put trace printouts in, if we need to; and
362  * we can also replace the allocator with an ElectricFence-like
363  * one.
364  */
365
366 #ifdef MINEFIELD
367 void *minefield_c_malloc(size_t size);
368 void minefield_c_free(void *p);
369 void *minefield_c_realloc(void *p, size_t size);
370 #endif
371
372 #ifdef MALLOC_LOG
373 static FILE *fp = NULL;
374
375 static char *mlog_file = NULL;
376 static int mlog_line = 0;
377
378 void mlog(char *file, int line)
379 {
380     mlog_file = file;
381     mlog_line = line;
382     if (!fp) {
383         fp = fopen("putty_mem.log", "w");
384         setvbuf(fp, NULL, _IONBF, BUFSIZ);
385     }
386     if (fp)
387         fprintf(fp, "%s:%d: ", file, line);
388 }
389 #endif
390
391 void *safemalloc(size_t size)
392 {
393     void *p;
394 #ifdef MINEFIELD
395     p = minefield_c_malloc(size);
396 #else
397     p = malloc(size);
398 #endif
399     if (!p) {
400         char str[200];
401 #ifdef MALLOC_LOG
402         sprintf(str, "Out of memory! (%s:%d, size=%d)",
403                 mlog_file, mlog_line, size);
404         fprintf(fp, "*** %s\n", str);
405         fclose(fp);
406 #else
407         strcpy(str, "Out of memory!");
408 #endif
409         modalfatalbox(str);
410     }
411 #ifdef MALLOC_LOG
412     if (fp)
413         fprintf(fp, "malloc(%d) returns %p\n", size, p);
414 #endif
415     return p;
416 }
417
418 void *saferealloc(void *ptr, size_t size)
419 {
420     void *p;
421     if (!ptr) {
422 #ifdef MINEFIELD
423         p = minefield_c_malloc(size);
424 #else
425         p = malloc(size);
426 #endif
427     } else {
428 #ifdef MINEFIELD
429         p = minefield_c_realloc(ptr, size);
430 #else
431         p = realloc(ptr, size);
432 #endif
433     }
434     if (!p) {
435         char str[200];
436 #ifdef MALLOC_LOG
437         sprintf(str, "Out of memory! (%s:%d, size=%d)",
438                 mlog_file, mlog_line, size);
439         fprintf(fp, "*** %s\n", str);
440         fclose(fp);
441 #else
442         strcpy(str, "Out of memory!");
443 #endif
444         modalfatalbox(str);
445     }
446 #ifdef MALLOC_LOG
447     if (fp)
448         fprintf(fp, "realloc(%p,%d) returns %p\n", ptr, size, p);
449 #endif
450     return p;
451 }
452
453 void safefree(void *ptr)
454 {
455     if (ptr) {
456 #ifdef MALLOC_LOG
457         if (fp)
458             fprintf(fp, "free(%p)\n", ptr);
459 #endif
460 #ifdef MINEFIELD
461         minefield_c_free(ptr);
462 #else
463         free(ptr);
464 #endif
465     }
466 #ifdef MALLOC_LOG
467     else if (fp)
468         fprintf(fp, "freeing null pointer - no action taken\n");
469 #endif
470 }
471
472 /* ----------------------------------------------------------------------
473  * Debugging routines.
474  */
475
476 #ifdef DEBUG
477 extern void dputs(char *);             /* defined in per-platform *misc.c */
478
479 void debug_printf(char *fmt, ...)
480 {
481     char *buf;
482     va_list ap;
483
484     va_start(ap, fmt);
485     buf = dupvprintf(fmt, ap);
486     dputs(buf);
487     sfree(buf);
488     va_end(ap);
489 }
490
491
492 void debug_memdump(void *buf, int len, int L)
493 {
494     int i;
495     unsigned char *p = buf;
496     char foo[17];
497     if (L) {
498         int delta;
499         debug_printf("\t%d (0x%x) bytes:\n", len, len);
500         delta = 15 & (int) p;
501         p -= delta;
502         len += delta;
503     }
504     for (; 0 < len; p += 16, len -= 16) {
505         dputs("  ");
506         if (L)
507             debug_printf("%p: ", p);
508         strcpy(foo, "................");        /* sixteen dots */
509         for (i = 0; i < 16 && i < len; ++i) {
510             if (&p[i] < (unsigned char *) buf) {
511                 dputs("   ");          /* 3 spaces */
512                 foo[i] = ' ';
513             } else {
514                 debug_printf("%c%02.2x",
515                         &p[i] != (unsigned char *) buf
516                         && i % 4 ? '.' : ' ', p[i]
517                     );
518                 if (p[i] >= ' ' && p[i] <= '~')
519                     foo[i] = (char) p[i];
520             }
521         }
522         foo[i] = '\0';
523         debug_printf("%*s%s\n", (16 - i) * 3 + 2, "", foo);
524     }
525 }
526
527 #endif                          /* def DEBUG */