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