Move a recently introduced utility function out of the file in which I
[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}
b61f81bc 102void add_prompt(prompts_t *p, char *promptstr, int echo)
edd0cb8a 103{
104 prompt_t *pr = snew(prompt_t);
edd0cb8a 105 pr->prompt = promptstr;
106 pr->echo = echo;
b61f81bc 107 pr->result = NULL;
108 pr->resultsize = 0;
edd0cb8a 109 p->n_prompts++;
110 p->prompts = sresize(p->prompts, p->n_prompts, prompt_t *);
111 p->prompts[p->n_prompts-1] = pr;
112}
b61f81bc 113void prompt_ensure_result_size(prompt_t *pr, int newlen)
114{
115 if ((int)pr->resultsize < newlen) {
116 char *newbuf;
117 newlen = newlen * 5 / 4 + 512; /* avoid too many small allocs */
118
119 /*
120 * We don't use sresize / realloc here, because we will be
121 * storing sensitive stuff like passwords in here, and we want
122 * to make sure that the data doesn't get copied around in
123 * memory without the old copy being destroyed.
124 */
125 newbuf = snewn(newlen, char);
126 memcpy(newbuf, pr->result, pr->resultsize);
127 memset(pr->result, '\0', pr->resultsize);
128 sfree(pr->result);
129 pr->result = newbuf;
130 pr->resultsize = newlen;
131 }
132}
133void prompt_set_result(prompt_t *pr, const char *newstr)
134{
135 prompt_ensure_result_size(pr, strlen(newstr) + 1);
136 strcpy(pr->result, newstr);
137}
edd0cb8a 138void free_prompts(prompts_t *p)
139{
140 size_t i;
141 for (i=0; i < p->n_prompts; i++) {
142 prompt_t *pr = p->prompts[i];
b61f81bc 143 memset(pr->result, 0, pr->resultsize); /* burn the evidence */
edd0cb8a 144 sfree(pr->result);
145 sfree(pr->prompt);
146 sfree(pr);
147 }
148 sfree(p->prompts);
149 sfree(p->name);
150 sfree(p->instruction);
151 sfree(p);
152}
153
03f64569 154/* ----------------------------------------------------------------------
155 * String handling routines.
156 */
157
57356d63 158char *dupstr(const char *s)
03f64569 159{
6d113886 160 char *p = NULL;
161 if (s) {
162 int len = strlen(s);
163 p = snewn(len + 1, char);
164 strcpy(p, s);
165 }
03f64569 166 return p;
167}
168
169/* Allocate the concatenation of N strings. Terminate arg list with NULL. */
57356d63 170char *dupcat(const char *s1, ...)
03f64569 171{
172 int len;
173 char *p, *q, *sn;
174 va_list ap;
175
176 len = strlen(s1);
177 va_start(ap, s1);
178 while (1) {
179 sn = va_arg(ap, char *);
180 if (!sn)
181 break;
182 len += strlen(sn);
183 }
184 va_end(ap);
185
3d88e64d 186 p = snewn(len + 1, char);
03f64569 187 strcpy(p, s1);
188 q = p + strlen(p);
189
190 va_start(ap, s1);
191 while (1) {
192 sn = va_arg(ap, char *);
193 if (!sn)
194 break;
195 strcpy(q, sn);
196 q += strlen(q);
197 }
198 va_end(ap);
199
200 return p;
201}
202
57356d63 203/*
204 * Do an sprintf(), but into a custom-allocated buffer.
205 *
28da9e3d 206 * Currently I'm doing this via vsnprintf. This has worked so far,
e1ef3c29 207 * but it's not good, because vsnprintf is not available on all
208 * platforms. There's an ifdef to use `_vsnprintf', which seems
209 * to be the local name for it on Windows. Other platforms may
210 * lack it completely, in which case it'll be time to rewrite
211 * this function in a totally different way.
28da9e3d 212 *
213 * The only `properly' portable solution I can think of is to
214 * implement my own format string scanner, which figures out an
215 * upper bound for the length of each formatting directive,
216 * allocates the buffer as it goes along, and calls sprintf() to
217 * actually process each directive. If I ever need to actually do
218 * this, some caveats:
219 *
220 * - It's very hard to find a reliable upper bound for
221 * floating-point values. %f, in particular, when supplied with
222 * a number near to the upper or lower limit of representable
223 * numbers, could easily take several hundred characters. It's
224 * probably feasible to predict this statically using the
225 * constants in <float.h>, or even to predict it dynamically by
226 * looking at the exponent of the specific float provided, but
227 * it won't be fun.
228 *
229 * - Don't forget to _check_, after calling sprintf, that it's
230 * used at most the amount of space we had available.
231 *
232 * - Fault any formatting directive we don't fully understand. The
233 * aim here is to _guarantee_ that we never overflow the buffer,
234 * because this is a security-critical function. If we see a
235 * directive we don't know about, we should panic and die rather
236 * than run any risk.
57356d63 237 */
238char *dupprintf(const char *fmt, ...)
239{
240 char *ret;
241 va_list ap;
242 va_start(ap, fmt);
243 ret = dupvprintf(fmt, ap);
244 va_end(ap);
245 return ret;
246}
247char *dupvprintf(const char *fmt, va_list ap)
248{
249 char *buf;
250 int len, size;
251
3d88e64d 252 buf = snewn(512, char);
57356d63 253 size = 512;
254
255 while (1) {
256#ifdef _WINDOWS
257#define vsnprintf _vsnprintf
258#endif
e1ef3c29 259#ifdef va_copy
260 /* Use the `va_copy' macro mandated by C99, if present.
261 * XXX some environments may have this as __va_copy() */
262 va_list aq;
263 va_copy(aq, ap);
264 len = vsnprintf(buf, size, fmt, aq);
265 va_end(aq);
266#else
267 /* Ugh. No va_copy macro, so do something nasty.
268 * Technically, you can't reuse a va_list like this: it is left
269 * unspecified whether advancing a va_list pointer modifies its
270 * value or something it points to, so on some platforms calling
271 * vsnprintf twice on the same va_list might fail hideously
272 * (indeed, it has been observed to).
273 * XXX the autoconf manual suggests that using memcpy() will give
274 * "maximum portability". */
57356d63 275 len = vsnprintf(buf, size, fmt, ap);
e1ef3c29 276#endif
57356d63 277 if (len >= 0 && len < size) {
278 /* This is the C99-specified criterion for snprintf to have
279 * been completely successful. */
280 return buf;
281 } else if (len > 0) {
282 /* This is the C99 error condition: the returned length is
283 * the required buffer size not counting the NUL. */
284 size = len + 1;
285 } else {
286 /* This is the pre-C99 glibc error condition: <0 means the
287 * buffer wasn't big enough, so we enlarge it a bit and hope. */
288 size += 512;
289 }
3d88e64d 290 buf = sresize(buf, size, char);
57356d63 291 }
292}
293
39934deb 294/*
295 * Read an entire line of text from a file. Return a buffer
296 * malloced to be as big as necessary (caller must free).
297 */
298char *fgetline(FILE *fp)
299{
300 char *ret = snewn(512, char);
301 int size = 512, len = 0;
302 while (fgets(ret + len, size - len, fp)) {
303 len += strlen(ret + len);
304 if (ret[len-1] == '\n')
305 break; /* got a newline, we're done */
306 size = len + 512;
307 ret = sresize(ret, size, char);
308 }
309 if (len == 0) { /* first fgets returned NULL */
310 sfree(ret);
311 return NULL;
312 }
313 ret[len] = '\0';
314 return ret;
315}
316
03f64569 317/* ----------------------------------------------------------------------
1549e076 318 * Base64 encoding routine. This is required in public-key writing
319 * but also in HTTP proxy handling, so it's centralised here.
320 */
321
322void base64_encode_atom(unsigned char *data, int n, char *out)
323{
324 static const char base64_chars[] =
325 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
326
327 unsigned word;
328
329 word = data[0] << 16;
330 if (n > 1)
331 word |= data[1] << 8;
332 if (n > 2)
333 word |= data[2];
334 out[0] = base64_chars[(word >> 18) & 0x3F];
335 out[1] = base64_chars[(word >> 12) & 0x3F];
336 if (n > 1)
337 out[2] = base64_chars[(word >> 6) & 0x3F];
338 else
339 out[2] = '=';
340 if (n > 2)
341 out[3] = base64_chars[word & 0x3F];
342 else
343 out[3] = '=';
344}
345
346/* ----------------------------------------------------------------------
5471d09a 347 * Generic routines to deal with send buffers: a linked list of
348 * smallish blocks, with the operations
349 *
350 * - add an arbitrary amount of data to the end of the list
351 * - remove the first N bytes from the list
352 * - return a (pointer,length) pair giving some initial data in
353 * the list, suitable for passing to a send or write system
354 * call
7983f47e 355 * - retrieve a larger amount of initial data from the list
5471d09a 356 * - return the current size of the buffer chain in bytes
357 */
358
359#define BUFFER_GRANULE 512
360
361struct bufchain_granule {
362 struct bufchain_granule *next;
363 int buflen, bufpos;
364 char buf[BUFFER_GRANULE];
365};
366
367void bufchain_init(bufchain *ch)
368{
369 ch->head = ch->tail = NULL;
370 ch->buffersize = 0;
371}
372
373void bufchain_clear(bufchain *ch)
374{
375 struct bufchain_granule *b;
376 while (ch->head) {
377 b = ch->head;
378 ch->head = ch->head->next;
379 sfree(b);
380 }
381 ch->tail = NULL;
382 ch->buffersize = 0;
383}
384
385int bufchain_size(bufchain *ch)
386{
387 return ch->buffersize;
388}
389
e0e7dff8 390void bufchain_add(bufchain *ch, const void *data, int len)
5471d09a 391{
e0e7dff8 392 const char *buf = (const char *)data;
5471d09a 393
bfa5400d 394 if (len == 0) return;
395
5471d09a 396 ch->buffersize += len;
397
398 if (ch->tail && ch->tail->buflen < BUFFER_GRANULE) {
399 int copylen = min(len, BUFFER_GRANULE - ch->tail->buflen);
400 memcpy(ch->tail->buf + ch->tail->buflen, buf, copylen);
401 buf += copylen;
402 len -= copylen;
403 ch->tail->buflen += copylen;
404 }
405 while (len > 0) {
406 int grainlen = min(len, BUFFER_GRANULE);
407 struct bufchain_granule *newbuf;
3d88e64d 408 newbuf = snew(struct bufchain_granule);
5471d09a 409 newbuf->bufpos = 0;
410 newbuf->buflen = grainlen;
411 memcpy(newbuf->buf, buf, grainlen);
412 buf += grainlen;
413 len -= grainlen;
414 if (ch->tail)
415 ch->tail->next = newbuf;
416 else
417 ch->head = ch->tail = newbuf;
418 newbuf->next = NULL;
419 ch->tail = newbuf;
420 }
421}
422
423void bufchain_consume(bufchain *ch, int len)
424{
7983f47e 425 struct bufchain_granule *tmp;
426
5471d09a 427 assert(ch->buffersize >= len);
7983f47e 428 while (len > 0) {
429 int remlen = len;
430 assert(ch->head != NULL);
431 if (remlen >= ch->head->buflen - ch->head->bufpos) {
432 remlen = ch->head->buflen - ch->head->bufpos;
433 tmp = ch->head;
434 ch->head = tmp->next;
435 sfree(tmp);
436 if (!ch->head)
437 ch->tail = NULL;
438 } else
439 ch->head->bufpos += remlen;
440 ch->buffersize -= remlen;
441 len -= remlen;
5471d09a 442 }
443}
444
445void bufchain_prefix(bufchain *ch, void **data, int *len)
446{
447 *len = ch->head->buflen - ch->head->bufpos;
448 *data = ch->head->buf + ch->head->bufpos;
449}
450
7983f47e 451void bufchain_fetch(bufchain *ch, void *data, int len)
452{
453 struct bufchain_granule *tmp;
454 char *data_c = (char *)data;
455
456 tmp = ch->head;
457
458 assert(ch->buffersize >= len);
459 while (len > 0) {
460 int remlen = len;
461
462 assert(tmp != NULL);
463 if (remlen >= tmp->buflen - tmp->bufpos)
464 remlen = tmp->buflen - tmp->bufpos;
465 memcpy(data_c, tmp->buf + tmp->bufpos, remlen);
466
467 tmp = tmp->next;
468 len -= remlen;
469 data_c += remlen;
470 }
471}
472
03f64569 473/* ----------------------------------------------------------------------
b191636d 474 * My own versions of malloc, realloc and free. Because I want
475 * malloc and realloc to bomb out and exit the program if they run
476 * out of memory, realloc to reliably call malloc if passed a NULL
477 * pointer, and free to reliably do nothing if passed a NULL
478 * pointer. We can also put trace printouts in, if we need to; and
479 * we can also replace the allocator with an ElectricFence-like
480 * one.
481 */
482
483#ifdef MINEFIELD
d0912d1f 484void *minefield_c_malloc(size_t size);
485void minefield_c_free(void *p);
486void *minefield_c_realloc(void *p, size_t size);
487#endif
374330e2 488
489#ifdef MALLOC_LOG
490static FILE *fp = NULL;
491
d7da76ca 492static char *mlog_file = NULL;
493static int mlog_line = 0;
494
32874aea 495void mlog(char *file, int line)
496{
d7da76ca 497 mlog_file = file;
498 mlog_line = line;
c662dbc0 499 if (!fp) {
374330e2 500 fp = fopen("putty_mem.log", "w");
c662dbc0 501 setvbuf(fp, NULL, _IONBF, BUFSIZ);
502 }
374330e2 503 if (fp)
32874aea 504 fprintf(fp, "%s:%d: ", file, line);
374330e2 505}
506#endif
507
46cfeac8 508void *safemalloc(size_t n, size_t size)
32874aea 509{
b191636d 510 void *p;
46cfeac8 511
512 if (n > INT_MAX / size) {
513 p = NULL;
514 } else {
515 size *= n;
66ab14c7 516 if (size == 0) size = 1;
b191636d 517#ifdef MINEFIELD
46cfeac8 518 p = minefield_c_malloc(size);
b191636d 519#else
46cfeac8 520 p = malloc(size);
b191636d 521#endif
46cfeac8 522 }
523
374330e2 524 if (!p) {
d7da76ca 525 char str[200];
526#ifdef MALLOC_LOG
527 sprintf(str, "Out of memory! (%s:%d, size=%d)",
528 mlog_file, mlog_line, size);
1b2ef365 529 fprintf(fp, "*** %s\n", str);
530 fclose(fp);
d7da76ca 531#else
532 strcpy(str, "Out of memory!");
533#endif
1709795f 534 modalfatalbox(str);
374330e2 535 }
536#ifdef MALLOC_LOG
537 if (fp)
538 fprintf(fp, "malloc(%d) returns %p\n", size, p);
539#endif
540 return p;
541}
542
46cfeac8 543void *saferealloc(void *ptr, size_t n, size_t size)
32874aea 544{
374330e2 545 void *p;
46cfeac8 546
547 if (n > INT_MAX / size) {
548 p = NULL;
549 } else {
550 size *= n;
551 if (!ptr) {
b191636d 552#ifdef MINEFIELD
46cfeac8 553 p = minefield_c_malloc(size);
b191636d 554#else
46cfeac8 555 p = malloc(size);
b191636d 556#endif
46cfeac8 557 } else {
b191636d 558#ifdef MINEFIELD
46cfeac8 559 p = minefield_c_realloc(ptr, size);
b191636d 560#else
46cfeac8 561 p = realloc(ptr, size);
b191636d 562#endif
46cfeac8 563 }
b191636d 564 }
46cfeac8 565
374330e2 566 if (!p) {
d7da76ca 567 char str[200];
568#ifdef MALLOC_LOG
569 sprintf(str, "Out of memory! (%s:%d, size=%d)",
570 mlog_file, mlog_line, size);
1b2ef365 571 fprintf(fp, "*** %s\n", str);
572 fclose(fp);
d7da76ca 573#else
574 strcpy(str, "Out of memory!");
575#endif
1709795f 576 modalfatalbox(str);
374330e2 577 }
578#ifdef MALLOC_LOG
579 if (fp)
580 fprintf(fp, "realloc(%p,%d) returns %p\n", ptr, size, p);
581#endif
582 return p;
583}
584
32874aea 585void safefree(void *ptr)
586{
374330e2 587 if (ptr) {
588#ifdef MALLOC_LOG
589 if (fp)
590 fprintf(fp, "free(%p)\n", ptr);
591#endif
b191636d 592#ifdef MINEFIELD
32874aea 593 minefield_c_free(ptr);
b191636d 594#else
32874aea 595 free(ptr);
b191636d 596#endif
374330e2 597 }
598#ifdef MALLOC_LOG
599 else if (fp)
600 fprintf(fp, "freeing null pointer - no action taken\n");
601#endif
602}
c82bda52 603
03f64569 604/* ----------------------------------------------------------------------
605 * Debugging routines.
606 */
607
c82bda52 608#ifdef DEBUG
d0912d1f 609extern void dputs(char *); /* defined in per-platform *misc.c */
db9c0f86 610
d0912d1f 611void debug_printf(char *fmt, ...)
32874aea 612{
57356d63 613 char *buf;
db9c0f86 614 va_list ap;
615
616 va_start(ap, fmt);
57356d63 617 buf = dupvprintf(fmt, ap);
32874aea 618 dputs(buf);
57356d63 619 sfree(buf);
c82bda52 620 va_end(ap);
621}
db9c0f86 622
623
32874aea 624void debug_memdump(void *buf, int len, int L)
625{
db9c0f86 626 int i;
627 unsigned char *p = buf;
765c4200 628 char foo[17];
db9c0f86 629 if (L) {
630 int delta;
d0912d1f 631 debug_printf("\t%d (0x%x) bytes:\n", len, len);
cc0966fa 632 delta = 15 & (unsigned long int) p;
db9c0f86 633 p -= delta;
634 len += delta;
635 }
636 for (; 0 < len; p += 16, len -= 16) {
32874aea 637 dputs(" ");
638 if (L)
d0912d1f 639 debug_printf("%p: ", p);
32874aea 640 strcpy(foo, "................"); /* sixteen dots */
db9c0f86 641 for (i = 0; i < 16 && i < len; ++i) {
642 if (&p[i] < (unsigned char *) buf) {
32874aea 643 dputs(" "); /* 3 spaces */
765c4200 644 foo[i] = ' ';
db9c0f86 645 } else {
d0912d1f 646 debug_printf("%c%02.2x",
32874aea 647 &p[i] != (unsigned char *) buf
648 && i % 4 ? '.' : ' ', p[i]
649 );
765c4200 650 if (p[i] >= ' ' && p[i] <= '~')
32874aea 651 foo[i] = (char) p[i];
db9c0f86 652 }
653 }
765c4200 654 foo[i] = '\0';
d0912d1f 655 debug_printf("%*s%s\n", (16 - i) * 3 + 2, "", foo);
db9c0f86 656 }
657}
658
32874aea 659#endif /* def DEBUG */
7374c779 660
661/*
4a693cfc 662 * Determine whether or not a Conf represents a session which can
663 * sensibly be launched right now.
7374c779 664 */
4a693cfc 665int conf_launchable(Conf *conf)
7374c779 666{
4a693cfc 667 if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL)
668 return conf_get_str(conf, CONF_serline)[0] != 0;
7374c779 669 else
4a693cfc 670 return conf_get_str(conf, CONF_host)[0] != 0;
7374c779 671}
672
4a693cfc 673char const *conf_dest(Conf *conf)
7374c779 674{
4a693cfc 675 if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL)
676 return conf_get_str(conf, CONF_serline);
7374c779 677 else
4a693cfc 678 return conf_get_str(conf, CONF_host);
7374c779 679}