util.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. /* Copyright (c) 2003-2004, Roger Dingledine
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2018, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file util.h
  7. * \brief Headers for util.c
  8. **/
  9. #ifndef TOR_UTIL_H
  10. #define TOR_UTIL_H
  11. #include "orconfig.h"
  12. #include "lib/cc/torint.h"
  13. #include "common/compat.h"
  14. #include "lib/ctime/di_ops.h"
  15. #include "lib/testsupport/testsupport.h"
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #ifdef _WIN32
  19. /* for the correct alias to struct stat */
  20. #include <sys/stat.h>
  21. #endif
  22. #include "lib/err/torerr.h"
  23. #include "lib/malloc/util_malloc.h"
  24. #include "common/util_bug.h"
  25. #ifndef O_BINARY
  26. #define O_BINARY 0
  27. #endif
  28. #ifndef O_TEXT
  29. #define O_TEXT 0
  30. #endif
  31. #ifndef O_NOFOLLOW
  32. #define O_NOFOLLOW 0
  33. #endif
  34. uint64_t tor_htonll(uint64_t a);
  35. uint64_t tor_ntohll(uint64_t a);
  36. void tor_log_mallinfo(int severity);
  37. /** Macro: yield a pointer to the field at position <b>off</b> within the
  38. * structure <b>st</b>. Example:
  39. * <pre>
  40. * struct a { int foo; int bar; } x;
  41. * off_t bar_offset = offsetof(struct a, bar);
  42. * int *bar_p = STRUCT_VAR_P(&x, bar_offset);
  43. * *bar_p = 3;
  44. * </pre>
  45. */
  46. #define STRUCT_VAR_P(st, off) ((void*) ( ((char*)(st)) + (off) ) )
  47. /** Macro: yield a pointer to an enclosing structure given a pointer to
  48. * a substructure at offset <b>off</b>. Example:
  49. * <pre>
  50. * struct base { ... };
  51. * struct subtype { int x; struct base b; } x;
  52. * struct base *bp = &x.base;
  53. * struct *sp = SUBTYPE_P(bp, struct subtype, b);
  54. * </pre>
  55. */
  56. #define SUBTYPE_P(p, subtype, basemember) \
  57. ((void*) ( ((char*)(p)) - offsetof(subtype, basemember) ))
  58. /* Logic */
  59. /** Macro: true if two values have the same boolean value. */
  60. #define bool_eq(a,b) (!(a)==!(b))
  61. /** Macro: true if two values have different boolean values. */
  62. #define bool_neq(a,b) (!(a)!=!(b))
  63. /* Math functions */
  64. double tor_mathlog(double d) ATTR_CONST;
  65. long tor_lround(double d) ATTR_CONST;
  66. int64_t tor_llround(double d) ATTR_CONST;
  67. int tor_log2(uint64_t u64) ATTR_CONST;
  68. uint64_t round_to_power_of_2(uint64_t u64);
  69. unsigned round_to_next_multiple_of(unsigned number, unsigned divisor);
  70. uint32_t round_uint32_to_next_multiple_of(uint32_t number, uint32_t divisor);
  71. uint64_t round_uint64_to_next_multiple_of(uint64_t number, uint64_t divisor);
  72. int64_t sample_laplace_distribution(double mu, double b, double p);
  73. int64_t add_laplace_noise(int64_t signal, double random, double delta_f,
  74. double epsilon);
  75. int n_bits_set_u8(uint8_t v);
  76. int64_t clamp_double_to_int64(double number);
  77. void simplify_fraction64(uint64_t *numer, uint64_t *denom);
  78. uint32_t tor_add_u32_nowrap(uint32_t a, uint32_t b);
  79. /* Compute the CEIL of <b>a</b> divided by <b>b</b>, for nonnegative <b>a</b>
  80. * and positive <b>b</b>. Works on integer types only. Not defined if a+(b-1)
  81. * can overflow. */
  82. #define CEIL_DIV(a,b) (((a)+((b)-1))/(b))
  83. /* Return <b>v</b> if it's between <b>min</b> and <b>max</b>. Otherwise
  84. * return <b>min</b> if <b>v</b> is smaller than <b>min</b>, or <b>max</b> if
  85. * <b>b</b> is larger than <b>max</b>.
  86. *
  87. * Requires that <b>min</b> is no more than <b>max</b>. May evaluate any of
  88. * its arguments more than once! */
  89. #define CLAMP(min,v,max) \
  90. ( ((v) < (min)) ? (min) : \
  91. ((v) > (max)) ? (max) : \
  92. (v) )
  93. /* String manipulation */
  94. /** Allowable characters in a hexadecimal string. */
  95. #define HEX_CHARACTERS "0123456789ABCDEFabcdef"
  96. void tor_strlower(char *s) ATTR_NONNULL((1));
  97. void tor_strupper(char *s) ATTR_NONNULL((1));
  98. int tor_strisprint(const char *s) ATTR_NONNULL((1));
  99. int tor_strisnonupper(const char *s) ATTR_NONNULL((1));
  100. int tor_strisspace(const char *s);
  101. int strcmp_opt(const char *s1, const char *s2);
  102. int strcmpstart(const char *s1, const char *s2) ATTR_NONNULL((1,2));
  103. int strcmp_len(const char *s1, const char *s2, size_t len) ATTR_NONNULL((1,2));
  104. int strcasecmpstart(const char *s1, const char *s2) ATTR_NONNULL((1,2));
  105. int strcmpend(const char *s1, const char *s2) ATTR_NONNULL((1,2));
  106. int strcasecmpend(const char *s1, const char *s2) ATTR_NONNULL((1,2));
  107. int fast_memcmpstart(const void *mem, size_t memlen, const char *prefix);
  108. void tor_strstrip(char *s, const char *strip) ATTR_NONNULL((1,2));
  109. long tor_parse_long(const char *s, int base, long min,
  110. long max, int *ok, char **next);
  111. unsigned long tor_parse_ulong(const char *s, int base, unsigned long min,
  112. unsigned long max, int *ok, char **next);
  113. double tor_parse_double(const char *s, double min, double max, int *ok,
  114. char **next);
  115. uint64_t tor_parse_uint64(const char *s, int base, uint64_t min,
  116. uint64_t max, int *ok, char **next);
  117. const char *hex_str(const char *from, size_t fromlen) ATTR_NONNULL((1));
  118. const char *eat_whitespace(const char *s);
  119. const char *eat_whitespace_eos(const char *s, const char *eos);
  120. const char *eat_whitespace_no_nl(const char *s);
  121. const char *eat_whitespace_eos_no_nl(const char *s, const char *eos);
  122. const char *find_whitespace(const char *s);
  123. const char *find_whitespace_eos(const char *s, const char *eos);
  124. const char *find_str_at_start_of_line(const char *haystack,
  125. const char *needle);
  126. int string_is_C_identifier(const char *string);
  127. int string_is_key_value(int severity, const char *string);
  128. int string_is_valid_dest(const char *string);
  129. int string_is_valid_nonrfc_hostname(const char *string);
  130. int string_is_valid_ipv4_address(const char *string);
  131. int string_is_valid_ipv6_address(const char *string);
  132. int tor_mem_is_zero(const char *mem, size_t len);
  133. int tor_digest_is_zero(const char *digest);
  134. int tor_digest256_is_zero(const char *digest);
  135. char *esc_for_log(const char *string) ATTR_MALLOC;
  136. char *esc_for_log_len(const char *chars, size_t n) ATTR_MALLOC;
  137. const char *escaped(const char *string);
  138. char *tor_escape_str_for_pt_args(const char *string,
  139. const char *chars_to_escape);
  140. struct smartlist_t;
  141. int tor_vsscanf(const char *buf, const char *pattern, va_list ap) \
  142. CHECK_SCANF(2, 0);
  143. int tor_sscanf(const char *buf, const char *pattern, ...)
  144. CHECK_SCANF(2, 3);
  145. void smartlist_add_asprintf(struct smartlist_t *sl, const char *pattern, ...)
  146. CHECK_PRINTF(2, 3);
  147. void smartlist_add_vasprintf(struct smartlist_t *sl, const char *pattern,
  148. va_list args)
  149. CHECK_PRINTF(2, 0);
  150. void smartlist_add_strdup(struct smartlist_t *sl, const char *string);
  151. /* Time helpers */
  152. long tv_udiff(const struct timeval *start, const struct timeval *end);
  153. long tv_mdiff(const struct timeval *start, const struct timeval *end);
  154. int64_t tv_to_msec(const struct timeval *tv);
  155. int tor_timegm(const struct tm *tm, time_t *time_out);
  156. #define RFC1123_TIME_LEN 29
  157. void format_rfc1123_time(char *buf, time_t t);
  158. int parse_rfc1123_time(const char *buf, time_t *t);
  159. #define ISO_TIME_LEN 19
  160. #define ISO_TIME_USEC_LEN (ISO_TIME_LEN+7)
  161. void format_local_iso_time(char *buf, time_t t);
  162. void format_iso_time(char *buf, time_t t);
  163. void format_local_iso_time_nospace(char *buf, time_t t);
  164. void format_iso_time_nospace(char *buf, time_t t);
  165. void format_iso_time_nospace_usec(char *buf, const struct timeval *tv);
  166. int parse_iso_time_(const char *cp, time_t *t, int strict, int nospace);
  167. int parse_iso_time(const char *buf, time_t *t);
  168. int parse_iso_time_nospace(const char *cp, time_t *t);
  169. int parse_http_time(const char *buf, struct tm *tm);
  170. int format_time_interval(char *out, size_t out_len, long interval);
  171. /* Cached time */
  172. #ifdef TIME_IS_FAST
  173. #define approx_time() time(NULL)
  174. #define update_approx_time(t) STMT_NIL
  175. #else
  176. time_t approx_time(void);
  177. void update_approx_time(time_t now);
  178. #endif /* defined(TIME_IS_FAST) */
  179. /* Rate-limiter */
  180. /** A ratelim_t remembers how often an event is occurring, and how often
  181. * it's allowed to occur. Typical usage is something like:
  182. *
  183. <pre>
  184. if (possibly_very_frequent_event()) {
  185. const int INTERVAL = 300;
  186. static ratelim_t warning_limit = RATELIM_INIT(INTERVAL);
  187. char *m;
  188. if ((m = rate_limit_log(&warning_limit, approx_time()))) {
  189. log_warn(LD_GENERAL, "The event occurred!%s", m);
  190. tor_free(m);
  191. }
  192. }
  193. </pre>
  194. As a convenience wrapper for logging, you can replace the above with:
  195. <pre>
  196. if (possibly_very_frequent_event()) {
  197. static ratelim_t warning_limit = RATELIM_INIT(300);
  198. log_fn_ratelim(&warning_limit, LOG_WARN, LD_GENERAL,
  199. "The event occurred!");
  200. }
  201. </pre>
  202. */
  203. typedef struct ratelim_t {
  204. int rate;
  205. time_t last_allowed;
  206. int n_calls_since_last_time;
  207. } ratelim_t;
  208. #define RATELIM_INIT(r) { (r), 0, 0 }
  209. #define RATELIM_TOOMANY (16*1000*1000)
  210. char *rate_limit_log(ratelim_t *lim, time_t now);
  211. /* File helpers */
  212. ssize_t write_all(tor_socket_t fd, const char *buf, size_t count,int isSocket);
  213. ssize_t read_all(tor_socket_t fd, char *buf, size_t count, int isSocket);
  214. /** Status of an I/O stream. */
  215. enum stream_status {
  216. IO_STREAM_OKAY,
  217. IO_STREAM_EAGAIN,
  218. IO_STREAM_TERM,
  219. IO_STREAM_CLOSED
  220. };
  221. const char *stream_status_to_string(enum stream_status stream_status);
  222. enum stream_status get_string_from_pipe(int fd, char *buf, size_t count);
  223. MOCK_DECL(int,tor_unlink,(const char *pathname));
  224. /** Return values from file_status(); see that function's documentation
  225. * for details. */
  226. typedef enum { FN_ERROR, FN_NOENT, FN_FILE, FN_DIR, FN_EMPTY } file_status_t;
  227. file_status_t file_status(const char *filename);
  228. /** Possible behaviors for check_private_dir() on encountering a nonexistent
  229. * directory; see that function's documentation for details. */
  230. typedef unsigned int cpd_check_t;
  231. #define CPD_NONE 0
  232. #define CPD_CREATE (1u << 0)
  233. #define CPD_CHECK (1u << 1)
  234. #define CPD_GROUP_OK (1u << 2)
  235. #define CPD_GROUP_READ (1u << 3)
  236. #define CPD_CHECK_MODE_ONLY (1u << 4)
  237. #define CPD_RELAX_DIRMODE_CHECK (1u << 5)
  238. MOCK_DECL(int, check_private_dir,
  239. (const char *dirname, cpd_check_t check,
  240. const char *effective_user));
  241. #define OPEN_FLAGS_REPLACE (O_WRONLY|O_CREAT|O_TRUNC)
  242. #define OPEN_FLAGS_APPEND (O_WRONLY|O_CREAT|O_APPEND)
  243. #define OPEN_FLAGS_DONT_REPLACE (O_CREAT|O_EXCL|O_APPEND|O_WRONLY)
  244. typedef struct open_file_t open_file_t;
  245. int start_writing_to_file(const char *fname, int open_flags, int mode,
  246. open_file_t **data_out);
  247. FILE *start_writing_to_stdio_file(const char *fname, int open_flags, int mode,
  248. open_file_t **data_out);
  249. FILE *fdopen_file(open_file_t *file_data);
  250. int finish_writing_to_file(open_file_t *file_data);
  251. int abort_writing_to_file(open_file_t *file_data);
  252. MOCK_DECL(int,
  253. write_str_to_file,(const char *fname, const char *str, int bin));
  254. MOCK_DECL(int,
  255. write_bytes_to_file,(const char *fname, const char *str, size_t len,
  256. int bin));
  257. /** An ad-hoc type to hold a string of characters and a count; used by
  258. * write_chunks_to_file. */
  259. typedef struct sized_chunk_t {
  260. const char *bytes;
  261. size_t len;
  262. } sized_chunk_t;
  263. int write_chunks_to_file(const char *fname, const struct smartlist_t *chunks,
  264. int bin, int no_tempfile);
  265. int append_bytes_to_file(const char *fname, const char *str, size_t len,
  266. int bin);
  267. int write_bytes_to_new_file(const char *fname, const char *str, size_t len,
  268. int bin);
  269. /** Flag for read_file_to_str: open the file in binary mode. */
  270. #define RFTS_BIN 1
  271. /** Flag for read_file_to_str: it's okay if the file doesn't exist. */
  272. #define RFTS_IGNORE_MISSING 2
  273. #ifndef _WIN32
  274. struct stat;
  275. #endif
  276. MOCK_DECL_ATTR(char *, read_file_to_str,
  277. (const char *filename, int flags, struct stat *stat_out),
  278. ATTR_MALLOC);
  279. char *read_file_to_str_until_eof(int fd, size_t max_bytes_to_read,
  280. size_t *sz_out)
  281. ATTR_MALLOC;
  282. const char *unescape_string(const char *s, char **result, size_t *size_out);
  283. char *get_unquoted_path(const char *path);
  284. char *expand_filename(const char *filename);
  285. MOCK_DECL(struct smartlist_t *, tor_listdir, (const char *dirname));
  286. int path_is_relative(const char *filename);
  287. /* Process helpers */
  288. void start_daemon(void);
  289. void finish_daemon(const char *desired_cwd);
  290. int write_pidfile(const char *filename);
  291. void tor_disable_spawning_background_processes(void);
  292. typedef struct process_handle_t process_handle_t;
  293. typedef struct process_environment_t process_environment_t;
  294. int tor_spawn_background(const char *const filename, const char **argv,
  295. process_environment_t *env,
  296. process_handle_t **process_handle_out);
  297. #define SPAWN_ERROR_MESSAGE "ERR: Failed to spawn background process - code "
  298. #ifdef _WIN32
  299. HANDLE load_windows_system_library(const TCHAR *library_name);
  300. #endif
  301. int environment_variable_names_equal(const char *s1, const char *s2);
  302. /* DOCDOC process_environment_t */
  303. struct process_environment_t {
  304. /** A pointer to a sorted empty-string-terminated sequence of
  305. * NUL-terminated strings of the form "NAME=VALUE". */
  306. char *windows_environment_block;
  307. /** A pointer to a NULL-terminated array of pointers to
  308. * NUL-terminated strings of the form "NAME=VALUE". */
  309. char **unixoid_environment_block;
  310. };
  311. process_environment_t *process_environment_make(struct smartlist_t *env_vars);
  312. void process_environment_free_(process_environment_t *env);
  313. #define process_environment_free(env) \
  314. FREE_AND_NULL(process_environment_t, process_environment_free_, (env))
  315. struct smartlist_t *get_current_process_environment_variables(void);
  316. void set_environment_variable_in_smartlist(struct smartlist_t *env_vars,
  317. const char *new_var,
  318. void (*free_old)(void*),
  319. int free_p);
  320. /* Values of process_handle_t.status. */
  321. #define PROCESS_STATUS_NOTRUNNING 0
  322. #define PROCESS_STATUS_RUNNING 1
  323. #define PROCESS_STATUS_ERROR -1
  324. #ifdef UTIL_PRIVATE
  325. struct waitpid_callback_t;
  326. /** Structure to represent the state of a process with which Tor is
  327. * communicating. The contents of this structure are private to util.c */
  328. struct process_handle_t {
  329. /** One of the PROCESS_STATUS_* values */
  330. int status;
  331. #ifdef _WIN32
  332. HANDLE stdin_pipe;
  333. HANDLE stdout_pipe;
  334. HANDLE stderr_pipe;
  335. PROCESS_INFORMATION pid;
  336. #else /* !(defined(_WIN32)) */
  337. int stdin_pipe;
  338. int stdout_pipe;
  339. int stderr_pipe;
  340. pid_t pid;
  341. /** If the process has not given us a SIGCHLD yet, this has the
  342. * waitpid_callback_t that gets invoked once it has. Otherwise this
  343. * contains NULL. */
  344. struct waitpid_callback_t *waitpid_cb;
  345. /** The exit status reported by waitpid. */
  346. int waitpid_exit_status;
  347. #endif /* defined(_WIN32) */
  348. };
  349. #endif /* defined(UTIL_PRIVATE) */
  350. /* Return values of tor_get_exit_code() */
  351. #define PROCESS_EXIT_RUNNING 1
  352. #define PROCESS_EXIT_EXITED 0
  353. #define PROCESS_EXIT_ERROR -1
  354. int tor_get_exit_code(process_handle_t *process_handle,
  355. int block, int *exit_code);
  356. int tor_split_lines(struct smartlist_t *sl, char *buf, int len);
  357. #ifdef _WIN32
  358. ssize_t tor_read_all_handle(HANDLE h, char *buf, size_t count,
  359. const process_handle_t *process);
  360. #else
  361. ssize_t tor_read_all_handle(int fd, char *buf, size_t count,
  362. const process_handle_t *process,
  363. int *eof);
  364. #endif /* defined(_WIN32) */
  365. ssize_t tor_read_all_from_process_stdout(
  366. const process_handle_t *process_handle, char *buf, size_t count);
  367. ssize_t tor_read_all_from_process_stderr(
  368. const process_handle_t *process_handle, char *buf, size_t count);
  369. char *tor_join_win_cmdline(const char *argv[]);
  370. int tor_process_get_pid(process_handle_t *process_handle);
  371. #ifdef _WIN32
  372. HANDLE tor_process_get_stdout_pipe(process_handle_t *process_handle);
  373. #else
  374. int tor_process_get_stdout_pipe(process_handle_t *process_handle);
  375. #endif
  376. #ifdef _WIN32
  377. MOCK_DECL(struct smartlist_t *,
  378. tor_get_lines_from_handle,(HANDLE *handle,
  379. enum stream_status *stream_status));
  380. #else
  381. MOCK_DECL(struct smartlist_t *,
  382. tor_get_lines_from_handle,(int fd,
  383. enum stream_status *stream_status));
  384. #endif /* defined(_WIN32) */
  385. int
  386. tor_terminate_process(process_handle_t *process_handle);
  387. MOCK_DECL(void,
  388. tor_process_handle_destroy,(process_handle_t *process_handle,
  389. int also_terminate_process));
  390. /* ===== Insecure rng */
  391. typedef struct tor_weak_rng_t {
  392. uint32_t state;
  393. } tor_weak_rng_t;
  394. #define TOR_WEAK_RNG_INIT {383745623}
  395. #define TOR_WEAK_RANDOM_MAX (INT_MAX)
  396. void tor_init_weak_random(tor_weak_rng_t *weak_rng, unsigned seed);
  397. int32_t tor_weak_random(tor_weak_rng_t *weak_rng);
  398. int32_t tor_weak_random_range(tor_weak_rng_t *rng, int32_t top);
  399. /** Randomly return true according to <b>rng</b> with probability 1 in
  400. * <b>n</b> */
  401. #define tor_weak_random_one_in_n(rng, n) (0==tor_weak_random_range((rng),(n)))
  402. #ifdef UTIL_PRIVATE
  403. /* Prototypes for private functions only used by util.c (and unit tests) */
  404. #ifndef _WIN32
  405. STATIC int format_helper_exit_status(unsigned char child_state,
  406. int saved_errno, char *hex_errno);
  407. /* Space for hex values of child state, a slash, saved_errno (with
  408. leading minus) and newline (no null) */
  409. #define HEX_ERRNO_SIZE (sizeof(char) * 2 + 1 + \
  410. 1 + sizeof(int) * 2 + 1)
  411. #endif /* !defined(_WIN32) */
  412. #endif /* defined(UTIL_PRIVATE) */
  413. #define ARRAY_LENGTH(x) ((sizeof(x)) / sizeof(x[0]))
  414. #endif /* !defined(TOR_UTIL_H) */