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 prompts_t
*new_prompts(void *frontend
)
92 prompts_t
*p
= snew(prompts_t
);
95 p
->frontend
= frontend
;
97 p
->to_server
= TRUE
; /* to be on the safe side */
98 p
->name
= p
->instruction
= NULL
;
99 p
->name_reqd
= p
->instr_reqd
= FALSE
;
102 void add_prompt(prompts_t
*p
, char *promptstr
, int echo
, size_t len
)
104 prompt_t
*pr
= snew(prompt_t
);
105 unsigned char *result
= snewn(len
, unsigned char);
106 pr
->prompt
= promptstr
;
109 pr
->result_len
= len
;
111 p
->prompts
= sresize(p
->prompts
, p
->n_prompts
, prompt_t
*);
112 p
->prompts
[p
->n_prompts
-1] = pr
;
114 void free_prompts(prompts_t
*p
)
117 for (i
=0; i
< p
->n_prompts
; i
++) {
118 prompt_t
*pr
= p
->prompts
[i
];
119 memset(pr
->result
, 0, pr
->result_len
); /* burn the evidence */
126 sfree(p
->instruction
);
130 /* ----------------------------------------------------------------------
131 * String handling routines.
134 char *dupstr(const char *s
)
139 p
= snewn(len
+ 1, char);
145 /* Allocate the concatenation of N strings. Terminate arg list with NULL. */
146 char *dupcat(const char *s1
, ...)
155 sn
= va_arg(ap
, char *);
162 p
= snewn(len
+ 1, char);
168 sn
= va_arg(ap
, char *);
180 * Do an sprintf(), but into a custom-allocated buffer.
182 * Currently I'm doing this via vsnprintf. This has worked so far,
183 * but it's not good, because:
185 * - vsnprintf is not available on all platforms. There's an ifdef
186 * to use `_vsnprintf', which seems to be the local name for it
187 * on Windows. Other platforms may lack it completely, in which
188 * case it'll be time to rewrite this function in a totally
191 * - technically you can't reuse a va_list like this: it is left
192 * unspecified whether advancing a va_list pointer modifies its
193 * value or something it points to, so on some platforms calling
194 * vsnprintf twice on the same va_list might fail hideously. It
195 * would be better to use the `va_copy' macro mandated by C99,
196 * but that too is not yet ubiquitous.
198 * The only `properly' portable solution I can think of is to
199 * implement my own format string scanner, which figures out an
200 * upper bound for the length of each formatting directive,
201 * allocates the buffer as it goes along, and calls sprintf() to
202 * actually process each directive. If I ever need to actually do
203 * this, some caveats:
205 * - It's very hard to find a reliable upper bound for
206 * floating-point values. %f, in particular, when supplied with
207 * a number near to the upper or lower limit of representable
208 * numbers, could easily take several hundred characters. It's
209 * probably feasible to predict this statically using the
210 * constants in <float.h>, or even to predict it dynamically by
211 * looking at the exponent of the specific float provided, but
214 * - Don't forget to _check_, after calling sprintf, that it's
215 * used at most the amount of space we had available.
217 * - Fault any formatting directive we don't fully understand. The
218 * aim here is to _guarantee_ that we never overflow the buffer,
219 * because this is a security-critical function. If we see a
220 * directive we don't know about, we should panic and die rather
223 char *dupprintf(const char *fmt
, ...)
228 ret
= dupvprintf(fmt
, ap
);
232 char *dupvprintf(const char *fmt
, va_list ap
)
237 buf
= snewn(512, char);
242 #define vsnprintf _vsnprintf
244 len
= vsnprintf(buf
, size
, fmt
, ap
);
245 if (len
>= 0 && len
< size
) {
246 /* This is the C99-specified criterion for snprintf to have
247 * been completely successful. */
249 } else if (len
> 0) {
250 /* This is the C99 error condition: the returned length is
251 * the required buffer size not counting the NUL. */
254 /* This is the pre-C99 glibc error condition: <0 means the
255 * buffer wasn't big enough, so we enlarge it a bit and hope. */
258 buf
= sresize(buf
, size
, char);
263 * Read an entire line of text from a file. Return a buffer
264 * malloced to be as big as necessary (caller must free).
266 char *fgetline(FILE *fp
)
268 char *ret
= snewn(512, char);
269 int size
= 512, len
= 0;
270 while (fgets(ret
+ len
, size
- len
, fp
)) {
271 len
+= strlen(ret
+ len
);
272 if (ret
[len
-1] == '\n')
273 break; /* got a newline, we're done */
275 ret
= sresize(ret
, size
, char);
277 if (len
== 0) { /* first fgets returned NULL */
285 /* ----------------------------------------------------------------------
286 * Base64 encoding routine. This is required in public-key writing
287 * but also in HTTP proxy handling, so it's centralised here.
290 void base64_encode_atom(unsigned char *data
, int n
, char *out
)
292 static const char base64_chars
[] =
293 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
297 word
= data
[0] << 16;
299 word
|= data
[1] << 8;
302 out
[0] = base64_chars
[(word
>> 18) & 0x3F];
303 out
[1] = base64_chars
[(word
>> 12) & 0x3F];
305 out
[2] = base64_chars
[(word
>> 6) & 0x3F];
309 out
[3] = base64_chars
[word
& 0x3F];
314 /* ----------------------------------------------------------------------
315 * Generic routines to deal with send buffers: a linked list of
316 * smallish blocks, with the operations
318 * - add an arbitrary amount of data to the end of the list
319 * - remove the first N bytes from the list
320 * - return a (pointer,length) pair giving some initial data in
321 * the list, suitable for passing to a send or write system
323 * - retrieve a larger amount of initial data from the list
324 * - return the current size of the buffer chain in bytes
327 #define BUFFER_GRANULE 512
329 struct bufchain_granule
{
330 struct bufchain_granule
*next
;
332 char buf
[BUFFER_GRANULE
];
335 void bufchain_init(bufchain
*ch
)
337 ch
->head
= ch
->tail
= NULL
;
341 void bufchain_clear(bufchain
*ch
)
343 struct bufchain_granule
*b
;
346 ch
->head
= ch
->head
->next
;
353 int bufchain_size(bufchain
*ch
)
355 return ch
->buffersize
;
358 void bufchain_add(bufchain
*ch
, const void *data
, int len
)
360 const char *buf
= (const char *)data
;
362 if (len
== 0) return;
364 ch
->buffersize
+= len
;
366 if (ch
->tail
&& ch
->tail
->buflen
< BUFFER_GRANULE
) {
367 int copylen
= min(len
, BUFFER_GRANULE
- ch
->tail
->buflen
);
368 memcpy(ch
->tail
->buf
+ ch
->tail
->buflen
, buf
, copylen
);
371 ch
->tail
->buflen
+= copylen
;
374 int grainlen
= min(len
, BUFFER_GRANULE
);
375 struct bufchain_granule
*newbuf
;
376 newbuf
= snew(struct bufchain_granule
);
378 newbuf
->buflen
= grainlen
;
379 memcpy(newbuf
->buf
, buf
, grainlen
);
383 ch
->tail
->next
= newbuf
;
385 ch
->head
= ch
->tail
= newbuf
;
391 void bufchain_consume(bufchain
*ch
, int len
)
393 struct bufchain_granule
*tmp
;
395 assert(ch
->buffersize
>= len
);
398 assert(ch
->head
!= NULL
);
399 if (remlen
>= ch
->head
->buflen
- ch
->head
->bufpos
) {
400 remlen
= ch
->head
->buflen
- ch
->head
->bufpos
;
402 ch
->head
= tmp
->next
;
407 ch
->head
->bufpos
+= remlen
;
408 ch
->buffersize
-= remlen
;
413 void bufchain_prefix(bufchain
*ch
, void **data
, int *len
)
415 *len
= ch
->head
->buflen
- ch
->head
->bufpos
;
416 *data
= ch
->head
->buf
+ ch
->head
->bufpos
;
419 void bufchain_fetch(bufchain
*ch
, void *data
, int len
)
421 struct bufchain_granule
*tmp
;
422 char *data_c
= (char *)data
;
426 assert(ch
->buffersize
>= len
);
431 if (remlen
>= tmp
->buflen
- tmp
->bufpos
)
432 remlen
= tmp
->buflen
- tmp
->bufpos
;
433 memcpy(data_c
, tmp
->buf
+ tmp
->bufpos
, remlen
);
441 /* ----------------------------------------------------------------------
442 * My own versions of malloc, realloc and free. Because I want
443 * malloc and realloc to bomb out and exit the program if they run
444 * out of memory, realloc to reliably call malloc if passed a NULL
445 * pointer, and free to reliably do nothing if passed a NULL
446 * pointer. We can also put trace printouts in, if we need to; and
447 * we can also replace the allocator with an ElectricFence-like
452 void *minefield_c_malloc(size_t size
);
453 void minefield_c_free(void *p
);
454 void *minefield_c_realloc(void *p
, size_t size
);
458 static FILE *fp
= NULL
;
460 static char *mlog_file
= NULL
;
461 static int mlog_line
= 0;
463 void mlog(char *file
, int line
)
468 fp
= fopen("putty_mem.log", "w");
469 setvbuf(fp
, NULL
, _IONBF
, BUFSIZ
);
472 fprintf(fp
, "%s:%d: ", file
, line
);
476 void *safemalloc(size_t n
, size_t size
)
480 if (n
> INT_MAX
/ size
) {
484 if (size
== 0) size
= 1;
486 p
= minefield_c_malloc(size
);
495 sprintf(str
, "Out of memory! (%s:%d, size=%d)",
496 mlog_file
, mlog_line
, size
);
497 fprintf(fp
, "*** %s\n", str
);
500 strcpy(str
, "Out of memory!");
506 fprintf(fp
, "malloc(%d) returns %p\n", size
, p
);
511 void *saferealloc(void *ptr
, size_t n
, size_t size
)
515 if (n
> INT_MAX
/ size
) {
521 p
= minefield_c_malloc(size
);
527 p
= minefield_c_realloc(ptr
, size
);
529 p
= realloc(ptr
, size
);
537 sprintf(str
, "Out of memory! (%s:%d, size=%d)",
538 mlog_file
, mlog_line
, size
);
539 fprintf(fp
, "*** %s\n", str
);
542 strcpy(str
, "Out of memory!");
548 fprintf(fp
, "realloc(%p,%d) returns %p\n", ptr
, size
, p
);
553 void safefree(void *ptr
)
558 fprintf(fp
, "free(%p)\n", ptr
);
561 minefield_c_free(ptr
);
568 fprintf(fp
, "freeing null pointer - no action taken\n");
572 /* ----------------------------------------------------------------------
573 * Debugging routines.
577 extern void dputs(char *); /* defined in per-platform *misc.c */
579 void debug_printf(char *fmt
, ...)
585 buf
= dupvprintf(fmt
, ap
);
592 void debug_memdump(void *buf
, int len
, int L
)
595 unsigned char *p
= buf
;
599 debug_printf("\t%d (0x%x) bytes:\n", len
, len
);
600 delta
= 15 & (int) p
;
604 for (; 0 < len
; p
+= 16, len
-= 16) {
607 debug_printf("%p: ", p
);
608 strcpy(foo
, "................"); /* sixteen dots */
609 for (i
= 0; i
< 16 && i
< len
; ++i
) {
610 if (&p
[i
] < (unsigned char *) buf
) {
611 dputs(" "); /* 3 spaces */
614 debug_printf("%c%02.2x",
615 &p
[i
] != (unsigned char *) buf
616 && i
% 4 ?
'.' : ' ', p
[i
]
618 if (p
[i
] >= ' ' && p
[i
] <= '~')
619 foo
[i
] = (char) p
[i
];
623 debug_printf("%*s%s\n", (16 - i
) * 3 + 2, "", foo
);
627 #endif /* def DEBUG */