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