2 * Platform-independent routines shared between all PuTTY programs.
13 * Parse a string block size specification. This is approximately a
14 * subset of the block size specs supported by GNU fileutils:
18 * All numbers are decimal, and suffixes refer to powers of two.
21 unsigned long parse_blocksize(const char *bs)
24 unsigned long r = strtoul(bs, &suf, 10);
26 while (isspace(*suf)) suf++;
35 r *= 1024ul * 1024ul * 1024ul;
45 /* ----------------------------------------------------------------------
46 * String handling routines.
49 char *dupstr(const char *s)
54 p = snewn(len + 1, char);
60 /* Allocate the concatenation of N strings. Terminate arg list with NULL. */
61 char *dupcat(const char *s1, ...)
70 sn = va_arg(ap, char *);
77 p = snewn(len + 1, char);
83 sn = va_arg(ap, char *);
95 * Do an sprintf(), but into a custom-allocated buffer.
97 * Currently I'm doing this via vsnprintf. This has worked so far,
98 * but it's not good, because:
100 * - vsnprintf is not available on all platforms. There's an ifdef
101 * to use `_vsnprintf', which seems to be the local name for it
102 * on Windows. Other platforms may lack it completely, in which
103 * case it'll be time to rewrite this function in a totally
106 * - technically you can't reuse a va_list like this: it is left
107 * unspecified whether advancing a va_list pointer modifies its
108 * value or something it points to, so on some platforms calling
109 * vsnprintf twice on the same va_list might fail hideously. It
110 * would be better to use the `va_copy' macro mandated by C99,
111 * but that too is not yet ubiquitous.
113 * The only `properly' portable solution I can think of is to
114 * implement my own format string scanner, which figures out an
115 * upper bound for the length of each formatting directive,
116 * allocates the buffer as it goes along, and calls sprintf() to
117 * actually process each directive. If I ever need to actually do
118 * this, some caveats:
120 * - It's very hard to find a reliable upper bound for
121 * floating-point values. %f, in particular, when supplied with
122 * a number near to the upper or lower limit of representable
123 * numbers, could easily take several hundred characters. It's
124 * probably feasible to predict this statically using the
125 * constants in <float.h>, or even to predict it dynamically by
126 * looking at the exponent of the specific float provided, but
129 * - Don't forget to _check_, after calling sprintf, that it's
130 * used at most the amount of space we had available.
132 * - Fault any formatting directive we don't fully understand. The
133 * aim here is to _guarantee_ that we never overflow the buffer,
134 * because this is a security-critical function. If we see a
135 * directive we don't know about, we should panic and die rather
138 char *dupprintf(const char *fmt, ...)
143 ret = dupvprintf(fmt, ap);
147 char *dupvprintf(const char *fmt, va_list ap)
152 buf = snewn(512, char);
157 #define vsnprintf _vsnprintf
159 len = vsnprintf(buf, size, fmt, ap);
160 if (len >= 0 && len < size) {
161 /* This is the C99-specified criterion for snprintf to have
162 * been completely successful. */
164 } else if (len > 0) {
165 /* This is the C99 error condition: the returned length is
166 * the required buffer size not counting the NUL. */
169 /* This is the pre-C99 glibc error condition: <0 means the
170 * buffer wasn't big enough, so we enlarge it a bit and hope. */
173 buf = sresize(buf, size, char);
178 * Read an entire line of text from a file. Return a buffer
179 * malloced to be as big as necessary (caller must free).
181 char *fgetline(FILE *fp)
183 char *ret = snewn(512, char);
184 int size = 512, len = 0;
185 while (fgets(ret + len, size - len, fp)) {
186 len += strlen(ret + len);
187 if (ret[len-1] == '\n')
188 break; /* got a newline, we're done */
190 ret = sresize(ret, size, char);
192 if (len == 0) { /* first fgets returned NULL */
200 /* ----------------------------------------------------------------------
201 * Base64 encoding routine. This is required in public-key writing
202 * but also in HTTP proxy handling, so it's centralised here.
205 void base64_encode_atom(unsigned char *data, int n, char *out)
207 static const char base64_chars[] =
208 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
212 word = data[0] << 16;
214 word |= data[1] << 8;
217 out[0] = base64_chars[(word >> 18) & 0x3F];
218 out[1] = base64_chars[(word >> 12) & 0x3F];
220 out[2] = base64_chars[(word >> 6) & 0x3F];
224 out[3] = base64_chars[word & 0x3F];
229 /* ----------------------------------------------------------------------
230 * Generic routines to deal with send buffers: a linked list of
231 * smallish blocks, with the operations
233 * - add an arbitrary amount of data to the end of the list
234 * - remove the first N bytes from the list
235 * - return a (pointer,length) pair giving some initial data in
236 * the list, suitable for passing to a send or write system
238 * - retrieve a larger amount of initial data from the list
239 * - return the current size of the buffer chain in bytes
242 #define BUFFER_GRANULE 512
244 struct bufchain_granule {
245 struct bufchain_granule *next;
247 char buf[BUFFER_GRANULE];
250 void bufchain_init(bufchain *ch)
252 ch->head = ch->tail = NULL;
256 void bufchain_clear(bufchain *ch)
258 struct bufchain_granule *b;
261 ch->head = ch->head->next;
268 int bufchain_size(bufchain *ch)
270 return ch->buffersize;
273 void bufchain_add(bufchain *ch, const void *data, int len)
275 const char *buf = (const char *)data;
277 if (len == 0) return;
279 ch->buffersize += len;
281 if (ch->tail && ch->tail->buflen < BUFFER_GRANULE) {
282 int copylen = min(len, BUFFER_GRANULE - ch->tail->buflen);
283 memcpy(ch->tail->buf + ch->tail->buflen, buf, copylen);
286 ch->tail->buflen += copylen;
289 int grainlen = min(len, BUFFER_GRANULE);
290 struct bufchain_granule *newbuf;
291 newbuf = snew(struct bufchain_granule);
293 newbuf->buflen = grainlen;
294 memcpy(newbuf->buf, buf, grainlen);
298 ch->tail->next = newbuf;
300 ch->head = ch->tail = newbuf;
306 void bufchain_consume(bufchain *ch, int len)
308 struct bufchain_granule *tmp;
310 assert(ch->buffersize >= len);
313 assert(ch->head != NULL);
314 if (remlen >= ch->head->buflen - ch->head->bufpos) {
315 remlen = ch->head->buflen - ch->head->bufpos;
317 ch->head = tmp->next;
322 ch->head->bufpos += remlen;
323 ch->buffersize -= remlen;
328 void bufchain_prefix(bufchain *ch, void **data, int *len)
330 *len = ch->head->buflen - ch->head->bufpos;
331 *data = ch->head->buf + ch->head->bufpos;
334 void bufchain_fetch(bufchain *ch, void *data, int len)
336 struct bufchain_granule *tmp;
337 char *data_c = (char *)data;
341 assert(ch->buffersize >= len);
346 if (remlen >= tmp->buflen - tmp->bufpos)
347 remlen = tmp->buflen - tmp->bufpos;
348 memcpy(data_c, tmp->buf + tmp->bufpos, remlen);
356 /* ----------------------------------------------------------------------
357 * My own versions of malloc, realloc and free. Because I want
358 * malloc and realloc to bomb out and exit the program if they run
359 * out of memory, realloc to reliably call malloc if passed a NULL
360 * pointer, and free to reliably do nothing if passed a NULL
361 * pointer. We can also put trace printouts in, if we need to; and
362 * we can also replace the allocator with an ElectricFence-like
367 void *minefield_c_malloc(size_t size);
368 void minefield_c_free(void *p);
369 void *minefield_c_realloc(void *p, size_t size);
373 static FILE *fp = NULL;
375 static char *mlog_file = NULL;
376 static int mlog_line = 0;
378 void mlog(char *file, int line)
383 fp = fopen("putty_mem.log", "w");
384 setvbuf(fp, NULL, _IONBF, BUFSIZ);
387 fprintf(fp, "%s:%d: ", file, line);
391 void *safemalloc(size_t size)
395 p = minefield_c_malloc(size);
402 sprintf(str, "Out of memory! (%s:%d, size=%d)",
403 mlog_file, mlog_line, size);
404 fprintf(fp, "*** %s\n", str);
407 strcpy(str, "Out of memory!");
413 fprintf(fp, "malloc(%d) returns %p\n", size, p);
418 void *saferealloc(void *ptr, size_t size)
423 p = minefield_c_malloc(size);
429 p = minefield_c_realloc(ptr, size);
431 p = realloc(ptr, size);
437 sprintf(str, "Out of memory! (%s:%d, size=%d)",
438 mlog_file, mlog_line, size);
439 fprintf(fp, "*** %s\n", str);
442 strcpy(str, "Out of memory!");
448 fprintf(fp, "realloc(%p,%d) returns %p\n", ptr, size, p);
453 void safefree(void *ptr)
458 fprintf(fp, "free(%p)\n", ptr);
461 minefield_c_free(ptr);
468 fprintf(fp, "freeing null pointer - no action taken\n");
472 /* ----------------------------------------------------------------------
473 * Debugging routines.
477 extern void dputs(char *); /* defined in per-platform *misc.c */
479 void debug_printf(char *fmt, ...)
485 buf = dupvprintf(fmt, ap);
492 void debug_memdump(void *buf, int len, int L)
495 unsigned char *p = buf;
499 debug_printf("\t%d (0x%x) bytes:\n", len, len);
500 delta = 15 & (int) p;
504 for (; 0 < len; p += 16, len -= 16) {
507 debug_printf("%p: ", p);
508 strcpy(foo, "................"); /* sixteen dots */
509 for (i = 0; i < 16 && i < len; ++i) {
510 if (&p[i] < (unsigned char *) buf) {
511 dputs(" "); /* 3 spaces */
514 debug_printf("%c%02.2x",
515 &p[i] != (unsigned char *) buf
516 && i % 4 ? '.' : ' ', p[i]
518 if (p[i] >= ' ' && p[i] <= '~')
519 foo[i] = (char) p[i];
523 debug_printf("%*s%s\n", (16 - i) * 3 + 2, "", foo);
527 #endif /* def DEBUG */