Correct some comments based on feedback from Thomas Dickey.
[u/mdw/putty] / misc.c
CommitLineData
f4ff9455 1/*
2 * Platform-independent routines shared between all PuTTY programs.
3 */
4
374330e2 5#include <stdio.h>
6#include <stdlib.h>
1709795f 7#include <stdarg.h>
57356d63 8#include <ctype.h>
5471d09a 9#include <assert.h>
374330e2 10#include "putty.h"
11
d57f70af 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 */
21unsigned 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
03f64569 45/* ----------------------------------------------------------------------
46 * String handling routines.
47 */
48
57356d63 49char *dupstr(const char *s)
03f64569 50{
6d113886 51 char *p = NULL;
52 if (s) {
53 int len = strlen(s);
54 p = snewn(len + 1, char);
55 strcpy(p, s);
56 }
03f64569 57 return p;
58}
59
60/* Allocate the concatenation of N strings. Terminate arg list with NULL. */
57356d63 61char *dupcat(const char *s1, ...)
03f64569 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
3d88e64d 77 p = snewn(len + 1, char);
03f64569 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
57356d63 94/*
95 * Do an sprintf(), but into a custom-allocated buffer.
96 *
28da9e3d 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.
57356d63 137 */
138char *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}
147char *dupvprintf(const char *fmt, va_list ap)
148{
149 char *buf;
150 int len, size;
151
3d88e64d 152 buf = snewn(512, char);
57356d63 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 }
3d88e64d 173 buf = sresize(buf, size, char);
57356d63 174 }
175}
176
39934deb 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 */
181char *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
03f64569 200/* ----------------------------------------------------------------------
1549e076 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
205void 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/* ----------------------------------------------------------------------
5471d09a 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
7983f47e 238 * - retrieve a larger amount of initial data from the list
5471d09a 239 * - return the current size of the buffer chain in bytes
240 */
241
242#define BUFFER_GRANULE 512
243
244struct bufchain_granule {
245 struct bufchain_granule *next;
246 int buflen, bufpos;
247 char buf[BUFFER_GRANULE];
248};
249
250void bufchain_init(bufchain *ch)
251{
252 ch->head = ch->tail = NULL;
253 ch->buffersize = 0;
254}
255
256void 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
268int bufchain_size(bufchain *ch)
269{
270 return ch->buffersize;
271}
272
e0e7dff8 273void bufchain_add(bufchain *ch, const void *data, int len)
5471d09a 274{
e0e7dff8 275 const char *buf = (const char *)data;
5471d09a 276
bfa5400d 277 if (len == 0) return;
278
5471d09a 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;
3d88e64d 291 newbuf = snew(struct bufchain_granule);
5471d09a 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
306void bufchain_consume(bufchain *ch, int len)
307{
7983f47e 308 struct bufchain_granule *tmp;
309
5471d09a 310 assert(ch->buffersize >= len);
7983f47e 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;
5471d09a 325 }
326}
327
328void 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
7983f47e 334void 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
03f64569 356/* ----------------------------------------------------------------------
b191636d 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
d0912d1f 367void *minefield_c_malloc(size_t size);
368void minefield_c_free(void *p);
369void *minefield_c_realloc(void *p, size_t size);
370#endif
374330e2 371
372#ifdef MALLOC_LOG
373static FILE *fp = NULL;
374
d7da76ca 375static char *mlog_file = NULL;
376static int mlog_line = 0;
377
32874aea 378void mlog(char *file, int line)
379{
d7da76ca 380 mlog_file = file;
381 mlog_line = line;
c662dbc0 382 if (!fp) {
374330e2 383 fp = fopen("putty_mem.log", "w");
c662dbc0 384 setvbuf(fp, NULL, _IONBF, BUFSIZ);
385 }
374330e2 386 if (fp)
32874aea 387 fprintf(fp, "%s:%d: ", file, line);
374330e2 388}
389#endif
390
32874aea 391void *safemalloc(size_t size)
392{
b191636d 393 void *p;
394#ifdef MINEFIELD
32874aea 395 p = minefield_c_malloc(size);
b191636d 396#else
32874aea 397 p = malloc(size);
b191636d 398#endif
374330e2 399 if (!p) {
d7da76ca 400 char str[200];
401#ifdef MALLOC_LOG
402 sprintf(str, "Out of memory! (%s:%d, size=%d)",
403 mlog_file, mlog_line, size);
1b2ef365 404 fprintf(fp, "*** %s\n", str);
405 fclose(fp);
d7da76ca 406#else
407 strcpy(str, "Out of memory!");
408#endif
1709795f 409 modalfatalbox(str);
374330e2 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
32874aea 418void *saferealloc(void *ptr, size_t size)
419{
374330e2 420 void *p;
b191636d 421 if (!ptr) {
422#ifdef MINEFIELD
32874aea 423 p = minefield_c_malloc(size);
b191636d 424#else
32874aea 425 p = malloc(size);
b191636d 426#endif
427 } else {
428#ifdef MINEFIELD
32874aea 429 p = minefield_c_realloc(ptr, size);
b191636d 430#else
32874aea 431 p = realloc(ptr, size);
b191636d 432#endif
433 }
374330e2 434 if (!p) {
d7da76ca 435 char str[200];
436#ifdef MALLOC_LOG
437 sprintf(str, "Out of memory! (%s:%d, size=%d)",
438 mlog_file, mlog_line, size);
1b2ef365 439 fprintf(fp, "*** %s\n", str);
440 fclose(fp);
d7da76ca 441#else
442 strcpy(str, "Out of memory!");
443#endif
1709795f 444 modalfatalbox(str);
374330e2 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
32874aea 453void safefree(void *ptr)
454{
374330e2 455 if (ptr) {
456#ifdef MALLOC_LOG
457 if (fp)
458 fprintf(fp, "free(%p)\n", ptr);
459#endif
b191636d 460#ifdef MINEFIELD
32874aea 461 minefield_c_free(ptr);
b191636d 462#else
32874aea 463 free(ptr);
b191636d 464#endif
374330e2 465 }
466#ifdef MALLOC_LOG
467 else if (fp)
468 fprintf(fp, "freeing null pointer - no action taken\n");
469#endif
470}
c82bda52 471
03f64569 472/* ----------------------------------------------------------------------
473 * Debugging routines.
474 */
475
c82bda52 476#ifdef DEBUG
d0912d1f 477extern void dputs(char *); /* defined in per-platform *misc.c */
db9c0f86 478
d0912d1f 479void debug_printf(char *fmt, ...)
32874aea 480{
57356d63 481 char *buf;
db9c0f86 482 va_list ap;
483
484 va_start(ap, fmt);
57356d63 485 buf = dupvprintf(fmt, ap);
32874aea 486 dputs(buf);
57356d63 487 sfree(buf);
c82bda52 488 va_end(ap);
489}
db9c0f86 490
491
32874aea 492void debug_memdump(void *buf, int len, int L)
493{
db9c0f86 494 int i;
495 unsigned char *p = buf;
765c4200 496 char foo[17];
db9c0f86 497 if (L) {
498 int delta;
d0912d1f 499 debug_printf("\t%d (0x%x) bytes:\n", len, len);
db9c0f86 500 delta = 15 & (int) p;
501 p -= delta;
502 len += delta;
503 }
504 for (; 0 < len; p += 16, len -= 16) {
32874aea 505 dputs(" ");
506 if (L)
d0912d1f 507 debug_printf("%p: ", p);
32874aea 508 strcpy(foo, "................"); /* sixteen dots */
db9c0f86 509 for (i = 0; i < 16 && i < len; ++i) {
510 if (&p[i] < (unsigned char *) buf) {
32874aea 511 dputs(" "); /* 3 spaces */
765c4200 512 foo[i] = ' ';
db9c0f86 513 } else {
d0912d1f 514 debug_printf("%c%02.2x",
32874aea 515 &p[i] != (unsigned char *) buf
516 && i % 4 ? '.' : ' ', p[i]
517 );
765c4200 518 if (p[i] >= ' ' && p[i] <= '~')
32874aea 519 foo[i] = (char) p[i];
db9c0f86 520 }
521 }
765c4200 522 foo[i] = '\0';
d0912d1f 523 debug_printf("%*s%s\n", (16 - i) * 3 + 2, "", foo);
db9c0f86 524 }
525}
526
32874aea 527#endif /* def DEBUG */