Support username/password authentication in SOCKS 5.
[u/mdw/putty] / misc.c
CommitLineData
374330e2 1#include <windows.h>
2#include <stdio.h>
3#include <stdlib.h>
5471d09a 4#include <assert.h>
374330e2 5#include "putty.h"
6
03f64569 7/* ----------------------------------------------------------------------
8 * String handling routines.
9 */
10
11char *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. */
20char *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/* ----------------------------------------------------------------------
1549e076 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
58void 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/* ----------------------------------------------------------------------
5471d09a 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
96struct bufchain_granule {
97 struct bufchain_granule *next;
98 int buflen, bufpos;
99 char buf[BUFFER_GRANULE];
100};
101
102void bufchain_init(bufchain *ch)
103{
104 ch->head = ch->tail = NULL;
105 ch->buffersize = 0;
106}
107
108void 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
120int bufchain_size(bufchain *ch)
121{
122 return ch->buffersize;
123}
124
125void 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
156void 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
171void 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
03f64569 177/* ----------------------------------------------------------------------
b191636d 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
209static int minefield_initialised = 0;
210static void *minefield_region = NULL;
211static long minefield_size = 0;
212static long minefield_npages = 0;
213static long minefield_curpos = 0;
214static unsigned short *minefield_admin = NULL;
215static void *minefield_pages = NULL;
216
32874aea 217static void minefield_admin_hide(int hide)
218{
b191636d 219 int access = hide ? PAGE_NOACCESS : PAGE_READWRITE;
32874aea 220 VirtualProtect(minefield_admin, minefield_npages * 2, access, NULL);
b191636d 221}
222
32874aea 223static void minefield_init(void)
224{
b191636d 225 int size;
226 int admin_size;
227 int i;
228
32874aea 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;
b191636d 234 }
235 minefield_size = size;
b191636d 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;
32874aea 243 admin_size = (minefield_npages * 2 + PAGESIZE - 1) & ~(PAGESIZE - 1);
b191636d 244 minefield_npages = (minefield_size - admin_size) / PAGESIZE;
32874aea 245 minefield_pages = (char *) minefield_region + admin_size;
b191636d 246
247 /*
248 * Commit the admin region.
249 */
250 VirtualAlloc(minefield_admin, minefield_npages * 2,
32874aea 251 MEM_COMMIT, PAGE_READWRITE);
b191636d 252
253 /*
254 * Mark all pages as unused (0xFFFF).
255 */
256 for (i = 0; i < minefield_npages; i++)
32874aea 257 minefield_admin[i] = 0xFFFF;
b191636d 258
259 /*
260 * Hide the admin region.
261 */
262 minefield_admin_hide(1);
263
264 minefield_initialised = 1;
265}
266
32874aea 267static void minefield_bomb(void)
268{
269 div(1, *(int *) minefield_pages);
b191636d 270}
271
32874aea 272static void *minefield_alloc(int size)
273{
b191636d 274 int npages;
275 int pos, lim, region_end, region_start;
276 int start;
277 int i;
278
32874aea 279 npages = (size + PAGESIZE - 1) / PAGESIZE;
b191636d 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) {
32874aea 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 }
b191636d 311 }
312
32874aea 313 minefield_curpos = pos - 1;
b191636d 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 */
32874aea 319 region_end = (start + npages + 1) * PAGESIZE;
b191636d 320 region_start = region_end - size;
321 /* FIXME: could align here if we wanted */
322
323 /*
324 * Update the admin region.
325 */
0f7432cc 326 for (i = start + 2; i < start + npages + 1; i++)
32874aea 327 minefield_admin[i] = 0xFFFE; /* used but no region starts here */
328 minefield_admin[start + 1] = region_start % PAGESIZE;
b191636d 329
330 minefield_admin_hide(1);
331
32874aea 332 VirtualAlloc((char *) minefield_pages + region_start, size,
333 MEM_COMMIT, PAGE_READWRITE);
334 return (char *) minefield_pages + region_start;
b191636d 335}
336
32874aea 337static void minefield_free(void *ptr)
338{
b191636d 339 int region_start, i, j;
340
341 minefield_admin_hide(0);
342
32874aea 343 region_start = (char *) ptr - (char *) minefield_pages;
b191636d 344 i = region_start / PAGESIZE;
345 if (i < 0 || i >= minefield_npages ||
32874aea 346 minefield_admin[i] != region_start % PAGESIZE)
347 minefield_bomb();
b191636d 348 for (j = i; j < minefield_npages && minefield_admin[j] != 0xFFFF; j++) {
32874aea 349 minefield_admin[j] = 0xFFFF;
b191636d 350 }
351
32874aea 352 VirtualFree(ptr, j * PAGESIZE - region_start, MEM_DECOMMIT);
b191636d 353
354 minefield_admin_hide(1);
355}
356
32874aea 357static int minefield_get_size(void *ptr)
358{
b191636d 359 int region_start, i, j;
360
361 minefield_admin_hide(0);
362
32874aea 363 region_start = (char *) ptr - (char *) minefield_pages;
b191636d 364 i = region_start / PAGESIZE;
365 if (i < 0 || i >= minefield_npages ||
32874aea 366 minefield_admin[i] != region_start % PAGESIZE)
367 minefield_bomb();
b191636d 368 for (j = i; j < minefield_npages && minefield_admin[j] != 0xFFFF; j++);
369
370 minefield_admin_hide(1);
371
32874aea 372 return j * PAGESIZE - region_start;
b191636d 373}
374
32874aea 375static void *minefield_c_malloc(size_t size)
376{
377 if (!minefield_initialised)
378 minefield_init();
b191636d 379 return minefield_alloc(size);
380}
381
32874aea 382static void minefield_c_free(void *p)
383{
384 if (!minefield_initialised)
385 minefield_init();
b191636d 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 */
32874aea 393static void *minefield_c_realloc(void *p, size_t size)
394{
b191636d 395 size_t oldsize;
396 void *q;
32874aea 397 if (!minefield_initialised)
398 minefield_init();
b191636d 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
32874aea 406#endif /* MINEFIELD */
374330e2 407
408#ifdef MALLOC_LOG
409static FILE *fp = NULL;
410
d7da76ca 411static char *mlog_file = NULL;
412static int mlog_line = 0;
413
32874aea 414void mlog(char *file, int line)
415{
d7da76ca 416 mlog_file = file;
417 mlog_line = line;
c662dbc0 418 if (!fp) {
374330e2 419 fp = fopen("putty_mem.log", "w");
c662dbc0 420 setvbuf(fp, NULL, _IONBF, BUFSIZ);
421 }
374330e2 422 if (fp)
32874aea 423 fprintf(fp, "%s:%d: ", file, line);
374330e2 424}
425#endif
426
32874aea 427void *safemalloc(size_t size)
428{
b191636d 429 void *p;
430#ifdef MINEFIELD
32874aea 431 p = minefield_c_malloc(size);
b191636d 432#else
32874aea 433 p = malloc(size);
b191636d 434#endif
374330e2 435 if (!p) {
d7da76ca 436 char str[200];
437#ifdef MALLOC_LOG
438 sprintf(str, "Out of memory! (%s:%d, size=%d)",
439 mlog_file, mlog_line, size);
1b2ef365 440 fprintf(fp, "*** %s\n", str);
441 fclose(fp);
d7da76ca 442#else
443 strcpy(str, "Out of memory!");
444#endif
445 MessageBox(NULL, str, "PuTTY Fatal Error",
374330e2 446 MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
93b581bd 447 cleanup_exit(1);
374330e2 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
32874aea 456void *saferealloc(void *ptr, size_t size)
457{
374330e2 458 void *p;
b191636d 459 if (!ptr) {
460#ifdef MINEFIELD
32874aea 461 p = minefield_c_malloc(size);
b191636d 462#else
32874aea 463 p = malloc(size);
b191636d 464#endif
465 } else {
466#ifdef MINEFIELD
32874aea 467 p = minefield_c_realloc(ptr, size);
b191636d 468#else
32874aea 469 p = realloc(ptr, size);
b191636d 470#endif
471 }
374330e2 472 if (!p) {
d7da76ca 473 char str[200];
474#ifdef MALLOC_LOG
475 sprintf(str, "Out of memory! (%s:%d, size=%d)",
476 mlog_file, mlog_line, size);
1b2ef365 477 fprintf(fp, "*** %s\n", str);
478 fclose(fp);
d7da76ca 479#else
480 strcpy(str, "Out of memory!");
481#endif
482 MessageBox(NULL, str, "PuTTY Fatal Error",
374330e2 483 MB_SYSTEMMODAL | MB_ICONERROR | MB_OK);
93b581bd 484 cleanup_exit(1);
374330e2 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
32874aea 493void safefree(void *ptr)
494{
374330e2 495 if (ptr) {
496#ifdef MALLOC_LOG
497 if (fp)
498 fprintf(fp, "free(%p)\n", ptr);
499#endif
b191636d 500#ifdef MINEFIELD
32874aea 501 minefield_c_free(ptr);
b191636d 502#else
32874aea 503 free(ptr);
b191636d 504#endif
374330e2 505 }
506#ifdef MALLOC_LOG
507 else if (fp)
508 fprintf(fp, "freeing null pointer - no action taken\n");
509#endif
510}
c82bda52 511
03f64569 512/* ----------------------------------------------------------------------
513 * Debugging routines.
514 */
515
c82bda52 516#ifdef DEBUG
517static FILE *debug_fp = NULL;
518static int debug_got_console = 0;
519
32874aea 520static void dputs(char *buf)
521{
c82bda52 522 DWORD dw;
c82bda52 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
32874aea 532 WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, strlen(buf), &dw,
533 NULL);
c82bda52 534 fputs(buf, debug_fp);
535 fflush(debug_fp);
db9c0f86 536}
537
538
32874aea 539void dprintf(char *fmt, ...)
540{
db9c0f86 541 char buf[2048];
542 va_list ap;
543
544 va_start(ap, fmt);
545 vsprintf(buf, fmt, ap);
32874aea 546 dputs(buf);
c82bda52 547 va_end(ap);
548}
db9c0f86 549
550
32874aea 551void debug_memdump(void *buf, int len, int L)
552{
db9c0f86 553 int i;
554 unsigned char *p = buf;
765c4200 555 char foo[17];
db9c0f86 556 if (L) {
557 int delta;
32874aea 558 dprintf("\t%d (0x%x) bytes:\n", len, len);
db9c0f86 559 delta = 15 & (int) p;
560 p -= delta;
561 len += delta;
562 }
563 for (; 0 < len; p += 16, len -= 16) {
32874aea 564 dputs(" ");
565 if (L)
566 dprintf("%p: ", p);
567 strcpy(foo, "................"); /* sixteen dots */
db9c0f86 568 for (i = 0; i < 16 && i < len; ++i) {
569 if (&p[i] < (unsigned char *) buf) {
32874aea 570 dputs(" "); /* 3 spaces */
765c4200 571 foo[i] = ' ';
db9c0f86 572 } else {
32874aea 573 dprintf("%c%02.2x",
574 &p[i] != (unsigned char *) buf
575 && i % 4 ? '.' : ' ', p[i]
576 );
765c4200 577 if (p[i] >= ' ' && p[i] <= '~')
32874aea 578 foo[i] = (char) p[i];
db9c0f86 579 }
580 }
765c4200 581 foo[i] = '\0';
32874aea 582 dprintf("%*s%s\n", (16 - i) * 3 + 2, "", foo);
db9c0f86 583 }
584}
585
32874aea 586#endif /* def DEBUG */