Now that Local proxy type exists on both Unix and Windows, document it and
[u/mdw/putty] / misc.c
CommitLineData
f4ff9455 1/*
2 * Platform-independent routines shared between all PuTTY programs.
3 */
4
374330e2 5#include <stdio.h>
6#include <stdlib.h>
1709795f 7#include <stdarg.h>
46cfeac8 8#include <limits.h>
57356d63 9#include <ctype.h>
5471d09a 10#include <assert.h>
374330e2 11#include "putty.h"
12
d57f70af 13/*
14 * Parse a string block size specification. This is approximately a
15 * subset of the block size specs supported by GNU fileutils:
16 * "nk" = n kilobytes
17 * "nM" = n megabytes
18 * "nG" = n gigabytes
19 * All numbers are decimal, and suffixes refer to powers of two.
20 * Case-insensitive.
21 */
22unsigned long parse_blocksize(const char *bs)
23{
24 char *suf;
25 unsigned long r = strtoul(bs, &suf, 10);
26 if (*suf != '\0') {
0d119367 27 while (*suf && isspace((unsigned char)*suf)) suf++;
d57f70af 28 switch (*suf) {
29 case 'k': case 'K':
30 r *= 1024ul;
31 break;
32 case 'm': case 'M':
33 r *= 1024ul * 1024ul;
34 break;
35 case 'g': case 'G':
36 r *= 1024ul * 1024ul * 1024ul;
37 break;
38 case '\0':
39 default:
40 break;
41 }
42 }
43 return r;
44}
45
d45d4c07 46/*
47 * Parse a ^C style character specification.
48 * Returns NULL in `next' if we didn't recognise it as a control character,
49 * in which case `c' should be ignored.
50 * The precise current parsing is an oddity inherited from the terminal
447940b3 51 * answerback-string parsing code. All sequences start with ^; all except
52 * ^<123> are two characters. The ones that are worth keeping are probably:
d45d4c07 53 * ^? 127
54 * ^@A-Z[\]^_ 0-31
55 * a-z 1-26
447940b3 56 * <num> specified by number (decimal, 0octal, 0xHEX)
d45d4c07 57 * ~ ^ escape
58 */
59char ctrlparse(char *s, char **next)
60{
61 char c = 0;
62 if (*s != '^') {
63 *next = NULL;
d45d4c07 64 } else {
65 s++;
66 if (*s == '\0') {
67 *next = NULL;
447940b3 68 } else if (*s == '<') {
69 s++;
70 c = (char)strtol(s, next, 0);
71 if ((*next == s) || (**next != '>')) {
72 c = 0;
73 *next = NULL;
74 } else
75 (*next)++;
d45d4c07 76 } else if (*s >= 'a' && *s <= 'z') {
77 c = (*s - ('a' - 1));
447940b3 78 *next = s+1;
d45d4c07 79 } else if ((*s >= '@' && *s <= '_') || *s == '?' || (*s & 0x80)) {
80 c = ('@' ^ *s);
447940b3 81 *next = s+1;
d45d4c07 82 } else if (*s == '~') {
83 c = '^';
447940b3 84 *next = s+1;
d45d4c07 85 }
d45d4c07 86 }
447940b3 87 return c;
d45d4c07 88}
89
edd0cb8a 90prompts_t *new_prompts(void *frontend)
91{
92 prompts_t *p = snew(prompts_t);
93 p->prompts = NULL;
94 p->n_prompts = 0;
95 p->frontend = frontend;
96 p->data = NULL;
97 p->to_server = TRUE; /* to be on the safe side */
98 p->name = p->instruction = NULL;
99 p->name_reqd = p->instr_reqd = FALSE;
100 return p;
101}
102void add_prompt(prompts_t *p, char *promptstr, int echo, size_t len)
103{
104 prompt_t *pr = snew(prompt_t);
105 unsigned char *result = snewn(len, unsigned char);
106 pr->prompt = promptstr;
107 pr->echo = echo;
108 pr->result = result;
109 pr->result_len = len;
110 p->n_prompts++;
111 p->prompts = sresize(p->prompts, p->n_prompts, prompt_t *);
112 p->prompts[p->n_prompts-1] = pr;
113}
114void free_prompts(prompts_t *p)
115{
116 size_t i;
117 for (i=0; i < p->n_prompts; i++) {
118 prompt_t *pr = p->prompts[i];
119 memset(pr->result, 0, pr->result_len); /* burn the evidence */
120 sfree(pr->result);
121 sfree(pr->prompt);
122 sfree(pr);
123 }
124 sfree(p->prompts);
125 sfree(p->name);
126 sfree(p->instruction);
127 sfree(p);
128}
129
03f64569 130/* ----------------------------------------------------------------------
131 * String handling routines.
132 */
133
57356d63 134char *dupstr(const char *s)
03f64569 135{
6d113886 136 char *p = NULL;
137 if (s) {
138 int len = strlen(s);
139 p = snewn(len + 1, char);
140 strcpy(p, s);
141 }
03f64569 142 return p;
143}
144
145/* Allocate the concatenation of N strings. Terminate arg list with NULL. */
57356d63 146char *dupcat(const char *s1, ...)
03f64569 147{
148 int len;
149 char *p, *q, *sn;
150 va_list ap;
151
152 len = strlen(s1);
153 va_start(ap, s1);
154 while (1) {
155 sn = va_arg(ap, char *);
156 if (!sn)
157 break;
158 len += strlen(sn);
159 }
160 va_end(ap);
161
3d88e64d 162 p = snewn(len + 1, char);
03f64569 163 strcpy(p, s1);
164 q = p + strlen(p);
165
166 va_start(ap, s1);
167 while (1) {
168 sn = va_arg(ap, char *);
169 if (!sn)
170 break;
171 strcpy(q, sn);
172 q += strlen(q);
173 }
174 va_end(ap);
175
176 return p;
177}
178
57356d63 179/*
180 * Do an sprintf(), but into a custom-allocated buffer.
181 *
28da9e3d 182 * Currently I'm doing this via vsnprintf. This has worked so far,
183 * but it's not good, because:
184 *
185 * - vsnprintf is not available on all platforms. There's an ifdef
186 * to use `_vsnprintf', which seems to be the local name for it
187 * on Windows. Other platforms may lack it completely, in which
188 * case it'll be time to rewrite this function in a totally
189 * different way.
190 *
191 * - technically you can't reuse a va_list like this: it is left
192 * unspecified whether advancing a va_list pointer modifies its
193 * value or something it points to, so on some platforms calling
194 * vsnprintf twice on the same va_list might fail hideously. It
195 * would be better to use the `va_copy' macro mandated by C99,
196 * but that too is not yet ubiquitous.
197 *
198 * The only `properly' portable solution I can think of is to
199 * implement my own format string scanner, which figures out an
200 * upper bound for the length of each formatting directive,
201 * allocates the buffer as it goes along, and calls sprintf() to
202 * actually process each directive. If I ever need to actually do
203 * this, some caveats:
204 *
205 * - It's very hard to find a reliable upper bound for
206 * floating-point values. %f, in particular, when supplied with
207 * a number near to the upper or lower limit of representable
208 * numbers, could easily take several hundred characters. It's
209 * probably feasible to predict this statically using the
210 * constants in <float.h>, or even to predict it dynamically by
211 * looking at the exponent of the specific float provided, but
212 * it won't be fun.
213 *
214 * - Don't forget to _check_, after calling sprintf, that it's
215 * used at most the amount of space we had available.
216 *
217 * - Fault any formatting directive we don't fully understand. The
218 * aim here is to _guarantee_ that we never overflow the buffer,
219 * because this is a security-critical function. If we see a
220 * directive we don't know about, we should panic and die rather
221 * than run any risk.
57356d63 222 */
223char *dupprintf(const char *fmt, ...)
224{
225 char *ret;
226 va_list ap;
227 va_start(ap, fmt);
228 ret = dupvprintf(fmt, ap);
229 va_end(ap);
230 return ret;
231}
232char *dupvprintf(const char *fmt, va_list ap)
233{
234 char *buf;
235 int len, size;
236
3d88e64d 237 buf = snewn(512, char);
57356d63 238 size = 512;
239
240 while (1) {
241#ifdef _WINDOWS
242#define vsnprintf _vsnprintf
243#endif
244 len = vsnprintf(buf, size, fmt, ap);
245 if (len >= 0 && len < size) {
246 /* This is the C99-specified criterion for snprintf to have
247 * been completely successful. */
248 return buf;
249 } else if (len > 0) {
250 /* This is the C99 error condition: the returned length is
251 * the required buffer size not counting the NUL. */
252 size = len + 1;
253 } else {
254 /* This is the pre-C99 glibc error condition: <0 means the
255 * buffer wasn't big enough, so we enlarge it a bit and hope. */
256 size += 512;
257 }
3d88e64d 258 buf = sresize(buf, size, char);
57356d63 259 }
260}
261
39934deb 262/*
263 * Read an entire line of text from a file. Return a buffer
264 * malloced to be as big as necessary (caller must free).
265 */
266char *fgetline(FILE *fp)
267{
268 char *ret = snewn(512, char);
269 int size = 512, len = 0;
270 while (fgets(ret + len, size - len, fp)) {
271 len += strlen(ret + len);
272 if (ret[len-1] == '\n')
273 break; /* got a newline, we're done */
274 size = len + 512;
275 ret = sresize(ret, size, char);
276 }
277 if (len == 0) { /* first fgets returned NULL */
278 sfree(ret);
279 return NULL;
280 }
281 ret[len] = '\0';
282 return ret;
283}
284
03f64569 285/* ----------------------------------------------------------------------
1549e076 286 * Base64 encoding routine. This is required in public-key writing
287 * but also in HTTP proxy handling, so it's centralised here.
288 */
289
290void base64_encode_atom(unsigned char *data, int n, char *out)
291{
292 static const char base64_chars[] =
293 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
294
295 unsigned word;
296
297 word = data[0] << 16;
298 if (n > 1)
299 word |= data[1] << 8;
300 if (n > 2)
301 word |= data[2];
302 out[0] = base64_chars[(word >> 18) & 0x3F];
303 out[1] = base64_chars[(word >> 12) & 0x3F];
304 if (n > 1)
305 out[2] = base64_chars[(word >> 6) & 0x3F];
306 else
307 out[2] = '=';
308 if (n > 2)
309 out[3] = base64_chars[word & 0x3F];
310 else
311 out[3] = '=';
312}
313
314/* ----------------------------------------------------------------------
5471d09a 315 * Generic routines to deal with send buffers: a linked list of
316 * smallish blocks, with the operations
317 *
318 * - add an arbitrary amount of data to the end of the list
319 * - remove the first N bytes from the list
320 * - return a (pointer,length) pair giving some initial data in
321 * the list, suitable for passing to a send or write system
322 * call
7983f47e 323 * - retrieve a larger amount of initial data from the list
5471d09a 324 * - return the current size of the buffer chain in bytes
325 */
326
327#define BUFFER_GRANULE 512
328
329struct bufchain_granule {
330 struct bufchain_granule *next;
331 int buflen, bufpos;
332 char buf[BUFFER_GRANULE];
333};
334
335void bufchain_init(bufchain *ch)
336{
337 ch->head = ch->tail = NULL;
338 ch->buffersize = 0;
339}
340
341void bufchain_clear(bufchain *ch)
342{
343 struct bufchain_granule *b;
344 while (ch->head) {
345 b = ch->head;
346 ch->head = ch->head->next;
347 sfree(b);
348 }
349 ch->tail = NULL;
350 ch->buffersize = 0;
351}
352
353int bufchain_size(bufchain *ch)
354{
355 return ch->buffersize;
356}
357
e0e7dff8 358void bufchain_add(bufchain *ch, const void *data, int len)
5471d09a 359{
e0e7dff8 360 const char *buf = (const char *)data;
5471d09a 361
bfa5400d 362 if (len == 0) return;
363
5471d09a 364 ch->buffersize += len;
365
366 if (ch->tail && ch->tail->buflen < BUFFER_GRANULE) {
367 int copylen = min(len, BUFFER_GRANULE - ch->tail->buflen);
368 memcpy(ch->tail->buf + ch->tail->buflen, buf, copylen);
369 buf += copylen;
370 len -= copylen;
371 ch->tail->buflen += copylen;
372 }
373 while (len > 0) {
374 int grainlen = min(len, BUFFER_GRANULE);
375 struct bufchain_granule *newbuf;
3d88e64d 376 newbuf = snew(struct bufchain_granule);
5471d09a 377 newbuf->bufpos = 0;
378 newbuf->buflen = grainlen;
379 memcpy(newbuf->buf, buf, grainlen);
380 buf += grainlen;
381 len -= grainlen;
382 if (ch->tail)
383 ch->tail->next = newbuf;
384 else
385 ch->head = ch->tail = newbuf;
386 newbuf->next = NULL;
387 ch->tail = newbuf;
388 }
389}
390
391void bufchain_consume(bufchain *ch, int len)
392{
7983f47e 393 struct bufchain_granule *tmp;
394
5471d09a 395 assert(ch->buffersize >= len);
7983f47e 396 while (len > 0) {
397 int remlen = len;
398 assert(ch->head != NULL);
399 if (remlen >= ch->head->buflen - ch->head->bufpos) {
400 remlen = ch->head->buflen - ch->head->bufpos;
401 tmp = ch->head;
402 ch->head = tmp->next;
403 sfree(tmp);
404 if (!ch->head)
405 ch->tail = NULL;
406 } else
407 ch->head->bufpos += remlen;
408 ch->buffersize -= remlen;
409 len -= remlen;
5471d09a 410 }
411}
412
413void bufchain_prefix(bufchain *ch, void **data, int *len)
414{
415 *len = ch->head->buflen - ch->head->bufpos;
416 *data = ch->head->buf + ch->head->bufpos;
417}
418
7983f47e 419void bufchain_fetch(bufchain *ch, void *data, int len)
420{
421 struct bufchain_granule *tmp;
422 char *data_c = (char *)data;
423
424 tmp = ch->head;
425
426 assert(ch->buffersize >= len);
427 while (len > 0) {
428 int remlen = len;
429
430 assert(tmp != NULL);
431 if (remlen >= tmp->buflen - tmp->bufpos)
432 remlen = tmp->buflen - tmp->bufpos;
433 memcpy(data_c, tmp->buf + tmp->bufpos, remlen);
434
435 tmp = tmp->next;
436 len -= remlen;
437 data_c += remlen;
438 }
439}
440
03f64569 441/* ----------------------------------------------------------------------
b191636d 442 * My own versions of malloc, realloc and free. Because I want
443 * malloc and realloc to bomb out and exit the program if they run
444 * out of memory, realloc to reliably call malloc if passed a NULL
445 * pointer, and free to reliably do nothing if passed a NULL
446 * pointer. We can also put trace printouts in, if we need to; and
447 * we can also replace the allocator with an ElectricFence-like
448 * one.
449 */
450
451#ifdef MINEFIELD
d0912d1f 452void *minefield_c_malloc(size_t size);
453void minefield_c_free(void *p);
454void *minefield_c_realloc(void *p, size_t size);
455#endif
374330e2 456
457#ifdef MALLOC_LOG
458static FILE *fp = NULL;
459
d7da76ca 460static char *mlog_file = NULL;
461static int mlog_line = 0;
462
32874aea 463void mlog(char *file, int line)
464{
d7da76ca 465 mlog_file = file;
466 mlog_line = line;
c662dbc0 467 if (!fp) {
374330e2 468 fp = fopen("putty_mem.log", "w");
c662dbc0 469 setvbuf(fp, NULL, _IONBF, BUFSIZ);
470 }
374330e2 471 if (fp)
32874aea 472 fprintf(fp, "%s:%d: ", file, line);
374330e2 473}
474#endif
475
46cfeac8 476void *safemalloc(size_t n, size_t size)
32874aea 477{
b191636d 478 void *p;
46cfeac8 479
480 if (n > INT_MAX / size) {
481 p = NULL;
482 } else {
483 size *= n;
66ab14c7 484 if (size == 0) size = 1;
b191636d 485#ifdef MINEFIELD
46cfeac8 486 p = minefield_c_malloc(size);
b191636d 487#else
46cfeac8 488 p = malloc(size);
b191636d 489#endif
46cfeac8 490 }
491
374330e2 492 if (!p) {
d7da76ca 493 char str[200];
494#ifdef MALLOC_LOG
495 sprintf(str, "Out of memory! (%s:%d, size=%d)",
496 mlog_file, mlog_line, size);
1b2ef365 497 fprintf(fp, "*** %s\n", str);
498 fclose(fp);
d7da76ca 499#else
500 strcpy(str, "Out of memory!");
501#endif
1709795f 502 modalfatalbox(str);
374330e2 503 }
504#ifdef MALLOC_LOG
505 if (fp)
506 fprintf(fp, "malloc(%d) returns %p\n", size, p);
507#endif
508 return p;
509}
510
46cfeac8 511void *saferealloc(void *ptr, size_t n, size_t size)
32874aea 512{
374330e2 513 void *p;
46cfeac8 514
515 if (n > INT_MAX / size) {
516 p = NULL;
517 } else {
518 size *= n;
519 if (!ptr) {
b191636d 520#ifdef MINEFIELD
46cfeac8 521 p = minefield_c_malloc(size);
b191636d 522#else
46cfeac8 523 p = malloc(size);
b191636d 524#endif
46cfeac8 525 } else {
b191636d 526#ifdef MINEFIELD
46cfeac8 527 p = minefield_c_realloc(ptr, size);
b191636d 528#else
46cfeac8 529 p = realloc(ptr, size);
b191636d 530#endif
46cfeac8 531 }
b191636d 532 }
46cfeac8 533
374330e2 534 if (!p) {
d7da76ca 535 char str[200];
536#ifdef MALLOC_LOG
537 sprintf(str, "Out of memory! (%s:%d, size=%d)",
538 mlog_file, mlog_line, size);
1b2ef365 539 fprintf(fp, "*** %s\n", str);
540 fclose(fp);
d7da76ca 541#else
542 strcpy(str, "Out of memory!");
543#endif
1709795f 544 modalfatalbox(str);
374330e2 545 }
546#ifdef MALLOC_LOG
547 if (fp)
548 fprintf(fp, "realloc(%p,%d) returns %p\n", ptr, size, p);
549#endif
550 return p;
551}
552
32874aea 553void safefree(void *ptr)
554{
374330e2 555 if (ptr) {
556#ifdef MALLOC_LOG
557 if (fp)
558 fprintf(fp, "free(%p)\n", ptr);
559#endif
b191636d 560#ifdef MINEFIELD
32874aea 561 minefield_c_free(ptr);
b191636d 562#else
32874aea 563 free(ptr);
b191636d 564#endif
374330e2 565 }
566#ifdef MALLOC_LOG
567 else if (fp)
568 fprintf(fp, "freeing null pointer - no action taken\n");
569#endif
570}
c82bda52 571
03f64569 572/* ----------------------------------------------------------------------
573 * Debugging routines.
574 */
575
c82bda52 576#ifdef DEBUG
d0912d1f 577extern void dputs(char *); /* defined in per-platform *misc.c */
db9c0f86 578
d0912d1f 579void debug_printf(char *fmt, ...)
32874aea 580{
57356d63 581 char *buf;
db9c0f86 582 va_list ap;
583
584 va_start(ap, fmt);
57356d63 585 buf = dupvprintf(fmt, ap);
32874aea 586 dputs(buf);
57356d63 587 sfree(buf);
c82bda52 588 va_end(ap);
589}
db9c0f86 590
591
32874aea 592void debug_memdump(void *buf, int len, int L)
593{
db9c0f86 594 int i;
595 unsigned char *p = buf;
765c4200 596 char foo[17];
db9c0f86 597 if (L) {
598 int delta;
d0912d1f 599 debug_printf("\t%d (0x%x) bytes:\n", len, len);
db9c0f86 600 delta = 15 & (int) p;
601 p -= delta;
602 len += delta;
603 }
604 for (; 0 < len; p += 16, len -= 16) {
32874aea 605 dputs(" ");
606 if (L)
d0912d1f 607 debug_printf("%p: ", p);
32874aea 608 strcpy(foo, "................"); /* sixteen dots */
db9c0f86 609 for (i = 0; i < 16 && i < len; ++i) {
610 if (&p[i] < (unsigned char *) buf) {
32874aea 611 dputs(" "); /* 3 spaces */
765c4200 612 foo[i] = ' ';
db9c0f86 613 } else {
d0912d1f 614 debug_printf("%c%02.2x",
32874aea 615 &p[i] != (unsigned char *) buf
616 && i % 4 ? '.' : ' ', p[i]
617 );
765c4200 618 if (p[i] >= ' ' && p[i] <= '~')
32874aea 619 foo[i] = (char) p[i];
db9c0f86 620 }
621 }
765c4200 622 foo[i] = '\0';
d0912d1f 623 debug_printf("%*s%s\n", (16 - i) * 3 + 2, "", foo);
db9c0f86 624 }
625}
626
32874aea 627#endif /* def DEBUG */