Oops, another missing forward-struct-declaration.
[u/mdw/putty] / misc.c
CommitLineData
374330e2 1#include <stdio.h>
2#include <stdlib.h>
1709795f 3#include <stdarg.h>
57356d63 4#include <ctype.h>
5471d09a 5#include <assert.h>
374330e2 6#include "putty.h"
7
03f64569 8/* ----------------------------------------------------------------------
9 * String handling routines.
10 */
11
57356d63 12char *dupstr(const char *s)
03f64569 13{
14 int len = strlen(s);
15 char *p = smalloc(len + 1);
16 strcpy(p, s);
17 return p;
18}
19
20/* Allocate the concatenation of N strings. Terminate arg list with NULL. */
57356d63 21char *dupcat(const char *s1, ...)
03f64569 22{
23 int len;
24 char *p, *q, *sn;
25 va_list ap;
26
27 len = strlen(s1);
28 va_start(ap, s1);
29 while (1) {
30 sn = va_arg(ap, char *);
31 if (!sn)
32 break;
33 len += strlen(sn);
34 }
35 va_end(ap);
36
37 p = smalloc(len + 1);
38 strcpy(p, s1);
39 q = p + strlen(p);
40
41 va_start(ap, s1);
42 while (1) {
43 sn = va_arg(ap, char *);
44 if (!sn)
45 break;
46 strcpy(q, sn);
47 q += strlen(q);
48 }
49 va_end(ap);
50
51 return p;
52}
53
57356d63 54/*
55 * Do an sprintf(), but into a custom-allocated buffer.
56 *
57 * Irritatingly, we don't seem to be able to do this portably using
58 * vsnprintf(), because there appear to be issues with re-using the
59 * same va_list for two calls, and the excellent C99 va_copy is not
60 * yet widespread. Bah. Instead I'm going to do a horrid, horrid
61 * hack, in which I trawl the format string myself, work out the
62 * maximum length of each format component, and resize the buffer
63 * before printing it.
64 */
65char *dupprintf(const char *fmt, ...)
66{
67 char *ret;
68 va_list ap;
69 va_start(ap, fmt);
70 ret = dupvprintf(fmt, ap);
71 va_end(ap);
72 return ret;
73}
74char *dupvprintf(const char *fmt, va_list ap)
75{
76 char *buf;
77 int len, size;
78
79 buf = smalloc(512);
80 size = 512;
81
82 while (1) {
83#ifdef _WINDOWS
84#define vsnprintf _vsnprintf
85#endif
86 len = vsnprintf(buf, size, fmt, ap);
87 if (len >= 0 && len < size) {
88 /* This is the C99-specified criterion for snprintf to have
89 * been completely successful. */
90 return buf;
91 } else if (len > 0) {
92 /* This is the C99 error condition: the returned length is
93 * the required buffer size not counting the NUL. */
94 size = len + 1;
95 } else {
96 /* This is the pre-C99 glibc error condition: <0 means the
97 * buffer wasn't big enough, so we enlarge it a bit and hope. */
98 size += 512;
99 }
100 buf = srealloc(buf, size);
101 }
102}
103
03f64569 104/* ----------------------------------------------------------------------
1549e076 105 * Base64 encoding routine. This is required in public-key writing
106 * but also in HTTP proxy handling, so it's centralised here.
107 */
108
109void base64_encode_atom(unsigned char *data, int n, char *out)
110{
111 static const char base64_chars[] =
112 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
113
114 unsigned word;
115
116 word = data[0] << 16;
117 if (n > 1)
118 word |= data[1] << 8;
119 if (n > 2)
120 word |= data[2];
121 out[0] = base64_chars[(word >> 18) & 0x3F];
122 out[1] = base64_chars[(word >> 12) & 0x3F];
123 if (n > 1)
124 out[2] = base64_chars[(word >> 6) & 0x3F];
125 else
126 out[2] = '=';
127 if (n > 2)
128 out[3] = base64_chars[word & 0x3F];
129 else
130 out[3] = '=';
131}
132
133/* ----------------------------------------------------------------------
5471d09a 134 * Generic routines to deal with send buffers: a linked list of
135 * smallish blocks, with the operations
136 *
137 * - add an arbitrary amount of data to the end of the list
138 * - remove the first N bytes from the list
139 * - return a (pointer,length) pair giving some initial data in
140 * the list, suitable for passing to a send or write system
141 * call
7983f47e 142 * - retrieve a larger amount of initial data from the list
5471d09a 143 * - return the current size of the buffer chain in bytes
144 */
145
146#define BUFFER_GRANULE 512
147
148struct bufchain_granule {
149 struct bufchain_granule *next;
150 int buflen, bufpos;
151 char buf[BUFFER_GRANULE];
152};
153
154void bufchain_init(bufchain *ch)
155{
156 ch->head = ch->tail = NULL;
157 ch->buffersize = 0;
158}
159
160void bufchain_clear(bufchain *ch)
161{
162 struct bufchain_granule *b;
163 while (ch->head) {
164 b = ch->head;
165 ch->head = ch->head->next;
166 sfree(b);
167 }
168 ch->tail = NULL;
169 ch->buffersize = 0;
170}
171
172int bufchain_size(bufchain *ch)
173{
174 return ch->buffersize;
175}
176
e0e7dff8 177void bufchain_add(bufchain *ch, const void *data, int len)
5471d09a 178{
e0e7dff8 179 const char *buf = (const char *)data;
5471d09a 180
181 ch->buffersize += len;
182
183 if (ch->tail && ch->tail->buflen < BUFFER_GRANULE) {
184 int copylen = min(len, BUFFER_GRANULE - ch->tail->buflen);
185 memcpy(ch->tail->buf + ch->tail->buflen, buf, copylen);
186 buf += copylen;
187 len -= copylen;
188 ch->tail->buflen += copylen;
189 }
190 while (len > 0) {
191 int grainlen = min(len, BUFFER_GRANULE);
192 struct bufchain_granule *newbuf;
193 newbuf = smalloc(sizeof(struct bufchain_granule));
194 newbuf->bufpos = 0;
195 newbuf->buflen = grainlen;
196 memcpy(newbuf->buf, buf, grainlen);
197 buf += grainlen;
198 len -= grainlen;
199 if (ch->tail)
200 ch->tail->next = newbuf;
201 else
202 ch->head = ch->tail = newbuf;
203 newbuf->next = NULL;
204 ch->tail = newbuf;
205 }
206}
207
208void bufchain_consume(bufchain *ch, int len)
209{
7983f47e 210 struct bufchain_granule *tmp;
211
5471d09a 212 assert(ch->buffersize >= len);
7983f47e 213 while (len > 0) {
214 int remlen = len;
215 assert(ch->head != NULL);
216 if (remlen >= ch->head->buflen - ch->head->bufpos) {
217 remlen = ch->head->buflen - ch->head->bufpos;
218 tmp = ch->head;
219 ch->head = tmp->next;
220 sfree(tmp);
221 if (!ch->head)
222 ch->tail = NULL;
223 } else
224 ch->head->bufpos += remlen;
225 ch->buffersize -= remlen;
226 len -= remlen;
5471d09a 227 }
228}
229
230void bufchain_prefix(bufchain *ch, void **data, int *len)
231{
232 *len = ch->head->buflen - ch->head->bufpos;
233 *data = ch->head->buf + ch->head->bufpos;
234}
235
7983f47e 236void bufchain_fetch(bufchain *ch, void *data, int len)
237{
238 struct bufchain_granule *tmp;
239 char *data_c = (char *)data;
240
241 tmp = ch->head;
242
243 assert(ch->buffersize >= len);
244 while (len > 0) {
245 int remlen = len;
246
247 assert(tmp != NULL);
248 if (remlen >= tmp->buflen - tmp->bufpos)
249 remlen = tmp->buflen - tmp->bufpos;
250 memcpy(data_c, tmp->buf + tmp->bufpos, remlen);
251
252 tmp = tmp->next;
253 len -= remlen;
254 data_c += remlen;
255 }
256}
257
03f64569 258/* ----------------------------------------------------------------------
b191636d 259 * My own versions of malloc, realloc and free. Because I want
260 * malloc and realloc to bomb out and exit the program if they run
261 * out of memory, realloc to reliably call malloc if passed a NULL
262 * pointer, and free to reliably do nothing if passed a NULL
263 * pointer. We can also put trace printouts in, if we need to; and
264 * we can also replace the allocator with an ElectricFence-like
265 * one.
266 */
267
268#ifdef MINEFIELD
269/*
270 * Minefield - a Windows equivalent for Electric Fence
271 */
272
273#define PAGESIZE 4096
274
275/*
276 * Design:
277 *
278 * We start by reserving as much virtual address space as Windows
279 * will sensibly (or not sensibly) let us have. We flag it all as
280 * invalid memory.
281 *
282 * Any allocation attempt is satisfied by committing one or more
283 * pages, with an uncommitted page on either side. The returned
284 * memory region is jammed up against the _end_ of the pages.
285 *
286 * Freeing anything causes instantaneous decommitment of the pages
287 * involved, so stale pointers are caught as soon as possible.
288 */
289
290static int minefield_initialised = 0;
291static void *minefield_region = NULL;
292static long minefield_size = 0;
293static long minefield_npages = 0;
294static long minefield_curpos = 0;
295static unsigned short *minefield_admin = NULL;
296static void *minefield_pages = NULL;
297
32874aea 298static void minefield_admin_hide(int hide)
299{
b191636d 300 int access = hide ? PAGE_NOACCESS : PAGE_READWRITE;
32874aea 301 VirtualProtect(minefield_admin, minefield_npages * 2, access, NULL);
b191636d 302}
303
32874aea 304static void minefield_init(void)
305{
b191636d 306 int size;
307 int admin_size;
308 int i;
309
32874aea 310 for (size = 0x40000000; size > 0; size = ((size >> 3) * 7) & ~0xFFF) {
311 minefield_region = VirtualAlloc(NULL, size,
312 MEM_RESERVE, PAGE_NOACCESS);
313 if (minefield_region)
314 break;
b191636d 315 }
316 minefield_size = size;
b191636d 317
318 /*
319 * Firstly, allocate a section of that to be the admin block.
320 * We'll need a two-byte field for each page.
321 */
322 minefield_admin = minefield_region;
323 minefield_npages = minefield_size / PAGESIZE;
32874aea 324 admin_size = (minefield_npages * 2 + PAGESIZE - 1) & ~(PAGESIZE - 1);
b191636d 325 minefield_npages = (minefield_size - admin_size) / PAGESIZE;
32874aea 326 minefield_pages = (char *) minefield_region + admin_size;
b191636d 327
328 /*
329 * Commit the admin region.
330 */
331 VirtualAlloc(minefield_admin, minefield_npages * 2,
32874aea 332 MEM_COMMIT, PAGE_READWRITE);
b191636d 333
334 /*
335 * Mark all pages as unused (0xFFFF).
336 */
337 for (i = 0; i < minefield_npages; i++)
32874aea 338 minefield_admin[i] = 0xFFFF;
b191636d 339
340 /*
341 * Hide the admin region.
342 */
343 minefield_admin_hide(1);
344
345 minefield_initialised = 1;
346}
347
32874aea 348static void minefield_bomb(void)
349{
350 div(1, *(int *) minefield_pages);
b191636d 351}
352
32874aea 353static void *minefield_alloc(int size)
354{
b191636d 355 int npages;
356 int pos, lim, region_end, region_start;
357 int start;
358 int i;
359
32874aea 360 npages = (size + PAGESIZE - 1) / PAGESIZE;
b191636d 361
362 minefield_admin_hide(0);
363
364 /*
365 * Search from current position until we find a contiguous
366 * bunch of npages+2 unused pages.
367 */
368 pos = minefield_curpos;
369 lim = minefield_npages;
370 while (1) {
32874aea 371 /* Skip over used pages. */
372 while (pos < lim && minefield_admin[pos] != 0xFFFF)
373 pos++;
374 /* Count unused pages. */
375 start = pos;
376 while (pos < lim && pos - start < npages + 2 &&
377 minefield_admin[pos] == 0xFFFF)
378 pos++;
379 if (pos - start == npages + 2)
380 break;
381 /* If we've reached the limit, reset the limit or stop. */
382 if (pos >= lim) {
383 if (lim == minefield_npages) {
384 /* go round and start again at zero */
385 lim = minefield_curpos;
386 pos = 0;
387 } else {
388 minefield_admin_hide(1);
389 return NULL;
390 }
391 }
b191636d 392 }
393
32874aea 394 minefield_curpos = pos - 1;
b191636d 395
396 /*
397 * We have npages+2 unused pages starting at start. We leave
398 * the first and last of these alone and use the rest.
399 */
32874aea 400 region_end = (start + npages + 1) * PAGESIZE;
b191636d 401 region_start = region_end - size;
402 /* FIXME: could align here if we wanted */
403
404 /*
405 * Update the admin region.
406 */
0f7432cc 407 for (i = start + 2; i < start + npages + 1; i++)
32874aea 408 minefield_admin[i] = 0xFFFE; /* used but no region starts here */
409 minefield_admin[start + 1] = region_start % PAGESIZE;
b191636d 410
411 minefield_admin_hide(1);
412
32874aea 413 VirtualAlloc((char *) minefield_pages + region_start, size,
414 MEM_COMMIT, PAGE_READWRITE);
415 return (char *) minefield_pages + region_start;
b191636d 416}
417
32874aea 418static void minefield_free(void *ptr)
419{
b191636d 420 int region_start, i, j;
421
422 minefield_admin_hide(0);
423
32874aea 424 region_start = (char *) ptr - (char *) minefield_pages;
b191636d 425 i = region_start / PAGESIZE;
426 if (i < 0 || i >= minefield_npages ||
32874aea 427 minefield_admin[i] != region_start % PAGESIZE)
428 minefield_bomb();
b191636d 429 for (j = i; j < minefield_npages && minefield_admin[j] != 0xFFFF; j++) {
32874aea 430 minefield_admin[j] = 0xFFFF;
b191636d 431 }
432
32874aea 433 VirtualFree(ptr, j * PAGESIZE - region_start, MEM_DECOMMIT);
b191636d 434
435 minefield_admin_hide(1);
436}
437
32874aea 438static int minefield_get_size(void *ptr)
439{
b191636d 440 int region_start, i, j;
441
442 minefield_admin_hide(0);
443
32874aea 444 region_start = (char *) ptr - (char *) minefield_pages;
b191636d 445 i = region_start / PAGESIZE;
446 if (i < 0 || i >= minefield_npages ||
32874aea 447 minefield_admin[i] != region_start % PAGESIZE)
448 minefield_bomb();
b191636d 449 for (j = i; j < minefield_npages && minefield_admin[j] != 0xFFFF; j++);
450
451 minefield_admin_hide(1);
452
32874aea 453 return j * PAGESIZE - region_start;
b191636d 454}
455
32874aea 456static void *minefield_c_malloc(size_t size)
457{
458 if (!minefield_initialised)
459 minefield_init();
b191636d 460 return minefield_alloc(size);
461}
462
32874aea 463static void minefield_c_free(void *p)
464{
465 if (!minefield_initialised)
466 minefield_init();
b191636d 467 minefield_free(p);
468}
469
470/*
471 * realloc _always_ moves the chunk, for rapid detection of code
472 * that assumes it won't.
473 */
32874aea 474static void *minefield_c_realloc(void *p, size_t size)
475{
b191636d 476 size_t oldsize;
477 void *q;
32874aea 478 if (!minefield_initialised)
479 minefield_init();
b191636d 480 q = minefield_alloc(size);
481 oldsize = minefield_get_size(p);
482 memcpy(q, p, (oldsize < size ? oldsize : size));
483 minefield_free(p);
484 return q;
485}
486
32874aea 487#endif /* MINEFIELD */
374330e2 488
489#ifdef MALLOC_LOG
490static FILE *fp = NULL;
491
d7da76ca 492static char *mlog_file = NULL;
493static int mlog_line = 0;
494
32874aea 495void mlog(char *file, int line)
496{
d7da76ca 497 mlog_file = file;
498 mlog_line = line;
c662dbc0 499 if (!fp) {
374330e2 500 fp = fopen("putty_mem.log", "w");
c662dbc0 501 setvbuf(fp, NULL, _IONBF, BUFSIZ);
502 }
374330e2 503 if (fp)
32874aea 504 fprintf(fp, "%s:%d: ", file, line);
374330e2 505}
506#endif
507
32874aea 508void *safemalloc(size_t size)
509{
b191636d 510 void *p;
511#ifdef MINEFIELD
32874aea 512 p = minefield_c_malloc(size);
b191636d 513#else
32874aea 514 p = malloc(size);
b191636d 515#endif
374330e2 516 if (!p) {
d7da76ca 517 char str[200];
518#ifdef MALLOC_LOG
519 sprintf(str, "Out of memory! (%s:%d, size=%d)",
520 mlog_file, mlog_line, size);
1b2ef365 521 fprintf(fp, "*** %s\n", str);
522 fclose(fp);
d7da76ca 523#else
524 strcpy(str, "Out of memory!");
525#endif
1709795f 526 modalfatalbox(str);
374330e2 527 }
528#ifdef MALLOC_LOG
529 if (fp)
530 fprintf(fp, "malloc(%d) returns %p\n", size, p);
531#endif
532 return p;
533}
534
32874aea 535void *saferealloc(void *ptr, size_t size)
536{
374330e2 537 void *p;
b191636d 538 if (!ptr) {
539#ifdef MINEFIELD
32874aea 540 p = minefield_c_malloc(size);
b191636d 541#else
32874aea 542 p = malloc(size);
b191636d 543#endif
544 } else {
545#ifdef MINEFIELD
32874aea 546 p = minefield_c_realloc(ptr, size);
b191636d 547#else
32874aea 548 p = realloc(ptr, size);
b191636d 549#endif
550 }
374330e2 551 if (!p) {
d7da76ca 552 char str[200];
553#ifdef MALLOC_LOG
554 sprintf(str, "Out of memory! (%s:%d, size=%d)",
555 mlog_file, mlog_line, size);
1b2ef365 556 fprintf(fp, "*** %s\n", str);
557 fclose(fp);
d7da76ca 558#else
559 strcpy(str, "Out of memory!");
560#endif
1709795f 561 modalfatalbox(str);
374330e2 562 }
563#ifdef MALLOC_LOG
564 if (fp)
565 fprintf(fp, "realloc(%p,%d) returns %p\n", ptr, size, p);
566#endif
567 return p;
568}
569
32874aea 570void safefree(void *ptr)
571{
374330e2 572 if (ptr) {
573#ifdef MALLOC_LOG
574 if (fp)
575 fprintf(fp, "free(%p)\n", ptr);
576#endif
b191636d 577#ifdef MINEFIELD
32874aea 578 minefield_c_free(ptr);
b191636d 579#else
32874aea 580 free(ptr);
b191636d 581#endif
374330e2 582 }
583#ifdef MALLOC_LOG
584 else if (fp)
585 fprintf(fp, "freeing null pointer - no action taken\n");
586#endif
587}
c82bda52 588
03f64569 589/* ----------------------------------------------------------------------
590 * Debugging routines.
591 */
592
c82bda52 593#ifdef DEBUG
594static FILE *debug_fp = NULL;
cbb9532e 595static HANDLE debug_hdl = INVALID_HANDLE_VALUE;
c82bda52 596static int debug_got_console = 0;
597
32874aea 598static void dputs(char *buf)
599{
c82bda52 600 DWORD dw;
c82bda52 601
602 if (!debug_got_console) {
cbb9532e 603 if (AllocConsole()) {
604 debug_got_console = 1;
605 debug_hdl = GetStdHandle(STD_OUTPUT_HANDLE);
606 }
c82bda52 607 }
608 if (!debug_fp) {
609 debug_fp = fopen("debug.log", "w");
610 }
611
cbb9532e 612 if (debug_hdl != INVALID_HANDLE_VALUE) {
613 WriteFile(debug_hdl, buf, strlen(buf), &dw, NULL);
614 }
c82bda52 615 fputs(buf, debug_fp);
616 fflush(debug_fp);
db9c0f86 617}
618
619
32874aea 620void dprintf(char *fmt, ...)
621{
57356d63 622 char *buf;
db9c0f86 623 va_list ap;
624
625 va_start(ap, fmt);
57356d63 626 buf = dupvprintf(fmt, ap);
32874aea 627 dputs(buf);
57356d63 628 sfree(buf);
c82bda52 629 va_end(ap);
630}
db9c0f86 631
632
32874aea 633void debug_memdump(void *buf, int len, int L)
634{
db9c0f86 635 int i;
636 unsigned char *p = buf;
765c4200 637 char foo[17];
db9c0f86 638 if (L) {
639 int delta;
32874aea 640 dprintf("\t%d (0x%x) bytes:\n", len, len);
db9c0f86 641 delta = 15 & (int) p;
642 p -= delta;
643 len += delta;
644 }
645 for (; 0 < len; p += 16, len -= 16) {
32874aea 646 dputs(" ");
647 if (L)
648 dprintf("%p: ", p);
649 strcpy(foo, "................"); /* sixteen dots */
db9c0f86 650 for (i = 0; i < 16 && i < len; ++i) {
651 if (&p[i] < (unsigned char *) buf) {
32874aea 652 dputs(" "); /* 3 spaces */
765c4200 653 foo[i] = ' ';
db9c0f86 654 } else {
32874aea 655 dprintf("%c%02.2x",
656 &p[i] != (unsigned char *) buf
657 && i % 4 ? '.' : ' ', p[i]
658 );
765c4200 659 if (p[i] >= ' ' && p[i] <= '~')
32874aea 660 foo[i] = (char) p[i];
db9c0f86 661 }
662 }
765c4200 663 foo[i] = '\0';
32874aea 664 dprintf("%*s%s\n", (16 - i) * 3 + 2, "", foo);
db9c0f86 665 }
666}
667
32874aea 668#endif /* def DEBUG */