misc.h 15 KB

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