1 /* Copyright (c) 2003-2004, Roger Dingledine
2 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
3 * Copyright (c) 2007-2013, The Tor Project, Inc. */
4 /* See LICENSE for licensing information */
8 * \brief Headers for util.c
21 /* for the correct alias to struct stat */
32 /* Replace assert() with a variant that sends failures to the log before
33 * calling assert() normally.
36 /* Nobody should ever want to build with NDEBUG set. 99% of our asserts will
37 * be outside the critical path anyway, so it's silly to disable bug-checking
38 * throughout the entire program just because a few asserts are slowing you
39 * down. Profile, optimize the critical path, and keep debugging on.
41 * And I'm not just saying that because some of our asserts check
42 * security-critical properties.
44 #error "Sorry; we don't support building with NDEBUG."
47 /** Like assert(3), but send assertion failures to the log as well as to
49 #define tor_assert(expr) STMT_BEGIN \
50 if (PREDICT_UNLIKELY(!(expr))) { \
51 log_err(LD_BUG, "%s:%d: %s: Assertion %s failed; aborting.", \
52 SHORT_FILE__, __LINE__, __func__, #expr); \
53 fprintf(stderr,"%s:%d %s: Assertion %s failed; aborting.\n", \
54 SHORT_FILE__, __LINE__, __func__, #expr); \
58 /* If we're building with dmalloc, we want all of our memory allocation
59 * functions to take an extra file/line pair of arguments. If not, not.
60 * We define DMALLOC_PARAMS to the extra parameters to insert in the
61 * function prototypes, and DMALLOC_ARGS to the extra arguments to add
64 #define DMALLOC_PARAMS , const char *file, const int line
65 #define DMALLOC_ARGS , SHORT_FILE__, __LINE__
67 #define DMALLOC_PARAMS
71 /** Define this if you want Tor to crash when any problem comes up,
72 * so you can get a coredump and track things down. */
73 // #define tor_fragile_assert() tor_assert(0)
74 #define tor_fragile_assert()
76 /* Memory management */
77 void *tor_malloc_(size_t size DMALLOC_PARAMS
) ATTR_MALLOC
;
78 void *tor_malloc_zero_(size_t size DMALLOC_PARAMS
) ATTR_MALLOC
;
79 void *tor_calloc_(size_t nmemb
, size_t size DMALLOC_PARAMS
) ATTR_MALLOC
;
80 void *tor_realloc_(void *ptr
, size_t size DMALLOC_PARAMS
);
81 char *tor_strdup_(const char *s DMALLOC_PARAMS
) ATTR_MALLOC
ATTR_NONNULL((1));
82 char *tor_strndup_(const char *s
, size_t n DMALLOC_PARAMS
)
83 ATTR_MALLOC
ATTR_NONNULL((1));
84 void *tor_memdup_(const void *mem
, size_t len DMALLOC_PARAMS
)
85 ATTR_MALLOC
ATTR_NONNULL((1));
86 void tor_free_(void *mem
);
88 extern int dmalloc_free(const char *file
, const int line
, void *pnt
,
90 #define tor_free(p) STMT_BEGIN \
91 if (PREDICT_LIKELY((p)!=NULL)) { \
92 dmalloc_free(SHORT_FILE__, __LINE__, (p), 0); \
97 /** Release memory allocated by tor_malloc, tor_realloc, tor_strdup, etc.
98 * Unlike the free() function, tor_free() will still work on NULL pointers,
99 * and it sets the pointer value to NULL after freeing it.
101 * This is a macro. If you need a function pointer to release memory from
102 * tor_malloc(), use tor_free_().
104 #define tor_free(p) STMT_BEGIN \
105 if (PREDICT_LIKELY((p)!=NULL)) { \
112 #define tor_malloc(size) tor_malloc_(size DMALLOC_ARGS)
113 #define tor_malloc_zero(size) tor_malloc_zero_(size DMALLOC_ARGS)
114 #define tor_calloc(nmemb,size) tor_calloc_(nmemb, size DMALLOC_ARGS)
115 #define tor_realloc(ptr, size) tor_realloc_(ptr, size DMALLOC_ARGS)
116 #define tor_strdup(s) tor_strdup_(s DMALLOC_ARGS)
117 #define tor_strndup(s, n) tor_strndup_(s, n DMALLOC_ARGS)
118 #define tor_memdup(s, n) tor_memdup_(s, n DMALLOC_ARGS)
120 void tor_log_mallinfo(int severity
);
122 /** Return the offset of <b>member</b> within the type <b>tp</b>, in bytes */
123 #if defined(__GNUC__) && __GNUC__ > 3
124 #define STRUCT_OFFSET(tp, member) __builtin_offsetof(tp, member)
126 #define STRUCT_OFFSET(tp, member) \
127 ((off_t) (((char*)&((tp*)0)->member)-(char*)0))
130 /** Macro: yield a pointer to the field at position <b>off</b> within the
131 * structure <b>st</b>. Example:
133 * struct a { int foo; int bar; } x;
134 * off_t bar_offset = STRUCT_OFFSET(struct a, bar);
135 * int *bar_p = STRUCT_VAR_P(&x, bar_offset);
139 #define STRUCT_VAR_P(st, off) ((void*) ( ((char*)(st)) + (off) ) )
141 /** Macro: yield a pointer to an enclosing structure given a pointer to
142 * a substructure at offset <b>off</b>. Example:
144 * struct base { ... };
145 * struct subtype { int x; struct base b; } x;
146 * struct base *bp = &x.base;
147 * struct *sp = SUBTYPE_P(bp, struct subtype, b);
150 #define SUBTYPE_P(p, subtype, basemember) \
151 ((void*) ( ((char*)(p)) - STRUCT_OFFSET(subtype, basemember) ))
154 /** Macro: true if two values have the same boolean value. */
155 #define bool_eq(a,b) (!(a)==!(b))
156 /** Macro: true if two values have different boolean values. */
157 #define bool_neq(a,b) (!(a)!=!(b))
160 double tor_mathlog(double d
) ATTR_CONST
;
161 long tor_lround(double d
) ATTR_CONST
;
162 int64_t tor_llround(double d
) ATTR_CONST
;
163 int tor_log2(uint64_t u64
) ATTR_CONST
;
164 uint64_t round_to_power_of_2(uint64_t u64
);
165 unsigned round_to_next_multiple_of(unsigned number
, unsigned divisor
);
166 uint32_t round_uint32_to_next_multiple_of(uint32_t number
, uint32_t divisor
);
167 uint64_t round_uint64_to_next_multiple_of(uint64_t number
, uint64_t divisor
);
168 int n_bits_set_u8(uint8_t v
);
170 /* Compute the CEIL of <b>a</b> divided by <b>b</b>, for nonnegative <b>a</b>
171 * and positive <b>b</b>. Works on integer types only. Not defined if a+b can
173 #define CEIL_DIV(a,b) (((a)+(b)-1)/(b))
175 /* String manipulation */
177 /** Allowable characters in a hexadecimal string. */
178 #define HEX_CHARACTERS "0123456789ABCDEFabcdef"
179 void tor_strlower(char *s
) ATTR_NONNULL((1));
180 void tor_strupper(char *s
) ATTR_NONNULL((1));
181 int tor_strisprint(const char *s
) ATTR_NONNULL((1));
182 int tor_strisnonupper(const char *s
) ATTR_NONNULL((1));
183 int strcmp_opt(const char *s1
, const char *s2
);
184 int strcmpstart(const char *s1
, const char *s2
) ATTR_NONNULL((1,2));
185 int strcmp_len(const char *s1
, const char *s2
, size_t len
) ATTR_NONNULL((1,2));
186 int strcasecmpstart(const char *s1
, const char *s2
) ATTR_NONNULL((1,2));
187 int strcmpend(const char *s1
, const char *s2
) ATTR_NONNULL((1,2));
188 int strcasecmpend(const char *s1
, const char *s2
) ATTR_NONNULL((1,2));
189 int fast_memcmpstart(const void *mem
, size_t memlen
, const char *prefix
);
190 void tor_strclear(char *s
);
192 void tor_strstrip(char *s
, const char *strip
) ATTR_NONNULL((1,2));
193 long tor_parse_long(const char *s
, int base
, long min
,
194 long max
, int *ok
, char **next
);
195 unsigned long tor_parse_ulong(const char *s
, int base
, unsigned long min
,
196 unsigned long max
, int *ok
, char **next
);
197 double tor_parse_double(const char *s
, double min
, double max
, int *ok
,
199 uint64_t tor_parse_uint64(const char *s
, int base
, uint64_t min
,
200 uint64_t max
, int *ok
, char **next
);
201 const char *hex_str(const char *from
, size_t fromlen
) ATTR_NONNULL((1));
202 const char *eat_whitespace(const char *s
);
203 const char *eat_whitespace_eos(const char *s
, const char *eos
);
204 const char *eat_whitespace_no_nl(const char *s
);
205 const char *eat_whitespace_eos_no_nl(const char *s
, const char *eos
);
206 const char *find_whitespace(const char *s
);
207 const char *find_whitespace_eos(const char *s
, const char *eos
);
208 const char *find_str_at_start_of_line(const char *haystack
,
210 int string_is_C_identifier(const char *string
);
212 int tor_mem_is_zero(const char *mem
, size_t len
);
213 int tor_digest_is_zero(const char *digest
);
214 int tor_digest256_is_zero(const char *digest
);
215 char *esc_for_log(const char *string
) ATTR_MALLOC
;
216 const char *escaped(const char *string
);
218 void wrap_string(struct smartlist_t
*out
, const char *string
, size_t width
,
219 const char *prefix0
, const char *prefixRest
);
220 int tor_vsscanf(const char *buf
, const char *pattern
, va_list ap
)
222 __attribute__((format(scanf
, 2, 0)))
225 int tor_sscanf(const char *buf
, const char *pattern
, ...)
227 __attribute__((format(scanf
, 2, 3)))
231 void smartlist_add_asprintf(struct smartlist_t
*sl
, const char *pattern
, ...)
233 void smartlist_add_vasprintf(struct smartlist_t
*sl
, const char *pattern
,
237 int hex_decode_digit(char c
);
238 void base16_encode(char *dest
, size_t destlen
, const char *src
, size_t srclen
);
239 int base16_decode(char *dest
, size_t destlen
, const char *src
, size_t srclen
);
242 long tv_udiff(const struct timeval
*start
, const struct timeval
*end
);
243 long tv_mdiff(const struct timeval
*start
, const struct timeval
*end
);
244 int tor_timegm(const struct tm
*tm
, time_t *time_out
);
245 #define RFC1123_TIME_LEN 29
246 void format_rfc1123_time(char *buf
, time_t t
);
247 int parse_rfc1123_time(const char *buf
, time_t *t
);
248 #define ISO_TIME_LEN 19
249 #define ISO_TIME_USEC_LEN (ISO_TIME_LEN+7)
250 void format_local_iso_time(char *buf
, time_t t
);
251 void format_iso_time(char *buf
, time_t t
);
252 void format_iso_time_nospace(char *buf
, time_t t
);
253 void format_iso_time_nospace_usec(char *buf
, const struct timeval
*tv
);
254 int parse_iso_time(const char *buf
, time_t *t
);
255 int parse_http_time(const char *buf
, struct tm
*tm
);
256 int format_time_interval(char *out
, size_t out_len
, long interval
);
260 #define approx_time() time(NULL)
261 #define update_approx_time(t) STMT_NIL
263 time_t approx_time(void);
264 void update_approx_time(time_t now
);
269 /** A ratelim_t remembers how often an event is occurring, and how often
270 * it's allowed to occur. Typical usage is something like:
273 if (possibly_very_frequent_event()) {
274 const int INTERVAL = 300;
275 static ratelim_t warning_limit = RATELIM_INIT(INTERVAL);
277 if ((m = rate_limit_log(&warning_limit, approx_time()))) {
278 log_warn(LD_GENERAL, "The event occurred!%s", m);
284 As a convenience wrapper for logging, you can replace the above with:
286 if (possibly_very_frequent_event()) {
287 static ratelim_t warning_limit = RATELIM_INIT(300);
288 log_fn_ratelim(&warning_limit, LOG_WARN, LD_GENERAL,
289 "The event occurred!");
293 typedef struct ratelim_t
{
296 int n_calls_since_last_time
;
299 #define RATELIM_INIT(r) { (r), 0, 0 }
301 char *rate_limit_log(ratelim_t
*lim
, time_t now
);
304 ssize_t
write_all(tor_socket_t fd
, const char *buf
, size_t count
,int isSocket
);
305 ssize_t
read_all(tor_socket_t fd
, char *buf
, size_t count
, int isSocket
);
307 /** Status of an I/O stream. */
315 const char *stream_status_to_string(enum stream_status stream_status
);
317 enum stream_status
get_string_from_pipe(FILE *stream
, char *buf
, size_t count
);
319 /** Return values from file_status(); see that function's documentation
321 typedef enum { FN_ERROR
, FN_NOENT
, FN_FILE
, FN_DIR
} file_status_t
;
322 file_status_t
file_status(const char *filename
);
324 /** Possible behaviors for check_private_dir() on encountering a nonexistent
325 * directory; see that function's documentation for details. */
326 typedef unsigned int cpd_check_t
;
330 #define CPD_GROUP_OK 4
331 #define CPD_CHECK_MODE_ONLY 8
332 int check_private_dir(const char *dirname
, cpd_check_t check
,
333 const char *effective_user
);
334 #define OPEN_FLAGS_REPLACE (O_WRONLY|O_CREAT|O_TRUNC)
335 #define OPEN_FLAGS_APPEND (O_WRONLY|O_CREAT|O_APPEND)
336 #define OPEN_FLAGS_DONT_REPLACE (O_CREAT|O_EXCL|O_APPEND|O_WRONLY)
337 typedef struct open_file_t open_file_t
;
338 int start_writing_to_file(const char *fname
, int open_flags
, int mode
,
339 open_file_t
**data_out
);
340 FILE *start_writing_to_stdio_file(const char *fname
, int open_flags
, int mode
,
341 open_file_t
**data_out
);
342 FILE *fdopen_file(open_file_t
*file_data
);
343 int finish_writing_to_file(open_file_t
*file_data
);
344 int abort_writing_to_file(open_file_t
*file_data
);
345 int write_str_to_file(const char *fname
, const char *str
, int bin
);
346 int write_bytes_to_file(const char *fname
, const char *str
, size_t len
,
348 /** An ad-hoc type to hold a string of characters and a count; used by
349 * write_chunks_to_file. */
350 typedef struct sized_chunk_t
{
354 int write_chunks_to_file(const char *fname
, const struct smartlist_t
*chunks
,
356 int append_bytes_to_file(const char *fname
, const char *str
, size_t len
,
358 int write_bytes_to_new_file(const char *fname
, const char *str
, size_t len
,
361 /** Flag for read_file_to_str: open the file in binary mode. */
363 /** Flag for read_file_to_str: it's okay if the file doesn't exist. */
364 #define RFTS_IGNORE_MISSING 2
369 char *read_file_to_str(const char *filename
, int flags
, struct stat
*stat_out
)
371 char *read_file_to_str_until_eof(int fd
, size_t max_bytes_to_read
,
374 const char *parse_config_line_from_str(const char *line
,
375 char **key_out
, char **value_out
);
376 char *expand_filename(const char *filename
);
377 struct smartlist_t
*tor_listdir(const char *dirname
);
378 int path_is_relative(const char *filename
);
380 /* Process helpers */
381 void start_daemon(void);
382 void finish_daemon(const char *desired_cwd
);
383 void write_pidfile(char *filename
);
385 /* Port forwarding */
386 void tor_check_port_forwarding(const char *filename
,
387 struct smartlist_t
*ports_to_forward
,
390 typedef struct process_handle_t process_handle_t
;
391 typedef struct process_environment_t process_environment_t
;
392 int tor_spawn_background(const char *const filename
, const char **argv
,
393 process_environment_t
*env
,
394 process_handle_t
**process_handle_out
);
396 #define SPAWN_ERROR_MESSAGE "ERR: Failed to spawn background process - code "
399 HANDLE
load_windows_system_library(const TCHAR
*library_name
);
402 int environment_variable_names_equal(const char *s1
, const char *s2
);
404 /* DOCDOC process_environment_t */
405 struct process_environment_t
{
406 /** A pointer to a sorted empty-string-terminated sequence of
407 * NUL-terminated strings of the form "NAME=VALUE". */
408 char *windows_environment_block
;
409 /** A pointer to a NULL-terminated array of pointers to
410 * NUL-terminated strings of the form "NAME=VALUE". */
411 char **unixoid_environment_block
;
414 process_environment_t
*process_environment_make(struct smartlist_t
*env_vars
);
415 void process_environment_free(process_environment_t
*env
);
417 struct smartlist_t
*get_current_process_environment_variables(void);
419 void set_environment_variable_in_smartlist(struct smartlist_t
*env_vars
,
421 void (*free_old
)(void*),
424 /* Values of process_handle_t.status. PROCESS_STATUS_NOTRUNNING must be
425 * 0 because tor_check_port_forwarding depends on this being the initial
426 * statue of the static instance of process_handle_t */
427 #define PROCESS_STATUS_NOTRUNNING 0
428 #define PROCESS_STATUS_RUNNING 1
429 #define PROCESS_STATUS_ERROR -1
432 /** Structure to represent the state of a process with which Tor is
433 * communicating. The contents of this structure are private to util.c */
434 struct process_handle_t
{
435 /** One of the PROCESS_STATUS_* values */
440 PROCESS_INFORMATION pid
;
451 /* Return values of tor_get_exit_code() */
452 #define PROCESS_EXIT_RUNNING 1
453 #define PROCESS_EXIT_EXITED 0
454 #define PROCESS_EXIT_ERROR -1
455 int tor_get_exit_code(const process_handle_t
*process_handle
,
456 int block
, int *exit_code
);
457 int tor_split_lines(struct smartlist_t
*sl
, char *buf
, int len
);
459 ssize_t
tor_read_all_handle(HANDLE h
, char *buf
, size_t count
,
460 const process_handle_t
*process
);
462 ssize_t
tor_read_all_handle(FILE *h
, char *buf
, size_t count
,
463 const process_handle_t
*process
,
466 ssize_t
tor_read_all_from_process_stdout(
467 const process_handle_t
*process_handle
, char *buf
, size_t count
);
468 ssize_t
tor_read_all_from_process_stderr(
469 const process_handle_t
*process_handle
, char *buf
, size_t count
);
470 char *tor_join_win_cmdline(const char *argv
[]);
472 int tor_process_get_pid(process_handle_t
*process_handle
);
474 HANDLE
tor_process_get_stdout_pipe(process_handle_t
*process_handle
);
476 FILE *tor_process_get_stdout_pipe(process_handle_t
*process_handle
);
481 tor_get_lines_from_handle(HANDLE
*handle
,
482 enum stream_status
*stream_status
);
485 tor_get_lines_from_handle(FILE *handle
,
486 enum stream_status
*stream_status
);
489 int tor_terminate_process(process_handle_t
*process_handle
);
490 void tor_process_handle_destroy(process_handle_t
*process_handle
,
491 int also_terminate_process
);
493 /* ===== Insecure rng */
494 typedef struct tor_weak_rng_t
{
498 #define TOR_WEAK_RNG_INIT {383745623}
499 #define TOR_WEAK_RANDOM_MAX (INT_MAX)
500 void tor_init_weak_random(tor_weak_rng_t
*weak_rng
, unsigned seed
);
501 int32_t tor_weak_random(tor_weak_rng_t
*weak_rng
);
502 int32_t tor_weak_random_range(tor_weak_rng_t
*rng
, int32_t top
);
503 /** Randomly return true according to <b>rng</b> with probability 1 in
505 #define tor_weak_random_one_in_n(rng, n) (0==tor_weak_random_range((rng),(n)))
508 /* Prototypes for private functions only used by util.c (and unit tests) */
510 int format_hex_number_for_helper_exit_status(unsigned int x
, char *buf
,
512 int format_helper_exit_status(unsigned char child_state
,
513 int saved_errno
, char *hex_errno
);
515 /* Space for hex values of child state, a slash, saved_errno (with
516 leading minus) and newline (no null) */
517 #define HEX_ERRNO_SIZE (sizeof(char) * 2 + 1 + \
518 1 + sizeof(int) * 2 + 1)
521 const char *libor_get_digests(void);