uint64_decimal() incorrectly output 0 as "" instead of "0". This only affected
[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>
57356d63 8#include <ctype.h>
5471d09a 9#include <assert.h>
374330e2 10#include "putty.h"
11
03f64569 12/* ----------------------------------------------------------------------
13 * String handling routines.
14 */
15
57356d63 16char *dupstr(const char *s)
03f64569 17{
6d113886 18 char *p = NULL;
19 if (s) {
20 int len = strlen(s);
21 p = snewn(len + 1, char);
22 strcpy(p, s);
23 }
03f64569 24 return p;
25}
26
27/* Allocate the concatenation of N strings. Terminate arg list with NULL. */
57356d63 28char *dupcat(const char *s1, ...)
03f64569 29{
30 int len;
31 char *p, *q, *sn;
32 va_list ap;
33
34 len = strlen(s1);
35 va_start(ap, s1);
36 while (1) {
37 sn = va_arg(ap, char *);
38 if (!sn)
39 break;
40 len += strlen(sn);
41 }
42 va_end(ap);
43
3d88e64d 44 p = snewn(len + 1, char);
03f64569 45 strcpy(p, s1);
46 q = p + strlen(p);
47
48 va_start(ap, s1);
49 while (1) {
50 sn = va_arg(ap, char *);
51 if (!sn)
52 break;
53 strcpy(q, sn);
54 q += strlen(q);
55 }
56 va_end(ap);
57
58 return p;
59}
60
57356d63 61/*
62 * Do an sprintf(), but into a custom-allocated buffer.
63 *
28da9e3d 64 * Currently I'm doing this via vsnprintf. This has worked so far,
65 * but it's not good, because:
66 *
67 * - vsnprintf is not available on all platforms. There's an ifdef
68 * to use `_vsnprintf', which seems to be the local name for it
69 * on Windows. Other platforms may lack it completely, in which
70 * case it'll be time to rewrite this function in a totally
71 * different way.
72 *
73 * - technically you can't reuse a va_list like this: it is left
74 * unspecified whether advancing a va_list pointer modifies its
75 * value or something it points to, so on some platforms calling
76 * vsnprintf twice on the same va_list might fail hideously. It
77 * would be better to use the `va_copy' macro mandated by C99,
78 * but that too is not yet ubiquitous.
79 *
80 * The only `properly' portable solution I can think of is to
81 * implement my own format string scanner, which figures out an
82 * upper bound for the length of each formatting directive,
83 * allocates the buffer as it goes along, and calls sprintf() to
84 * actually process each directive. If I ever need to actually do
85 * this, some caveats:
86 *
87 * - It's very hard to find a reliable upper bound for
88 * floating-point values. %f, in particular, when supplied with
89 * a number near to the upper or lower limit of representable
90 * numbers, could easily take several hundred characters. It's
91 * probably feasible to predict this statically using the
92 * constants in <float.h>, or even to predict it dynamically by
93 * looking at the exponent of the specific float provided, but
94 * it won't be fun.
95 *
96 * - Don't forget to _check_, after calling sprintf, that it's
97 * used at most the amount of space we had available.
98 *
99 * - Fault any formatting directive we don't fully understand. The
100 * aim here is to _guarantee_ that we never overflow the buffer,
101 * because this is a security-critical function. If we see a
102 * directive we don't know about, we should panic and die rather
103 * than run any risk.
57356d63 104 */
105char *dupprintf(const char *fmt, ...)
106{
107 char *ret;
108 va_list ap;
109 va_start(ap, fmt);
110 ret = dupvprintf(fmt, ap);
111 va_end(ap);
112 return ret;
113}
114char *dupvprintf(const char *fmt, va_list ap)
115{
116 char *buf;
117 int len, size;
118
3d88e64d 119 buf = snewn(512, char);
57356d63 120 size = 512;
121
122 while (1) {
123#ifdef _WINDOWS
124#define vsnprintf _vsnprintf
125#endif
126 len = vsnprintf(buf, size, fmt, ap);
127 if (len >= 0 && len < size) {
128 /* This is the C99-specified criterion for snprintf to have
129 * been completely successful. */
130 return buf;
131 } else if (len > 0) {
132 /* This is the C99 error condition: the returned length is
133 * the required buffer size not counting the NUL. */
134 size = len + 1;
135 } else {
136 /* This is the pre-C99 glibc error condition: <0 means the
137 * buffer wasn't big enough, so we enlarge it a bit and hope. */
138 size += 512;
139 }
3d88e64d 140 buf = sresize(buf, size, char);
57356d63 141 }
142}
143
03f64569 144/* ----------------------------------------------------------------------
1549e076 145 * Base64 encoding routine. This is required in public-key writing
146 * but also in HTTP proxy handling, so it's centralised here.
147 */
148
149void base64_encode_atom(unsigned char *data, int n, char *out)
150{
151 static const char base64_chars[] =
152 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
153
154 unsigned word;
155
156 word = data[0] << 16;
157 if (n > 1)
158 word |= data[1] << 8;
159 if (n > 2)
160 word |= data[2];
161 out[0] = base64_chars[(word >> 18) & 0x3F];
162 out[1] = base64_chars[(word >> 12) & 0x3F];
163 if (n > 1)
164 out[2] = base64_chars[(word >> 6) & 0x3F];
165 else
166 out[2] = '=';
167 if (n > 2)
168 out[3] = base64_chars[word & 0x3F];
169 else
170 out[3] = '=';
171}
172
173/* ----------------------------------------------------------------------
5471d09a 174 * Generic routines to deal with send buffers: a linked list of
175 * smallish blocks, with the operations
176 *
177 * - add an arbitrary amount of data to the end of the list
178 * - remove the first N bytes from the list
179 * - return a (pointer,length) pair giving some initial data in
180 * the list, suitable for passing to a send or write system
181 * call
7983f47e 182 * - retrieve a larger amount of initial data from the list
5471d09a 183 * - return the current size of the buffer chain in bytes
184 */
185
186#define BUFFER_GRANULE 512
187
188struct bufchain_granule {
189 struct bufchain_granule *next;
190 int buflen, bufpos;
191 char buf[BUFFER_GRANULE];
192};
193
194void bufchain_init(bufchain *ch)
195{
196 ch->head = ch->tail = NULL;
197 ch->buffersize = 0;
198}
199
200void bufchain_clear(bufchain *ch)
201{
202 struct bufchain_granule *b;
203 while (ch->head) {
204 b = ch->head;
205 ch->head = ch->head->next;
206 sfree(b);
207 }
208 ch->tail = NULL;
209 ch->buffersize = 0;
210}
211
212int bufchain_size(bufchain *ch)
213{
214 return ch->buffersize;
215}
216
e0e7dff8 217void bufchain_add(bufchain *ch, const void *data, int len)
5471d09a 218{
e0e7dff8 219 const char *buf = (const char *)data;
5471d09a 220
bfa5400d 221 if (len == 0) return;
222
5471d09a 223 ch->buffersize += len;
224
225 if (ch->tail && ch->tail->buflen < BUFFER_GRANULE) {
226 int copylen = min(len, BUFFER_GRANULE - ch->tail->buflen);
227 memcpy(ch->tail->buf + ch->tail->buflen, buf, copylen);
228 buf += copylen;
229 len -= copylen;
230 ch->tail->buflen += copylen;
231 }
232 while (len > 0) {
233 int grainlen = min(len, BUFFER_GRANULE);
234 struct bufchain_granule *newbuf;
3d88e64d 235 newbuf = snew(struct bufchain_granule);
5471d09a 236 newbuf->bufpos = 0;
237 newbuf->buflen = grainlen;
238 memcpy(newbuf->buf, buf, grainlen);
239 buf += grainlen;
240 len -= grainlen;
241 if (ch->tail)
242 ch->tail->next = newbuf;
243 else
244 ch->head = ch->tail = newbuf;
245 newbuf->next = NULL;
246 ch->tail = newbuf;
247 }
248}
249
250void bufchain_consume(bufchain *ch, int len)
251{
7983f47e 252 struct bufchain_granule *tmp;
253
5471d09a 254 assert(ch->buffersize >= len);
7983f47e 255 while (len > 0) {
256 int remlen = len;
257 assert(ch->head != NULL);
258 if (remlen >= ch->head->buflen - ch->head->bufpos) {
259 remlen = ch->head->buflen - ch->head->bufpos;
260 tmp = ch->head;
261 ch->head = tmp->next;
262 sfree(tmp);
263 if (!ch->head)
264 ch->tail = NULL;
265 } else
266 ch->head->bufpos += remlen;
267 ch->buffersize -= remlen;
268 len -= remlen;
5471d09a 269 }
270}
271
272void bufchain_prefix(bufchain *ch, void **data, int *len)
273{
274 *len = ch->head->buflen - ch->head->bufpos;
275 *data = ch->head->buf + ch->head->bufpos;
276}
277
7983f47e 278void bufchain_fetch(bufchain *ch, void *data, int len)
279{
280 struct bufchain_granule *tmp;
281 char *data_c = (char *)data;
282
283 tmp = ch->head;
284
285 assert(ch->buffersize >= len);
286 while (len > 0) {
287 int remlen = len;
288
289 assert(tmp != NULL);
290 if (remlen >= tmp->buflen - tmp->bufpos)
291 remlen = tmp->buflen - tmp->bufpos;
292 memcpy(data_c, tmp->buf + tmp->bufpos, remlen);
293
294 tmp = tmp->next;
295 len -= remlen;
296 data_c += remlen;
297 }
298}
299
03f64569 300/* ----------------------------------------------------------------------
b191636d 301 * My own versions of malloc, realloc and free. Because I want
302 * malloc and realloc to bomb out and exit the program if they run
303 * out of memory, realloc to reliably call malloc if passed a NULL
304 * pointer, and free to reliably do nothing if passed a NULL
305 * pointer. We can also put trace printouts in, if we need to; and
306 * we can also replace the allocator with an ElectricFence-like
307 * one.
308 */
309
310#ifdef MINEFIELD
d0912d1f 311void *minefield_c_malloc(size_t size);
312void minefield_c_free(void *p);
313void *minefield_c_realloc(void *p, size_t size);
314#endif
374330e2 315
316#ifdef MALLOC_LOG
317static FILE *fp = NULL;
318
d7da76ca 319static char *mlog_file = NULL;
320static int mlog_line = 0;
321
32874aea 322void mlog(char *file, int line)
323{
d7da76ca 324 mlog_file = file;
325 mlog_line = line;
c662dbc0 326 if (!fp) {
374330e2 327 fp = fopen("putty_mem.log", "w");
c662dbc0 328 setvbuf(fp, NULL, _IONBF, BUFSIZ);
329 }
374330e2 330 if (fp)
32874aea 331 fprintf(fp, "%s:%d: ", file, line);
374330e2 332}
333#endif
334
32874aea 335void *safemalloc(size_t size)
336{
b191636d 337 void *p;
338#ifdef MINEFIELD
32874aea 339 p = minefield_c_malloc(size);
b191636d 340#else
32874aea 341 p = malloc(size);
b191636d 342#endif
374330e2 343 if (!p) {
d7da76ca 344 char str[200];
345#ifdef MALLOC_LOG
346 sprintf(str, "Out of memory! (%s:%d, size=%d)",
347 mlog_file, mlog_line, size);
1b2ef365 348 fprintf(fp, "*** %s\n", str);
349 fclose(fp);
d7da76ca 350#else
351 strcpy(str, "Out of memory!");
352#endif
1709795f 353 modalfatalbox(str);
374330e2 354 }
355#ifdef MALLOC_LOG
356 if (fp)
357 fprintf(fp, "malloc(%d) returns %p\n", size, p);
358#endif
359 return p;
360}
361
32874aea 362void *saferealloc(void *ptr, size_t size)
363{
374330e2 364 void *p;
b191636d 365 if (!ptr) {
366#ifdef MINEFIELD
32874aea 367 p = minefield_c_malloc(size);
b191636d 368#else
32874aea 369 p = malloc(size);
b191636d 370#endif
371 } else {
372#ifdef MINEFIELD
32874aea 373 p = minefield_c_realloc(ptr, size);
b191636d 374#else
32874aea 375 p = realloc(ptr, size);
b191636d 376#endif
377 }
374330e2 378 if (!p) {
d7da76ca 379 char str[200];
380#ifdef MALLOC_LOG
381 sprintf(str, "Out of memory! (%s:%d, size=%d)",
382 mlog_file, mlog_line, size);
1b2ef365 383 fprintf(fp, "*** %s\n", str);
384 fclose(fp);
d7da76ca 385#else
386 strcpy(str, "Out of memory!");
387#endif
1709795f 388 modalfatalbox(str);
374330e2 389 }
390#ifdef MALLOC_LOG
391 if (fp)
392 fprintf(fp, "realloc(%p,%d) returns %p\n", ptr, size, p);
393#endif
394 return p;
395}
396
32874aea 397void safefree(void *ptr)
398{
374330e2 399 if (ptr) {
400#ifdef MALLOC_LOG
401 if (fp)
402 fprintf(fp, "free(%p)\n", ptr);
403#endif
b191636d 404#ifdef MINEFIELD
32874aea 405 minefield_c_free(ptr);
b191636d 406#else
32874aea 407 free(ptr);
b191636d 408#endif
374330e2 409 }
410#ifdef MALLOC_LOG
411 else if (fp)
412 fprintf(fp, "freeing null pointer - no action taken\n");
413#endif
414}
c82bda52 415
03f64569 416/* ----------------------------------------------------------------------
417 * Debugging routines.
418 */
419
c82bda52 420#ifdef DEBUG
d0912d1f 421extern void dputs(char *); /* defined in per-platform *misc.c */
db9c0f86 422
d0912d1f 423void debug_printf(char *fmt, ...)
32874aea 424{
57356d63 425 char *buf;
db9c0f86 426 va_list ap;
427
428 va_start(ap, fmt);
57356d63 429 buf = dupvprintf(fmt, ap);
32874aea 430 dputs(buf);
57356d63 431 sfree(buf);
c82bda52 432 va_end(ap);
433}
db9c0f86 434
435
32874aea 436void debug_memdump(void *buf, int len, int L)
437{
db9c0f86 438 int i;
439 unsigned char *p = buf;
765c4200 440 char foo[17];
db9c0f86 441 if (L) {
442 int delta;
d0912d1f 443 debug_printf("\t%d (0x%x) bytes:\n", len, len);
db9c0f86 444 delta = 15 & (int) p;
445 p -= delta;
446 len += delta;
447 }
448 for (; 0 < len; p += 16, len -= 16) {
32874aea 449 dputs(" ");
450 if (L)
d0912d1f 451 debug_printf("%p: ", p);
32874aea 452 strcpy(foo, "................"); /* sixteen dots */
db9c0f86 453 for (i = 0; i < 16 && i < len; ++i) {
454 if (&p[i] < (unsigned char *) buf) {
32874aea 455 dputs(" "); /* 3 spaces */
765c4200 456 foo[i] = ' ';
db9c0f86 457 } else {
d0912d1f 458 debug_printf("%c%02.2x",
32874aea 459 &p[i] != (unsigned char *) buf
460 && i % 4 ? '.' : ' ', p[i]
461 );
765c4200 462 if (p[i] >= ' ' && p[i] <= '~')
32874aea 463 foo[i] = (char) p[i];
db9c0f86 464 }
465 }
765c4200 466 foo[i] = '\0';
d0912d1f 467 debug_printf("%*s%s\n", (16 - i) * 3 + 2, "", foo);
db9c0f86 468 }
469}
470
32874aea 471#endif /* def DEBUG */