tor  master
Data Structures | Macros | Typedefs | Enumerations | Functions
util.h File Reference

Headers for util.c. More...

#include "orconfig.h"
#include "torint.h"
#include "compat.h"
#include "di_ops.h"
#include "testsupport.h"
#include <stdio.h>
#include <stdlib.h>
#include "util_bug.h"
Include dependency graph for util.h:

Go to the source code of this file.

Data Structures

struct  ratelim_t
 
struct  sized_chunk_t
 
struct  process_environment_t
 
struct  tor_weak_rng_t
 

Macros

#define O_BINARY   0
 
#define O_TEXT   0
 
#define O_NOFOLLOW   0
 
#define DMALLOC_PARAMS
 
#define DMALLOC_ARGS
 
#define tor_free(p)
 
#define tor_malloc(size)   tor_malloc_(size DMALLOC_ARGS)
 
#define tor_malloc_zero(size)   tor_malloc_zero_(size DMALLOC_ARGS)
 
#define tor_calloc(nmemb, size)   tor_calloc_(nmemb, size DMALLOC_ARGS)
 
#define tor_realloc(ptr, size)   tor_realloc_(ptr, size DMALLOC_ARGS)
 
#define tor_reallocarray(ptr, sz1, sz2)   tor_reallocarray_((ptr), (sz1), (sz2) DMALLOC_ARGS)
 
#define tor_strdup(s)   tor_strdup_(s DMALLOC_ARGS)
 
#define tor_strndup(s, n)   tor_strndup_(s, n DMALLOC_ARGS)
 
#define tor_memdup(s, n)   tor_memdup_(s, n DMALLOC_ARGS)
 
#define tor_memdup_nulterm(s, n)   tor_memdup_nulterm_(s, n DMALLOC_ARGS)
 
#define raw_malloc   malloc
 
#define raw_realloc   realloc
 
#define raw_free   free
 
#define raw_strdup   strdup
 
#define FREE_AND_NULL(typename, freefn, var)
 
#define STRUCT_VAR_P(st, off)   ((void*) ( ((char*)(st)) + (off) ) )
 
#define SUBTYPE_P(p, subtype, basemember)   ((void*) ( ((char*)(p)) - offsetof(subtype, basemember) ))
 
#define bool_eq(a, b)   (!(a)==!(b))
 
#define bool_neq(a, b)   (!(a)!=!(b))
 
#define CEIL_DIV(a, b)   (((a)+((b)-1))/(b))
 
#define CLAMP(min, v, max)
 
#define HEX_CHARACTERS   "0123456789ABCDEFabcdef"
 
#define RFC1123_TIME_LEN   29
 
#define ISO_TIME_LEN   19
 
#define ISO_TIME_USEC_LEN   (ISO_TIME_LEN+7)
 
#define RATELIM_INIT(r)   { (r), 0, 0 }
 
#define RATELIM_TOOMANY   (16*1000*1000)
 
#define CPD_NONE   0
 
#define CPD_CREATE   (1u << 0)
 
#define CPD_CHECK   (1u << 1)
 
#define CPD_GROUP_OK   (1u << 2)
 
#define CPD_GROUP_READ   (1u << 3)
 
#define CPD_CHECK_MODE_ONLY   (1u << 4)
 
#define CPD_RELAX_DIRMODE_CHECK   (1u << 5)
 
#define OPEN_FLAGS_REPLACE   (O_WRONLY|O_CREAT|O_TRUNC)
 
#define OPEN_FLAGS_APPEND   (O_WRONLY|O_CREAT|O_APPEND)
 
#define OPEN_FLAGS_DONT_REPLACE   (O_CREAT|O_EXCL|O_APPEND|O_WRONLY)
 
#define RFTS_BIN   1
 
#define RFTS_IGNORE_MISSING   2
 
#define SPAWN_ERROR_MESSAGE   "ERR: Failed to spawn background process - code "
 
#define process_environment_free(env)   FREE_AND_NULL(process_environment_t, process_environment_free_, (env))
 
#define PROCESS_STATUS_NOTRUNNING   0
 
#define PROCESS_STATUS_RUNNING   1
 
#define PROCESS_STATUS_ERROR   -1
 
#define PROCESS_EXIT_RUNNING   1
 
#define PROCESS_EXIT_EXITED   0
 
#define PROCESS_EXIT_ERROR   -1
 
#define TOR_WEAK_RNG_INIT   {383745623}
 
#define TOR_WEAK_RANDOM_MAX   (INT_MAX)
 
#define tor_weak_random_one_in_n(rng, n)   (0==tor_weak_random_range((rng),(n)))
 
#define ARRAY_LENGTH(x)   ((sizeof(x)) / sizeof(x[0]))
 

Typedefs

typedef struct ratelim_t ratelim_t
 
typedef unsigned int cpd_check_t
 
typedef struct open_file_t open_file_t
 
typedef struct sized_chunk_t sized_chunk_t
 
typedef struct process_handle_t process_handle_t
 
typedef struct process_environment_t process_environment_t
 
typedef struct tor_weak_rng_t tor_weak_rng_t
 

Enumerations

enum  stream_status { IO_STREAM_OKAY, IO_STREAM_EAGAIN, IO_STREAM_TERM, IO_STREAM_CLOSED }
 
enum  file_status_t {
  FN_ERROR, FN_NOENT, FN_FILE, FN_DIR,
  FN_EMPTY
}
 

Functions

void * tor_malloc_ (size_t size DMALLOC_PARAMS) ATTR_MALLOC
 
void * tor_malloc_zero_ (size_t size DMALLOC_PARAMS) ATTR_MALLOC
 
void * tor_calloc_ (size_t nmemb, size_t size DMALLOC_PARAMS) ATTR_MALLOC
 
void * tor_realloc_ (void *ptr, size_t size DMALLOC_PARAMS)
 
void * tor_reallocarray_ (void *ptr, size_t size1, size_t size2 DMALLOC_PARAMS)
 
char * tor_strdup_ (const char *s DMALLOC_PARAMS) ATTR_MALLOC ATTR_NONNULL((1))
 
char * tor_strndup_ (const char *s, size_t n DMALLOC_PARAMS) ATTR_MALLOC ATTR_NONNULL((1))
 
void * tor_memdup_ (const void *mem, size_t len DMALLOC_PARAMS) ATTR_MALLOC ATTR_NONNULL((1))
 
void * tor_memdup_nulterm_ (const void *mem, size_t len DMALLOC_PARAMS) ATTR_MALLOC ATTR_NONNULL((1))
 
void tor_free_ (void *mem)
 
uint64_t tor_htonll (uint64_t a)
 
uint64_t tor_ntohll (uint64_t a)
 
void tor_log_mallinfo (int severity)
 
double tor_mathlog (double d) ATTR_CONST
 
long tor_lround (double d) ATTR_CONST
 
int64_t tor_llround (double d) ATTR_CONST
 
int tor_log2 (uint64_t u64) ATTR_CONST
 
uint64_t round_to_power_of_2 (uint64_t u64)
 
unsigned round_to_next_multiple_of (unsigned number, unsigned divisor)
 
uint32_t round_uint32_to_next_multiple_of (uint32_t number, uint32_t divisor)
 
uint64_t round_uint64_to_next_multiple_of (uint64_t number, uint64_t divisor)
 
int64_t sample_laplace_distribution (double mu, double b, double p)
 
int64_t add_laplace_noise (int64_t signal, double random, double delta_f, double epsilon)
 
int n_bits_set_u8 (uint8_t v)
 
int64_t clamp_double_to_int64 (double number)
 
void simplify_fraction64 (uint64_t *numer, uint64_t *denom)
 
uint32_t tor_add_u32_nowrap (uint32_t a, uint32_t b)
 
void tor_strlower (char *s) ATTR_NONNULL((1))
 
void tor_strupper (char *s) ATTR_NONNULL((1))
 
int tor_strisprint (const char *s) ATTR_NONNULL((1))
 
int tor_strisnonupper (const char *s) ATTR_NONNULL((1))
 
int tor_strisspace (const char *s)
 
int strcmp_opt (const char *s1, const char *s2)
 
int strcmpstart (const char *s1, const char *s2) ATTR_NONNULL((1
 
int int strcmp_len (const char *s1, const char *s2, size_t len) ATTR_NONNULL((1
 
int int int strcasecmpstart (const char *s1, const char *s2) ATTR_NONNULL((1
 
int int int int strcmpend (const char *s1, const char *s2) ATTR_NONNULL((1
 
int int int int int strcasecmpend (const char *s1, const char *s2) ATTR_NONNULL((1
 
int int int int int int fast_memcmpstart (const void *mem, size_t memlen, const char *prefix)
 
void tor_strstrip (char *s, const char *strip) ATTR_NONNULL((1
 
void long tor_parse_long (const char *s, int base, long min, long max, int *ok, char **next)
 
unsigned long tor_parse_ulong (const char *s, int base, unsigned long min, unsigned long max, int *ok, char **next)
 
double tor_parse_double (const char *s, double min, double max, int *ok, char **next)
 
uint64_t tor_parse_uint64 (const char *s, int base, uint64_t min, uint64_t max, int *ok, char **next)
 
const char * hex_str (const char *from, size_t fromlen) ATTR_NONNULL((1))
 
const char * eat_whitespace (const char *s)
 
const char * eat_whitespace_eos (const char *s, const char *eos)
 
const char * eat_whitespace_no_nl (const char *s)
 
const char * eat_whitespace_eos_no_nl (const char *s, const char *eos)
 
const char * find_whitespace (const char *s)
 
const char * find_whitespace_eos (const char *s, const char *eos)
 
const char * find_str_at_start_of_line (const char *haystack, const char *needle)
 
int string_is_C_identifier (const char *string)
 
int string_is_key_value (int severity, const char *string)
 
int string_is_valid_dest (const char *string)
 
int string_is_valid_nonrfc_hostname (const char *string)
 
int string_is_valid_ipv4_address (const char *string)
 
int string_is_valid_ipv6_address (const char *string)
 
int tor_mem_is_zero (const char *mem, size_t len)
 
int tor_digest_is_zero (const char *digest)
 
int tor_digest256_is_zero (const char *digest)
 
char * esc_for_log (const char *string) ATTR_MALLOC
 
char * esc_for_log_len (const char *chars, size_t n) ATTR_MALLOC
 
const char * escaped (const char *string)
 
char * tor_escape_str_for_pt_args (const char *string, const char *chars_to_escape)
 
int tor_vsscanf (const char *buf, const char *pattern, va_list ap) CHECK_SCANF(2
 
int int tor_sscanf (const char *buf, const char *pattern,...) CHECK_SCANF(2
 
int int void smartlist_add_asprintf (struct smartlist_t *sl, const char *pattern,...) CHECK_PRINTF(2
 
int int void void smartlist_add_vasprintf (struct smartlist_t *sl, const char *pattern, va_list args) CHECK_PRINTF(2
 
int int void void void smartlist_add_strdup (struct smartlist_t *sl, const char *string)
 
long tv_udiff (const struct timeval *start, const struct timeval *end)
 
long tv_mdiff (const struct timeval *start, const struct timeval *end)
 
int64_t tv_to_msec (const struct timeval *tv)
 
int tor_timegm (const struct tm *tm, time_t *time_out)
 
void format_rfc1123_time (char *buf, time_t t)
 
int parse_rfc1123_time (const char *buf, time_t *t)
 
void format_local_iso_time (char *buf, time_t t)
 
void format_iso_time (char *buf, time_t t)
 
void format_local_iso_time_nospace (char *buf, time_t t)
 
void format_iso_time_nospace (char *buf, time_t t)
 
void format_iso_time_nospace_usec (char *buf, const struct timeval *tv)
 
int parse_iso_time_ (const char *cp, time_t *t, int strict, int nospace)
 
int parse_iso_time (const char *buf, time_t *t)
 
int parse_iso_time_nospace (const char *cp, time_t *t)
 
int parse_http_time (const char *buf, struct tm *tm)
 
int format_time_interval (char *out, size_t out_len, long interval)
 
time_t approx_time (void)
 
void update_approx_time (time_t now)
 
char * rate_limit_log (ratelim_t *lim, time_t now)
 
ssize_t write_all (tor_socket_t fd, const char *buf, size_t count, int isSocket)
 
ssize_t read_all (tor_socket_t fd, char *buf, size_t count, int isSocket)
 
const char * stream_status_to_string (enum stream_status stream_status)
 
enum stream_status get_string_from_pipe (int fd, char *buf, size_t count)
 
 MOCK_DECL (int, tor_unlink,(const char *pathname))
 
file_status_t file_status (const char *filename)
 
 MOCK_DECL (int, check_private_dir,(const char *dirname, cpd_check_t check, const char *effective_user))
 
int start_writing_to_file (const char *fname, int open_flags, int mode, open_file_t **data_out)
 
FILE * start_writing_to_stdio_file (const char *fname, int open_flags, int mode, open_file_t **data_out)
 
FILE * fdopen_file (open_file_t *file_data)
 
int finish_writing_to_file (open_file_t *file_data)
 
int abort_writing_to_file (open_file_t *file_data)
 
 MOCK_DECL (int, write_str_to_file,(const char *fname, const char *str, int bin))
 
 MOCK_DECL (int, write_bytes_to_file,(const char *fname, const char *str, size_t len, int bin))
 
int write_chunks_to_file (const char *fname, const struct smartlist_t *chunks, int bin, int no_tempfile)
 
int append_bytes_to_file (const char *fname, const char *str, size_t len, int bin)
 
int write_bytes_to_new_file (const char *fname, const char *str, size_t len, int bin)
 
 MOCK_DECL_ATTR (char *, read_file_to_str,(const char *filename, int flags, struct stat *stat_out), ATTR_MALLOC)
 
char * read_file_to_str_until_eof (int fd, size_t max_bytes_to_read, size_t *sz_out) ATTR_MALLOC
 
const char * unescape_string (const char *s, char **result, size_t *size_out)
 
char * get_unquoted_path (const char *path)
 
char * expand_filename (const char *filename)
 
 MOCK_DECL (struct smartlist_t *, tor_listdir,(const char *dirname))
 
int path_is_relative (const char *filename)
 
void start_daemon (void)
 
void finish_daemon (const char *desired_cwd)
 
int write_pidfile (const char *filename)
 
void tor_disable_spawning_background_processes (void)
 
int tor_spawn_background (const char *const filename, const char **argv, process_environment_t *env, process_handle_t **process_handle_out)
 
int environment_variable_names_equal (const char *s1, const char *s2)
 
process_environment_tprocess_environment_make (struct smartlist_t *env_vars)
 
void process_environment_free_ (process_environment_t *env)
 
struct smartlist_tget_current_process_environment_variables (void)
 
void set_environment_variable_in_smartlist (struct smartlist_t *env_vars, const char *new_var, void(*free_old)(void *), int free_p)
 
int tor_get_exit_code (process_handle_t *process_handle, int block, int *exit_code)
 
int tor_split_lines (struct smartlist_t *sl, char *buf, int len)
 
ssize_t tor_read_all_handle (int fd, char *buf, size_t count, const process_handle_t *process, int *eof)
 
ssize_t tor_read_all_from_process_stdout (const process_handle_t *process_handle, char *buf, size_t count)
 
ssize_t tor_read_all_from_process_stderr (const process_handle_t *process_handle, char *buf, size_t count)
 
char * tor_join_win_cmdline (const char *argv[])
 
int tor_process_get_pid (process_handle_t *process_handle)
 
int tor_process_get_stdout_pipe (process_handle_t *process_handle)
 
 MOCK_DECL (struct smartlist_t *, tor_get_lines_from_handle,(int fd, enum stream_status *stream_status))
 
int tor_terminate_process (process_handle_t *process_handle)
 
 MOCK_DECL (void, tor_process_handle_destroy,(process_handle_t *process_handle, int also_terminate_process))
 
void tor_init_weak_random (tor_weak_rng_t *weak_rng, unsigned seed)
 
int32_t tor_weak_random (tor_weak_rng_t *weak_rng)
 
int32_t tor_weak_random_range (tor_weak_rng_t *rng, int32_t top)
 
int format_hex_number_sigsafe (unsigned long x, char *buf, int max_len)
 
int format_dec_number_sigsafe (unsigned long x, char *buf, int max_len)
 
int size_mul_check (const size_t x, const size_t y)
 

Detailed Description

Headers for util.c.

Macro Definition Documentation

◆ bool_eq

#define bool_eq (   a,
 
)    (!(a)==!(b))

Macro: true if two values have the same boolean value.

◆ bool_neq

#define bool_neq (   a,
 
)    (!(a)!=!(b))

Macro: true if two values have different boolean values.

◆ CLAMP

#define CLAMP (   min,
  v,
  max 
)
Value:
( ((v) < (min)) ? (min) : \
((v) > (max)) ? (max) : \
(v) )

◆ FREE_AND_NULL

#define FREE_AND_NULL (   typename,
  freefn,
  var 
)
Value:
do { \
/* only evaluate (var) once. */ \
typename **tmp__free__ptr ## freefn = &(var); \
freefn(*tmp__free__ptr ## freefn); \
(*tmp__free__ptr ## freefn) = NULL; \
} while (0)

◆ HEX_CHARACTERS

#define HEX_CHARACTERS   "0123456789ABCDEFabcdef"

Allowable characters in a hexadecimal string.

◆ RFTS_BIN

#define RFTS_BIN   1

Flag for read_file_to_str: open the file in binary mode.

◆ RFTS_IGNORE_MISSING

#define RFTS_IGNORE_MISSING   2

Flag for read_file_to_str: it's okay if the file doesn't exist.

◆ STRUCT_VAR_P

#define STRUCT_VAR_P (   st,
  off 
)    ((void*) ( ((char*)(st)) + (off) ) )

Macro: yield a pointer to the field at position off within the structure st. Example:

  struct a { int foo; int bar; } x;
  off_t bar_offset = offsetof(struct a, bar);
  int *bar_p = STRUCT_VAR_P(&x, bar_offset);
  *bar_p = 3;

◆ SUBTYPE_P

#define SUBTYPE_P (   p,
  subtype,
  basemember 
)    ((void*) ( ((char*)(p)) - offsetof(subtype, basemember) ))

Macro: yield a pointer to an enclosing structure given a pointer to a substructure at offset off. Example:

  struct base { ... };
  struct subtype { int x; struct base b; } x;
  struct base *bp = &x.base;
  struct *sp = SUBTYPE_P(bp, struct subtype, b);

◆ tor_free

#define tor_free (   p)
Value:
STMT_BEGIN \
raw_free(p); \
(p)=NULL; \
STMT_END

Release memory allocated by tor_malloc, tor_realloc, tor_strdup, etc. Unlike the free() function, the tor_free() macro sets the pointer value to NULL after freeing it.

This is a macro. If you need a function pointer to release memory from tor_malloc(), use tor_free_().

Note that this macro takes the address of the pointer it is going to free and clear. If that pointer is stored with a nonstandard alignment (eg because of a "packed" pragma) it is not correct to use tor_free().

◆ tor_weak_random_one_in_n

#define tor_weak_random_one_in_n (   rng,
 
)    (0==tor_weak_random_range((rng),(n)))

Randomly return true according to rng with probability 1 in n

Typedef Documentation

◆ cpd_check_t

typedef unsigned int cpd_check_t

Possible behaviors for check_private_dir() on encountering a nonexistent directory; see that function's documentation for details.

◆ ratelim_t

typedef struct ratelim_t ratelim_t

A ratelim_t remembers how often an event is occurring, and how often it's allowed to occur. Typical usage is something like:

 if (possibly_very_frequent_event()) {
   const int INTERVAL = 300;
   static ratelim_t warning_limit = RATELIM_INIT(INTERVAL);
   char *m;
   if ((m = rate_limit_log(&warning_limit, approx_time()))) {
     log_warn(LD_GENERAL, "The event occurred!%s", m);
     tor_free(m);
   }
 }

As a convenience wrapper for logging, you can replace the above with:

if (possibly_very_frequent_event()) {
  static ratelim_t warning_limit = RATELIM_INIT(300);
  log_fn_ratelim(&warning_limit, LOG_WARN, LD_GENERAL,
                 "The event occurred!");
}

◆ sized_chunk_t

typedef struct sized_chunk_t sized_chunk_t

An ad-hoc type to hold a string of characters and a count; used by write_chunks_to_file.

Enumeration Type Documentation

◆ file_status_t

Return values from file_status(); see that function's documentation for details.

◆ stream_status

Status of an I/O stream.

Function Documentation

◆ abort_writing_to_file()

int abort_writing_to_file ( open_file_t file_data)

Finish writing to file_data: close the file handle, free memory as needed, and if using a temporary file, delete it.

Here is the caller graph for this function:

◆ add_laplace_noise()

int64_t add_laplace_noise ( int64_t  signal_,
double  random_,
double  delta_f,
double  epsilon 
)

Add random noise between INT64_MIN and INT64_MAX coming from a Laplace distribution with mu = 0 and b = delta_f/epsilon to signal based on the provided random value in [0.0, 1.0[. The epsilon value must be between ]0.0, 1.0]. delta_f must be greater than 0.

Here is the call graph for this function:

◆ append_bytes_to_file()

int append_bytes_to_file ( const char *  fname,
const char *  str,
size_t  len,
int  bin 
)

As write_bytes_to_file, but if the file already exists, append the bytes to the end of the file instead of overwriting it.

◆ approx_time()

time_t approx_time ( void  )

Return a cached estimate of the current time from when update_approx_time() was last called. This is a hack to avoid calling time(NULL) on critical paths: please do not even think of calling it anywhere else.

Here is the caller graph for this function:

◆ clamp_double_to_int64()

int64_t clamp_double_to_int64 ( double  number)

Cast a given double value to a int64_t. Return 0 if number is NaN. Returns either INT64_MIN or INT64_MAX if number is outside of the int64_t range.

◆ eat_whitespace()

const char* eat_whitespace ( const char *  s)

Return a pointer to the first char of s that is not whitespace and not a comment, or to the terminating NUL if no such character exists.

Here is the caller graph for this function:

◆ eat_whitespace_eos()

const char* eat_whitespace_eos ( const char *  s,
const char *  eos 
)

Return a pointer to the first char of s that is not whitespace and not a comment, or to the terminating NUL if no such character exists.

◆ eat_whitespace_eos_no_nl()

const char* eat_whitespace_eos_no_nl ( const char *  s,
const char *  eos 
)

As eat_whitespace_no_nl, but stop at eos whether we have found a non-whitespace character or not.

◆ eat_whitespace_no_nl()

const char* eat_whitespace_no_nl ( const char *  s)

Return a pointer to the first char of s that is not a space or a tab or a \r, or to the terminating NUL if no such character exists.

Here is the caller graph for this function:

◆ environment_variable_names_equal()

int environment_variable_names_equal ( const char *  s1,
const char *  s2 
)

Return non-zero iff getenv would consider s1 and s2 to have the same name as strings in a process's environment.

Here is the caller graph for this function:

◆ esc_for_log()

char* esc_for_log ( const char *  s)

Allocate and return a new string representing the contents of s, surrounded by quotes and using standard C escapes.

Generally, we use this for logging values that come in over the network to keep them from tricking users, and for sending certain values to the controller.

We trust values from the resolver, OS, configuration file, and command line to not be maliciously ill-formed. We validate incoming routerdescs and SOCKS requests and addresses from BEGIN cells as they're parsed; afterwards, we trust them as non-malicious.

Here is the caller graph for this function:

◆ esc_for_log_len()

char* esc_for_log_len ( const char *  chars,
size_t  n 
)

Similar to esc_for_log. Allocate and return a new string representing the first n characters in chars, surround by quotes and using standard C escapes. If a NUL character is encountered in chars, the resulting string will be terminated there.

◆ escaped()

const char* escaped ( const char *  s)

Allocate and return a new string representing the contents of s, surrounded by quotes and using standard C escapes.

THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main thread. Also, each call invalidates the last-returned value, so don't try log_warn(LD_GENERAL, "%s %s", escaped(a), escaped(b));

Here is the call graph for this function:
Here is the caller graph for this function:

◆ expand_filename()

char* expand_filename ( const char *  filename)

Expand any homedir prefix on filename; return a newly allocated string.

◆ fast_memcmpstart()

int int int int int int fast_memcmpstart ( const void *  mem,
size_t  memlen,
const char *  prefix 
)

Compare the value of the string prefix with the start of the memlen-byte memory chunk at mem. Return as for strcmp.

[As fast_memcmp(mem, prefix, strlen(prefix)) but returns -1 if memlen is less than strlen(prefix).]

◆ fdopen_file()

FILE* fdopen_file ( open_file_t file_data)

Given file_data from start_writing_to_file(), return a stdio FILE* that can be used to write to the same file. The caller should not mix stdio calls with non-stdio calls.

Here is the caller graph for this function:

◆ file_status()

file_status_t file_status ( const char *  fname)

Return: FN_ERROR if filename can't be read, is NULL, or is zero-length, FN_NOENT if it doesn't exist, FN_FILE if it is a non-empty regular file, or a FIFO on unix-like systems, FN_EMPTY for zero-byte regular files, FN_DIR if it's a directory, and FN_ERROR for any other file type. On FN_ERROR and FN_NOENT, sets errno. (errno is not set when FN_ERROR is returned due to an unhandled file type.)

Here is the caller graph for this function:

◆ find_str_at_start_of_line()

const char* find_str_at_start_of_line ( const char *  haystack,
const char *  needle 
)

Return the first occurrence of needle in haystack that occurs at the start of a line (that is, at the beginning of haystack or immediately after a newline). Return NULL if no such string is found.

◆ find_whitespace()

const char* find_whitespace ( const char *  s)

Return a pointer to the first char of s that is whitespace or #, or to the terminating NUL if no such character exists.

Here is the caller graph for this function:

◆ find_whitespace_eos()

const char* find_whitespace_eos ( const char *  s,
const char *  eos 
)

As find_whitespace, but stop at eos whether we have found a whitespace or not.

◆ finish_daemon()

void finish_daemon ( const char *  desired_cwd)

Finish putting the process into daemon mode: drop standard fds, and tell the parent process to exit. (Note: it's safe to call this more than once: calls after the first are ignored. Calls start_daemon first if it hasn't been called already.)

Here is the call graph for this function:

◆ finish_writing_to_file()

int finish_writing_to_file ( open_file_t file_data)

Finish writing to file_data: close the file handle, free memory as needed, and if using a temporary file, replace the original file with the temporary file.

◆ format_dec_number_sigsafe()

int format_dec_number_sigsafe ( unsigned long  x,
char *  buf,
int  buf_len 
)

As format_hex_number_sigsafe, but format the number in base 10.

Here is the caller graph for this function:

◆ format_hex_number_sigsafe()

int format_hex_number_sigsafe ( unsigned long  x,
char *  buf,
int  buf_len 
)

Helper function to output hex numbers from within a signal handler.

Writes the nul-terminated hexadecimal digits of x into a buffer buf of size buf_len, and return the actual number of digits written, not counting the terminal NUL.

If there is insufficient space, write nothing and return 0.

This accepts an unsigned int because format_helper_exit_status() needs to call it with a signed int and an unsigned char, and since the C standard does not guarantee that an int is wider than a char (an int must be at least 16 bits but it is permitted for a char to be that wide as well), we can't assume a signed int is sufficient to accommodate an unsigned char. Thus, format_helper_exit_status() will still need to emit any require '-' on its own.

For most purposes, you'd want to use tor_snprintf("%x") instead of this function; it's designed to be used in code paths where you can't call arbitrary C functions.

Here is the caller graph for this function:

◆ format_iso_time()

void format_iso_time ( char *  buf,
time_t  t 
)

Set buf to the ISO8601 encoding of the GMT value of t. The buffer must be at least ISO_TIME_LEN+1 bytes long.

Here is the caller graph for this function:

◆ format_iso_time_nospace()

void format_iso_time_nospace ( char *  buf,
time_t  t 
)

As format_iso_time, but use the yyyy-mm-ddThh:mm:ss format to avoid embedding an internal space.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ format_iso_time_nospace_usec()

void format_iso_time_nospace_usec ( char *  buf,
const struct timeval tv 
)

As format_iso_time_nospace, but include microseconds in decimal fixed-point format. Requires that buf be at least ISO_TIME_USEC_LEN+1 bytes long.

Here is the call graph for this function:

◆ format_local_iso_time()

void format_local_iso_time ( char *  buf,
time_t  t 
)

Set buf to the ISO8601 encoding of the local value of t. The buffer must be at least ISO_TIME_LEN+1 bytes long.

(ISO8601 format is 2006-10-29 10:57:20)

Here is the caller graph for this function:

◆ format_local_iso_time_nospace()

void format_local_iso_time_nospace ( char *  buf,
time_t  t 
)

As format_local_iso_time, but use the yyyy-mm-ddThh:mm:ss format to avoid embedding an internal space.

Here is the call graph for this function:

◆ format_rfc1123_time()

void format_rfc1123_time ( char *  buf,
time_t  t 
)

Set buf to the RFC1123 encoding of the UTC value of t. The buffer must be at least RFC1123_TIME_LEN+1 bytes long.

(RFC1123 format is "Fri, 29 Sep 2006 15:54:20 GMT". Note the "GMT" rather than "UTC".)

Here is the call graph for this function:

◆ format_time_interval()

int format_time_interval ( char *  out,
size_t  out_len,
long  interval 
)

Given an interval in seconds, try to write it to the out_len-byte buffer in out in a human-readable form. Returns a non-negative integer on success, -1 on failure.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ get_current_process_environment_variables()

struct smartlist_t* get_current_process_environment_variables ( void  )

Return a newly allocated smartlist containing every variable in this process's environment, as a NUL-terminated string of the form "NAME=VALUE". Note that on some/many/most/all OSes, the parent process can put strings not of that form in our environment; callers should try to not get crashed by that.

The returned strings are heap-allocated, and must be freed by the caller.

Here is the call graph for this function:

◆ get_string_from_pipe()

enum stream_status get_string_from_pipe ( int  fd,
char *  buf_out,
size_t  count 
)

Reads from fd and stores input in buf_out making sure it's below count bytes. If the string has a trailing newline, we strip it off.

This function is specifically created to handle input from managed proxies, according to the pluggable transports spec. Make sure it fits your needs before using it.

Returns: IO_STREAM_CLOSED: If the stream is closed. IO_STREAM_EAGAIN: If there is nothing to read and we should check back later. IO_STREAM_TERM: If something is wrong with the stream. IO_STREAM_OKAY: If everything went okay and we got a string in buf_out.

Here is the caller graph for this function:

◆ get_unquoted_path()

char* get_unquoted_path ( const char *  path)

Removes enclosing quotes from path and unescapes quotes between the enclosing quotes. Backslashes are not unescaped. Return the unquoted path on success or 0 if path is not quoted correctly.

◆ hex_str()

const char* hex_str ( const char *  from,
size_t  fromlen 
)

Return a pointer to a NUL-terminated hexadecimal string encoding the first fromlen bytes of from. (fromlen must be <= 32.) The result does not need to be deallocated, but repeated calls to hex_str will trash old results.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ n_bits_set_u8()

int n_bits_set_u8 ( uint8_t  v)

Return the number of bits set in v.

◆ parse_http_time()

int parse_http_time ( const char *  date,
struct tm *  tm 
)

Given a date in one of the three formats allowed by HTTP (ugh), parse it into tm. Return 0 on success, negative on failure.

Here is the call graph for this function:

◆ parse_iso_time()

int parse_iso_time ( const char *  cp,
time_t *  t 
)

Given an ISO-formatted UTC time value (after the epoch) in cp, parse it and store its value in *t. Return 0 on success, -1 on failure. Reject the string if any characters are present after the time.

Here is the call graph for this function:

◆ parse_iso_time_()

int parse_iso_time_ ( const char *  cp,
time_t *  t,
int  strict,
int  nospace 
)

Given an ISO-formatted UTC time value (after the epoch) in cp, parse it and store its value in *t. Return 0 on success, -1 on failure. Ignore extraneous stuff in cp after the end of the time string, unless strict is set. If nospace is set, expect the YYYY-MM-DDTHH:MM:SS format.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ parse_iso_time_nospace()

int parse_iso_time_nospace ( const char *  cp,
time_t *  t 
)

As parse_iso_time, but parses a time encoded by format_iso_time_nospace().

Here is the call graph for this function:

◆ parse_rfc1123_time()

int parse_rfc1123_time ( const char *  buf,
time_t *  t 
)

Parse the (a subset of) the RFC1123 encoding of some time (in UTC) from buf, and store the result in *t.

Note that we only accept the subset generated by format_rfc1123_time above, not the full range of formats suggested by RFC 1123.

Return 0 on success, -1 on failure.

◆ path_is_relative()

int path_is_relative ( const char *  filename)

Return true iff filename is a relative path.

◆ process_environment_free_()

void process_environment_free_ ( process_environment_t env)

Free env (assuming it was produced by process_environment_make).

◆ process_environment_make()

process_environment_t* process_environment_make ( struct smartlist_t env_vars)

Make a process_environment_t containing the environment variables specified in env_vars (as C strings of the form "NAME=VALUE").

◆ rate_limit_log()

char* rate_limit_log ( ratelim_t lim,
time_t  now 
)

If the rate-limiter lim is ready at now, return a newly allocated string indicating how many messages were suppressed, suitable to append to a log message. Otherwise return NULL.

◆ read_all()

ssize_t read_all ( tor_socket_t  fd,
char *  buf,
size_t  count,
int  isSocket 
)

Read from fd to buf, until we get count bytes or reach the end of the file. isSocket must be 1 if fd was returned by socket() or accept(), and 0 if fd was returned by open(). Return the number of bytes read, or -1 on error. Only use if fd is a blocking fd.

◆ read_file_to_str_until_eof()

char* read_file_to_str_until_eof ( int  fd,
size_t  max_bytes_to_read,
size_t *  sz_out 
)

Read the contents of the open file fd presuming it is a FIFO (or similar) file descriptor for which the size of the file isn't known ahead of time. Return NULL on failure, and a NUL-terminated string on success. On success, set sz_out to the number of bytes read.

◆ round_to_next_multiple_of()

unsigned round_to_next_multiple_of ( unsigned  number,
unsigned  divisor 
)

Return the lowest x such that x is at least number, and x modulo divisor == 0. If no such x can be expressed as an unsigned, return UINT_MAX. Asserts if divisor is zero.

◆ round_to_power_of_2()

uint64_t round_to_power_of_2 ( uint64_t  u64)

Return the power of 2 in range [1,UINT64_MAX] closest to u64. If there are two powers of 2 equally close, round down.

Here is the call graph for this function:

◆ round_uint32_to_next_multiple_of()

uint32_t round_uint32_to_next_multiple_of ( uint32_t  number,
uint32_t  divisor 
)

Return the lowest x such that x is at least number, and x modulo divisor == 0. If no such x can be expressed as a uint32_t, return UINT32_MAX. Asserts if divisor is zero.

◆ round_uint64_to_next_multiple_of()

uint64_t round_uint64_to_next_multiple_of ( uint64_t  number,
uint64_t  divisor 
)

Return the lowest x such that x is at least number, and x modulo divisor == 0. If no such x can be expressed as a uint64_t, return UINT64_MAX. Asserts if divisor is zero.

◆ sample_laplace_distribution()

int64_t sample_laplace_distribution ( double  mu,
double  b,
double  p 
)

Transform a random value p from the uniform distribution in [0.0, 1.0[ into a Laplace distributed value with location parameter mu and scale parameter b. Truncate the final result to be an integer in [INT64_MIN, INT64_MAX].

Here is the caller graph for this function:

◆ set_environment_variable_in_smartlist()

void set_environment_variable_in_smartlist ( struct smartlist_t env_vars,
const char *  new_var,
void(*)(void *)  free_old,
int  free_p 
)

For each string s in env_vars such that environment_variable_names_equal(s, new_var), remove it; if free_p is non-zero, call free_old(s). If new_var contains '=', insert it into env_vars.

Here is the call graph for this function:

◆ size_mul_check()

int size_mul_check ( const size_t  x,
const size_t  y 
)

Return non-zero if and only if the product of the arguments is exact, and cannot overflow.

◆ smartlist_add_strdup()

int int void void void smartlist_add_strdup ( struct smartlist_t sl,
const char *  string 
)

Append a copy of string to sl

Here is the caller graph for this function:

◆ start_daemon()

void start_daemon ( void  )

Start putting the process into daemon mode: fork and drop all resources except standard fds. The parent process never returns, but stays around until finish_daemon is called. (Note: it's safe to call this more than once: calls after the first are ignored.)

Here is the caller graph for this function:

◆ start_writing_to_file()

int start_writing_to_file ( const char *  fname,
int  open_flags,
int  mode,
open_file_t **  data_out 
)

Try to start writing to the file in fname, passing the flags open_flags to the open() syscall, creating the file (if needed) with access value mode. If the O_APPEND flag is set, we append to the original file. Otherwise, we open a new temporary file in the same directory, and either replace the original or remove the temporary file when we're done.

Return the fd for the newly opened file, and store working data in *data_out. The caller should not close the fd manually: instead, call finish_writing_to_file() or abort_writing_to_file(). Returns -1 on failure.

NOTE: When not appending, the flags O_CREAT and O_TRUNC are treated as true and the flag O_EXCL is treated as false.

NOTE: Ordinarily, O_APPEND means "seek to the end of the file before each write()". We don't do that.

Here is the caller graph for this function:

◆ start_writing_to_stdio_file()

FILE* start_writing_to_stdio_file ( const char *  fname,
int  open_flags,
int  mode,
open_file_t **  data_out 
)

Combines start_writing_to_file with fdopen_file(): arguments are as for start_writing_to_file, but

Here is the call graph for this function:

◆ strcmp_opt()

int strcmp_opt ( const char *  s1,
const char *  s2 
)

As strcmp, except that either string may be NULL. The NULL string is considered to be before any non-NULL string.

Here is the caller graph for this function:

◆ stream_status_to_string()

const char* stream_status_to_string ( enum stream_status stream_status  )

Return a string corresponding to stream_status.

◆ string_is_C_identifier()

int string_is_C_identifier ( const char *  string)

Returns true if string could be a C identifier. A C identifier must begin with a letter or an underscore and the rest of its characters can be letters, numbers or underscores. No length limit is imposed.

◆ string_is_key_value()

int string_is_key_value ( int  severity,
const char *  string 
)

Return true if string is a valid 'key=[value]' string. "value" is optional, to indicate the empty string. Log at logging severity if something ugly happens.

Here is the call graph for this function:

◆ string_is_valid_dest()

int string_is_valid_dest ( const char *  string)

Return true iff string is a valid destination address, i.e. either a DNS hostname or IPv4/IPv6 address string.

◆ string_is_valid_ipv4_address()

int string_is_valid_ipv4_address ( const char *  string)

Return true if string represents a valid IPv4 adddress in 'a.b.c.d' form.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ string_is_valid_ipv6_address()

int string_is_valid_ipv6_address ( const char *  string)

Return true if string represents a valid IPv6 address in a form that inet_pton() can parse.

Here is the call graph for this function:

◆ string_is_valid_nonrfc_hostname()

int string_is_valid_nonrfc_hostname ( const char *  string)

Return true iff string matches a pattern of DNS names that we allow Tor clients to connect to.

Note: This allows certain technically invalid characters ('_') to cope with misconfigured zones that have been encountered in the wild.

Here is the call graph for this function:

◆ tor_calloc_()

void* tor_calloc_ ( size_t  nmemb,
size_t size  DMALLOC_PARAMS 
)

Allocate a chunk of nmemb*size bytes of memory, fill the memory with zero bytes, and return a pointer to the result. Log and terminate the process on error. (Same as calloc(nmemb,size), but never returns NULL.) The second argument (size) should preferably be non-zero and a compile-time constant.

◆ tor_digest256_is_zero()

int tor_digest256_is_zero ( const char *  digest)

Return true iff the DIGEST256_LEN bytes in digest are all zero.

Here is the call graph for this function:

◆ tor_digest_is_zero()

int tor_digest_is_zero ( const char *  digest)

Return true iff the DIGEST_LEN bytes in digest are all zero.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ tor_disable_spawning_background_processes()

void tor_disable_spawning_background_processes ( void  )

Turn off may_spawn_background_process, so that all future calls to tor_spawn_background are guaranteed to fail.

◆ tor_escape_str_for_pt_args()

char* tor_escape_str_for_pt_args ( const char *  string,
const char *  chars_to_escape 
)

Return a newly allocated string equal to string, except that every character in chars_to_escape is preceded by a backslash.

Here is the caller graph for this function:

◆ tor_free_()

void tor_free_ ( void *  mem)

Helper for places that need to take a function pointer to the right spelling of "free()".

Here is the caller graph for this function:

◆ tor_get_exit_code()

int tor_get_exit_code ( process_handle_t *  process_handle,
int  block,
int *  exit_code 
)

Get the exit code of a process specified by process_handle and store it in exit_code, if set to a non-NULL value. If block is set to true, the call will block until the process has exited. Otherwise if the process is still running, the function will return PROCESS_EXIT_RUNNING, and exit_code will be left unchanged. Returns PROCESS_EXIT_EXITED if the process did exit. If there is a failure, PROCESS_EXIT_ERROR will be returned and the contents of exit_code (if non-NULL) will be undefined. N.B. Under *nix operating systems, this will probably not work in Tor, because waitpid() is called in main.c to reap any terminated child processes.

Here is the caller graph for this function:

◆ tor_htonll()

uint64_t tor_htonll ( uint64_t  a)

Return a uint64_t value from a in network byte order.

Here is the caller graph for this function:

◆ tor_init_weak_random()

void tor_init_weak_random ( tor_weak_rng_t rng,
unsigned  seed 
)

Initialize the insecure RNG rng from a seed value seed.

Here is the caller graph for this function:

◆ tor_join_win_cmdline()

char* tor_join_win_cmdline ( const char *  argv[])

Format a command line for use on Windows, which takes the command as a string rather than string array. Follows the rules from "Parsing C++ Command-Line Arguments" in MSDN. Algorithm based on list2cmdline in the Python subprocess module. Returns a newly allocated string

Here is the call graph for this function:

◆ tor_llround()

int64_t tor_llround ( double  d)

Return the 64-bit integer closest to d. We define this wrapper here so that not all users of math.h need to use the right incantations to get the c99 functions.

Here is the caller graph for this function:

◆ tor_log2()

int tor_log2 ( uint64_t  u64)

Returns floor(log2(u64)). If u64 is 0, (incorrectly) returns 0.

Here is the caller graph for this function:

◆ tor_log_mallinfo()

void tor_log_mallinfo ( int  severity)

Call the platform malloc info function, and dump the results to the log at level severity. If no such function exists, do nothing.

Here is the call graph for this function:

◆ tor_lround()

long tor_lround ( double  d)

Return the long integer closest to d. We define this wrapper here so that not all users of math.h need to use the right incantations to get the c99 functions.

Here is the caller graph for this function:

◆ tor_malloc_()

void* tor_malloc_ ( size_t size  DMALLOC_PARAMS)

Allocate a chunk of size bytes of memory, and return a pointer to result. On error, log and terminate the process. (Same as malloc(size), but never returns NULL.)

file and line are used if dmalloc is enabled, and ignored otherwise.

Here is the caller graph for this function:

◆ tor_malloc_zero_()

void* tor_malloc_zero_ ( size_t size  DMALLOC_PARAMS)

Allocate a chunk of size bytes of memory, fill the memory with zero bytes, and return a pointer to the result. Log and terminate the process on error. (Same as calloc(size,1), but never returns NULL.)

◆ tor_mathlog()

double tor_mathlog ( double  d)

Returns the natural logarithm of d base e. We defined this wrapper here so to avoid conflicts with old versions of tor_log(), which were named log().

Here is the caller graph for this function:

◆ tor_mem_is_zero()

int tor_mem_is_zero ( const char *  mem,
size_t  len 
)

Return true iff the 'len' bytes at 'mem' are all zero.

Here is the caller graph for this function:

◆ tor_memdup_()

void* tor_memdup_ ( const void *  mem,
size_t len  DMALLOC_PARAMS 
)

Allocate a chunk of len bytes, with the same contents as the len bytes starting at mem.

◆ tor_memdup_nulterm_()

void* tor_memdup_nulterm_ ( const void *  mem,
size_t len  DMALLOC_PARAMS 
)

As tor_memdup(), but add an extra 0 byte at the end of the resulting memory.

◆ tor_ntohll()

uint64_t tor_ntohll ( uint64_t  a)

Return a uint64_t value from a in host byte order.

Here is the call graph for this function:

◆ tor_parse_double()

double tor_parse_double ( const char *  s,
double  min,
double  max,
int *  ok,
char **  next 
)

As tor_parse_long(), but return a double.

◆ tor_parse_long()

void long tor_parse_long ( const char *  s,
int  base,
long  min,
long  max,
int *  ok,
char **  next 
)

Extract a long from the start of s, in the given numeric base. If base is 0, s is parsed as a decimal, octal, or hex number in the syntax of a C integer literal. If there is unconverted data and next is provided, set *next to the first unconverted character. An error has occurred if no characters are converted; or if there are unconverted characters and next is NULL; or if the parsed value is not between min and max. When no error occurs, return the parsed value and set *ok (if provided) to

  1. When an error occurs, return 0 and set *ok (if provided) to 0.
Here is the caller graph for this function:

◆ tor_parse_uint64()

uint64_t tor_parse_uint64 ( const char *  s,
int  base,
uint64_t  min,
uint64_t  max,
int *  ok,
char **  next 
)

As tor_parse_long, but return a uint64_t. Only base 10 is guaranteed to work for now.

◆ tor_parse_ulong()

unsigned long tor_parse_ulong ( const char *  s,
int  base,
unsigned long  min,
unsigned long  max,
int *  ok,
char **  next 
)

As tor_parse_long(), but return an unsigned long.

Here is the caller graph for this function:

◆ tor_process_get_pid()

int tor_process_get_pid ( process_handle_t *  process_handle)

Return the Process ID of process_handle.

◆ tor_read_all_from_process_stderr()

ssize_t tor_read_all_from_process_stderr ( const process_handle_t *  process_handle,
char *  buf,
size_t  count 
)

Read from stdout of a process until the process exits.

Here is the call graph for this function:

◆ tor_read_all_from_process_stdout()

ssize_t tor_read_all_from_process_stdout ( const process_handle_t *  process_handle,
char *  buf,
size_t  count 
)

Read from stdout of a process until the process exits.

Here is the call graph for this function:

◆ tor_read_all_handle()

ssize_t tor_read_all_handle ( int  fd,
char *  buf,
size_t  count,
const process_handle_t *  process,
int *  eof 
)

Read from a handle fd into buf, up to count bytes. If process is NULL, the function will return immediately if there is nothing more to read. Otherwise data will be read until end of file, or count bytes are read. Returns the number of bytes read, or -1 on error. Sets eof to true if eof is not NULL and the end of the file has been reached.

Here is the caller graph for this function:

◆ tor_realloc_()

void* tor_realloc_ ( void *  ptr,
size_t size  DMALLOC_PARAMS 
)

Change the size of the memory block pointed to by ptr to size bytes long; return the new memory block. On error, log and terminate. (Like realloc(ptr,size), but never returns NULL.)

Here is the caller graph for this function:

◆ tor_spawn_background()

int tor_spawn_background ( const char *const  filename,
const char **  argv,
process_environment_t env,
process_handle_t **  process_handle_out 
)

Start a program in the background. If filename contains a '/', then it will be treated as an absolute or relative path. Otherwise, on non-Windows systems, the system path will be searched for filename. On Windows, only the current directory will be searched. Here, to search the system path (as well as the application directory, current working directory, and system directories), set filename to NULL.

The strings in argv will be passed as the command line arguments of the child program (following convention, argv[0] should normally be the filename of the executable, and this must be the case if filename is NULL). The last element of argv must be NULL. A handle to the child process will be returned in process_handle (which must be non-NULL). Read process_handle.status to find out if the process was successfully launched. For convenience, process_handle.status is returned by this function.

Some parts of this code are based on the POSIX subprocess module from Python, and example code from http://msdn.microsoft.com/en-us/library/ms682499%28v=vs.85%29.aspx.

◆ tor_split_lines()

int tor_split_lines ( smartlist_t sl,
char *  buf,
int  len 
)

Split buf into lines, and add to smartlist. The buffer buf will be modified. The resulting smartlist will consist of pointers to buf, so there is no need to free the contents of sl. buf must be a NUL-terminated string. len should be set to the length of the buffer excluding the NUL. Non-printable characters (including NUL) will be replaced with "."

Here is the call graph for this function:

◆ tor_strdup_()

char* tor_strdup_ ( const char *s  DMALLOC_PARAMS)

Return a newly allocated copy of the NUL-terminated string s. On error, log and terminate. (Like strdup(s), but never returns NULL.)

◆ tor_strisnonupper()

int tor_strisnonupper ( const char *  s)

Return 1 if no character in s is uppercase, else return 0.

◆ tor_strisprint()

int tor_strisprint ( const char *  s)

Return 1 if every character in s is printable, else return 0.

◆ tor_strisspace()

int tor_strisspace ( const char *  s)

Return true iff every character in s is whitespace space; else return false.

◆ tor_strlower()

void tor_strlower ( char *  s)

Convert all alphabetic characters in the nul-terminated string s to lowercase.

◆ tor_strndup_()

char* tor_strndup_ ( const char *  s,
size_t n  DMALLOC_PARAMS 
)

Allocate and return a new string containing the first n characters of s. If s is longer than n characters, only the first n are copied. The result is always NUL-terminated. (Like strndup(s,n), but never returns NULL.)

◆ tor_strupper()

void tor_strupper ( char *  s)

Convert all alphabetic characters in the nul-terminated string s to lowercase.

◆ tor_terminate_process()

int tor_terminate_process ( process_handle_t *  process_handle)

Terminate the process of process_handle, if that process has not already exited.

Return 0 if we succeeded in terminating the process (or if the process already exited), and -1 if we tried to kill the process but failed.

Based on code originally borrowed from Python's os.kill.

Here is the call graph for this function:
Here is the caller graph for this function:

◆ tor_timegm()

int tor_timegm ( const struct tm *  tm,
time_t *  time_out 
)

Compute a time_t given a struct tm. The result is given in UTC, and does not account for leap seconds. Return 0 on success, -1 on failure.

Here is the caller graph for this function:

◆ tor_weak_random()

int32_t tor_weak_random ( tor_weak_rng_t rng)

Return a randomly chosen value in the range 0..TOR_WEAK_RANDOM_MAX based on the RNG state of rng. This entropy will not be cryptographically strong; do not rely on it for anything an adversary should not be able to predict.

◆ tor_weak_random_range()

int32_t tor_weak_random_range ( tor_weak_rng_t rng,
int32_t  top 
)

Return a random number in the range [0 , top). {That is, the range of integers i such that 0 <= i < top.} Chooses uniformly. Requires that top is greater than 0. This randomness is not cryptographically strong; do not rely on it for anything an adversary should not be able to predict.

◆ tv_mdiff()

long tv_mdiff ( const struct timeval start,
const struct timeval end 
)

Return the number of milliseconds elapsed between *start and *end. If the tv_usec difference is 500, rounds away from zero. Returns LONG_MAX on overflow and underflow.

Here is the caller graph for this function:

◆ tv_to_msec()

int64_t tv_to_msec ( const struct timeval tv)

Converts timeval to milliseconds.

◆ tv_udiff()

long tv_udiff ( const struct timeval start,
const struct timeval end 
)

Return the number of microseconds elapsed between *start and *end. Returns LONG_MAX on overflow and underflow.

◆ unescape_string()

const char* unescape_string ( const char *  s,
char **  result,
size_t *  size_out 
)

Given a c-style double-quoted escaped string in s, extract and decode its contents into a newly allocated string. On success, assign this string to *result, assign its length to size_out (if provided), and return a pointer to the position in s immediately after the string. On failure, return NULL.

◆ update_approx_time()

void update_approx_time ( time_t  now)

Update the cached estimate of the current time. This function SHOULD be called once per second, and MUST be called before the first call to get_approx_time.

Here is the caller graph for this function:

◆ write_all()

ssize_t write_all ( tor_socket_t  fd,
const char *  buf,
size_t  count,
int  isSocket 
)

Write count bytes from buf to fd. isSocket must be 1 if fd was returned by socket() or accept(), and 0 if fd was returned by open(). Return the number of bytes written, or -1 on error. Only use if fd is a blocking fd.

◆ write_bytes_to_new_file()

int write_bytes_to_new_file ( const char *  fname,
const char *  str,
size_t  len,
int  bin 
)

Like write_str_to_file(), but also return -1 if there was a file already residing in fname.

◆ write_pidfile()

int write_pidfile ( const char *  filename)

Write the current process ID, followed by NL, into filename. Return 0 on success, -1 on failure.