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 are two characters,
52 * starting with '^'. The ones that are worth keeping are probably:
58 char ctrlparse(char *s
, char **next
)
69 } else if (*s
>= 'a' && *s
<= 'z') {
71 } else if ((*s
>= '@' && *s
<= '_') || *s
== '?' || (*s
& 0x80)) {
73 } else if (*s
== '~') {
82 /* ----------------------------------------------------------------------
83 * String handling routines.
86 char *dupstr(const char *s
)
91 p
= snewn(len
+ 1, char);
97 /* Allocate the concatenation of N strings. Terminate arg list with NULL. */
98 char *dupcat(const char *s1
, ...)
107 sn
= va_arg(ap
, char *);
114 p
= snewn(len
+ 1, char);
120 sn
= va_arg(ap
, char *);
132 * Do an sprintf(), but into a custom-allocated buffer.
134 * Currently I'm doing this via vsnprintf. This has worked so far,
135 * but it's not good, because:
137 * - vsnprintf is not available on all platforms. There's an ifdef
138 * to use `_vsnprintf', which seems to be the local name for it
139 * on Windows. Other platforms may lack it completely, in which
140 * case it'll be time to rewrite this function in a totally
143 * - technically you can't reuse a va_list like this: it is left
144 * unspecified whether advancing a va_list pointer modifies its
145 * value or something it points to, so on some platforms calling
146 * vsnprintf twice on the same va_list might fail hideously. It
147 * would be better to use the `va_copy' macro mandated by C99,
148 * but that too is not yet ubiquitous.
150 * The only `properly' portable solution I can think of is to
151 * implement my own format string scanner, which figures out an
152 * upper bound for the length of each formatting directive,
153 * allocates the buffer as it goes along, and calls sprintf() to
154 * actually process each directive. If I ever need to actually do
155 * this, some caveats:
157 * - It's very hard to find a reliable upper bound for
158 * floating-point values. %f, in particular, when supplied with
159 * a number near to the upper or lower limit of representable
160 * numbers, could easily take several hundred characters. It's
161 * probably feasible to predict this statically using the
162 * constants in <float.h>, or even to predict it dynamically by
163 * looking at the exponent of the specific float provided, but
166 * - Don't forget to _check_, after calling sprintf, that it's
167 * used at most the amount of space we had available.
169 * - Fault any formatting directive we don't fully understand. The
170 * aim here is to _guarantee_ that we never overflow the buffer,
171 * because this is a security-critical function. If we see a
172 * directive we don't know about, we should panic and die rather
175 char *dupprintf(const char *fmt
, ...)
180 ret
= dupvprintf(fmt
, ap
);
184 char *dupvprintf(const char *fmt
, va_list ap
)
189 buf
= snewn(512, char);
194 #define vsnprintf _vsnprintf
196 len
= vsnprintf(buf
, size
, fmt
, ap
);
197 if (len
>= 0 && len
< size
) {
198 /* This is the C99-specified criterion for snprintf to have
199 * been completely successful. */
201 } else if (len
> 0) {
202 /* This is the C99 error condition: the returned length is
203 * the required buffer size not counting the NUL. */
206 /* This is the pre-C99 glibc error condition: <0 means the
207 * buffer wasn't big enough, so we enlarge it a bit and hope. */
210 buf
= sresize(buf
, size
, char);
215 * Read an entire line of text from a file. Return a buffer
216 * malloced to be as big as necessary (caller must free).
218 char *fgetline(FILE *fp
)
220 char *ret
= snewn(512, char);
221 int size
= 512, len
= 0;
222 while (fgets(ret
+ len
, size
- len
, fp
)) {
223 len
+= strlen(ret
+ len
);
224 if (ret
[len
-1] == '\n')
225 break; /* got a newline, we're done */
227 ret
= sresize(ret
, size
, char);
229 if (len
== 0) { /* first fgets returned NULL */
237 /* ----------------------------------------------------------------------
238 * Base64 encoding routine. This is required in public-key writing
239 * but also in HTTP proxy handling, so it's centralised here.
242 void base64_encode_atom(unsigned char *data
, int n
, char *out
)
244 static const char base64_chars
[] =
245 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
249 word
= data
[0] << 16;
251 word
|= data
[1] << 8;
254 out
[0] = base64_chars
[(word
>> 18) & 0x3F];
255 out
[1] = base64_chars
[(word
>> 12) & 0x3F];
257 out
[2] = base64_chars
[(word
>> 6) & 0x3F];
261 out
[3] = base64_chars
[word
& 0x3F];
266 /* ----------------------------------------------------------------------
267 * Generic routines to deal with send buffers: a linked list of
268 * smallish blocks, with the operations
270 * - add an arbitrary amount of data to the end of the list
271 * - remove the first N bytes from the list
272 * - return a (pointer,length) pair giving some initial data in
273 * the list, suitable for passing to a send or write system
275 * - retrieve a larger amount of initial data from the list
276 * - return the current size of the buffer chain in bytes
279 #define BUFFER_GRANULE 512
281 struct bufchain_granule
{
282 struct bufchain_granule
*next
;
284 char buf
[BUFFER_GRANULE
];
287 void bufchain_init(bufchain
*ch
)
289 ch
->head
= ch
->tail
= NULL
;
293 void bufchain_clear(bufchain
*ch
)
295 struct bufchain_granule
*b
;
298 ch
->head
= ch
->head
->next
;
305 int bufchain_size(bufchain
*ch
)
307 return ch
->buffersize
;
310 void bufchain_add(bufchain
*ch
, const void *data
, int len
)
312 const char *buf
= (const char *)data
;
314 if (len
== 0) return;
316 ch
->buffersize
+= len
;
318 if (ch
->tail
&& ch
->tail
->buflen
< BUFFER_GRANULE
) {
319 int copylen
= min(len
, BUFFER_GRANULE
- ch
->tail
->buflen
);
320 memcpy(ch
->tail
->buf
+ ch
->tail
->buflen
, buf
, copylen
);
323 ch
->tail
->buflen
+= copylen
;
326 int grainlen
= min(len
, BUFFER_GRANULE
);
327 struct bufchain_granule
*newbuf
;
328 newbuf
= snew(struct bufchain_granule
);
330 newbuf
->buflen
= grainlen
;
331 memcpy(newbuf
->buf
, buf
, grainlen
);
335 ch
->tail
->next
= newbuf
;
337 ch
->head
= ch
->tail
= newbuf
;
343 void bufchain_consume(bufchain
*ch
, int len
)
345 struct bufchain_granule
*tmp
;
347 assert(ch
->buffersize
>= len
);
350 assert(ch
->head
!= NULL
);
351 if (remlen
>= ch
->head
->buflen
- ch
->head
->bufpos
) {
352 remlen
= ch
->head
->buflen
- ch
->head
->bufpos
;
354 ch
->head
= tmp
->next
;
359 ch
->head
->bufpos
+= remlen
;
360 ch
->buffersize
-= remlen
;
365 void bufchain_prefix(bufchain
*ch
, void **data
, int *len
)
367 *len
= ch
->head
->buflen
- ch
->head
->bufpos
;
368 *data
= ch
->head
->buf
+ ch
->head
->bufpos
;
371 void bufchain_fetch(bufchain
*ch
, void *data
, int len
)
373 struct bufchain_granule
*tmp
;
374 char *data_c
= (char *)data
;
378 assert(ch
->buffersize
>= len
);
383 if (remlen
>= tmp
->buflen
- tmp
->bufpos
)
384 remlen
= tmp
->buflen
- tmp
->bufpos
;
385 memcpy(data_c
, tmp
->buf
+ tmp
->bufpos
, remlen
);
393 /* ----------------------------------------------------------------------
394 * My own versions of malloc, realloc and free. Because I want
395 * malloc and realloc to bomb out and exit the program if they run
396 * out of memory, realloc to reliably call malloc if passed a NULL
397 * pointer, and free to reliably do nothing if passed a NULL
398 * pointer. We can also put trace printouts in, if we need to; and
399 * we can also replace the allocator with an ElectricFence-like
404 void *minefield_c_malloc(size_t size
);
405 void minefield_c_free(void *p
);
406 void *minefield_c_realloc(void *p
, size_t size
);
410 static FILE *fp
= NULL
;
412 static char *mlog_file
= NULL
;
413 static int mlog_line
= 0;
415 void mlog(char *file
, int line
)
420 fp
= fopen("putty_mem.log", "w");
421 setvbuf(fp
, NULL
, _IONBF
, BUFSIZ
);
424 fprintf(fp
, "%s:%d: ", file
, line
);
428 void *safemalloc(size_t n
, size_t size
)
432 if (n
> INT_MAX
/ size
) {
437 p
= minefield_c_malloc(size
);
446 sprintf(str
, "Out of memory! (%s:%d, size=%d)",
447 mlog_file
, mlog_line
, size
);
448 fprintf(fp
, "*** %s\n", str
);
451 strcpy(str
, "Out of memory!");
457 fprintf(fp
, "malloc(%d) returns %p\n", size
, p
);
462 void *saferealloc(void *ptr
, size_t n
, size_t size
)
466 if (n
> INT_MAX
/ size
) {
472 p
= minefield_c_malloc(size
);
478 p
= minefield_c_realloc(ptr
, size
);
480 p
= realloc(ptr
, size
);
488 sprintf(str
, "Out of memory! (%s:%d, size=%d)",
489 mlog_file
, mlog_line
, size
);
490 fprintf(fp
, "*** %s\n", str
);
493 strcpy(str
, "Out of memory!");
499 fprintf(fp
, "realloc(%p,%d) returns %p\n", ptr
, size
, p
);
504 void safefree(void *ptr
)
509 fprintf(fp
, "free(%p)\n", ptr
);
512 minefield_c_free(ptr
);
519 fprintf(fp
, "freeing null pointer - no action taken\n");
523 /* ----------------------------------------------------------------------
524 * Debugging routines.
528 extern void dputs(char *); /* defined in per-platform *misc.c */
530 void debug_printf(char *fmt
, ...)
536 buf
= dupvprintf(fmt
, ap
);
543 void debug_memdump(void *buf
, int len
, int L
)
546 unsigned char *p
= buf
;
550 debug_printf("\t%d (0x%x) bytes:\n", len
, len
);
551 delta
= 15 & (int) p
;
555 for (; 0 < len
; p
+= 16, len
-= 16) {
558 debug_printf("%p: ", p
);
559 strcpy(foo
, "................"); /* sixteen dots */
560 for (i
= 0; i
< 16 && i
< len
; ++i
) {
561 if (&p
[i
] < (unsigned char *) buf
) {
562 dputs(" "); /* 3 spaces */
565 debug_printf("%c%02.2x",
566 &p
[i
] != (unsigned char *) buf
567 && i
% 4 ?
'.' : ' ', p
[i
]
569 if (p
[i
] >= ' ' && p
[i
] <= '~')
570 foo
[i
] = (char) p
[i
];
574 debug_printf("%*s%s\n", (16 - i
) * 3 + 2, "", foo
);
578 #endif /* def DEBUG */