Don't offer repeat key exchange as a special command in SSH-1.
[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
39934deb 144/*
145 * Read an entire line of text from a file. Return a buffer
146 * malloced to be as big as necessary (caller must free).
147 */
148char *fgetline(FILE *fp)
149{
150 char *ret = snewn(512, char);
151 int size = 512, len = 0;
152 while (fgets(ret + len, size - len, fp)) {
153 len += strlen(ret + len);
154 if (ret[len-1] == '\n')
155 break; /* got a newline, we're done */
156 size = len + 512;
157 ret = sresize(ret, size, char);
158 }
159 if (len == 0) { /* first fgets returned NULL */
160 sfree(ret);
161 return NULL;
162 }
163 ret[len] = '\0';
164 return ret;
165}
166
03f64569 167/* ----------------------------------------------------------------------
1549e076 168 * Base64 encoding routine. This is required in public-key writing
169 * but also in HTTP proxy handling, so it's centralised here.
170 */
171
172void base64_encode_atom(unsigned char *data, int n, char *out)
173{
174 static const char base64_chars[] =
175 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
176
177 unsigned word;
178
179 word = data[0] << 16;
180 if (n > 1)
181 word |= data[1] << 8;
182 if (n > 2)
183 word |= data[2];
184 out[0] = base64_chars[(word >> 18) & 0x3F];
185 out[1] = base64_chars[(word >> 12) & 0x3F];
186 if (n > 1)
187 out[2] = base64_chars[(word >> 6) & 0x3F];
188 else
189 out[2] = '=';
190 if (n > 2)
191 out[3] = base64_chars[word & 0x3F];
192 else
193 out[3] = '=';
194}
195
196/* ----------------------------------------------------------------------
5471d09a 197 * Generic routines to deal with send buffers: a linked list of
198 * smallish blocks, with the operations
199 *
200 * - add an arbitrary amount of data to the end of the list
201 * - remove the first N bytes from the list
202 * - return a (pointer,length) pair giving some initial data in
203 * the list, suitable for passing to a send or write system
204 * call
7983f47e 205 * - retrieve a larger amount of initial data from the list
5471d09a 206 * - return the current size of the buffer chain in bytes
207 */
208
209#define BUFFER_GRANULE 512
210
211struct bufchain_granule {
212 struct bufchain_granule *next;
213 int buflen, bufpos;
214 char buf[BUFFER_GRANULE];
215};
216
217void bufchain_init(bufchain *ch)
218{
219 ch->head = ch->tail = NULL;
220 ch->buffersize = 0;
221}
222
223void bufchain_clear(bufchain *ch)
224{
225 struct bufchain_granule *b;
226 while (ch->head) {
227 b = ch->head;
228 ch->head = ch->head->next;
229 sfree(b);
230 }
231 ch->tail = NULL;
232 ch->buffersize = 0;
233}
234
235int bufchain_size(bufchain *ch)
236{
237 return ch->buffersize;
238}
239
e0e7dff8 240void bufchain_add(bufchain *ch, const void *data, int len)
5471d09a 241{
e0e7dff8 242 const char *buf = (const char *)data;
5471d09a 243
bfa5400d 244 if (len == 0) return;
245
5471d09a 246 ch->buffersize += len;
247
248 if (ch->tail && ch->tail->buflen < BUFFER_GRANULE) {
249 int copylen = min(len, BUFFER_GRANULE - ch->tail->buflen);
250 memcpy(ch->tail->buf + ch->tail->buflen, buf, copylen);
251 buf += copylen;
252 len -= copylen;
253 ch->tail->buflen += copylen;
254 }
255 while (len > 0) {
256 int grainlen = min(len, BUFFER_GRANULE);
257 struct bufchain_granule *newbuf;
3d88e64d 258 newbuf = snew(struct bufchain_granule);
5471d09a 259 newbuf->bufpos = 0;
260 newbuf->buflen = grainlen;
261 memcpy(newbuf->buf, buf, grainlen);
262 buf += grainlen;
263 len -= grainlen;
264 if (ch->tail)
265 ch->tail->next = newbuf;
266 else
267 ch->head = ch->tail = newbuf;
268 newbuf->next = NULL;
269 ch->tail = newbuf;
270 }
271}
272
273void bufchain_consume(bufchain *ch, int len)
274{
7983f47e 275 struct bufchain_granule *tmp;
276
5471d09a 277 assert(ch->buffersize >= len);
7983f47e 278 while (len > 0) {
279 int remlen = len;
280 assert(ch->head != NULL);
281 if (remlen >= ch->head->buflen - ch->head->bufpos) {
282 remlen = ch->head->buflen - ch->head->bufpos;
283 tmp = ch->head;
284 ch->head = tmp->next;
285 sfree(tmp);
286 if (!ch->head)
287 ch->tail = NULL;
288 } else
289 ch->head->bufpos += remlen;
290 ch->buffersize -= remlen;
291 len -= remlen;
5471d09a 292 }
293}
294
295void bufchain_prefix(bufchain *ch, void **data, int *len)
296{
297 *len = ch->head->buflen - ch->head->bufpos;
298 *data = ch->head->buf + ch->head->bufpos;
299}
300
7983f47e 301void bufchain_fetch(bufchain *ch, void *data, int len)
302{
303 struct bufchain_granule *tmp;
304 char *data_c = (char *)data;
305
306 tmp = ch->head;
307
308 assert(ch->buffersize >= len);
309 while (len > 0) {
310 int remlen = len;
311
312 assert(tmp != NULL);
313 if (remlen >= tmp->buflen - tmp->bufpos)
314 remlen = tmp->buflen - tmp->bufpos;
315 memcpy(data_c, tmp->buf + tmp->bufpos, remlen);
316
317 tmp = tmp->next;
318 len -= remlen;
319 data_c += remlen;
320 }
321}
322
03f64569 323/* ----------------------------------------------------------------------
b191636d 324 * My own versions of malloc, realloc and free. Because I want
325 * malloc and realloc to bomb out and exit the program if they run
326 * out of memory, realloc to reliably call malloc if passed a NULL
327 * pointer, and free to reliably do nothing if passed a NULL
328 * pointer. We can also put trace printouts in, if we need to; and
329 * we can also replace the allocator with an ElectricFence-like
330 * one.
331 */
332
333#ifdef MINEFIELD
d0912d1f 334void *minefield_c_malloc(size_t size);
335void minefield_c_free(void *p);
336void *minefield_c_realloc(void *p, size_t size);
337#endif
374330e2 338
339#ifdef MALLOC_LOG
340static FILE *fp = NULL;
341
d7da76ca 342static char *mlog_file = NULL;
343static int mlog_line = 0;
344
32874aea 345void mlog(char *file, int line)
346{
d7da76ca 347 mlog_file = file;
348 mlog_line = line;
c662dbc0 349 if (!fp) {
374330e2 350 fp = fopen("putty_mem.log", "w");
c662dbc0 351 setvbuf(fp, NULL, _IONBF, BUFSIZ);
352 }
374330e2 353 if (fp)
32874aea 354 fprintf(fp, "%s:%d: ", file, line);
374330e2 355}
356#endif
357
32874aea 358void *safemalloc(size_t size)
359{
b191636d 360 void *p;
361#ifdef MINEFIELD
32874aea 362 p = minefield_c_malloc(size);
b191636d 363#else
32874aea 364 p = malloc(size);
b191636d 365#endif
374330e2 366 if (!p) {
d7da76ca 367 char str[200];
368#ifdef MALLOC_LOG
369 sprintf(str, "Out of memory! (%s:%d, size=%d)",
370 mlog_file, mlog_line, size);
1b2ef365 371 fprintf(fp, "*** %s\n", str);
372 fclose(fp);
d7da76ca 373#else
374 strcpy(str, "Out of memory!");
375#endif
1709795f 376 modalfatalbox(str);
374330e2 377 }
378#ifdef MALLOC_LOG
379 if (fp)
380 fprintf(fp, "malloc(%d) returns %p\n", size, p);
381#endif
382 return p;
383}
384
32874aea 385void *saferealloc(void *ptr, size_t size)
386{
374330e2 387 void *p;
b191636d 388 if (!ptr) {
389#ifdef MINEFIELD
32874aea 390 p = minefield_c_malloc(size);
b191636d 391#else
32874aea 392 p = malloc(size);
b191636d 393#endif
394 } else {
395#ifdef MINEFIELD
32874aea 396 p = minefield_c_realloc(ptr, size);
b191636d 397#else
32874aea 398 p = realloc(ptr, size);
b191636d 399#endif
400 }
374330e2 401 if (!p) {
d7da76ca 402 char str[200];
403#ifdef MALLOC_LOG
404 sprintf(str, "Out of memory! (%s:%d, size=%d)",
405 mlog_file, mlog_line, size);
1b2ef365 406 fprintf(fp, "*** %s\n", str);
407 fclose(fp);
d7da76ca 408#else
409 strcpy(str, "Out of memory!");
410#endif
1709795f 411 modalfatalbox(str);
374330e2 412 }
413#ifdef MALLOC_LOG
414 if (fp)
415 fprintf(fp, "realloc(%p,%d) returns %p\n", ptr, size, p);
416#endif
417 return p;
418}
419
32874aea 420void safefree(void *ptr)
421{
374330e2 422 if (ptr) {
423#ifdef MALLOC_LOG
424 if (fp)
425 fprintf(fp, "free(%p)\n", ptr);
426#endif
b191636d 427#ifdef MINEFIELD
32874aea 428 minefield_c_free(ptr);
b191636d 429#else
32874aea 430 free(ptr);
b191636d 431#endif
374330e2 432 }
433#ifdef MALLOC_LOG
434 else if (fp)
435 fprintf(fp, "freeing null pointer - no action taken\n");
436#endif
437}
c82bda52 438
03f64569 439/* ----------------------------------------------------------------------
440 * Debugging routines.
441 */
442
c82bda52 443#ifdef DEBUG
d0912d1f 444extern void dputs(char *); /* defined in per-platform *misc.c */
db9c0f86 445
d0912d1f 446void debug_printf(char *fmt, ...)
32874aea 447{
57356d63 448 char *buf;
db9c0f86 449 va_list ap;
450
451 va_start(ap, fmt);
57356d63 452 buf = dupvprintf(fmt, ap);
32874aea 453 dputs(buf);
57356d63 454 sfree(buf);
c82bda52 455 va_end(ap);
456}
db9c0f86 457
458
32874aea 459void debug_memdump(void *buf, int len, int L)
460{
db9c0f86 461 int i;
462 unsigned char *p = buf;
765c4200 463 char foo[17];
db9c0f86 464 if (L) {
465 int delta;
d0912d1f 466 debug_printf("\t%d (0x%x) bytes:\n", len, len);
db9c0f86 467 delta = 15 & (int) p;
468 p -= delta;
469 len += delta;
470 }
471 for (; 0 < len; p += 16, len -= 16) {
32874aea 472 dputs(" ");
473 if (L)
d0912d1f 474 debug_printf("%p: ", p);
32874aea 475 strcpy(foo, "................"); /* sixteen dots */
db9c0f86 476 for (i = 0; i < 16 && i < len; ++i) {
477 if (&p[i] < (unsigned char *) buf) {
32874aea 478 dputs(" "); /* 3 spaces */
765c4200 479 foo[i] = ' ';
db9c0f86 480 } else {
d0912d1f 481 debug_printf("%c%02.2x",
32874aea 482 &p[i] != (unsigned char *) buf
483 && i % 4 ? '.' : ' ', p[i]
484 );
765c4200 485 if (p[i] >= ' ' && p[i] <= '~')
32874aea 486 foo[i] = (char) p[i];
db9c0f86 487 }
488 }
765c4200 489 foo[i] = '\0';
d0912d1f 490 debug_printf("%*s%s\n", (16 - i) * 3 + 2, "", foo);
db9c0f86 491 }
492}
493
32874aea 494#endif /* def DEBUG */