util.c File Reference

Common functions for strings, IO, network, data structures, process control. More...

#include "orconfig.h"
#include "util.h"
#include "log.h"
#include "crypto.h"
#include "torint.h"
#include "container.h"
#include "address.h"
#include <dirent.h>
#include <pwd.h>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/fcntl.h>
#include <fcntl.h>
#include <time.h>
#include <malloc.h>

Data Structures

struct  open_file_t

Defines

#define _GNU_SOURCE
#define __USE_ISOC99   1
#define DMALLOC_FN_ARGS
#define CHECK_STRTOX_RESULT()
#define IS_LEAPYEAR(y)   (!(y % 4) && ((y % 100) || !(y % 400)))
#define TOR_ISODIGIT(c)   ('0' <= (c) && (c) <= '7')
#define MAX_SCANF_WIDTH   9999

Functions

void * _tor_malloc (size_t size DMALLOC_PARAMS)
void * _tor_malloc_zero (size_t size DMALLOC_PARAMS)
void * _tor_realloc (void *ptr, size_t size DMALLOC_PARAMS)
char * _tor_strdup (const char *s DMALLOC_PARAMS)
char * _tor_strndup (const char *s, size_t n DMALLOC_PARAMS)
void * _tor_memdup (const void *mem, size_t len DMALLOC_PARAMS)
void _tor_free (void *mem)
void * _tor_malloc_roundup (size_t *sizep DMALLOC_PARAMS)
void tor_log_mallinfo (int severity)
double tor_mathlog (double d)
long tor_lround (double d)
int tor_log2 (uint64_t u64)
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)
void tor_strstrip (char *s, const char *strip)
const char * hex_str (const char *from, size_t fromlen)
void tor_strlower (char *s)
void tor_strupper (char *s)
int tor_strisprint (const char *s)
int tor_strisnonupper (const char *s)
int strcmpstart (const char *s1, const char *s2)
int strcmp_len (const char *s1, const char *s2, size_t s1_len)
int strcasecmpstart (const char *s1, const char *s2)
int strcmpend (const char *s1, const char *s2)
int strcasecmpend (const char *s1, const char *s2)
int memcmpstart (const void *mem, size_t memlen, const char *prefix)
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 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)
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)
void base16_encode (char *dest, size_t destlen, const char *src, size_t srclen)
static INLINE int _hex_decode_digit (char c)
int hex_decode_digit (char c)
int base16_decode (char *dest, size_t destlen, const char *src, size_t srclen)
char * esc_for_log (const char *s)
const char * escaped (const char *s)
void wrap_string (smartlist_t *out, const char *string, size_t width, const char *prefix0, const char *prefixRest)
double tv_to_double (const struct timeval *tv)
int64_t tv_to_msec (const struct timeval *tv)
int64_t tv_to_usec (const struct timeval *tv)
long tv_udiff (const struct timeval *start, const struct timeval *end)
long tv_mdiff (const struct timeval *start, const struct timeval *end)
static int n_leapdays (int y1, int y2)
time_t tor_timegm (struct tm *tm)
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)
int parse_iso_time (const char *cp, time_t *t)
int parse_http_time (const char *date, 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)
void ftime_set_maximum_sloppiness (int seconds)
void ftime_set_estimated_skew (int seconds)
int ftime_maybe_after (time_t now, time_t when)
int ftime_maybe_before (time_t now, time_t when)
int ftime_definitely_after (time_t now, time_t when)
int ftime_definitely_before (time_t now, time_t when)
ssize_t write_all (int fd, const char *buf, size_t count, int isSocket)
ssize_t read_all (int fd, char *buf, size_t count, int isSocket)
static void clean_name_for_stat (char *name)
file_status_t file_status (const char *fname)
int check_private_dir (const char *dirname, cpd_check_t check)
int write_str_to_file (const char *fname, const char *str, int bin)
int start_writing_to_file (const char *fname, int open_flags, int mode, open_file_t **data_out)
FILE * fdopen_file (open_file_t *file_data)
FILE * start_writing_to_stdio_file (const char *fname, int open_flags, int mode, open_file_t **data_out)
static int finish_writing_to_file_impl (open_file_t *file_data, int abort_write)
int finish_writing_to_file (open_file_t *file_data)
int abort_writing_to_file (open_file_t *file_data)
static int write_chunks_to_file_impl (const char *fname, const smartlist_t *chunks, int open_flags)
int write_chunks_to_file (const char *fname, const smartlist_t *chunks, int bin)
int write_bytes_to_file (const char *fname, const char *str, size_t len, int bin)
int append_bytes_to_file (const char *fname, const char *str, size_t len, int bin)
char * read_file_to_str (const char *filename, int flags, struct stat *stat_out)
static const char * unescape_string (const char *s, char **result, size_t *size_out)
const char * parse_config_line_from_str (const char *line, char **key_out, char **value_out)
char * expand_filename (const char *filename)
static int digit_to_num (char d)
static int scan_unsigned (const char **bufp, unsigned *out, int width)
static int scan_string (const char **bufp, char *out, int width)
int tor_vsscanf (const char *buf, const char *pattern, va_list ap)
int tor_sscanf (const char *buf, const char *pattern,...)
smartlist_ttor_listdir (const char *dirname)
int path_is_relative (const char *filename)
void start_daemon (void)
void finish_daemon (const char *desired_cwd)
void write_pidfile (char *filename)

Variables

static const int days_per_month []
static const char * WEEKDAY_NAMES []
static const char * MONTH_NAMES []
static time_t cached_approx_time = 0
static int ftime_skew = 0
static int ftime_slop = 60
static int start_daemon_called = 0
static int finish_daemon_called = 0
static int daemon_filedes [2]


Detailed Description

Common functions for strings, IO, network, data structures, process control.


Define Documentation

 
#define CHECK_STRTOX_RESULT (  ) 

Value:

/* Was at least one character converted? */           \
  if (endptr == s)                                      \
    goto err;                                           \
  /* Were there unexpected unconverted characters? */   \
  if (!next && *endptr)                                 \
    goto err;                                           \
  /* Is r within limits? */                             \
  if (r < min || r > max)                               \
    goto err;                                           \
  if (ok) *ok = 1;                                      \
  if (next) *next = endptr;                             \
  return r;                                             \
 err:                                                   \
  if (ok) *ok = 0;                                      \
  if (next) *next = endptr;                             \
  return 0

#define IS_LEAPYEAR (  )     (!(y % 4) && ((y % 100) || !(y % 400)))

Yield true iff y is a leap-year.

Referenced by tor_timegm().


Function Documentation

static INLINE int _hex_decode_digit ( char  c  )  [static]

Helper: given a hex digit, return its value, or -1 if it isn't hex.

Referenced by base16_decode(), and hex_decode_digit().

void _tor_free ( void *  mem  ) 

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.

References LD_MM.

Referenced by _tor_malloc_roundup(), _tor_malloc_zero(), _tor_memdup(), _tor_strndup(), and tor_main().

void* _tor_malloc_roundup ( size_t *sizep  DMALLOC_PARAMS  ) 

Allocate and return a chunk of memory of size at least *size, using the same resources we would use to malloc *sizep. Set *sizep to the number of usable bytes in the chunk of memory.

References _tor_malloc().

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.)

References _tor_malloc().

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.

References _tor_malloc(), and tor_assert.

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.)

References LD_MM.

Referenced by tor_main().

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.)

References LD_MM, and tor_assert.

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.)

References _tor_malloc(), and tor_assert.

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.

References finish_writing_to_file_impl().

Referenced by geoip_dirreq_stats_write(), geoip_entry_stats_write(), rend_service_load_keys(), rep_hist_buffer_stats_write(), rep_hist_exit_stats_write(), rep_hist_record_mtbf_data(), start_writing_to_stdio_file(), and write_chunks_to_file_impl().

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.

References smartlist_add(), smartlist_create(), smartlist_free(), and write_chunks_to_file_impl().

Referenced by signed_desc_append_to_journal().

time_t approx_time ( void   ) 

int base16_decode ( char *  dest,
size_t  destlen,
const char *  src,
size_t  srclen 
)

void base16_encode ( char *  dest,
size_t  destlen,
const char *  src,
size_t  srclen 
)

Encode the srclen bytes at src in a NUL-terminated, uppercase hexadecimal string; store it in the destlen-byte buffer dest.

References tor_assert.

Referenced by circuit_list_path_impl(), connection_ap_make_link(), connection_dir_client_reached_eof(), connection_or_check_valid_tls_handshake(), connection_or_init_conn_from_address(), control_event_guard(), crypto_pk_get_fingerprint(), directory_get_consensus_url(), dirserv_get_name_status(), dirserv_get_networkstatus_v2(), dirvote_fetch_missing_votes(), do_hash_password(), entry_guard_set_status(), entry_guards_update_state(), extrainfo_dump_to_string(), fetch_bridge_descriptors(), format_networkstatus_vote(), getinfo_helper_entry_guards(), getinfo_helper_misc(), hex_str(), initiate_descriptor_downloads(), list_single_server_status(), networkstatus_add_detached_signatures(), networkstatus_compute_consensus(), networkstatus_format_signatures(), networkstatus_get_cache_filename(), networkstatus_get_detached_signatures(), orconn_target_get_name(), remove_dead_entry_guards(), remove_obsolete_entry_guards(), rend_mid_establish_rendezvous(), rend_mid_rendezvous(), rend_parse_introduction_points(), rend_service_introduce(), rend_service_launch_establish_intro(), rend_service_rendezvous_has_opened(), rep_hist_dump_stats(), rep_hist_record_mtbf_data(), router_dump_router_to_string(), router_get_verbose_nickname(), router_load_extrainfo_from_string(), router_load_routers_from_string(), router_rebuild_descriptor(), router_set_networkstatus_v2(), routerstatus_format_entry(), routerstatus_get_verbose_nickname(), and update_v2_networkstatus_cache_downloads().

int check_private_dir ( const char *  dirname,
cpd_check_t  check 
)

Check whether dirname exists and is private. If yes return 0. If it does not exist, and check==CPD_CREATE is set, try to create it and return 0 on success. If it does not exist, and check==CPD_CHECK, and we think we can create it, return 0. Else return -1.

References clean_name_for_stat(), LD_FS, LD_GENERAL, tor_assert, and tor_free.

Referenced by geoip_bridge_stats_write(), geoip_dirreq_stats_write(), geoip_entry_stats_write(), init_keys(), load_bridge_stats(), options_act_reversible(), rend_service_load_keys(), rep_hist_buffer_stats_write(), and rep_hist_exit_stats_write().

static void clean_name_for_stat ( char *  name  )  [static]

Clean up name so that we can use it in a call to "stat". On Unix, we do nothing. On Windows, we remove a trailing slash, unless the path is the root of a disk.

Referenced by check_private_dir(), and file_status().

static int digit_to_num ( char  d  )  [static]

Helper: given an ASCII-encoded decimal digit, return its numeric value. NOTE: requires that its input be in-bounds.

References tor_assert.

Referenced by scan_unsigned(), and tor_vsscanf().

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.

References tor_assert.

Referenced by authority_cert_parse_from_string(), config_parse_units(), get_token_arguments(), parse_log_severity_config(), rend_parse_client_keys(), router_parse_addr_policy_item_from_string(), router_parse_addr_policy_private(), tor_addr_port_parse(), tor_version_as_new_as(), and tor_version_parse().

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.

References tor_assert.

Referenced by find_start_of_next_microdesc(), find_start_of_next_router_or_extrainfo(), get_next_token(), microdescs_parse_from_string(), and tokenize_string().

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.

Referenced by get_next_token().

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.

Referenced by parse_bridge_stats_controller(), and parse_http_url().

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.

References tor_snprintf().

Referenced by control_event_logmsg(), dirserv_get_status_impl(), esc_router_info(), escaped(), evdns_callback(), get_assigned_option(), handle_control_protocolinfo(), parse_addr_port(), parse_iso_time(), and parse_rfc1123_time().

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));

References esc_for_log(), and tor_free.

Referenced by add_fingerprint_to_dir(), authority_cert_parse_from_string(), circuit_build_failed(), command_process_create_cell(), connection_ap_process_natd(), connection_dir_client_reached_eof(), connection_read_https_proxy_response(), connection_read_proxy_handshake(), dir_networkstatus_download_failed(), dir_routerdesc_download_failed(), dir_split_resource_into_fingerprint_pairs(), dir_split_resource_into_fingerprints(), directory_handle_command(), dirserv_add_multiple_descriptors(), dirserv_get_status_impl(), dirserv_read_measured_bandwidths(), entry_guards_parse_state(), escaped_safe_str(), escaped_safe_str_client(), evdns_log_cb(), extrainfo_parse_entry_from_string(), fetch_from_buf_socks(), geoip_parse_entry(), handle_control_protocolinfo(), http_set_address_origin(), init_cookie_authentication(), load_downloaded_routers(), measured_bw_line_parse(), microdescs_parse_from_string(), networkstatus_parse_detached_signatures(), networkstatus_parse_vote_from_string(), networkstatus_v2_parse_from_string(), parse_addr_and_port_range(), parse_addr_port(), parse_http_response(), parse_port_config(), parse_port_range(), remove_obsolete_entry_guards(), rend_parse_client_keys(), rend_parse_introduction_points(), rend_parse_v2_service_descriptor(), rend_service_introduce(), rend_service_load_keys(), rep_hist_load_mtbf_data(), router_dump_router_to_string(), router_get_consensus_status_by_nickname(), router_new_address_suggestion(), router_parse_addr_policy(), router_parse_addr_policy_item_from_string(), router_parse_entry_from_string(), router_rebuild_descriptor(), routerstatus_parse_entry_from_string(), signed_descriptor_get_body_impl(), tor_addr_parse_mask_ports(), and tor_free_all().

char* expand_filename ( const char *  filename  ) 

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

References get_user_homedir(), LD_CONFIG, strcmpend(), tor_assert, tor_free, and tor_snprintf().

Referenced by find_torrc_filename(), and normalize_data_directory().

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.

References open_file_t::binary, open_file_t::fd, open_file_t::filename, LD_FS, open_file_t::stdio_file, and tor_assert.

Referenced by start_writing_to_stdio_file().

file_status_t file_status ( const char *  fname  ) 

Return FN_ERROR if filename can't be read, FN_NOENT if it doesn't exist, FN_FILE if it is a regular file, or FN_DIR if it's a directory. On FN_ERROR, sets errno.

References clean_name_for_stat(), and tor_free.

Referenced by dirserv_clear_old_networkstatuses(), find_torrc_filename(), init_key_from_file(), init_keys(), load_stats_file(), load_torrc_from_disk(), networkstatus_v2_list_clean(), or_state_load(), replace_file(), rotate_onion_key(), router_reload_router_list_impl(), and write_configuration_file().

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.

Referenced by parse_bridge_stats_controller().

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.

Referenced by get_token_arguments(), parse_http_url(), tor_version_as_new_as(), tor_version_parse(), and version_from_platform().

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.

Referenced by get_next_token().

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.)

References daemon_filedes, finish_daemon_called, LD_GENERAL, start_daemon(), and start_daemon_called.

Referenced by options_act().

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.

References finish_writing_to_file_impl().

Referenced by geoip_dirreq_stats_write(), geoip_entry_stats_write(), microdesc_cache_rebuild(), rend_service_load_keys(), rep_hist_buffer_stats_write(), rep_hist_exit_stats_write(), rep_hist_record_mtbf_data(), and write_chunks_to_file_impl().

static int finish_writing_to_file_impl ( open_file_t file_data,
int  abort_write 
) [static]

Helper function: close and free the underlying file and memory in file_data. If we were writing into a temporary file, then delete that file (if abort_write is true) or replaces the target file with the temporary file (if abort_write is false).

References open_file_t::fd, open_file_t::filename, LD_FS, open_file_t::rename_on_close, replace_file(), open_file_t::stdio_file, open_file_t::tempname, tor_assert, and tor_free.

Referenced by abort_writing_to_file(), and finish_writing_to_file().

void format_iso_time ( char *  buf,
time_t  t 
)

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)

Referenced by accounting_set_wakeup_time(), consider_hibernation(), control_event_address_mapped(), or_state_save(), remove_dead_entry_guards(), remove_file_if_very_old(), rep_hist_note_router_reachable(), rep_hist_note_router_unreachable(), and update_consensus_networkstatus_fetch_time().

void format_rfc1123_time ( char *  buf,
time_t  t 
)

Set buf to the RFC1123 encoding of the GMT 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)

References MONTH_NAMES, tor_assert, and WEEKDAY_NAMES.

Referenced by directory_send_command(), and write_http_response_header_impl().

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. Return 0 on success, -1 on failure.

References tor_snprintf().

Referenced by command_process_netinfo_cell(), connection_dir_client_reached_eof(), networkstatus_set_current_consensus(), and router_set_networkstatus_v2().

int ftime_definitely_after ( time_t  now,
time_t  when 
)

Return true if we think that now is definitely after when.

References ftime_skew, and ftime_slop.

Referenced by authority_certs_fetch_missing(), and trusted_dirs_remove_old_certs().

int ftime_definitely_before ( time_t  now,
time_t  when 
)

Return true if we think that now is definitely before when.

References ftime_skew, and ftime_slop.

Referenced by networkstatus_set_current_consensus().

int ftime_maybe_after ( time_t  now,
time_t  when 
)

Return true iff we think that now might be after when.

References ftime_skew, and ftime_slop.

int ftime_maybe_before ( time_t  now,
time_t  when 
)

Return true iff we think that now might be before when.

References ftime_skew, and ftime_slop.

void ftime_set_estimated_skew ( int  seconds  ) 

Set the amount by which we believe our system clock to differ from real time.

References ftime_skew.

void ftime_set_maximum_sloppiness ( int  seconds  ) 

Set the largest amount of sloppiness we'll allow in fuzzy time comparisons.

References ftime_slop, and tor_assert.

int hex_decode_digit ( char  c  ) 

Helper: given a hex digit, return its value, or -1 if it isn't hex.

References _hex_decode_digit().

Referenced by tor_addr_parse_reverse_lookup_name(), and unescape_string().

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.

References base16_encode().

Referenced by authority_certs_fetch_missing(), dirvote_act(), dirvote_add_vote(), handle_control_attachstream(), list_v3_auth_ids(), networkstatus_check_consensus_signature(), rep_hist_note_router_reachable(), rep_hist_note_router_unreachable(), router_add_to_routerlist(), router_load_routers_from_string(), router_parse_directory(), and trusted_dirs_load_certs_from_string().

int 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 memcmp(mem, prefix, strlen(prefix)) but returns -1 if memlen is less than strlen(prefix).]

Referenced by rend_decrypt_introduction_points(), and rend_parse_introduction_points().

static int n_leapdays ( int  y1,
int  y2 
) [static]

Helper: Return the number of leap-days between Jan 1, y1 and Jan 1, y2.

Referenced by tor_timegm().

const char* parse_config_line_from_str ( const char *  line,
char **  key_out,
char **  value_out 
)

Given a string containing part of a configuration file or similar format, advance past comments and whitespace and try to parse a single line. If we parse a line successfully, set *key_out to a new string holding the key portion and *value_out to a new string holding the value portion of the line, and return a pointer to the start of the next line. If we run out of data, return a pointer to the end of the string. If we encounter an error, return NULL.

References tor_assert, and unescape_string().

Referenced by config_get_lines().

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.

References MONTH_NAMES, tor_assert, and tor_sscanf().

Referenced by directory_handle_command_get().

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

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

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

Return 0 on success, -1 on failure.

References esc_for_log(), LD_GENERAL, MONTH_NAMES, tor_free, tor_sscanf(), and tor_timegm().

Referenced by parse_http_response().

int path_is_relative ( const char *  filename  ) 

Return true iff filename is a relative path.

Referenced by options_validate().

ssize_t read_all ( int  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.

Referenced by cpuworker_main(), crypto_seed_rng(), and read_file_to_str().

char* read_file_to_str ( const char *  filename,
int  flags,
struct stat *  stat_out 
)

Read the contents of filename into a newly allocated string; return the string on success or NULL on failure.

If stat_out is provided, store the result of stat()ing the file into stat_out.

If flags & RFTS_BIN, open the file in binary mode. If flags & RFTS_IGNORE_MISSING, don't warn if the file doesn't exist.

References LD_FS, read_all(), RFTS_BIN, RFTS_IGNORE_MISSING, tor_assert, tor_free, and tor_strstrip().

Referenced by crypto_pk_read_private_key_from_filename(), dirserv_load_fingerprint_file(), init_keys(), load_authority_keyset(), load_bridge_stats(), load_stats_file(), load_torrc_from_disk(), microdesc_cache_reload(), options_act(), or_state_load(), rend_service_load_keys(), rep_hist_load_mtbf_data(), router_reload_consensus_networkstatus(), router_reload_router_list_impl(), router_reload_v2_networkstatus(), trusted_dirs_reload_certs(), and write_configuration_file().

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.

Referenced by geoip_get_client_history(), and geoip_get_request_history().

uint64_t round_to_power_of_2 ( uint64_t  u64  ) 

Return the power of 2 closest to u64.

References tor_log2().

Referenced by mp_pool_new().

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.

Referenced by geoip_dirreq_stats_write(), geoip_get_dirreq_history(), and rep_hist_exit_stats_write().

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.

Referenced by rep_hist_exit_stats_write().

static int scan_string ( const char **  bufp,
char *  out,
int  width 
) [static]

Helper: copy up to width non-space characters from bufp to out. Make sure out is nul-terminated. Advance bufp to the next non-space character or the EOS.

Referenced by tor_vsscanf().

static int scan_unsigned ( const char **  bufp,
unsigned *  out,
int  width 
) [static]

Helper: Read an unsigned int from *bufp of up to width characters. (Handle arbitrary width if width is less than 0.) On success, store the result in out, advance bufp to the next character, and return 0. On failure, return -1.

References digit_to_num().

Referenced by tor_vsscanf().

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.)

References daemon_filedes, LD_GENERAL, set_main_thread(), and start_daemon_called.

Referenced by finish_daemon(), and options_act_reversible().

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.

References open_file_t::binary, open_file_t::fd, open_file_t::filename, LD_FS, LD_GENERAL, open_file_t::rename_on_close, open_file_t::tempname, tor_assert, tor_fd_seekend(), tor_free, and tor_snprintf().

Referenced by start_writing_to_stdio_file(), and write_chunks_to_file_impl().

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

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

Compares the last strlen(s2) characters of s1 with s2. Returns as for strcasecmp.

Referenced by address_is_in_virtual_range(), connection_ap_handshake_rewrite_and_attach(), consider_recording_trackhost(), and tor_addr_parse_reverse_lookup_name().

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

Compares the first strlen(s2) characters of s1 with s2. Returns as for strcasecmp.

Referenced by circuit_purpose_from_string(), find_element_starting_with(), handle_control_postdescriptor(), http_get_header(), parse_dir_server_line(), parse_log_severity_config(), and tor_version_parse().

int strcmp_len ( const char *  s1,
const char *  s2,
size_t  s1_len 
)

Compare the s1_len-byte string s1 with s2, without depending on a terminating nul in s1. Sorting order is first by length, then lexically; return values are as for strcmp.

Referenced by get_next_token().

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

Compares the last strlen(s2) characters of s1 with s2. Returns as for strcmp.

Referenced by clear_trackexithost_mappings(), expand_filename(), and rend_parse_service_authorization().

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

int tor_digest256_is_zero ( const char *  digest  ) 

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

References DIGEST256_LEN, and tor_mem_is_zero().

int tor_digest_is_zero ( const char *  digest  ) 

smartlist_t* tor_listdir ( const char *  dirname  )  [read]

Return a new list containing the filenames in the directory dirname. Return NULL on error or if dirname is not a directory.

References LD_FS, smartlist_add(), smartlist_create(), tor_free, and tor_snprintf().

Referenced by router_reload_v2_networkstatus().

int tor_log2 ( uint64_t  u64  ) 

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

Referenced by digestset_new(), and round_to_power_of_2().

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.

References LD_MM, and tor_log().

Referenced by dumpmemusage().

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 incancations to get the c99 functions.

Referenced by circuit_build_times_add_timeout_worker(), circuit_build_times_generate_sample(), circuit_build_times_network_check_changed(), circuit_build_times_network_check_live(), and circuit_build_times_set_timeout().

double tor_mathlog ( double  d  ) 

Returns the natural logarithm of d base 2. We define this wrapper here so as to make it easier not to conflict with Tor's log() macro.

Referenced by circuit_build_times_initial_alpha(), and circuit_build_times_update_alpha().

int tor_mem_is_zero ( const char *  mem,
size_t  len 
)

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

As tor_parse_long(), but return a double.

Referenced by config_parse_units().

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 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.

Referenced by _cmp_int_strings(), accounting_parse_options(), compute_consensus_method(), config_assign_value(), connection_ap_process_natd(), dirvote_compute_params(), handle_control_protocolinfo(), measured_bw_line_parse(), networkstatus_parse_vote_from_string(), networkstatus_v2_parse_from_string(), parse_addr_port(), parse_dir_server_line(), parse_port_config(), parse_port_range(), parse_possibly_bad_iso_time(), rend_parse_introduction_points(), rend_parse_v2_service_descriptor(), rep_hist_load_mtbf_data(), router_parse_entry_from_string(), routerstatus_parse_entry_from_string(), and tor_addr_port_parse().

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.

References tor_assert.

Referenced by config_parse_units(), get_stream(), and rep_hist_load_state().

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

int tor_sscanf ( const char *  buf,
const char *  pattern,
  ... 
)

Minimal sscanf replacement: parse buf according to pattern and store the results in the corresponding argument fields. Differs from sscanf in that it: Only handles u and Ns. Does not handle arbitrarily long widths. u does not consume any space. Is locale-independent. Returns -1 on malformed patterns.

(As with other locale-independent functions, we need this to parse data that is in ASCII without worrying that the C library's locale-handling will make miscellaneous characters look like numbers, spaces, and so on.)

References tor_vsscanf().

Referenced by parse_http_response(), parse_http_time(), parse_iso_time(), parse_rfc1123_time(), tor_inet_aton(), and tor_inet_pton().

int tor_strisnonupper ( const char *  s  ) 

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

Referenced by assert_resolve_ok().

int tor_strisprint ( const char *  s  ) 

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

Referenced by fetch_from_buf_socks().

void tor_strlower ( char *  s  ) 

void tor_strstrip ( char *  s,
const char *  strip 
)

Remove from the string s every character which appears in strip.

Referenced by add_fingerprint_to_dir(), dirserv_load_fingerprint_file(), read_file_to_str(), router_parse_entry_from_string(), and smartlist_split_string().

void tor_strupper ( char *  s  ) 

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

time_t tor_timegm ( struct tm *  tm  ) 

Return a time_t given a struct tm. The result is given in GMT, and does not account for leap seconds.

References days_per_month, IS_LEAPYEAR, LD_BUG, n_leapdays(), and tor_assert.

Referenced by directory_handle_command_get(), dirvote_get_start_of_next_interval(), parse_iso_time(), and parse_rfc1123_time().

int tor_vsscanf ( const char *  buf,
const char *  pattern,
va_list  ap 
)

Locale-independent, minimal, no-surprises scanf variant, accepting only a restricted pattern format. For more info on what it supports, see tor_sscanf() documentation.

References digit_to_num(), scan_string(), and scan_unsigned().

Referenced by tor_sscanf().

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

Return the number of milliseconds elapsed between *start and *end.

References LD_GENERAL.

Referenced by circuit_send_next_onion_skin(), and geoip_get_dirreq_history().

double tv_to_double ( const struct timeval *  tv  ) 

Converts struct timeval to a double value. Preserves microsecond precision, but just barely. Error is approx +/- 0.1 usec when dealing with epoch values.

int64_t tv_to_msec ( const struct timeval *  tv  ) 

Converts timeval to milliseconds.

int64_t tv_to_usec ( const struct timeval *  tv  ) 

Converts timeval to microseconds.

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

Return the number of microseconds elapsed between *start and *end.

References LD_GENERAL.

static const char* unescape_string ( const char *  s,
char **  result,
size_t *  size_out 
) [static]

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.

References hex_decode_digit(), tor_fragile_assert, and tor_free.

Referenced by parse_config_line_from_str().

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.

References cached_approx_time.

Referenced by do_main_loop(), second_elapsed_callback(), and tor_main().

void wrap_string ( smartlist_t out,
const char *  string,
size_t  width,
const char *  prefix0,
const char *  prefixRest 
)

Rudimentary string wrapping code: given a un-wrapped string (no newlines!), break the string into newline-terminated lines of no more than width characters long (not counting newline) and insert them into out in order. Precede the first line with prefix0, and subsequent lines with prefixRest.

References smartlist_add(), and tor_assert.

ssize_t write_all ( int  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.

References tor_assert.

Referenced by cpuworker_main(), log_tor_version(), logv(), and write_chunks_to_file_impl().

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

As write_str_to_file, but does not assume a NUL-terminated string. Instead, we write len bytes, starting at str.

References smartlist_add(), smartlist_create(), smartlist_free(), and write_chunks_to_file_impl().

Referenced by init_cookie_authentication(), and write_str_to_file().

int write_chunks_to_file ( const char *  fname,
const smartlist_t chunks,
int  bin 
)

Given a smartlist of sized_chunk_t, write them atomically to a file fname, overwriting or creating the file as necessary.

References write_chunks_to_file_impl().

Referenced by dirvote_compute_consensuses(), and router_rebuild_store().

static int write_chunks_to_file_impl ( const char *  fname,
const smartlist_t chunks,
int  open_flags 
) [static]

Helper: given a set of flags as passed to open(2), open the file fname and write all the sized_chunk_t structs in chunks to the file. Do so as atomically as possible e.g. by opening temp files and renaming.

References abort_writing_to_file(), finish_writing_to_file(), LD_FS, start_writing_to_file(), tor_assert, and write_all().

Referenced by append_bytes_to_file(), write_bytes_to_file(), and write_chunks_to_file().

void write_pidfile ( char *  filename  ) 

Write the current process ID, followed by NL, into filename.

References LD_FS.

Referenced by options_act().

int write_str_to_file ( const char *  fname,
const char *  str,
int  bin 
)

Create a file named fname with the contents str. Overwrite the previous fname if possible. Return 0 on success, -1 on failure.

This function replaces the old file atomically, if possible. This function, and all other functions in util.c that create files, create them with mode 0600.

References LD_BUG, and write_bytes_to_file().

Referenced by add_networkstatus_to_cache(), crypto_pk_write_private_key_to_filename(), dump_desc(), geoip_bridge_stats_write(), init_keys(), microdesc_cache_rebuild(), networkstatus_dump_bridge_status_to_file(), networkstatus_set_current_consensus(), or_state_save(), rend_service_load_keys(), and write_configuration_file().


Variable Documentation

time_t cached_approx_time = 0 [static]

Cached estimate of the current time. Updated around once per second; may be a few seconds off if we are really busy. This is a hack to avoid calling time(NULL) (which not everybody has optimized) on critical paths.

Referenced by approx_time(), and update_approx_time().

int daemon_filedes[2] [static]

Socketpair used to communicate between parent and child process while daemonizing.

Referenced by finish_daemon(), and start_daemon().

const int days_per_month[] [static]

Initial value:

  { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
Number of days per month in non-leap year; used by tor_timegm.

Referenced by tor_timegm().

int finish_daemon_called = 0 [static]

True iff we've called finish_daemon().

Referenced by finish_daemon().

int ftime_skew = 0 [static]

Our current estimate of our skew, such that we think the current time is closest to time(NULL)+ftime_skew.

Referenced by ftime_definitely_after(), ftime_definitely_before(), ftime_maybe_after(), ftime_maybe_before(), and ftime_set_estimated_skew().

int ftime_slop = 60 [static]

const char* MONTH_NAMES[] [static]

Initial value:

  { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }
A c-locale array of 3-letter names of months, starting with Jan.

Referenced by format_rfc1123_time(), parse_http_time(), and parse_rfc1123_time().

int start_daemon_called = 0 [static]

True iff we've called start_daemon().

Referenced by finish_daemon(), and start_daemon().

const char* WEEKDAY_NAMES[] [static]

Initial value:

  { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }
A c-locale array of 3-letter names of weekdays, starting with Sun.

Referenced by format_rfc1123_time().


Generated on Tue May 25 00:31:00 2010 for tor by  doxygen 1.5.6