2 * Platform-independent routines shared between all PuTTY programs.
14 * Parse a string block size specification. This is approximately a
15 * subset of the block size specs supported by GNU fileutils:
19 * All numbers are decimal, and suffixes refer to powers of two.
22 unsigned long parse_blocksize(const char *bs)
25 unsigned long r = strtoul(bs, &suf, 10);
27 while (*suf && isspace((unsigned char)*suf)) suf++;
36 r *= 1024ul * 1024ul * 1024ul;
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
51 * answerback-string parsing code. All sequences start with ^; all except
52 * ^<123> are two characters. The ones that are worth keeping are probably:
56 * <num> specified by number (decimal, 0octal, 0xHEX)
59 char ctrlparse(char *s, char **next)
68 } else if (*s == '<') {
70 c = (char)strtol(s, next, 0);
71 if ((*next == s) || (**next != '>')) {
76 } else if (*s >= 'a' && *s <= 'z') {
79 } else if ((*s >= '@' && *s <= '_') || *s == '?' || (*s & 0x80)) {
82 } else if (*s == '~') {
90 prompts_t *new_prompts(void *frontend)
92 prompts_t *p = snew(prompts_t);
95 p->frontend = frontend;
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;
102 void add_prompt(prompts_t *p, char *promptstr, int echo)
104 prompt_t *pr = snew(prompt_t);
105 pr->prompt = promptstr;
110 p->prompts = sresize(p->prompts, p->n_prompts, prompt_t *);
111 p->prompts[p->n_prompts-1] = pr;
113 void prompt_ensure_result_size(prompt_t *pr, int newlen)
115 if ((int)pr->resultsize < newlen) {
117 newlen = newlen * 5 / 4 + 512; /* avoid too many small allocs */
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.
125 newbuf = snewn(newlen, char);
126 memcpy(newbuf, pr->result, pr->resultsize);
127 memset(pr->result, '\0', pr->resultsize);
130 pr->resultsize = newlen;
133 void prompt_set_result(prompt_t *pr, const char *newstr)
135 prompt_ensure_result_size(pr, strlen(newstr) + 1);
136 strcpy(pr->result, newstr);
138 void free_prompts(prompts_t *p)
141 for (i=0; i < p->n_prompts; i++) {
142 prompt_t *pr = p->prompts[i];
143 memset(pr->result, 0, pr->resultsize); /* burn the evidence */
150 sfree(p->instruction);
154 /* ----------------------------------------------------------------------
155 * String handling routines.
158 char *dupstr(const char *s)
163 p = snewn(len + 1, char);
169 /* Allocate the concatenation of N strings. Terminate arg list with NULL. */
170 char *dupcat(const char *s1, ...)
179 sn = va_arg(ap, char *);
186 p = snewn(len + 1, char);
192 sn = va_arg(ap, char *);
204 * Do an sprintf(), but into a custom-allocated buffer.
206 * Currently I'm doing this via vsnprintf. This has worked so far,
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.
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:
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
229 * - Don't forget to _check_, after calling sprintf, that it's
230 * used at most the amount of space we had available.
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
238 char *dupprintf(const char *fmt, ...)
243 ret = dupvprintf(fmt, ap);
247 char *dupvprintf(const char *fmt, va_list ap)
252 buf = snewn(512, char);
257 #define vsnprintf _vsnprintf
260 /* Use the `va_copy' macro mandated by C99, if present.
261 * XXX some environments may have this as __va_copy() */
264 len = vsnprintf(buf, size, fmt, aq);
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". */
275 len = vsnprintf(buf, size, fmt, ap);
277 if (len >= 0 && len < size) {
278 /* This is the C99-specified criterion for snprintf to have
279 * been completely successful. */
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. */
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. */
290 buf = sresize(buf, size, char);
295 * Read an entire line of text from a file. Return a buffer
296 * malloced to be as big as necessary (caller must free).
298 char *fgetline(FILE *fp)
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 */
307 ret = sresize(ret, size, char);
309 if (len == 0) { /* first fgets returned NULL */
317 /* ----------------------------------------------------------------------
318 * Base64 encoding routine. This is required in public-key writing
319 * but also in HTTP proxy handling, so it's centralised here.
322 void base64_encode_atom(unsigned char *data, int n, char *out)
324 static const char base64_chars[] =
325 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
329 word = data[0] << 16;
331 word |= data[1] << 8;
334 out[0] = base64_chars[(word >> 18) & 0x3F];
335 out[1] = base64_chars[(word >> 12) & 0x3F];
337 out[2] = base64_chars[(word >> 6) & 0x3F];
341 out[3] = base64_chars[word & 0x3F];
346 /* ----------------------------------------------------------------------
347 * Generic routines to deal with send buffers: a linked list of
348 * smallish blocks, with the operations
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
355 * - retrieve a larger amount of initial data from the list
356 * - return the current size of the buffer chain in bytes
359 #define BUFFER_GRANULE 512
361 struct bufchain_granule {
362 struct bufchain_granule *next;
364 char buf[BUFFER_GRANULE];
367 void bufchain_init(bufchain *ch)
369 ch->head = ch->tail = NULL;
373 void bufchain_clear(bufchain *ch)
375 struct bufchain_granule *b;
378 ch->head = ch->head->next;
385 int bufchain_size(bufchain *ch)
387 return ch->buffersize;
390 void bufchain_add(bufchain *ch, const void *data, int len)
392 const char *buf = (const char *)data;
394 if (len == 0) return;
396 ch->buffersize += len;
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);
403 ch->tail->buflen += copylen;
406 int grainlen = min(len, BUFFER_GRANULE);
407 struct bufchain_granule *newbuf;
408 newbuf = snew(struct bufchain_granule);
410 newbuf->buflen = grainlen;
411 memcpy(newbuf->buf, buf, grainlen);
415 ch->tail->next = newbuf;
417 ch->head = ch->tail = newbuf;
423 void bufchain_consume(bufchain *ch, int len)
425 struct bufchain_granule *tmp;
427 assert(ch->buffersize >= len);
430 assert(ch->head != NULL);
431 if (remlen >= ch->head->buflen - ch->head->bufpos) {
432 remlen = ch->head->buflen - ch->head->bufpos;
434 ch->head = tmp->next;
439 ch->head->bufpos += remlen;
440 ch->buffersize -= remlen;
445 void bufchain_prefix(bufchain *ch, void **data, int *len)
447 *len = ch->head->buflen - ch->head->bufpos;
448 *data = ch->head->buf + ch->head->bufpos;
451 void bufchain_fetch(bufchain *ch, void *data, int len)
453 struct bufchain_granule *tmp;
454 char *data_c = (char *)data;
458 assert(ch->buffersize >= len);
463 if (remlen >= tmp->buflen - tmp->bufpos)
464 remlen = tmp->buflen - tmp->bufpos;
465 memcpy(data_c, tmp->buf + tmp->bufpos, remlen);
473 /* ----------------------------------------------------------------------
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
484 void *minefield_c_malloc(size_t size);
485 void minefield_c_free(void *p);
486 void *minefield_c_realloc(void *p, size_t size);
490 static FILE *fp = NULL;
492 static char *mlog_file = NULL;
493 static int mlog_line = 0;
495 void mlog(char *file, int line)
500 fp = fopen("putty_mem.log", "w");
501 setvbuf(fp, NULL, _IONBF, BUFSIZ);
504 fprintf(fp, "%s:%d: ", file, line);
508 void *safemalloc(size_t n, size_t size)
512 if (n > INT_MAX / size) {
516 if (size == 0) size = 1;
518 p = minefield_c_malloc(size);
527 sprintf(str, "Out of memory! (%s:%d, size=%d)",
528 mlog_file, mlog_line, size);
529 fprintf(fp, "*** %s\n", str);
532 strcpy(str, "Out of memory!");
538 fprintf(fp, "malloc(%d) returns %p\n", size, p);
543 void *saferealloc(void *ptr, size_t n, size_t size)
547 if (n > INT_MAX / size) {
553 p = minefield_c_malloc(size);
559 p = minefield_c_realloc(ptr, size);
561 p = realloc(ptr, size);
569 sprintf(str, "Out of memory! (%s:%d, size=%d)",
570 mlog_file, mlog_line, size);
571 fprintf(fp, "*** %s\n", str);
574 strcpy(str, "Out of memory!");
580 fprintf(fp, "realloc(%p,%d) returns %p\n", ptr, size, p);
585 void safefree(void *ptr)
590 fprintf(fp, "free(%p)\n", ptr);
593 minefield_c_free(ptr);
600 fprintf(fp, "freeing null pointer - no action taken\n");
604 /* ----------------------------------------------------------------------
605 * Debugging routines.
609 extern void dputs(char *); /* defined in per-platform *misc.c */
611 void debug_printf(char *fmt, ...)
617 buf = dupvprintf(fmt, ap);
624 void debug_memdump(void *buf, int len, int L)
627 unsigned char *p = buf;
631 debug_printf("\t%d (0x%x) bytes:\n", len, len);
632 delta = 15 & (unsigned long int) p;
636 for (; 0 < len; p += 16, len -= 16) {
639 debug_printf("%p: ", p);
640 strcpy(foo, "................"); /* sixteen dots */
641 for (i = 0; i < 16 && i < len; ++i) {
642 if (&p[i] < (unsigned char *) buf) {
643 dputs(" "); /* 3 spaces */
646 debug_printf("%c%02.2x",
647 &p[i] != (unsigned char *) buf
648 && i % 4 ? '.' : ' ', p[i]
650 if (p[i] >= ' ' && p[i] <= '~')
651 foo[i] = (char) p[i];
655 debug_printf("%*s%s\n", (16 - i) * 3 + 2, "", foo);
659 #endif /* def DEBUG */
662 * Determine whether or not a Conf represents a session which can
663 * sensibly be launched right now.
665 int conf_launchable(Conf *conf)
667 if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL)
668 return conf_get_str(conf, CONF_serline)[0] != 0;
670 return conf_get_str(conf, CONF_host)[0] != 0;
673 char const *conf_dest(Conf *conf)
675 if (conf_get_int(conf, CONF_protocol) == PROT_SERIAL)
676 return conf_get_str(conf, CONF_serline);
678 return conf_get_str(conf, CONF_host);