misc.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. /*
  2. * Header for miscellaneous helper functions, mostly defined in the
  3. * utils subdirectory.
  4. */
  5. #ifndef PUTTY_MISC_H
  6. #define PUTTY_MISC_H
  7. #include "defs.h"
  8. #include "puttymem.h"
  9. #include "marshal.h"
  10. #include <stdio.h> /* for FILE * */
  11. #include <stdarg.h> /* for va_list */
  12. #include <stdlib.h> /* for abort */
  13. #include <time.h> /* for struct tm */
  14. #include <limits.h> /* for INT_MAX/MIN */
  15. #include <assert.h> /* for assert (obviously) */
  16. unsigned long parse_blocksize(const char *bs);
  17. char ctrlparse(char *s, char **next);
  18. size_t host_strcspn(const char *s, const char *set);
  19. char *host_strchr(const char *s, int c);
  20. char *host_strrchr(const char *s, int c);
  21. char *host_strduptrim(const char *s);
  22. char *dupstr(const char *s);
  23. char *dupcat_fn(const char *s1, ...);
  24. #define dupcat(...) dupcat_fn(__VA_ARGS__, (const char *)NULL)
  25. char *dupprintf(const char *fmt, ...) PRINTF_LIKE(1, 2);
  26. char *dupvprintf(const char *fmt, va_list ap);
  27. void burnstr(char *string);
  28. /*
  29. * The visible part of a strbuf structure. There's a surrounding
  30. * implementation struct in strbuf.c, which isn't exposed to client
  31. * code.
  32. */
  33. struct strbuf {
  34. char *s;
  35. unsigned char *u;
  36. size_t len;
  37. BinarySink_IMPLEMENTATION;
  38. };
  39. /* strbuf constructors: strbuf_new_nm and strbuf_new differ in that a
  40. * strbuf constructed using the _nm version will resize itself by
  41. * alloc/copy/smemclr/free instead of realloc. Use that version for
  42. * data sensitive enough that it's worth costing performance to
  43. * avoid copies of it lingering in process memory. */
  44. strbuf *strbuf_new(void);
  45. strbuf *strbuf_new_nm(void);
  46. void strbuf_free(strbuf *buf);
  47. void *strbuf_append(strbuf *buf, size_t len);
  48. void strbuf_shrink_to(strbuf *buf, size_t new_len);
  49. void strbuf_shrink_by(strbuf *buf, size_t amount_to_remove);
  50. char *strbuf_to_str(strbuf *buf); /* does free buf, but you must free result */
  51. static inline void strbuf_clear(strbuf *buf) { strbuf_shrink_to(buf, 0); }
  52. bool strbuf_chomp(strbuf *buf, char char_to_remove);
  53. strbuf *strbuf_new_for_agent_query(void);
  54. void strbuf_finalise_agent_query(strbuf *buf);
  55. /* String-to-Unicode converters that auto-allocate the destination and
  56. * work around the rather deficient interface of mb_to_wc. */
  57. wchar_t *dup_mb_to_wc_c(int codepage, int flags, const char *string, int len);
  58. wchar_t *dup_mb_to_wc(int codepage, int flags, const char *string);
  59. static inline int toint(unsigned u)
  60. {
  61. /*
  62. * Convert an unsigned to an int, without running into the
  63. * undefined behaviour which happens by the strict C standard if
  64. * the value overflows. You'd hope that sensible compilers would
  65. * do the sensible thing in response to a cast, but actually I
  66. * don't trust modern compilers not to do silly things like
  67. * assuming that _obviously_ you wouldn't have caused an overflow
  68. * and so they can elide an 'if (i < 0)' test immediately after
  69. * the cast.
  70. *
  71. * Sensible compilers ought of course to optimise this entire
  72. * function into 'just return the input value', and since it's
  73. * also declared inline, elide it completely in their output.
  74. */
  75. if (u <= (unsigned)INT_MAX)
  76. return (int)u;
  77. else if (u >= (unsigned)INT_MIN) /* wrap in cast _to_ unsigned is OK */
  78. return INT_MIN + (int)(u - (unsigned)INT_MIN);
  79. else
  80. return INT_MIN; /* fallback; should never occur on binary machines */
  81. }
  82. char *fgetline(FILE *fp);
  83. bool read_file_into(BinarySink *bs, FILE *fp);
  84. char *chomp(char *str);
  85. bool strstartswith(const char *s, const char *t);
  86. bool strendswith(const char *s, const char *t);
  87. void base64_encode_atom(const unsigned char *data, int n, char *out);
  88. int base64_decode_atom(const char *atom, unsigned char *out);
  89. struct bufchain_granule;
  90. struct bufchain_tag {
  91. struct bufchain_granule *head, *tail;
  92. size_t buffersize; /* current amount of buffered data */
  93. void (*queue_idempotent_callback)(IdempotentCallback *ic);
  94. IdempotentCallback *ic;
  95. };
  96. void bufchain_init(bufchain *ch);
  97. void bufchain_clear(bufchain *ch);
  98. size_t bufchain_size(bufchain *ch);
  99. void bufchain_add(bufchain *ch, const void *data, size_t len);
  100. ptrlen bufchain_prefix(bufchain *ch);
  101. void bufchain_consume(bufchain *ch, size_t len);
  102. void bufchain_fetch(bufchain *ch, void *data, size_t len);
  103. void bufchain_fetch_consume(bufchain *ch, void *data, size_t len);
  104. bool bufchain_try_consume(bufchain *ch, size_t len);
  105. bool bufchain_try_fetch(bufchain *ch, void *data, size_t len);
  106. bool bufchain_try_fetch_consume(bufchain *ch, void *data, size_t len);
  107. size_t bufchain_fetch_consume_up_to(bufchain *ch, void *data, size_t len);
  108. void bufchain_set_callback_inner(
  109. bufchain *ch, IdempotentCallback *ic,
  110. void (*queue_idempotent_callback)(IdempotentCallback *ic));
  111. static inline void bufchain_set_callback(bufchain *ch, IdempotentCallback *ic)
  112. {
  113. extern void queue_idempotent_callback(struct IdempotentCallback *ic);
  114. /* Wrapper that puts in the standard queue_idempotent_callback
  115. * function. Lives here rather than in bufchain.c so that
  116. * standalone programs can use the bufchain facility without this
  117. * optional callback feature and not need to provide a stub of
  118. * queue_idempotent_callback. */
  119. bufchain_set_callback_inner(ch, ic, queue_idempotent_callback);
  120. }
  121. bool validate_manual_hostkey(char *key);
  122. struct tm ltime(void);
  123. /*
  124. * Special form of strcmp which can cope with NULL inputs. NULL is
  125. * defined to sort before even the empty string.
  126. */
  127. int nullstrcmp(const char *a, const char *b);
  128. static inline ptrlen make_ptrlen(const void *ptr, size_t len)
  129. {
  130. ptrlen pl;
  131. pl.ptr = ptr;
  132. pl.len = len;
  133. return pl;
  134. }
  135. static inline ptrlen ptrlen_from_asciz(const char *str)
  136. {
  137. return make_ptrlen(str, strlen(str));
  138. }
  139. static inline ptrlen ptrlen_from_strbuf(strbuf *sb)
  140. {
  141. return make_ptrlen(sb->u, sb->len);
  142. }
  143. bool ptrlen_eq_string(ptrlen pl, const char *str);
  144. bool ptrlen_eq_ptrlen(ptrlen pl1, ptrlen pl2);
  145. int ptrlen_strcmp(ptrlen pl1, ptrlen pl2);
  146. /* ptrlen_startswith and ptrlen_endswith write through their 'tail'
  147. * argument if and only if it is non-NULL and they return true. Hence
  148. * you can write ptrlen_startswith(thing, prefix, &thing), writing
  149. * back to the same ptrlen it read from, to remove a prefix if present
  150. * and say whether it did so. */
  151. bool ptrlen_startswith(ptrlen whole, ptrlen prefix, ptrlen *tail);
  152. bool ptrlen_endswith(ptrlen whole, ptrlen suffix, ptrlen *tail);
  153. ptrlen ptrlen_get_word(ptrlen *input, const char *separators);
  154. char *mkstr(ptrlen pl);
  155. int string_length_for_printf(size_t);
  156. /* Derive two printf arguments from a ptrlen, suitable for "%.*s" */
  157. #define PTRLEN_PRINTF(pl) \
  158. string_length_for_printf((pl).len), (const char *)(pl).ptr
  159. /* Make a ptrlen out of a compile-time string literal. We try to
  160. * enforce that it _is_ a string literal by token-pasting "" on to it,
  161. * which should provoke a compile error if it's any other kind of
  162. * string. */
  163. #define PTRLEN_LITERAL(stringlit) \
  164. TYPECHECK("" stringlit "", make_ptrlen(stringlit, sizeof(stringlit)-1))
  165. /* Make a ptrlen out of a compile-time string literal in a way that
  166. * allows you to declare the ptrlen itself as a compile-time initialiser. */
  167. #define PTRLEN_DECL_LITERAL(stringlit) \
  168. { TYPECHECK("" stringlit "", stringlit), sizeof(stringlit)-1 }
  169. /* Make a ptrlen out of a constant byte array. */
  170. #define PTRLEN_FROM_CONST_BYTES(a) make_ptrlen(a, sizeof(a))
  171. /* Wipe sensitive data out of memory that's about to be freed. Simpler
  172. * than memset because we don't need the fill char parameter; also
  173. * attempts (by fiddly use of volatile) to inhibit the compiler from
  174. * over-cleverly trying to optimise the memset away because it knows
  175. * the variable is going out of scope. */
  176. void smemclr(void *b, size_t len);
  177. /* Compare two fixed-length chunks of memory for equality, without
  178. * data-dependent control flow (so an attacker with a very accurate
  179. * stopwatch can't try to guess where the first mismatching byte was).
  180. * Returns false for mismatch or true for equality (unlike memcmp),
  181. * hinted at by the 'eq' in the name. */
  182. bool smemeq(const void *av, const void *bv, size_t len);
  183. /* Encode a single UTF-8 character. Assumes that illegal characters
  184. * (such as things in the surrogate range, or > 0x10FFFF) have already
  185. * been removed. */
  186. size_t encode_utf8(void *output, unsigned long ch);
  187. /* Encode a wide-character string into UTF-8. Tolerates surrogates if
  188. * sizeof(wchar_t) == 2, assuming that in that case the wide string is
  189. * encoded in UTF-16. */
  190. char *encode_wide_string_as_utf8(const wchar_t *wstr);
  191. /* Write a string out in C string-literal format. */
  192. void write_c_string_literal(FILE *fp, ptrlen str);
  193. char *buildinfo(const char *newline);
  194. /*
  195. * A function you can put at points in the code where execution should
  196. * never reach in the first place. Better than assert(false), or even
  197. * assert(false && "some explanatory message"), because some compilers
  198. * don't interpret assert(false) as a declaration of unreachability,
  199. * so they may still warn about pointless things like some variable
  200. * not being initialised on the unreachable code path.
  201. *
  202. * I follow the assertion with a call to abort() just in case someone
  203. * compiles with -DNDEBUG, and I wrap that abort inside my own
  204. * function labelled NORETURN just in case some unusual kind of system
  205. * header wasn't foresighted enough to label abort() itself that way.
  206. */
  207. static inline NORETURN void unreachable_internal(void) {
  208. #ifndef WINSCP_VS
  209. // Not to try to link to VS abort
  210. abort();
  211. #endif
  212. }
  213. #define unreachable(msg) (assert(false && msg), unreachable_internal())
  214. /*
  215. * Debugging functions.
  216. *
  217. * Output goes to debug.log
  218. *
  219. * debug() is like printf().
  220. *
  221. * dmemdump() and dmemdumpl() both do memory dumps. The difference
  222. * is that dmemdumpl() is more suited for when the memory address is
  223. * important (say because you'll be recording pointer values later
  224. * on). dmemdump() is more concise.
  225. */
  226. #ifdef DEBUG
  227. void debug_printf(const char *fmt, ...) PRINTF_LIKE(1, 2);
  228. void debug_memdump(const void *buf, int len, bool L);
  229. #define debug(...) (debug_printf(__VA_ARGS__))
  230. #define dmemdump(buf,len) (debug_memdump(buf, len, false))
  231. #define dmemdumpl(buf,len) (debug_memdump(buf, len, true))
  232. #else
  233. #define debug(...) ((void)0)
  234. #define dmemdump(buf,len) ((void)0)
  235. #define dmemdumpl(buf,len) ((void)0)
  236. #endif
  237. #ifndef lenof
  238. #define lenof(x) ( (sizeof((x))) / (sizeof(*(x))))
  239. #endif
  240. #ifndef min
  241. #define min(x,y) ( (x) < (y) ? (x) : (y) )
  242. #endif
  243. #ifndef max
  244. #define max(x,y) ( (x) > (y) ? (x) : (y) )
  245. #endif
  246. static inline uint64_t GET_64BIT_LSB_FIRST(const void *vp)
  247. {
  248. const uint8_t *p = (const uint8_t *)vp;
  249. return (((uint64_t)p[0] ) | ((uint64_t)p[1] << 8) |
  250. ((uint64_t)p[2] << 16) | ((uint64_t)p[3] << 24) |
  251. ((uint64_t)p[4] << 32) | ((uint64_t)p[5] << 40) |
  252. ((uint64_t)p[6] << 48) | ((uint64_t)p[7] << 56));
  253. }
  254. static inline void PUT_64BIT_LSB_FIRST(void *vp, uint64_t value)
  255. {
  256. uint8_t *p = (uint8_t *)vp;
  257. p[0] = (uint8_t)(value);
  258. p[1] = (uint8_t)(value >> 8);
  259. p[2] = (uint8_t)(value >> 16);
  260. p[3] = (uint8_t)(value >> 24);
  261. p[4] = (uint8_t)(value >> 32);
  262. p[5] = (uint8_t)(value >> 40);
  263. p[6] = (uint8_t)(value >> 48);
  264. p[7] = (uint8_t)(value >> 56);
  265. }
  266. static inline uint32_t GET_32BIT_LSB_FIRST(const void *vp)
  267. {
  268. const uint8_t *p = (const uint8_t *)vp;
  269. return (((uint32_t)p[0] ) | ((uint32_t)p[1] << 8) |
  270. ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24));
  271. }
  272. static inline void PUT_32BIT_LSB_FIRST(void *vp, uint32_t value)
  273. {
  274. uint8_t *p = (uint8_t *)vp;
  275. p[0] = (uint8_t)(value);
  276. p[1] = (uint8_t)(value >> 8);
  277. p[2] = (uint8_t)(value >> 16);
  278. p[3] = (uint8_t)(value >> 24);
  279. }
  280. static inline uint16_t GET_16BIT_LSB_FIRST(const void *vp)
  281. {
  282. const uint8_t *p = (const uint8_t *)vp;
  283. return (((uint16_t)p[0] ) | ((uint16_t)p[1] << 8));
  284. }
  285. static inline void PUT_16BIT_LSB_FIRST(void *vp, uint16_t value)
  286. {
  287. uint8_t *p = (uint8_t *)vp;
  288. p[0] = (uint8_t)(value);
  289. p[1] = (uint8_t)(value >> 8);
  290. }
  291. static inline uint64_t GET_64BIT_MSB_FIRST(const void *vp)
  292. {
  293. const uint8_t *p = (const uint8_t *)vp;
  294. return (((uint64_t)p[7] ) | ((uint64_t)p[6] << 8) |
  295. ((uint64_t)p[5] << 16) | ((uint64_t)p[4] << 24) |
  296. ((uint64_t)p[3] << 32) | ((uint64_t)p[2] << 40) |
  297. ((uint64_t)p[1] << 48) | ((uint64_t)p[0] << 56));
  298. }
  299. static inline void PUT_64BIT_MSB_FIRST(void *vp, uint64_t value)
  300. {
  301. uint8_t *p = (uint8_t *)vp;
  302. p[7] = (uint8_t)(value);
  303. p[6] = (uint8_t)(value >> 8);
  304. p[5] = (uint8_t)(value >> 16);
  305. p[4] = (uint8_t)(value >> 24);
  306. p[3] = (uint8_t)(value >> 32);
  307. p[2] = (uint8_t)(value >> 40);
  308. p[1] = (uint8_t)(value >> 48);
  309. p[0] = (uint8_t)(value >> 56);
  310. }
  311. static inline uint32_t GET_32BIT_MSB_FIRST(const void *vp)
  312. {
  313. const uint8_t *p = (const uint8_t *)vp;
  314. return (((uint32_t)p[3] ) | ((uint32_t)p[2] << 8) |
  315. ((uint32_t)p[1] << 16) | ((uint32_t)p[0] << 24));
  316. }
  317. static inline void PUT_32BIT_MSB_FIRST(void *vp, uint32_t value)
  318. {
  319. uint8_t *p = (uint8_t *)vp;
  320. p[3] = (uint8_t)(value);
  321. p[2] = (uint8_t)(value >> 8);
  322. p[1] = (uint8_t)(value >> 16);
  323. p[0] = (uint8_t)(value >> 24);
  324. }
  325. static inline uint16_t GET_16BIT_MSB_FIRST(const void *vp)
  326. {
  327. const uint8_t *p = (const uint8_t *)vp;
  328. return (((uint16_t)p[1] ) | ((uint16_t)p[0] << 8));
  329. }
  330. static inline void PUT_16BIT_MSB_FIRST(void *vp, uint16_t value)
  331. {
  332. uint8_t *p = (uint8_t *)vp;
  333. p[1] = (uint8_t)(value);
  334. p[0] = (uint8_t)(value >> 8);
  335. }
  336. /* For use in X11-related applications, an endianness-variable form of
  337. * {GET,PUT}_16BIT which expects 'endian' to be either 'B' or 'l' */
  338. static inline uint16_t GET_16BIT_X11(char endian, const void *p)
  339. {
  340. return endian == 'B' ? GET_16BIT_MSB_FIRST(p) : GET_16BIT_LSB_FIRST(p);
  341. }
  342. static inline void PUT_16BIT_X11(char endian, void *p, uint16_t value)
  343. {
  344. if (endian == 'B')
  345. PUT_16BIT_MSB_FIRST(p, value);
  346. else
  347. PUT_16BIT_LSB_FIRST(p, value);
  348. }
  349. /* Replace NULL with the empty string, permitting an idiom in which we
  350. * get a string (pointer,length) pair that might be NULL,0 and can
  351. * then safely say things like printf("%.*s", length, NULLTOEMPTY(ptr)) */
  352. static inline const char *NULLTOEMPTY(const char *s)
  353. {
  354. return s ? s : "";
  355. }
  356. /* StripCtrlChars, defined in stripctrl.c: an adapter you can put on
  357. * the front of one BinarySink and which functions as one in turn.
  358. * Interprets its input as a stream of multibyte characters in the
  359. * system locale, and removes any that are not either printable
  360. * characters or newlines. */
  361. struct StripCtrlChars {
  362. BinarySink_IMPLEMENTATION;
  363. /* and this is contained in a larger structure */
  364. };
  365. StripCtrlChars *stripctrl_new(
  366. BinarySink *bs_out, bool permit_cr, wchar_t substitution);
  367. StripCtrlChars *stripctrl_new_term_fn(
  368. BinarySink *bs_out, bool permit_cr, wchar_t substitution,
  369. Terminal *term, unsigned long (*translate)(
  370. Terminal *, term_utf8_decode *, unsigned char));
  371. #define stripctrl_new_term(bs, cr, sub, term) \
  372. stripctrl_new_term_fn(bs, cr, sub, term, term_translate)
  373. void stripctrl_retarget(StripCtrlChars *sccpub, BinarySink *new_bs_out);
  374. void stripctrl_reset(StripCtrlChars *sccpub);
  375. void stripctrl_free(StripCtrlChars *sanpub);
  376. void stripctrl_enable_line_limiting(StripCtrlChars *sccpub);
  377. #ifndef WINSCP
  378. char *stripctrl_string_ptrlen(StripCtrlChars *sccpub, ptrlen str);
  379. static inline char *stripctrl_string(StripCtrlChars *sccpub, const char *str)
  380. {
  381. return stripctrl_string_ptrlen(sccpub, ptrlen_from_asciz(str));
  382. }
  383. #endif
  384. #ifdef MPEXT
  385. // Recent PuTTY code uses C99 standard that allows code before initialization.
  386. // Frequently that code are assertions. This assert implementation allows being used before code.
  387. #define pinitassert(P) const int __assert_dummy = 1/((int)(P))
  388. #endif
  389. /*
  390. * A mechanism for loading a file from disk into a memory buffer where
  391. * it can be picked apart as a BinarySource.
  392. */
  393. struct LoadedFile {
  394. char *data;
  395. size_t len, max_size;
  396. BinarySource_IMPLEMENTATION;
  397. };
  398. typedef enum {
  399. LF_OK, /* file loaded successfully */
  400. LF_TOO_BIG, /* file didn't fit in buffer */
  401. LF_ERROR, /* error from stdio layer */
  402. } LoadFileStatus;
  403. LoadedFile *lf_new(size_t max_size);
  404. void lf_free(LoadedFile *lf);
  405. LoadFileStatus lf_load_fp(LoadedFile *lf, FILE *fp);
  406. LoadFileStatus lf_load(LoadedFile *lf, const Filename *filename);
  407. static inline ptrlen ptrlen_from_lf(LoadedFile *lf)
  408. { return make_ptrlen(lf->data, lf->len); }
  409. /* Set the memory block of 'size' bytes at 'out' to the bitwise XOR of
  410. * the two blocks of the same size at 'in1' and 'in2'.
  411. *
  412. * 'out' may point to exactly the same address as one of the inputs,
  413. * but if the input and output blocks overlap in any other way, the
  414. * result of this function is not guaranteed. No memmove-style effort
  415. * is made to handle difficult overlap cases. */
  416. void memxor(uint8_t *out, const uint8_t *in1, const uint8_t *in2, size_t size);
  417. #endif