Introduce framework for authenticating with the local X server.
[u/mdw/putty] / misc.c
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <stdarg.h>
4 #include <ctype.h>
5 #include <assert.h>
6 #include "putty.h"
7
8 /* ----------------------------------------------------------------------
9 * String handling routines.
10 */
11
12 char *dupstr(const char *s)
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. */
21 char *dupcat(const char *s1, ...)
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
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 */
65 char *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 }
74 char *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
104 /* ----------------------------------------------------------------------
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
109 void 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 /* ----------------------------------------------------------------------
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
142 * - retrieve a larger amount of initial data from the list
143 * - return the current size of the buffer chain in bytes
144 */
145
146 #define BUFFER_GRANULE 512
147
148 struct bufchain_granule {
149 struct bufchain_granule *next;
150 int buflen, bufpos;
151 char buf[BUFFER_GRANULE];
152 };
153
154 void bufchain_init(bufchain *ch)
155 {
156 ch->head = ch->tail = NULL;
157 ch->buffersize = 0;
158 }
159
160 void 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
172 int bufchain_size(bufchain *ch)
173 {
174 return ch->buffersize;
175 }
176
177 void bufchain_add(bufchain *ch, const void *data, int len)
178 {
179 const char *buf = (const char *)data;
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
208 void bufchain_consume(bufchain *ch, int len)
209 {
210 struct bufchain_granule *tmp;
211
212 assert(ch->buffersize >= len);
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;
227 }
228 }
229
230 void 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
236 void 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
258 /* ----------------------------------------------------------------------
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
290 static int minefield_initialised = 0;
291 static void *minefield_region = NULL;
292 static long minefield_size = 0;
293 static long minefield_npages = 0;
294 static long minefield_curpos = 0;
295 static unsigned short *minefield_admin = NULL;
296 static void *minefield_pages = NULL;
297
298 static void minefield_admin_hide(int hide)
299 {
300 int access = hide ? PAGE_NOACCESS : PAGE_READWRITE;
301 VirtualProtect(minefield_admin, minefield_npages * 2, access, NULL);
302 }
303
304 static void minefield_init(void)
305 {
306 int size;
307 int admin_size;
308 int i;
309
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;
315 }
316 minefield_size = size;
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;
324 admin_size = (minefield_npages * 2 + PAGESIZE - 1) & ~(PAGESIZE - 1);
325 minefield_npages = (minefield_size - admin_size) / PAGESIZE;
326 minefield_pages = (char *) minefield_region + admin_size;
327
328 /*
329 * Commit the admin region.
330 */
331 VirtualAlloc(minefield_admin, minefield_npages * 2,
332 MEM_COMMIT, PAGE_READWRITE);
333
334 /*
335 * Mark all pages as unused (0xFFFF).
336 */
337 for (i = 0; i < minefield_npages; i++)
338 minefield_admin[i] = 0xFFFF;
339
340 /*
341 * Hide the admin region.
342 */
343 minefield_admin_hide(1);
344
345 minefield_initialised = 1;
346 }
347
348 static void minefield_bomb(void)
349 {
350 div(1, *(int *) minefield_pages);
351 }
352
353 static void *minefield_alloc(int size)
354 {
355 int npages;
356 int pos, lim, region_end, region_start;
357 int start;
358 int i;
359
360 npages = (size + PAGESIZE - 1) / PAGESIZE;
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) {
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 }
392 }
393
394 minefield_curpos = pos - 1;
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 */
400 region_end = (start + npages + 1) * PAGESIZE;
401 region_start = region_end - size;
402 /* FIXME: could align here if we wanted */
403
404 /*
405 * Update the admin region.
406 */
407 for (i = start + 2; i < start + npages + 1; i++)
408 minefield_admin[i] = 0xFFFE; /* used but no region starts here */
409 minefield_admin[start + 1] = region_start % PAGESIZE;
410
411 minefield_admin_hide(1);
412
413 VirtualAlloc((char *) minefield_pages + region_start, size,
414 MEM_COMMIT, PAGE_READWRITE);
415 return (char *) minefield_pages + region_start;
416 }
417
418 static void minefield_free(void *ptr)
419 {
420 int region_start, i, j;
421
422 minefield_admin_hide(0);
423
424 region_start = (char *) ptr - (char *) minefield_pages;
425 i = region_start / PAGESIZE;
426 if (i < 0 || i >= minefield_npages ||
427 minefield_admin[i] != region_start % PAGESIZE)
428 minefield_bomb();
429 for (j = i; j < minefield_npages && minefield_admin[j] != 0xFFFF; j++) {
430 minefield_admin[j] = 0xFFFF;
431 }
432
433 VirtualFree(ptr, j * PAGESIZE - region_start, MEM_DECOMMIT);
434
435 minefield_admin_hide(1);
436 }
437
438 static int minefield_get_size(void *ptr)
439 {
440 int region_start, i, j;
441
442 minefield_admin_hide(0);
443
444 region_start = (char *) ptr - (char *) minefield_pages;
445 i = region_start / PAGESIZE;
446 if (i < 0 || i >= minefield_npages ||
447 minefield_admin[i] != region_start % PAGESIZE)
448 minefield_bomb();
449 for (j = i; j < minefield_npages && minefield_admin[j] != 0xFFFF; j++);
450
451 minefield_admin_hide(1);
452
453 return j * PAGESIZE - region_start;
454 }
455
456 static void *minefield_c_malloc(size_t size)
457 {
458 if (!minefield_initialised)
459 minefield_init();
460 return minefield_alloc(size);
461 }
462
463 static void minefield_c_free(void *p)
464 {
465 if (!minefield_initialised)
466 minefield_init();
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 */
474 static void *minefield_c_realloc(void *p, size_t size)
475 {
476 size_t oldsize;
477 void *q;
478 if (!minefield_initialised)
479 minefield_init();
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
487 #endif /* MINEFIELD */
488
489 #ifdef MALLOC_LOG
490 static FILE *fp = NULL;
491
492 static char *mlog_file = NULL;
493 static int mlog_line = 0;
494
495 void mlog(char *file, int line)
496 {
497 mlog_file = file;
498 mlog_line = line;
499 if (!fp) {
500 fp = fopen("putty_mem.log", "w");
501 setvbuf(fp, NULL, _IONBF, BUFSIZ);
502 }
503 if (fp)
504 fprintf(fp, "%s:%d: ", file, line);
505 }
506 #endif
507
508 void *safemalloc(size_t size)
509 {
510 void *p;
511 #ifdef MINEFIELD
512 p = minefield_c_malloc(size);
513 #else
514 p = malloc(size);
515 #endif
516 if (!p) {
517 char str[200];
518 #ifdef MALLOC_LOG
519 sprintf(str, "Out of memory! (%s:%d, size=%d)",
520 mlog_file, mlog_line, size);
521 fprintf(fp, "*** %s\n", str);
522 fclose(fp);
523 #else
524 strcpy(str, "Out of memory!");
525 #endif
526 modalfatalbox(str);
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
535 void *saferealloc(void *ptr, size_t size)
536 {
537 void *p;
538 if (!ptr) {
539 #ifdef MINEFIELD
540 p = minefield_c_malloc(size);
541 #else
542 p = malloc(size);
543 #endif
544 } else {
545 #ifdef MINEFIELD
546 p = minefield_c_realloc(ptr, size);
547 #else
548 p = realloc(ptr, size);
549 #endif
550 }
551 if (!p) {
552 char str[200];
553 #ifdef MALLOC_LOG
554 sprintf(str, "Out of memory! (%s:%d, size=%d)",
555 mlog_file, mlog_line, size);
556 fprintf(fp, "*** %s\n", str);
557 fclose(fp);
558 #else
559 strcpy(str, "Out of memory!");
560 #endif
561 modalfatalbox(str);
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
570 void safefree(void *ptr)
571 {
572 if (ptr) {
573 #ifdef MALLOC_LOG
574 if (fp)
575 fprintf(fp, "free(%p)\n", ptr);
576 #endif
577 #ifdef MINEFIELD
578 minefield_c_free(ptr);
579 #else
580 free(ptr);
581 #endif
582 }
583 #ifdef MALLOC_LOG
584 else if (fp)
585 fprintf(fp, "freeing null pointer - no action taken\n");
586 #endif
587 }
588
589 /* ----------------------------------------------------------------------
590 * Debugging routines.
591 */
592
593 #ifdef DEBUG
594 static FILE *debug_fp = NULL;
595 static HANDLE debug_hdl = INVALID_HANDLE_VALUE;
596 static int debug_got_console = 0;
597
598 static void dputs(char *buf)
599 {
600 DWORD dw;
601
602 if (!debug_got_console) {
603 if (AllocConsole()) {
604 debug_got_console = 1;
605 debug_hdl = GetStdHandle(STD_OUTPUT_HANDLE);
606 }
607 }
608 if (!debug_fp) {
609 debug_fp = fopen("debug.log", "w");
610 }
611
612 if (debug_hdl != INVALID_HANDLE_VALUE) {
613 WriteFile(debug_hdl, buf, strlen(buf), &dw, NULL);
614 }
615 fputs(buf, debug_fp);
616 fflush(debug_fp);
617 }
618
619
620 void dprintf(char *fmt, ...)
621 {
622 char *buf;
623 va_list ap;
624
625 va_start(ap, fmt);
626 buf = dupvprintf(fmt, ap);
627 dputs(buf);
628 sfree(buf);
629 va_end(ap);
630 }
631
632
633 void debug_memdump(void *buf, int len, int L)
634 {
635 int i;
636 unsigned char *p = buf;
637 char foo[17];
638 if (L) {
639 int delta;
640 dprintf("\t%d (0x%x) bytes:\n", len, len);
641 delta = 15 & (int) p;
642 p -= delta;
643 len += delta;
644 }
645 for (; 0 < len; p += 16, len -= 16) {
646 dputs(" ");
647 if (L)
648 dprintf("%p: ", p);
649 strcpy(foo, "................"); /* sixteen dots */
650 for (i = 0; i < 16 && i < len; ++i) {
651 if (&p[i] < (unsigned char *) buf) {
652 dputs(" "); /* 3 spaces */
653 foo[i] = ' ';
654 } else {
655 dprintf("%c%02.2x",
656 &p[i] != (unsigned char *) buf
657 && i % 4 ? '.' : ' ', p[i]
658 );
659 if (p[i] >= ' ' && p[i] <= '~')
660 foo[i] = (char) p[i];
661 }
662 }
663 foo[i] = '\0';
664 dprintf("%*s%s\n", (16 - i) * 3 + 2, "", foo);
665 }
666 }
667
668 #endif /* def DEBUG */