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