util.h File Reference

Headers for util.c. More...

#include "orconfig.h"
#include "torint.h"
#include "compat.h"
#include <stdio.h>
#include <stdlib.h>

Go to the source code of this file.

Data Structures

struct  sized_chunk_t

Defines

#define O_BINARY   0
#define O_TEXT   0
#define tor_assert(expr)
#define DMALLOC_PARAMS
#define DMALLOC_ARGS
#define tor_fragile_assert()
#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_malloc_roundup(szp)   _tor_malloc_roundup(szp DMALLOC_ARGS)
#define tor_realloc(ptr, size)   _tor_realloc(ptr, size 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 STRUCT_OFFSET(tp, member)   ((off_t) (((char*)&((tp*)0)->member)-(char*)0))
#define STRUCT_VAR_P(st, off)   ((void*) ( ((char*)(st)) + (off) ) )
#define SUBTYPE_P(p, subtype, basemember)   ((void*) ( ((char*)(p)) - STRUCT_OFFSET(subtype, basemember) ))
#define bool_eq(a, b)   (!(a)==!(b))
#define bool_neq(a, b)   (!(a)!=!(b))
#define HEX_CHARACTERS   "0123456789ABCDEFabcdef"
#define RFC1123_TIME_LEN   29
#define ISO_TIME_LEN   19
#define OPEN_FLAGS_REPLACE   (O_WRONLY|O_CREAT|O_TRUNC)
#define OPEN_FLAGS_APPEND   (O_WRONLY|O_CREAT|O_APPEND)
#define RFTS_BIN   1
#define RFTS_IGNORE_MISSING   2

Typedefs

typedef struct open_file_t open_file_t

Enumerations

enum  file_status_t { FN_ERROR, FN_NOENT, FN_FILE, FN_DIR }
enum  cpd_check_t { CPD_NONE, CPD_CREATE, CPD_CHECK }

Functions

void * _tor_malloc (size_t size DMALLOC_PARAMS) ATTR_MALLOC
void * _tor_malloc_zero (size_t size DMALLOC_PARAMS) ATTR_MALLOC
void * _tor_malloc_roundup (size_t *size DMALLOC_PARAMS) ATTR_MALLOC
void * _tor_realloc (void *ptr, size_t size 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_free (void *mem)
void tor_log_mallinfo (int severity)
double tor_mathlog (double d) ATTR_CONST
long tor_lround (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)
void tor_strlower (char *s) ATTR_NONNULL((1))
void tor_strupper (char *s) ATTR_NONNULL((1))
int tor_strisprint (const char *s) ATTR_PURE ATTR_NONNULL((1))
int tor_strisnonupper (const char *s) ATTR_PURE ATTR_NONNULL((1))
int strcmpstart (const char *s1, const char *s2) ATTR_PURE ATTR_NONNULL((1
int int strcmp_len (const char *s1, const char *s2, size_t len) ATTR_PURE ATTR_NONNULL((1
int int int strcasecmpstart (const char *s1, const char *s2) ATTR_PURE ATTR_NONNULL((1
int int int int strcmpend (const char *s1, const char *s2) ATTR_PURE ATTR_NONNULL((1
int int int int int strcasecmpend (const char *s1, const char *s2) ATTR_PURE ATTR_NONNULL((1
int int int int int int memcmpstart (const void *mem, size_t memlen, const char *prefix) ATTR_PURE
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) ATTR_PURE
const char * eat_whitespace_eos (const char *s, const char *eos) ATTR_PURE
const char * eat_whitespace_no_nl (const char *s) ATTR_PURE
const char * eat_whitespace_eos_no_nl (const char *s, const char *eos) ATTR_PURE
const char * find_whitespace (const char *s) ATTR_PURE
const char * find_whitespace_eos (const char *s, const char *eos) ATTR_PURE
const char * find_str_at_start_of_line (const char *haystack, const char *needle) ATTR_PURE
int tor_mem_is_zero (const char *mem, size_t len) ATTR_PURE
int tor_digest_is_zero (const char *digest) ATTR_PURE
int tor_digest256_is_zero (const char *digest) ATTR_PURE
char * esc_for_log (const char *string) ATTR_MALLOC
const char * escaped (const char *string)
void wrap_string (struct smartlist_t *out, const char *string, size_t width, const char *prefix0, const char *prefixRest)
int tor_vsscanf (const char *buf, const char *pattern, va_list ap)
int tor_sscanf (const char *buf, const char *pattern,...)
int hex_decode_digit (char c)
void base16_encode (char *dest, size_t destlen, const char *src, size_t srclen)
int base16_decode (char *dest, size_t destlen, const char *src, size_t srclen)
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)
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 *buf, 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)
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)
file_status_t file_status (const char *filename)
int check_private_dir (const char *dirname, cpd_check_t check)
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)
int write_str_to_file (const char *fname, const char *str, int bin)
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 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) ATTR_MALLOC
const char * parse_config_line_from_str (const char *line, char **key_out, char **value_out)
char * expand_filename (const char *filename)
struct smartlist_ttor_listdir (const char *dirname)
int path_is_relative (const char *filename) ATTR_PURE
void start_daemon (void)
void finish_daemon (const char *desired_cwd)
void write_pidfile (char *filename)
const char * libor_get_digests (void)


Detailed Description

Headers for util.c.


Define Documentation

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

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

Referenced by circuit_set_n_circid_orconn(), circuit_set_p_circid_orconn(), options_act(), and routerstatus_parse_entry_from_string().

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

Macro: true if two values have different boolean values.

Referenced by directory_remove_invalid().

#define HEX_CHARACTERS   "0123456789ABCDEFabcdef"

Allowable characters in a hexadecimal string.

Referenced by is_legal_hexdigest().

#define RFTS_BIN   1

Flag for read_file_to_str: open the file in binary mode.

Referenced by read_file_to_str(), and router_reload_router_list_impl().

#define RFTS_IGNORE_MISSING   2

#define STRUCT_OFFSET ( tp,
member   )     ((off_t) (((char*)&((tp*)0)->member)-(char*)0))

Return the offset of member within the type tp, in bytes

Referenced by add_cell_ewma_to_conn(), mp_pool_new(), pop_first_cell_ewma_from_conn(), purge_expired_resolves(), remove_cell_ewma_from_conn(), and set_expiry().

#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 = STRUCT_OFFSET(struct a, bar);
   int *bar_p = STRUCT_VAR_P(&x, bar_offset);
   *bar_p = 3;
 

Referenced by config_alloc(), config_assign_line(), config_assign_value(), config_dump(), config_free(), get_assigned_option(), and option_clear().

#define SUBTYPE_P ( p,
subtype,
basemember   )     ((void*) ( ((char*)(p)) - STRUCT_OFFSET(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);
 

Referenced by cell_ewma_to_circuit().

#define tor_assert ( expr   ) 

Value:

STMT_BEGIN                                     \
    if (PREDICT_UNLIKELY(!(expr))) {                                    \
      log_err(LD_BUG, "%s:%d: %s: Assertion %s failed; aborting.",      \
          _SHORT_FILE_, __LINE__, __func__, #expr);                     \
      fprintf(stderr,"%s:%d %s: Assertion %s failed; aborting.\n",      \
              _SHORT_FILE_, __LINE__, __func__, #expr);                 \
      abort();                                                          \
    } STMT_END
Like assert(3), but send assertion failures to the log as well as to stderr.

Referenced by _circuit_mark_for_close(), _connection_free(), _connection_mark_for_close(), _connection_mark_unattached_ap(), _crypto_new_pk_env_rsa(), _crypto_pk_env_get_evp_pkey(), _dirreq_map_put(), _find_by_keyword(), _routerlist_find_elt(), _tor_memdup(), _tor_strdup(), _tor_strndup(), accounting_parse_options(), accounting_set_wakeup_time(), add_answer_to_cache(), add_cell_ewma_to_conn(), add_connection_to_closeable_list(), add_fingerprint_to_dir(), add_nickname_list_to_smartlist(), add_spaces_to_fp(), addr_policy_free(), address_is_in_virtual_range(), addressmap_get_virtual_address(), addressmap_register_virtual_address(), aes_set_key(), alloc_chunk(), any_bridge_descriptors_known(), assert_active_circuits_ok(), assert_addr_policy_ok(), assert_all_pending_dns_resolves_ok(), assert_buf_ok(), assert_circuit_ok(), assert_connection_edge_not_dns_pending(), assert_connection_ok(), assert_cpath_layer_ok(), assert_cpath_ok(), assert_freelist_ok(), assert_resolve_ok(), assign_onionskin_to_cpuworker(), authdir_wants_to_reject_router(), authority_cert_dup(), authority_cert_get_all(), authority_cert_parse_from_string(), base16_encode(), base32_decode(), base32_encode(), base64_decode(), base64_encode(), buf_add_chunk_with_capacity(), buf_find_pos_of_char(), buf_find_string_offset(), buf_pullup(), buf_remove_from_front(), buf_shrink_freelists(), cell_queue_append(), cell_queue_pop(), check_private_dir(), check_signature_token(), choose_good_middle_server(), chunk_grow(), chunk_new_with_alloc_size(), circuit_all_predicted_ports_handled(), circuit_append_new_exit(), circuit_build_times_add_time(), circuit_build_times_calculate_timeout(), circuit_build_times_cdf(), circuit_build_times_count_pretimeouts(), circuit_build_times_generate_sample(), circuit_build_times_initial_alpha(), circuit_build_times_new_consensus_params(), circuit_build_times_parse_state(), circuit_build_times_update_alpha(), circuit_deliver_create_cell(), circuit_detach_stream(), circuit_discard_optional_exit_enclaves(), circuit_extend(), circuit_finish_handshake(), circuit_free(), circuit_get_all_pending_on_or_conn(), circuit_get_best(), circuit_get_by_edge_conn(), circuit_get_by_rend_query_and_purpose(), circuit_get_next_by_pk_and_purpose(), circuit_get_open_circ_or_launch(), circuit_handle_first_hop(), circuit_init_cpath_crypto(), circuit_is_acceptable(), circuit_launch_by_extend_info(), circuit_list_path_impl(), circuit_n_conn_done(), circuit_package_relay_cell(), circuit_receive_relay_cell(), circuit_remove_handled_ports(), circuit_send_next_onion_skin(), circuit_set_n_circid_orconn(), circuit_set_p_circid_orconn(), circuit_set_state(), circuit_truncated(), clean_cell_pool(), client_dns_set_addressmap(), client_dns_set_addressmap_impl(), command_process_create_cell(), command_process_netinfo_cell(), command_process_versions_cell(), compare_tor_addr_to_addr_policy(), compute_consensus_method(), config_assign_value(), config_dump(), config_free(), config_parse_units(), connection_about_to_close_connection(), connection_add(), connection_ap_can_use_exit(), connection_ap_expire_beginning(), connection_ap_handshake_attach_chosen_circuit(), connection_ap_handshake_attach_circuit(), connection_ap_handshake_process_socks(), connection_ap_handshake_rewrite_and_attach(), connection_ap_handshake_send_begin(), connection_ap_handshake_send_resolve(), connection_ap_handshake_socks_reply(), connection_ap_make_link(), connection_ap_process_end_not_open(), connection_ap_process_natd(), connection_ap_process_transparent(), connection_bucket_refill(), connection_bucket_should_increase(), connection_connect(), connection_control_finished_flushing(), connection_control_process_inbuf(), connection_control_reached_eof(), connection_cpu_finished_flushing(), connection_cpu_process_inbuf(), connection_create_listener(), connection_dir_client_reached_eof(), connection_dir_download_cert_failed(), connection_dir_download_routerdesc_failed(), connection_dir_finished_connecting(), connection_dir_finished_flushing(), connection_dir_process_inbuf(), connection_dirserv_add_dir_bytes_to_outbuf(), connection_dirserv_flushed_some(), connection_dns_remove(), connection_edge_end_errno(), connection_edge_finished_connecting(), connection_edge_finished_flushing(), connection_edge_is_rendezvous_stream(), connection_edge_package_raw_inbuf(), connection_edge_process_inbuf(), connection_edge_process_relay_cell(), connection_edge_process_relay_cell_not_open(), connection_edge_send_command(), connection_exit_begin_conn(), connection_expire_held_open(), connection_finished_connecting(), connection_finished_flushing(), connection_flushed_some(), connection_free(), connection_get_by_type_state_rendquery(), connection_handle_listener_read(), connection_handle_read_impl(), connection_handle_write_impl(), connection_is_reading(), connection_is_writing(), connection_link_connections(), connection_or_check_valid_tls_handshake(), connection_or_connect(), connection_or_finished_connecting(), connection_or_finished_flushing(), connection_or_flush_from_first_active_circuit(), connection_or_get_for_extend(), connection_or_nonopen_was_started_here(), connection_or_process_inbuf(), connection_or_remove_from_identity_map(), connection_or_send_destroy(), connection_or_send_versions(), connection_or_set_identity_digest(), connection_or_write_cell_to_buf(), connection_or_write_var_cell_to_buf(), connection_process_inbuf(), connection_proxy_connect(), connection_read_proxy_handshake(), connection_remove(), connection_start_reading(), connection_start_reading_from_linked_conn(), connection_start_writing(), connection_state_is_connecting(), connection_state_is_open(), connection_stop_reading(), connection_stop_reading_from_linked_conn(), connection_stop_writing(), connection_tls_continue_handshake(), consider_hibernation(), control_event_circuit_status(), control_event_stream_status(), cpuworker_main(), crypto_cipher_decrypt(), crypto_cipher_decrypt_init_cipher(), crypto_cipher_decrypt_with_iv(), crypto_cipher_encrypt(), crypto_cipher_encrypt_init_cipher(), crypto_cipher_encrypt_with_iv(), crypto_cipher_generate_key(), crypto_cipher_set_iv(), crypto_cipher_set_key(), crypto_dh_compute_secret(), crypto_dh_free(), crypto_dh_get_bytes(), crypto_dh_get_public(), crypto_digest(), crypto_digest_add_bytes(), crypto_digest_all(), crypto_digest_assign(), crypto_digest_dup(), crypto_digest_get_digest(), crypto_expand_key_material(), crypto_free_cipher_env(), crypto_get_rsa_padding(), crypto_get_rsa_padding_overhead(), crypto_hmac_sha1(), crypto_pk_check_key(), crypto_pk_cmp_keys(), crypto_pk_copy_full(), crypto_pk_dup_key(), crypto_pk_generate_key_with_bits(), crypto_pk_key_is_private(), crypto_pk_keysize(), crypto_pk_private_decrypt(), crypto_pk_private_hybrid_decrypt(), crypto_pk_private_sign(), crypto_pk_public_checksig(), crypto_pk_public_checksig_digest(), crypto_pk_public_encrypt(), crypto_pk_public_hybrid_encrypt(), crypto_pk_read_private_key_from_string(), crypto_pk_read_public_key_from_string(), crypto_pk_write_key_to_string_impl(), crypto_pk_write_private_key_to_filename(), crypto_rand(), crypto_rand_int(), crypto_rand_uint64(), crypto_random_hostname(), decide_to_advertise_dirport(), decode_escaped_string(), decode_hashed_passwords(), digestmap_assert_ok(), digestmap_free(), digestmap_get(), digestmap_iter_get(), digestmap_iter_init(), digestmap_iter_next(), digestmap_iter_next_rmv(), digestmap_remove(), digestmap_set(), digit_to_num(), dir_routerdesc_download_failed(), dir_split_resource_into_fingerprints(), directory_get_from_all_authorities(), directory_get_from_hs_dir(), directory_handle_command(), directory_handle_command_get(), directory_handle_command_post(), directory_initiate_command_rend(), directory_post_to_dirservers(), directory_send_command(), dirserv_add_extrainfo(), dirserv_add_multiple_descriptors(), dirserv_dump_directory_to_string(), dirserv_estimate_data_size(), dirserv_generate_networkstatus_vote_obj(), dirserv_get_networkstatus_v2(), dirserv_get_networkstatus_v2_fingerprints(), dirserv_get_nickname_by_digest(), dirserv_orconn_tls_done(), dirserv_set_cached_networkstatus_v2(), dirvote_add_signatures_to_pending_consensus(), dirvote_add_vote(), dirvote_compute_consensuses(), dirvote_compute_params(), dirvote_format_microdesc_vote_line(), dirvote_get_pending_consensus(), dirvote_get_preferred_voting_intervals(), dirvote_publish_consensus(), dirvote_recalculate_timing(), dns_cancel_pending_resolve(), dns_found_answer(), dns_resolve(), dns_resolve_impl(), dnsserv_close_listener(), dnsserv_configure_listener(), do_list_fingerprint(), download_status_increment_failure(), dump_desc(), dup_onion_keys(), eat_whitespace(), eat_whitespace_eos(), edge_connection_new(), edge_of_accounting_period_containing(), enable_control_logging(), entry_guard_set_status(), entry_guards_compute_status(), entry_guards_prepend_from_config(), entry_is_live(), evdns_log_cb(), evdns_server_callback(), exit_policy_is_general_exit_helper(), exit_policy_remove_redundancies(), expand_filename(), extend_info_dup(), extend_info_from_router(), extrainfo_get_by_descriptor_digest(), extrainfo_insert(), extrainfo_parse_entry_from_string(), fdopen_file(), fetch_from_buf(), fetch_from_buf_http(), fetch_from_buf_socks(), fetch_from_buf_socks_client(), find_dir_signing_key(), find_dl_schedule_and_len(), find_intro_circuit(), find_start_of_next_router_or_extrainfo(), finish_writing_to_file_impl(), flush_buf(), flush_buf_tls(), flush_chunk(), flush_chunk_tls(), format_networkstatus_vote(), format_rfc1123_time(), ftime_set_maximum_sloppiness(), geoip_add_entry(), geoip_get_client_history(), geoip_note_ns_response(), get_assigned_option(), get_identity_key(), get_interface_address6(), get_next_token(), get_onion_key(), get_options(), get_or_state(), get_unique_circ_id_by_conn(), get_user_homedir(), get_voter(), handle_control_authenticate(), handle_control_getconf(), handle_control_postdescriptor(), handle_getinfo_helper(), hex_digest_matches(), hibernate_end(), hid_serv_get_responsible_directories(), HT_HEAD(), HT_PROTOTYPE(), init_cell_pool(), init_dh_param(), init_key_from_file(), init_keys(), is_legal_hexdigest(), is_legal_nickname(), launch_resolve(), launch_test_addresses(), launch_wildcard_check(), learned_bridge_descriptor(), link_apconn_to_circ(), list_pending_downloads(), list_server_status_v1(), list_single_server_status(), load_downloaded_routers(), load_torrc_from_disk(), make_circuit_active_on_conn(), make_circuit_inactive_on_conn(), make_consensus_method_list(), memarea_alloc(), memarea_assert_ok(), memarea_get_stats(), microdesc_cache_rebuild(), microdescs_parse_from_string(), move_buf_to_buf(), mp_pool_new(), munge_extrainfo_into_routerinfo(), networkstatus_add_detached_signatures(), networkstatus_check_consensus_signature(), networkstatus_compute_consensus(), networkstatus_get_detached_signatures(), networkstatus_parse_detached_signatures(), networkstatus_parse_vote_from_string(), networkstatus_v2_parse_from_string(), new_route_len(), next_circ_on_conn_p(), onion_next_task(), onion_pending_add(), onion_skin_client_handshake(), onion_skin_create(), options_act_reversible(), options_dup(), options_get_datadir_fname2_suffix(), options_init_from_string(), options_validate(), or_state_save(), or_state_set(), orconn_target_get_name(), parse_addr_and_port_range(), parse_addr_port(), parse_bridge_stats_controller(), parse_config_line_from_str(), parse_http_response(), parse_http_time(), parse_port_range(), peek_from_buf(), pick_entry_guards(), policy_expand_private(), policy_summarize(), policy_summary_accept(), policy_summary_add_item(), policy_summary_item_split(), policy_summary_reject(), prev_circ_on_conn_p(), process_pending_task(), purge_expired_resolves(), read_file_to_str(), read_to_buf(), read_to_buf_tls(), read_to_chunk(), read_to_chunk_tls(), realign_pointer(), rectify_client_ciphers(), relay_crypt(), relay_send_command_from_edge(), remove_cell_ewma_from_conn(), remove_obsolete_entry_guards(), rend_cache_lookup_entry(), rend_cache_lookup_v2_desc_as_dir(), rend_cache_store(), rend_cache_store_v2_desc_as_client(), rend_cache_store_v2_desc_as_dir(), rend_check_authorization(), rend_client_introcirc_has_opened(), rend_client_introduction_acked(), rend_client_lookup_service_authorization(), rend_client_receive_rendezvous(), rend_client_refetch_v2_renddesc(), rend_client_rendcirc_has_opened(), rend_client_send_establish_rendezvous(), rend_client_send_introduction(), rend_config_services(), rend_data_dup(), rend_decrypt_introduction_points(), rend_encode_v2_descriptors(), rend_encrypt_v2_intro_points_basic(), rend_encrypt_v2_intro_points_stealth(), rend_get_service_id(), rend_id_is_in_interval(), rend_parse_client_keys(), rend_parse_introduction_points(), rend_parse_service_descriptor(), rend_parse_v2_service_descriptor(), rend_service_intro_established(), rend_service_intro_has_opened(), rend_service_introduce(), rend_service_relaunch_rendezvous(), rend_service_rendezvous_has_opened(), rend_service_set_connection_addr_port(), rend_services_introduce(), rep_hist_exit_stats_write(), rep_hist_fill_bandwidth_history(), rep_hist_get_bandwidth_lines(), rep_hist_get_predicted_ports(), rep_hist_load_state(), rep_hist_note_router_reachable(), rep_hist_note_router_unreachable(), rep_hist_note_used_port(), resolve_my_address(), retry_listeners(), router_add_to_routerlist(), router_choose_random_node(), router_differences_are_cosmetic(), router_dump_router_to_string(), router_get_by_descriptor_digest(), router_get_by_digest(), router_get_by_extrainfo_digest(), router_get_by_hexdigest(), router_get_by_nickname(), router_get_my_descriptor(), router_handles_some_port(), router_load_single_router(), router_nickname_is_in_list(), router_parse_addr_policy(), router_parse_directory(), router_parse_entry_from_string(), router_parse_list_from_string(), router_parse_runningrouters(), router_pick_trusteddirserver(), router_purpose_to_string(), router_rebuild_descriptor(), router_set_networkstatus_v2(), router_set_status(), routerinfo_incompatible_with_extrainfo(), routerlist_assert_ok(), routerlist_descriptors_added(), routerlist_insert(), routerlist_insert_old(), routerlist_remove(), routerlist_remove_old(), routerlist_remove_old_cached_routers_with_id(), routerlist_replace(), routerset_get_all_routers(), routerset_refresh_countries(), routerset_subtract_routers(), routerset_union(), routerstatus_format_entry(), routerstatus_has_changed(), routerstatus_parse_entry_from_string(), run_connection_housekeeping(), safe_str(), safe_str_client(), scale_active_circuits(), secret_to_key(), send_control_event_string(), send_resolved_cell(), send_resolved_hostname_cell(), set_expiry(), set_log_severity_config(), set_max_file_descriptors(), set_options(), set_streams_blocked_on_circ(), should_use_create_fast_for_circuit(), signed_descriptor_get_body_impl(), smartlist_add_all(), smartlist_bsearch_idx(), smartlist_choose_by_bandwidth(), smartlist_choose_by_bandwidth_weights(), smartlist_del(), smartlist_del_keeporder(), smartlist_ensure_capacity(), smartlist_insert(), smartlist_join_strings2(), smartlist_pop_last(), smartlist_pqueue_assert_ok(), smartlist_pqueue_pop(), smartlist_pqueue_remove(), smartlist_reverse(), smartlist_split_string(), smartlist_string_remove(), spawn_cpuworker(), spawn_exit(), spawn_func(), start_writing_to_file(), strmap_assert_ok(), strmap_free(), strmap_get(), strmap_iter_get(), strmap_iter_init(), strmap_iter_next(), strmap_iter_next_rmv(), strmap_remove(), strmap_set(), switch_id(), TO_CONTROL_CONN(), TO_DIR_CONN(), TO_EDGE_CONN(), TO_OR_CIRCUIT(), TO_OR_CONN(), TO_ORIGIN_CIRCUIT(), tokenize_string(), tor_addr_compare_masked(), tor_addr_copy(), tor_addr_from_ipv4n(), tor_addr_from_ipv6_bytes(), tor_addr_from_sockaddr(), tor_addr_from_str(), tor_addr_is_loopback(), tor_addr_is_null(), tor_addr_is_v4(), tor_addr_lookup(), tor_addr_parse_mask_ports(), tor_addr_port_parse(), tor_addr_to_str(), tor_asprintf(), tor_check_dh_key(), tor_close_socket(), tor_gzip_compress(), tor_gzip_uncompress(), tor_inet_pton(), tor_libevent_initialize(), tor_lockfile_unlock(), tor_main(), tor_memmem(), tor_mmap_file(), tor_mutex_acquire(), tor_mutex_release(), tor_mutex_uninit(), tor_parse_uint64(), tor_strtok_r_impl(), tor_timegm(), tor_tls_context_decref(), tor_tls_context_new(), tor_tls_create_certificate(), tor_tls_free(), tor_tls_get_pending_bytes(), tor_tls_handshake(), tor_tls_is_server(), tor_tls_new(), tor_tls_read(), tor_tls_renegotiate(), tor_tls_set_logged_address(), tor_tls_shutdown(), tor_tls_write(), tor_version_as_new_as(), tor_version_compare(), tor_version_is_obsolete(), tor_version_parse(), tor_version_same_series(), tor_zlib_process(), update_consensus_networkstatus_fetch_time(), update_consensus_router_descriptor_downloads(), update_or_history(), validate_data_directory(), validate_ports_csv(), wrap_string(), write_all(), write_chunks_to_file_impl(), write_configuration_file(), write_escaped_data(), write_http_response_header_impl(), and write_to_buf().

 
#define tor_fragile_assert (  ) 

Define this if you want Tor to crash when any problem comes up, so you can get a coredump and track things down.

Referenced by _connection_mark_for_close(), _connection_write_to_buf_impl(), choose_good_exit_server(), choose_random_entry(), circuit_detach_stream(), circuit_launch_by_extend_info(), command_process_cell(), command_process_var_cell(), conn_read_callback(), conn_write_callback(), connection_about_to_close_connection(), connection_ap_get_original_destination(), connection_buckets_decrement(), connection_close_immediate(), connection_dir_finished_flushing(), connection_edge_end(), connection_edge_finished_flushing(), connection_edge_process_inbuf(), connection_finished_connecting(), connection_finished_flushing(), connection_free(), connection_handle_read_impl(), connection_or_finished_flushing(), connection_process_inbuf(), connection_proxy_connect(), connection_reached_eof(), connection_read_proxy_handshake(), crypto_digest_add_bytes(), crypto_digest_algorithm_get_name(), crypto_digest_get_digest(), dns_cancel_pending_resolve(), dns_resolve_impl(), evdns_get_orig_address(), getinfo_helper_events(), networkstatus_get_flavor_name(), purge_expired_resolves(), rend_process_relay_cell(), router_get_consensus_status_by_nickname(), smartlist_choose_by_bandwidth(), smartlist_choose_by_bandwidth_weights(), tor_addr_compare_masked(), tor_addr_hash(), tor_addr_is_loopback(), tor_mutex_acquire(), tor_mutex_init(), tor_mutex_release(), tor_mutex_uninit(), and unescape_string().

#define tor_free (  ) 

Value:

STMT_BEGIN                                 \
    if (PREDICT_LIKELY((p)!=NULL)) {                           \
      free(p);                                                 \
      (p)=NULL;                                                \
    }                                                          \
  STMT_END
Release memory allocated by tor_malloc, tor_realloc, tor_strdup, etc. Unlike the free() function, tor_free() will still work on NULL pointers, and it 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().

Referenced by _connection_free(), _free_cached_resolve(), _free_link_history(), _openssl_dynlock_destroy_cb(), _remove_old_client_helper(), _tor_free(), accounting_parse_options(), add_fingerprint_to_dir(), add_networkstatus_to_cache(), add_nickname_list_to_smartlist(), add_temp_log(), addr_policy_free(), addressmap_ent_free(), addressmap_register(), addressmap_register_virtual_address(), addressmap_rewrite(), addressmap_rewrite_reverse(), addressmap_virtaddress_ent_free(), addressmap_virtaddress_remove(), aes_free_cipher(), alloc_http_authenticator(), assign_onionskin_to_cpuworker(), authority_cert_free(), authority_cert_parse_from_string(), base32_decode(), buf_free(), buf_shrink_freelists(), cached_dir_decref(), cell_queue_clear(), check_nickname_list(), check_private_dir(), check_signature_token(), choose_good_exit_server_general(), chunk_free_unchecked(), circuit_all_predicted_ports_handled(), circuit_build_times_mode(), circuit_build_times_new_consensus_params(), circuit_build_times_parse_state(), circuit_build_times_update_state(), circuit_discard_optional_exit_enclaves(), circuit_free(), circuit_free_cpath_node(), circuit_get_open_circ_or_launch(), circuit_list_path_impl(), circuit_log_path(), circuit_n_conn_done(), circuit_remove_handled_ports(), clean_accepted_intros(), clear_bridge_list(), clear_cached_dir(), clear_geoip_db(), clear_pending_onions(), clear_trackexithost_mappings(), client_check_address_changed(), client_dns_set_reverse_addressmap(), client_likes_consensus(), config_assign(), config_assign_line(), config_assign_value(), config_dump(), config_free(), config_free_all(), config_free_lines(), config_get_lines(), config_register_addressmaps(), configure_nameservers(), connection_ap_handshake_attach_circuit(), connection_ap_handshake_send_resolve(), connection_ap_handshake_socks_resolved(), connection_ap_process_end_not_open(), connection_dir_client_reached_eof(), connection_dir_download_cert_failed(), connection_dir_download_networkstatus_failed(), connection_dirserv_add_microdescs_to_outbuf(), connection_dirserv_add_networkstatus_bytes_to_outbuf(), connection_dirserv_add_servers_to_outbuf(), connection_dns_remove(), connection_exit_begin_conn(), connection_free_all(), connection_or_check_valid_tls_handshake(), connection_or_init_conn_from_address(), connection_proxy_connect(), connection_read_https_proxy_response(), connection_read_proxy_handshake(), connection_unregister_events(), control_event_circuit_status(), control_event_descriptors_changed(), control_event_logmsg(), control_event_networkstatus_changed_helper(), control_event_or_authdir_new_descriptor(), control_event_stream_status(), control_setconf_helper(), cpuworker_main(), create_inet_sockaddr(), crypto_dh_compute_secret(), crypto_dh_free(), crypto_dh_new(), crypto_expand_key_material(), crypto_free_cipher_env(), crypto_free_digest_env(), crypto_free_pk_env(), crypto_global_cleanup(), crypto_pk_asn1_decode(), crypto_pk_asn1_encode(), crypto_pk_get_digest(), crypto_pk_private_hybrid_decrypt(), crypto_pk_public_checksig_digest(), crypto_pk_public_hybrid_encrypt(), crypto_pk_read_private_key_from_filename(), crypto_pk_write_private_key_to_filename(), crypto_random_hostname(), decode_hashed_passwords(), digestmap_free(), digestmap_iter_next_rmv(), digestmap_remove(), digestset_free(), dir_split_resource_into_fingerprint_pairs(), dir_split_resource_into_fingerprints(), directory_clean_last_hid_serv_requests(), directory_get_consensus_url(), directory_handle_command(), directory_handle_command_get(), directory_handle_command_post(), directory_post_to_dirservers(), directory_post_to_hs_dir(), directory_send_command(), dirserv_add_descriptor(), dirserv_clear_old_networkstatuses(), dirserv_dump_directory_to_string(), dirserv_free_fingerprint_list(), dirserv_generate_networkstatus_vote_obj(), dirserv_get_networkstatus_v2(), dirserv_get_routerdesc_fingerprints(), dirserv_get_routerdescs(), dirserv_get_status_impl(), dirserv_load_fingerprint_file(), dirserv_regenerate_directory(), dirserv_remove_old_statuses(), dirvote_act(), dirvote_add_vote(), dirvote_clear_pending_consensuses(), dirvote_clear_votes(), dirvote_compute_consensuses(), dirvote_compute_params(), dirvote_create_microdescriptor(), dirvote_free_all(), dirvote_perform_vote(), dns_cancel_pending_resolve(), dns_found_answer(), dns_free_all(), dns_reset(), dns_reset_correctness_checks(), dns_resolve(), dnsserv_launch_request(), dnsserv_resolved(), document_signature_free(), dump_desc(), entry_guard_free(), entry_guards_parse_state(), entry_guards_prepend_from_config(), esc_router_info(), escaped(), evdns_callback(), evdns_log_cb(), evdns_server_callback(), evdns_wildcard_check_callback(), expand_filename(), extend_info_free(), extrainfo_dump_to_string(), extrainfo_free(), fast_client_handshake(), fast_server_handshake(), fetch_from_buf_socks(), file_status(), find_torrc_filename(), finish_writing_to_file_impl(), format_networkstatus_vote(), format_versions_list(), free_or_history(), generate_runningrouters(), geoip_bridge_stats_write(), geoip_dirreq_stats_write(), geoip_entry_stats_write(), geoip_free_all(), geoip_get_client_history(), geoip_get_dirreq_history(), geoip_get_request_history(), geoip_load_file(), get_assigned_option(), get_default_nickname(), getargs_helper(), getinfo_helper_config(), getinfo_helper_dir(), getinfo_helper_entry_guards(), getinfo_helper_events(), getinfo_helper_networkstatus(), handle_control_attachstream(), handle_control_authenticate(), handle_control_closecircuit(), handle_control_closestream(), handle_control_extendcircuit(), handle_control_getconf(), handle_control_getinfo(), handle_control_loadconf(), handle_control_mapaddress(), handle_control_postdescriptor(), handle_control_protocolinfo(), handle_control_redirectstream(), handle_control_resolve(), handle_control_setcircuitpurpose(), handle_control_setevents(), handle_control_signal(), handle_control_usefeature(), HT_HEAD(), http_set_address_origin(), init_cookie_authentication(), init_keys(), initiate_descriptor_downloads(), launch_direct_bridge_descriptor_fetch(), launch_resolve(), launch_test_addresses(), launch_wildcard_check(), list_getinfo_options(), list_server_status_v1(), list_v3_auth_ids(), load_authority_keyset(), load_bridge_stats(), load_stats_file(), load_torrc_from_disk(), log_cert_lifetime(), log_credential_status(), log_entry_guards(), log_free(), log_set_application_name(), logs_free_all(), logv(), lookup_last_hid_serv_request(), make_consensus_method_list(), measured_bw_line_parse(), memarea_clear_freelist(), memarea_drop_all(), microdesc_cache_rebuild(), microdesc_cache_reload(), microdesc_free(), microdesc_free_all(), munge_extrainfo_into_routerinfo(), networkstatus_check_document_signature(), networkstatus_compute_consensus(), networkstatus_dump_bridge_status_to_file(), networkstatus_format_signatures(), networkstatus_free_all(), networkstatus_get_detached_signatures(), networkstatus_note_certs_arrived(), networkstatus_parse_detached_signatures(), networkstatus_parse_vote_from_string(), networkstatus_set_current_consensus(), networkstatus_v2_free(), networkstatus_v2_list_clean(), networkstatus_vote_free(), normalize_data_directory(), ns_detached_signatures_free(), onion_pending_add(), onion_pending_remove(), onion_skin_client_handshake(), onion_skin_server_handshake(), onionskin_answer(), option_clear(), option_reset(), options_act(), options_act_reversible(), options_dup(), options_init_from_string(), options_init_from_torrc(), options_init_logs(), options_validate(), or_handshake_state_free(), or_state_load(), or_state_save(), or_state_set(), parse_addr_and_port_range(), parse_addr_policy(), parse_addr_port(), parse_bridge_line(), parse_bridge_stats_controller(), parse_dir_server_line(), parse_http_response(), parse_iso_time(), parse_log_severity_config(), parse_port_config(), parse_rfc1123_time(), policy_summarize(), predicted_ports_free(), purge_expired_resolves(), read_bandwidth_usage(), read_file_to_str(), relay_send_command_from_edge(), remove_obsolete_entry_guards(), rend_authorized_client_free(), rend_cache_entry_free(), rend_cache_store(), rend_cache_store_v2_desc_as_client(), rend_cache_store_v2_desc_as_dir(), rend_config_services(), rend_data_free(), rend_decrypt_introduction_points(), rend_desc_v2_is_parsable(), rend_encode_v2_descriptors(), rend_encode_v2_intro_points(), rend_encoded_v2_service_descriptor_free(), rend_encrypt_v2_intro_points_basic(), rend_encrypt_v2_intro_points_stealth(), rend_intro_point_free(), rend_parse_service_authorization(), rend_parse_v2_service_descriptor(), rend_service_authorization_free(), rend_service_descriptor_free(), rend_service_free(), rend_service_load_keys(), rep_hist_buffer_stats_write(), rep_hist_exit_stats_write(), rep_hist_free_all(), rep_hist_get_predicted_ports(), rep_hist_get_router_stability_doc(), rep_hist_load_mtbf_data(), rep_hist_load_state(), rep_hist_record_mtbf_data(), rep_hist_update_state(), rep_history_clean(), retry_listeners(), rotate_onion_key(), router_append_dirobj_signature(), router_dump_router_to_string(), router_free_all(), router_load_routers_from_string(), router_nickname_is_in_list(), router_rebuild_descriptor(), router_rebuild_store(), router_reload_consensus_networkstatus(), router_reload_router_list_impl(), router_reload_v2_networkstatus(), router_reset_warnings(), router_set_networkstatus_v2(), router_upload_dir_desc_to_dirservers(), routerinfo_free(), routerinfo_incompatible_with_extrainfo(), routerlist_free(), routerlist_free_all(), routerlist_remove_old_cached_routers_with_id(), routerlist_reset_warnings(), routerset_free(), routerset_parse(), routerset_union(), routerstatus_format_entry(), routerstatus_free(), secret_to_key(), set_cached_dir(), signed_desc_append_to_journal(), signed_descriptor_free(), smartlist_choose_by_bandwidth(), smartlist_choose_by_bandwidth_weights(), smartlist_free(), smartlist_string_remove(), spawn_cpuworker(), start_writing_to_file(), strmap_free(), strmap_get_lc(), strmap_iter_next_rmv(), strmap_remove(), strmap_remove_lc(), strmap_set_lc(), tell_controller_about_resolved_result(), tor_addr_from_str(), tor_addr_parse_mask_ports(), tor_addr_port_parse(), tor_event_free(), tor_free_all(), tor_gzip_compress(), tor_gzip_uncompress(), tor_listdir(), tor_lockfile_unlock(), tor_munmap_file(), tor_mutex_free(), tor_pthread_helper_fn(), tor_tls_client_is_using_v2_ciphers(), tor_tls_context_decref(), tor_tls_context_new(), tor_tls_free(), tor_tls_free_all(), tor_tls_new(), tor_tls_set_logged_address(), tor_vasprintf(), tor_version_is_obsolete(), tor_zlib_free(), tor_zlib_new(), trusted_dir_server_free(), trusted_dirs_load_certs_from_string(), trusted_dirs_reload_certs(), try_locking(), unescape_string(), var_cell_free(), vote_routerstatus_free(), and write_configuration_file().


Enumeration Type Documentation

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

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


Function Documentation

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

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

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

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

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

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

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

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

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


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