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 /* ----------------------------------------------------------------------
91 * String handling routines.
94 char *dupstr(const char *s)
99 p = snewn(len + 1, char);
105 /* Allocate the concatenation of N strings. Terminate arg list with NULL. */
106 char *dupcat(const char *s1, ...)
115 sn = va_arg(ap, char *);
122 p = snewn(len + 1, char);
128 sn = va_arg(ap, char *);
140 * Do an sprintf(), but into a custom-allocated buffer.
142 * Currently I'm doing this via vsnprintf. This has worked so far,
143 * but it's not good, because:
145 * - vsnprintf is not available on all platforms. There's an ifdef
146 * to use `_vsnprintf', which seems to be the local name for it
147 * on Windows. Other platforms may lack it completely, in which
148 * case it'll be time to rewrite this function in a totally
151 * - technically you can't reuse a va_list like this: it is left
152 * unspecified whether advancing a va_list pointer modifies its
153 * value or something it points to, so on some platforms calling
154 * vsnprintf twice on the same va_list might fail hideously. It
155 * would be better to use the `va_copy' macro mandated by C99,
156 * but that too is not yet ubiquitous.
158 * The only `properly' portable solution I can think of is to
159 * implement my own format string scanner, which figures out an
160 * upper bound for the length of each formatting directive,
161 * allocates the buffer as it goes along, and calls sprintf() to
162 * actually process each directive. If I ever need to actually do
163 * this, some caveats:
165 * - It's very hard to find a reliable upper bound for
166 * floating-point values. %f, in particular, when supplied with
167 * a number near to the upper or lower limit of representable
168 * numbers, could easily take several hundred characters. It's
169 * probably feasible to predict this statically using the
170 * constants in <float.h>, or even to predict it dynamically by
171 * looking at the exponent of the specific float provided, but
174 * - Don't forget to _check_, after calling sprintf, that it's
175 * used at most the amount of space we had available.
177 * - Fault any formatting directive we don't fully understand. The
178 * aim here is to _guarantee_ that we never overflow the buffer,
179 * because this is a security-critical function. If we see a
180 * directive we don't know about, we should panic and die rather
183 char *dupprintf(const char *fmt, ...)
188 ret = dupvprintf(fmt, ap);
192 char *dupvprintf(const char *fmt, va_list ap)
197 buf = snewn(512, char);
202 #define vsnprintf _vsnprintf
204 len = vsnprintf(buf, size, fmt, ap);
205 if (len >= 0 && len < size) {
206 /* This is the C99-specified criterion for snprintf to have
207 * been completely successful. */
209 } else if (len > 0) {
210 /* This is the C99 error condition: the returned length is
211 * the required buffer size not counting the NUL. */
214 /* This is the pre-C99 glibc error condition: <0 means the
215 * buffer wasn't big enough, so we enlarge it a bit and hope. */
218 buf = sresize(buf, size, char);
223 * Read an entire line of text from a file. Return a buffer
224 * malloced to be as big as necessary (caller must free).
226 char *fgetline(FILE *fp)
228 char *ret = snewn(512, char);
229 int size = 512, len = 0;
230 while (fgets(ret + len, size - len, fp)) {
231 len += strlen(ret + len);
232 if (ret[len-1] == '\n')
233 break; /* got a newline, we're done */
235 ret = sresize(ret, size, char);
237 if (len == 0) { /* first fgets returned NULL */
245 /* ----------------------------------------------------------------------
246 * Base64 encoding routine. This is required in public-key writing
247 * but also in HTTP proxy handling, so it's centralised here.
250 void base64_encode_atom(unsigned char *data, int n, char *out)
252 static const char base64_chars[] =
253 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
257 word = data[0] << 16;
259 word |= data[1] << 8;
262 out[0] = base64_chars[(word >> 18) & 0x3F];
263 out[1] = base64_chars[(word >> 12) & 0x3F];
265 out[2] = base64_chars[(word >> 6) & 0x3F];
269 out[3] = base64_chars[word & 0x3F];
274 /* ----------------------------------------------------------------------
275 * Generic routines to deal with send buffers: a linked list of
276 * smallish blocks, with the operations
278 * - add an arbitrary amount of data to the end of the list
279 * - remove the first N bytes from the list
280 * - return a (pointer,length) pair giving some initial data in
281 * the list, suitable for passing to a send or write system
283 * - retrieve a larger amount of initial data from the list
284 * - return the current size of the buffer chain in bytes
287 #define BUFFER_GRANULE 512
289 struct bufchain_granule {
290 struct bufchain_granule *next;
292 char buf[BUFFER_GRANULE];
295 void bufchain_init(bufchain *ch)
297 ch->head = ch->tail = NULL;
301 void bufchain_clear(bufchain *ch)
303 struct bufchain_granule *b;
306 ch->head = ch->head->next;
313 int bufchain_size(bufchain *ch)
315 return ch->buffersize;
318 void bufchain_add(bufchain *ch, const void *data, int len)
320 const char *buf = (const char *)data;
322 if (len == 0) return;
324 ch->buffersize += len;
326 if (ch->tail && ch->tail->buflen < BUFFER_GRANULE) {
327 int copylen = min(len, BUFFER_GRANULE - ch->tail->buflen);
328 memcpy(ch->tail->buf + ch->tail->buflen, buf, copylen);
331 ch->tail->buflen += copylen;
334 int grainlen = min(len, BUFFER_GRANULE);
335 struct bufchain_granule *newbuf;
336 newbuf = snew(struct bufchain_granule);
338 newbuf->buflen = grainlen;
339 memcpy(newbuf->buf, buf, grainlen);
343 ch->tail->next = newbuf;
345 ch->head = ch->tail = newbuf;
351 void bufchain_consume(bufchain *ch, int len)
353 struct bufchain_granule *tmp;
355 assert(ch->buffersize >= len);
358 assert(ch->head != NULL);
359 if (remlen >= ch->head->buflen - ch->head->bufpos) {
360 remlen = ch->head->buflen - ch->head->bufpos;
362 ch->head = tmp->next;
367 ch->head->bufpos += remlen;
368 ch->buffersize -= remlen;
373 void bufchain_prefix(bufchain *ch, void **data, int *len)
375 *len = ch->head->buflen - ch->head->bufpos;
376 *data = ch->head->buf + ch->head->bufpos;
379 void bufchain_fetch(bufchain *ch, void *data, int len)
381 struct bufchain_granule *tmp;
382 char *data_c = (char *)data;
386 assert(ch->buffersize >= len);
391 if (remlen >= tmp->buflen - tmp->bufpos)
392 remlen = tmp->buflen - tmp->bufpos;
393 memcpy(data_c, tmp->buf + tmp->bufpos, remlen);
401 /* ----------------------------------------------------------------------
402 * My own versions of malloc, realloc and free. Because I want
403 * malloc and realloc to bomb out and exit the program if they run
404 * out of memory, realloc to reliably call malloc if passed a NULL
405 * pointer, and free to reliably do nothing if passed a NULL
406 * pointer. We can also put trace printouts in, if we need to; and
407 * we can also replace the allocator with an ElectricFence-like
412 void *minefield_c_malloc(size_t size);
413 void minefield_c_free(void *p);
414 void *minefield_c_realloc(void *p, size_t size);
418 static FILE *fp = NULL;
420 static char *mlog_file = NULL;
421 static int mlog_line = 0;
423 void mlog(char *file, int line)
428 fp = fopen("putty_mem.log", "w");
429 setvbuf(fp, NULL, _IONBF, BUFSIZ);
432 fprintf(fp, "%s:%d: ", file, line);
436 void *safemalloc(size_t n, size_t size)
440 if (n > INT_MAX / size) {
445 p = minefield_c_malloc(size);
454 sprintf(str, "Out of memory! (%s:%d, size=%d)",
455 mlog_file, mlog_line, size);
456 fprintf(fp, "*** %s\n", str);
459 strcpy(str, "Out of memory!");
465 fprintf(fp, "malloc(%d) returns %p\n", size, p);
470 void *saferealloc(void *ptr, size_t n, size_t size)
474 if (n > INT_MAX / size) {
480 p = minefield_c_malloc(size);
486 p = minefield_c_realloc(ptr, size);
488 p = realloc(ptr, size);
496 sprintf(str, "Out of memory! (%s:%d, size=%d)",
497 mlog_file, mlog_line, size);
498 fprintf(fp, "*** %s\n", str);
501 strcpy(str, "Out of memory!");
507 fprintf(fp, "realloc(%p,%d) returns %p\n", ptr, size, p);
512 void safefree(void *ptr)
517 fprintf(fp, "free(%p)\n", ptr);
520 minefield_c_free(ptr);
527 fprintf(fp, "freeing null pointer - no action taken\n");
531 /* ----------------------------------------------------------------------
532 * Debugging routines.
536 extern void dputs(char *); /* defined in per-platform *misc.c */
538 void debug_printf(char *fmt, ...)
544 buf = dupvprintf(fmt, ap);
551 void debug_memdump(void *buf, int len, int L)
554 unsigned char *p = buf;
558 debug_printf("\t%d (0x%x) bytes:\n", len, len);
559 delta = 15 & (int) p;
563 for (; 0 < len; p += 16, len -= 16) {
566 debug_printf("%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 */
573 debug_printf("%c%02.2x",
574 &p[i] != (unsigned char *) buf
575 && i % 4 ? '.' : ' ', p[i]
577 if (p[i] >= ' ' && p[i] <= '~')
578 foo[i] = (char) p[i];
582 debug_printf("%*s%s\n", (16 - i) * 3 + 2, "", foo);
586 #endif /* def DEBUG */