Back to index

tor  0.2.3.18-rc
Classes | Functions | Variables
circuitbuild.h File Reference

Header file for circuitbuild.c. More...

This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Classes

struct  transport_t
 Represents a pluggable transport proxy used by a bridge. More...

Functions

char * circuit_list_path (origin_circuit_t *circ, int verbose)
 If verbose is false, allocate and return a comma-separated list of the currently built elements of circ.
char * circuit_list_path_for_controller (origin_circuit_t *circ)
 Allocate and return a comma-separated list of the currently built elements of circ, giving each as a verbose nickname.
void circuit_log_path (int severity, unsigned int domain, origin_circuit_t *circ)
 Log, at severity severity, the nicknames of each router in circ's cpath.
void circuit_rep_hist_note_result (origin_circuit_t *circ)
 Tell the rep(utation)hist(ory) module about the status of the links in circ.
origin_circuit_torigin_circuit_init (uint8_t purpose, int flags)
 Create and return a new origin circuit.
origin_circuit_tcircuit_establish_circuit (uint8_t purpose, extend_info_t *exit, int flags)
 Build a new circuit for purpose.
int circuit_handle_first_hop (origin_circuit_t *circ)
 Start establishing the first hop of our circuit.
void circuit_n_conn_done (or_connection_t *or_conn, int status)
 Find any circuits that are waiting on or_conn to become open and get them to send their create cells forward.
int inform_testing_reachability (void)
 We've decided to start our reachability testing.
int circuit_timeout_want_to_count_circ (origin_circuit_t *circ)
 Return true if circ is the type of circuit we want to count timeouts from.
int circuit_send_next_onion_skin (origin_circuit_t *circ)
 This is the backbone function for building circuits.
void circuit_note_clock_jumped (int seconds_elapsed)
 Our clock just jumped by seconds_elapsed.
int circuit_extend (cell_t *cell, circuit_t *circ)
 Take the 'extend' cell, pull out addr/port plus the onion skin and identity digest for the next hop.
int circuit_init_cpath_crypto (crypt_path_t *cpath, const char *key_data, int reverse)
 Initialize cpath->{f|b}_{crypto|digest} from the key material in key_data.
int circuit_finish_handshake (origin_circuit_t *circ, uint8_t cell_type, const uint8_t *reply)
 A created or extended cell came back to us on the circuit, and it included reply as its body.
int circuit_truncated (origin_circuit_t *circ, crypt_path_t *layer)
 We received a relay truncated cell on circ.
int onionskin_answer (or_circuit_t *circ, uint8_t cell_type, const char *payload, const char *keys)
 Given a response payload and keys, initialize, then send a created cell back.
int circuit_all_predicted_ports_handled (time_t now, int *need_uptime, int *need_capacity)
 Return 1 if we already have circuits present or on the way for all anticipated ports.
int circuit_append_new_exit (origin_circuit_t *circ, extend_info_t *info)
 Give circ a new exit destination to exit, and add a hop to the cpath reflecting this.
int circuit_extend_to_new_exit (origin_circuit_t *circ, extend_info_t *info)
 Take an open circ, and add a new hop at the end, based on info.
void onion_append_to_cpath (crypt_path_t **head_ptr, crypt_path_t *new_hop)
 Add new_hop to the end of the doubly-linked-list head_ptr.
extend_info_textend_info_alloc (const char *nickname, const char *digest, crypto_pk_t *onion_key, const tor_addr_t *addr, uint16_t port)
 Allocate a new extend_info object based on the various arguments.
extend_info_textend_info_from_router (const routerinfo_t *r, int for_direct_connect)
 Allocate and return a new extend_info_t that can be used to build a circuit to or through the router r.
extend_info_textend_info_from_node (const node_t *node, int for_direct_connect)
 Allocate and return a new extend_info that can be used to build a circuit to or through the node node.
extend_info_textend_info_dup (extend_info_t *info)
 Allocate and return a new extend_info_t with the same contents as info.
void extend_info_free (extend_info_t *info)
 Release storage held by an extend_info_t struct.
const node_tbuild_state_get_exit_node (cpath_build_state_t *state)
 Return the routerinfo_t for the chosen exit router in state.
const char * build_state_get_exit_nickname (cpath_build_state_t *state)
 Return the nickname for the chosen exit router in state.
void entry_guards_compute_status (const or_options_t *options, time_t now)
 A new directory or router-status has arrived; update the down/listed status of the entry guards.
int entry_guard_register_connect_status (const char *digest, int succeeded, int mark_relay_status, time_t now)
 Called when a connection to an OR with the identity digest digest is established (succeeded==1) or has failed (succeeded==0).
void entry_nodes_should_be_added (void)
 Called when the value of EntryNodes changes in our configuration.
int entry_list_is_constrained (const or_options_t *options)
 Return 0 if we're fine adding arbitrary routers out of the directory to our entry guard list, or return 1 if we have a list already and we must stick to it.
const node_tchoose_random_entry (cpath_build_state_t *state)
 Pick a live (up and listed) entry guard from entry_guards.
int entry_guards_parse_state (or_state_t *state, int set, char **msg)
 Parse state and learn about the entry guards it describes.
void entry_guards_update_state (or_state_t *state)
 If the entry guard info has not changed, do nothing and return.
int getinfo_helper_entry_guards (control_connection_t *conn, const char *question, char **answer, const char **errmsg)
 If question is the string "entry-guards", then dump to *answer a newly allocated string describing all of the nodes in the global entry_guards list.
void mark_bridge_list (void)
 Mark every entry of the bridge list to be removed on our next call to sweep_bridge_list unless it has first been un-marked.
void sweep_bridge_list (void)
 Remove every entry of the bridge list that was marked with mark_bridge_list if it has not subsequently been un-marked.
void mark_transport_list (void)
 Mark every entry of the transport list to be removed on our next call to sweep_transport_list unless it has first been un-marked.
void sweep_transport_list (void)
 Remove every entry of the transport list that was marked with mark_transport_list if it has not subsequently been un-marked.
int routerinfo_is_a_configured_bridge (const routerinfo_t *ri)
 Return 1 if ri is one of our known bridges, else 0.
int node_is_a_configured_bridge (const node_t *node)
 Return 1 if node is one of our configured bridges, else 0.
void learned_router_identity (const tor_addr_t *addr, uint16_t port, const char *digest)
 We made a connection to a router at addr:port without knowing its digest.
void bridge_add_from_config (const tor_addr_t *addr, uint16_t port, const char *digest, const char *transport_name)
 Remember a new bridge at addr:port.
void retry_bridge_descriptor_fetch_directly (const char *digest)
 Fetching the bridge descriptor from the bridge authority returned a "not found".
void fetch_bridge_descriptors (const or_options_t *options, time_t now)
 For each bridge in our list for which we don't currently have a descriptor, fetch a new copy of its descriptor -- either directly from the bridge or via a bridge authority.
void learned_bridge_descriptor (routerinfo_t *ri, int from_cache)
 We just learned a descriptor for a bridge.
int any_bridge_descriptors_known (void)
 Return 1 if any of our entry guards have descriptors that are marked with purpose 'bridge' and are running.
int any_pending_bridge_descriptor_fetches (void)
 Return 1 if there are any directory conns fetching bridge descriptors that aren't marked for close.
int entries_known_but_down (const or_options_t *options)
 Do we know any descriptors for our bridges / entrynodes, and are all the ones we have descriptors for down?
void entries_retry_all (const or_options_t *options)
 Mark all down known bridges / entrynodes up.
int any_bridges_dont_support_microdescriptors (void)
 Return true if we've ever had a bridge running a Tor version that can't provide microdescriptors to us.
void entry_guards_free_all (void)
 Release all storage held by the list of entry guards and related memory structs.
int circuit_build_times_enough_to_compute (circuit_build_times_t *cbt)
 Return true iff cbt has recorded enough build times that we want to start acting on the timeout it implies.
void circuit_build_times_update_state (circuit_build_times_t *cbt, or_state_t *state)
 Output a histogram of current circuit build times to the or_state_t state structure.
int circuit_build_times_parse_state (circuit_build_times_t *cbt, or_state_t *state)
 Load histogram from state, shuffling the resulting array after we do so.
void circuit_build_times_count_timeout (circuit_build_times_t *cbt, int did_onehop)
 Update timeout counts to determine if we need to expire our build time history due to excessive timeouts.
int circuit_build_times_count_close (circuit_build_times_t *cbt, int did_onehop, time_t start_time)
 Store a timeout as a synthetic value.
void circuit_build_times_set_timeout (circuit_build_times_t *cbt)
 Exposed function to compute a new timeout.
int circuit_build_times_add_time (circuit_build_times_t *cbt, build_time_t time)
 Add a new build time value time to the set of build times.
int circuit_build_times_needs_circuits (circuit_build_times_t *cbt)
 Returns true if we need circuits to be built.
int circuit_build_times_needs_circuits_now (circuit_build_times_t *cbt)
 Returns true if we should build a timeout test circuit right now.
void circuit_build_times_init (circuit_build_times_t *cbt)
 Initialize the buildtimes structure for first use.
void circuit_build_times_free_timeouts (circuit_build_times_t *cbt)
 Free the saved timeouts, if the cbtdisabled consensus parameter got turned on or something.
void circuit_build_times_new_consensus_params (circuit_build_times_t *cbt, networkstatus_t *ns)
 This function is called when we get a consensus update.
double circuit_build_times_timeout_rate (const circuit_build_times_t *cbt)
 Count the number of timeouts in a set of cbt data.
double circuit_build_times_close_rate (const circuit_build_times_t *cbt)
 Count the number of closed circuits in a set of cbt data.
void circuit_build_times_network_is_live (circuit_build_times_t *cbt)
 Called to indicate that the network showed some signs of liveness, i.e.
int circuit_build_times_network_check_live (circuit_build_times_t *cbt)
 When the network is not live, we do not record circuit build times.
void circuit_build_times_network_circ_success (circuit_build_times_t *cbt)
 Called to indicate that we completed a circuit.
int circuit_build_times_get_bw_scale (networkstatus_t *ns)
void clear_transport_list (void)
 Initialize the pluggable transports list to empty, creating it if needed.
int transport_add_from_config (const tor_addr_t *addr, uint16_t port, const char *name, int socks_ver)
 Remember a new pluggable transport proxy at addr:port.
int transport_add (transport_t *t)
 Add transport t to the internal list of pluggable transports.
void transport_free (transport_t *transport)
 Free the pluggable transport struct transport.
transport_ttransport_new (const tor_addr_t *addr, uint16_t port, const char *name, int socks_ver)
 Returns a transport_t struct for a transport proxy supporting the protocol name listening at addr:port using SOCKS version socks_ver.
const char * find_transport_name_by_bridge_addrport (const tor_addr_t *addr, uint16_t port)
int find_transport_by_bridge_addrport (const tor_addr_t *addr, uint16_t port, const transport_t **transport)
 If addr and port match the address and port of a bridge of ours that uses pluggable transports, place its transport in transport.
transport_ttransport_get_by_name (const char *name)
 Returns the transport in our transport list that has the name name.

Variables

circuit_build_times_t circ_times
 Global list of circuit build times.

Detailed Description

Header file for circuitbuild.c.

Definition in file circuitbuild.h.


Class Documentation

struct transport_t

Represents a pluggable transport proxy used by a bridge.

Definition at line 16 of file circuitbuild.h.

Collaboration diagram for transport_t:
Class Members
tor_addr_t addr Address of proxy.
unsigned marked_for_removal: 1 Boolean: We are re-parsing our transport list, and we are going to remove this one if we don't find it in the list of configured transports.
char * name Name of pluggable transport protocol.
uint16_t port Port of proxy.
int socks_version SOCKS version: One of PROXY_SOCKS4, PROXY_SOCKS5.

Function Documentation

Return 1 if any of our entry guards have descriptors that are marked with purpose 'bridge' and are running.

Else return 0.

We use this function to decide if we're ready to start building circuits through our bridges, or if we need to wait until the directory "server/authority" requests finish.

Definition at line 5677 of file circuitbuild.c.

{
  tor_assert(get_options()->UseBridges);
  return choose_random_entry(NULL)!=NULL ? 1 : 0;
}

Here is the call graph for this function:

Here is the caller graph for this function:

Return true if we've ever had a bridge running a Tor version that can't provide microdescriptors to us.

In that case fall back to asking for full descriptors. Eventually all bridges will support microdescriptors and we can take this check out; see bug 4013.

Definition at line 5768 of file circuitbuild.c.

{
  const node_t *node;
  static int ever_answered_yes = 0;
  if (!get_options()->UseBridges || !entry_guards)
    return 0;
  if (ever_answered_yes)
    return 1; /* if we ever answer 'yes', always answer 'yes' */
  SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, e) {
    node = node_get_by_id(e->identity);
    if (node && node->ri &&
        node_is_bridge(node) && node_is_a_configured_bridge(node) &&
        !tor_version_supports_microdescriptors(node->ri->platform)) {
      /* This is one of our current bridges, and we know enough about
       * it to know that it won't be able to answer our microdescriptor
       * questions. */
      ever_answered_yes = 1;
      return 1;
    }
  } SMARTLIST_FOREACH_END(e);
  return 0;
}

Here is the call graph for this function:

Here is the caller graph for this function:

Return 1 if there are any directory conns fetching bridge descriptors that aren't marked for close.

We use this to guess if we should tell the controller that we have a problem.

Definition at line 5687 of file circuitbuild.c.

{
  smartlist_t *conns = get_connection_array();
  SMARTLIST_FOREACH(conns, connection_t *, conn,
  {
    if (conn->type == CONN_TYPE_DIR &&
        conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
        TO_DIR_CONN(conn)->router_purpose == ROUTER_PURPOSE_BRIDGE &&
        !conn->marked_for_close &&
        conn->linked &&
        conn->linked_conn && !conn->linked_conn->marked_for_close) {
      log_debug(LD_DIR, "found one: %s", conn->address);
      return 1;
    }
  });
  return 0;
}

Here is the call graph for this function:

Here is the caller graph for this function:

void bridge_add_from_config ( const tor_addr_t addr,
uint16_t  port,
const char *  digest,
const char *  transport_name 
)

Remember a new bridge at addr:port.

If digest is set, it tells us the identity key too. If we already had the bridge in our list, unmark it, and don't actually add anything new. If transport_name is non-NULL - the bridge is associated with a pluggable transport - we assign the transport to the bridge.

Definition at line 5328 of file circuitbuild.c.

{
  bridge_info_t *b;

  bridge_resolve_conflicts(addr, port, digest, transport_name);

  b = tor_malloc_zero(sizeof(bridge_info_t));
  tor_addr_copy(&b->addr, addr);
  b->port = port;
  if (digest)
    memcpy(b->identity, digest, DIGEST_LEN);
  if (transport_name)
    b->transport_name = tor_strdup(transport_name);
  b->fetch_status.schedule = DL_SCHED_BRIDGE;
  if (!bridge_list)
    bridge_list = smartlist_new();

  smartlist_add(bridge_list, b);
}

Here is the call graph for this function:

Here is the caller graph for this function:

Return the nickname for the chosen exit router in state.

If there is no chosen exit, or if we don't know the routerinfo_t for the chosen exit, return NULL.

Definition at line 3746 of file circuitbuild.c.

{
  if (!state || !state->chosen_exit)
    return NULL;
  return state->chosen_exit->nickname;
}

Here is the caller graph for this function:

Return the routerinfo_t for the chosen exit router in state.

If there is no chosen exit, or if we don't know the routerinfo_t for the chosen exit, return NULL.

Definition at line 3734 of file circuitbuild.c.

{
  if (!state || !state->chosen_exit)
    return NULL;
  return node_get_by_id(state->chosen_exit->identity_digest);
}

Here is the call graph for this function:

Here is the caller graph for this function:

Pick a live (up and listed) entry guard from entry_guards.

If state is non-NULL, this is for a specific circuit -- make sure not to pick this circuit's exit or any node in the exit's family. If state is NULL, we're looking for a random guard (likely a bridge).

Definition at line 4479 of file circuitbuild.c.

{
  const or_options_t *options = get_options();
  smartlist_t *live_entry_guards = smartlist_new();
  smartlist_t *exit_family = smartlist_new();
  const node_t *chosen_exit =
    state?build_state_get_exit_node(state) : NULL;
  const node_t *node = NULL;
  int need_uptime = state ? state->need_uptime : 0;
  int need_capacity = state ? state->need_capacity : 0;
  int preferred_min, consider_exit_family = 0;

  if (chosen_exit) {
    nodelist_add_node_and_family(exit_family, chosen_exit);
    consider_exit_family = 1;
  }

  if (!entry_guards)
    entry_guards = smartlist_new();

  if (should_add_entry_nodes)
    entry_guards_set_from_config(options);

  if (!entry_list_is_constrained(options) &&
      smartlist_len(entry_guards) < options->NumEntryGuards)
    pick_entry_guards(options);

 retry:
  smartlist_clear(live_entry_guards);
  SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, entry) {
      const char *msg;
      node = entry_is_live(entry, need_uptime, need_capacity, 0, &msg);
      if (!node)
        continue; /* down, no point */
      if (node == chosen_exit)
        continue; /* don't pick the same node for entry and exit */
      if (consider_exit_family && smartlist_isin(exit_family, node))
        continue; /* avoid relays that are family members of our exit */
#if 0 /* since EntryNodes is always strict now, this clause is moot */
      if (options->EntryNodes &&
          !routerset_contains_node(options->EntryNodes, node)) {
        /* We've come to the end of our preferred entry nodes. */
        if (smartlist_len(live_entry_guards))
          goto choose_and_finish; /* only choose from the ones we like */
        if (options->StrictNodes) {
          /* in theory this case should never happen, since
           * entry_guards_set_from_config() drops unwanted relays */
          tor_fragile_assert();
        } else {
          log_info(LD_CIRC,
                   "No relays from EntryNodes available. Using others.");
        }
      }
#endif
      smartlist_add(live_entry_guards, (void*)node);
      if (!entry->made_contact) {
        /* Always start with the first not-yet-contacted entry
         * guard. Otherwise we might add several new ones, pick
         * the second new one, and now we've expanded our entry
         * guard list without needing to. */
        goto choose_and_finish;
      }
      if (smartlist_len(live_entry_guards) >= options->NumEntryGuards)
        goto choose_and_finish; /* we have enough */
  } SMARTLIST_FOREACH_END(entry);

  if (entry_list_is_constrained(options)) {
    /* If we prefer the entry nodes we've got, and we have at least
     * one choice, that's great. Use it. */
    preferred_min = 1;
  } else {
    /* Try to have at least 2 choices available. This way we don't
     * get stuck with a single live-but-crummy entry and just keep
     * using him.
     * (We might get 2 live-but-crummy entry guards, but so be it.) */
    preferred_min = 2;
  }

  if (smartlist_len(live_entry_guards) < preferred_min) {
    if (!entry_list_is_constrained(options)) {
      /* still no? try adding a new entry then */
      /* XXX if guard doesn't imply fast and stable, then we need
       * to tell add_an_entry_guard below what we want, or it might
       * be a long time til we get it. -RD */
      node = add_an_entry_guard(NULL, 0, 0);
      if (node) {
        entry_guards_changed();
        /* XXX we start over here in case the new node we added shares
         * a family with our exit node. There's a chance that we'll just
         * load up on entry guards here, if the network we're using is
         * one big family. Perhaps we should teach add_an_entry_guard()
         * to understand nodes-to-avoid-if-possible? -RD */
        goto retry;
      }
    }
    if (!node && need_uptime) {
      need_uptime = 0; /* try without that requirement */
      goto retry;
    }
    if (!node && need_capacity) {
      /* still no? last attempt, try without requiring capacity */
      need_capacity = 0;
      goto retry;
    }
#if 0
    /* Removing this retry logic: if we only allow one exit, and it is in the
       same family as all our entries, then we are just plain not going to win
       here. */
    if (!node && entry_list_is_constrained(options) && consider_exit_family) {
      /* still no? if we're using bridges or have strictentrynodes
       * set, and our chosen exit is in the same family as all our
       * bridges/entry guards, then be flexible about families. */
      consider_exit_family = 0;
      goto retry;
    }
#endif
    /* live_entry_guards may be empty below. Oh well, we tried. */
  }

 choose_and_finish:
  if (entry_list_is_constrained(options)) {
    /* We need to weight by bandwidth, because our bridges or entryguards
     * were not already selected proportional to their bandwidth. */
    node = node_sl_choose_by_bandwidth(live_entry_guards, WEIGHT_FOR_GUARD);
  } else {
    /* We choose uniformly at random here, because choose_good_entry_server()
     * already weights its choices by bandwidth, so we don't want to
     * *double*-weight our guard selection. */
    node = smartlist_choose(live_entry_guards);
  }
  smartlist_free(live_entry_guards);
  smartlist_free(exit_family);
  return node;
}

Here is the call graph for this function:

Here is the caller graph for this function:

int circuit_all_predicted_ports_handled ( time_t  now,
int *  need_uptime,
int *  need_capacity 
)

Return 1 if we already have circuits present or on the way for all anticipated ports.

Return 0 if we should make more.

If we're returning 0, set need_uptime and need_capacity to indicate any requirements that the unhandled ports have.

Definition at line 2922 of file circuitbuild.c.

{
  int i, enough;
  uint16_t *port;
  smartlist_t *sl = circuit_get_unhandled_ports(now);
  smartlist_t *LongLivedServices = get_options()->LongLivedPorts;
  tor_assert(need_uptime);
  tor_assert(need_capacity);
  // Always predict need_capacity
  *need_capacity = 1;
  enough = (smartlist_len(sl) == 0);
  for (i = 0; i < smartlist_len(sl); ++i) {
    port = smartlist_get(sl, i);
    if (smartlist_string_num_isin(LongLivedServices, *port))
      *need_uptime = 1;
    tor_free(port);
  }
  smartlist_free(sl);
  return enough;
}

Here is the call graph for this function:

Here is the caller graph for this function:

Give circ a new exit destination to exit, and add a hop to the cpath reflecting this.

Don't send the next extend cell -- the caller will do this if it wants to.

Definition at line 3359 of file circuitbuild.c.

{
  cpath_build_state_t *state;
  tor_assert(exit);
  tor_assert(circ);

  state = circ->build_state;
  tor_assert(state);
  extend_info_free(state->chosen_exit);
  state->chosen_exit = extend_info_dup(exit);

  ++circ->build_state->desired_path_len;
  onion_append_hop(&circ->cpath, exit);
  return 0;
}

Here is the call graph for this function:

Here is the caller graph for this function:

Add a new build time value time to the set of build times.

Time units are milliseconds.

circuit_build_times cbt is a circular array, so loop around when array is full.

Definition at line 654 of file circuitbuild.c.

{
  if (time <= 0 || time > CBT_BUILD_TIME_MAX) {
    log_warn(LD_BUG, "Circuit build time is too large (%u)."
                      "This is probably a bug.", time);
    tor_fragile_assert();
    return -1;
  }

  log_debug(LD_CIRC, "Adding circuit build time %u", time);

  cbt->circuit_build_times[cbt->build_times_idx] = time;
  cbt->build_times_idx = (cbt->build_times_idx + 1) % CBT_NCIRCUITS_TO_OBSERVE;
  if (cbt->total_build_times < CBT_NCIRCUITS_TO_OBSERVE)
    cbt->total_build_times++;

  if ((cbt->total_build_times % CBT_SAVE_STATE_EVERY) == 0) {
    /* Save state every n circuit builds */
    if (!unit_tests && !get_options()->AvoidDiskWrites)
      or_state_mark_dirty(get_or_state(), 0);
  }

  return 0;
}

Here is the call graph for this function:

Here is the caller graph for this function:

Count the number of closed circuits in a set of cbt data.

Definition at line 1489 of file circuitbuild.c.

{
  int i=0,closed=0;
  for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
    if (cbt->circuit_build_times[i] == CBT_BUILD_ABANDONED) {
       closed++;
    }
  }

  if (!cbt->total_build_times)
    return 0;

  return ((double)closed)/cbt->total_build_times;
}

Here is the caller graph for this function:

int circuit_build_times_count_close ( circuit_build_times_t cbt,
int  did_onehop,
time_t  start_time 
)

Store a timeout as a synthetic value.

Returns true if the store was successful and we should possibly update our timeout estimate.

Definition at line 1511 of file circuitbuild.c.

{
  if (circuit_build_times_disabled()) {
    cbt->close_ms = cbt->timeout_ms
                  = circuit_build_times_get_initial_timeout();
    return 0;
  }

  /* Record this force-close to help determine if the network is dead */
  circuit_build_times_network_close(cbt, did_onehop, start_time);

  /* Only count timeouts if network is live.. */
  if (!circuit_build_times_network_check_live(cbt)) {
    return 0;
  }

  circuit_build_times_add_time(cbt, CBT_BUILD_ABANDONED);
  return 1;
}

Here is the call graph for this function:

Here is the caller graph for this function:

void circuit_build_times_count_timeout ( circuit_build_times_t cbt,
int  did_onehop 
)

Update timeout counts to determine if we need to expire our build time history due to excessive timeouts.

We do not record any actual time values at this stage; we are only interested in recording the fact that a timeout happened. We record the time values via circuit_build_times_count_close() and circuit_build_times_add_time().

Definition at line 1543 of file circuitbuild.c.

{
  if (circuit_build_times_disabled()) {
    cbt->close_ms = cbt->timeout_ms
                  = circuit_build_times_get_initial_timeout();
    return;
  }

  /* Register the fact that a timeout just occurred. */
  circuit_build_times_network_timeout(cbt, did_onehop);

  /* If there are a ton of timeouts, we should reset
   * the circuit build timeout. */
  circuit_build_times_network_check_changed(cbt);
}

Here is the call graph for this function:

Here is the caller graph for this function:

Return true iff cbt has recorded enough build times that we want to start acting on the timeout it implies.

Definition at line 259 of file circuitbuild.c.

Here is the call graph for this function:

Here is the caller graph for this function:

Free the saved timeouts, if the cbtdisabled consensus parameter got turned on or something.

Definition at line 606 of file circuitbuild.c.

Here is the caller graph for this function:

Definition at line 290 of file circuitbuild.c.

Here is the call graph for this function:

Here is the caller graph for this function:

Initialize the buildtimes structure for first use.

Sets the initial timeout values based on either the config setting, the consensus param, or the default (CBT_DEFAULT_TIMEOUT_INITIAL_VALUE).

Definition at line 580 of file circuitbuild.c.

{
  memset(cbt, 0, sizeof(*cbt));
  /*
   * Check if we really are using adaptive timeouts, and don't keep
   * track of this stuff if not.
   */
  if (!circuit_build_times_disabled()) {
    cbt->liveness.num_recent_circs =
      circuit_build_times_recent_circuit_count(NULL);
    cbt->liveness.timeouts_after_firsthop =
      tor_malloc_zero(sizeof(int8_t)*cbt->liveness.num_recent_circs);
  } else {
    cbt->liveness.num_recent_circs = 0;
    cbt->liveness.timeouts_after_firsthop = NULL;
  }
  cbt->close_ms = cbt->timeout_ms = circuit_build_times_get_initial_timeout();
  control_event_buildtimeout_set(cbt, BUILDTIMEOUT_SET_EVENT_RESET);
}

Here is the call graph for this function:

Here is the caller graph for this function:

Returns true if we need circuits to be built.

Definition at line 1245 of file circuitbuild.c.

{
  /* Return true if < MIN_CIRCUITS_TO_OBSERVE */
  return !circuit_build_times_enough_to_compute(cbt);
}

Here is the call graph for this function:

Here is the caller graph for this function:

Returns true if we should build a timeout test circuit right now.

Definition at line 1256 of file circuitbuild.c.

Here is the call graph for this function:

Here is the caller graph for this function:

When the network is not live, we do not record circuit build times.

The network is considered not live if there has been at least one circuit build that began and ended (had its close_ms measurement period expire) since we last received a cell.

Also has the side effect of rewinding the circuit time history in the case of recent liveness changes.

Definition at line 1389 of file circuitbuild.c.

{
  if (cbt->liveness.nonlive_timeouts > 0) {
    return 0;
  }

  return 1;
}

Here is the caller graph for this function:

Called to indicate that we completed a circuit.

Because this circuit succeeded, it doesn't count as a timeout-after-the-first-hop.

This is used by circuit_build_times_network_check_changed() to determine if we had too many recent timeouts and need to reset our learned timeout to something higher.

Definition at line 1297 of file circuitbuild.c.

{
  /* Check for NULLness because we might not be using adaptive timeouts */
  if (cbt->liveness.timeouts_after_firsthop &&
      cbt->liveness.num_recent_circs > 0) {
    cbt->liveness.timeouts_after_firsthop[cbt->liveness.after_firsthop_idx]
      = 0;
    cbt->liveness.after_firsthop_idx++;
    cbt->liveness.after_firsthop_idx %= cbt->liveness.num_recent_circs;
  }
}

Here is the caller graph for this function:

Called to indicate that the network showed some signs of liveness, i.e.

we received a cell.

This is used by circuit_build_times_network_check_live() to decide if we should record the circuit build timeout or not.

This function is called every time we receive a cell. Avoid syscalls, events, and other high-intensity work.

Definition at line 1273 of file circuitbuild.c.

{
  time_t now = approx_time();
  if (cbt->liveness.nonlive_timeouts > 0) {
    log_notice(LD_CIRC,
               "Tor now sees network activity. Restoring circuit build "
               "timeout recording. Network was down for %d seconds "
               "during %d circuit attempts.",
               (int)(now - cbt->liveness.network_last_live),
               cbt->liveness.nonlive_timeouts);
  }
  cbt->liveness.network_last_live = now;
  cbt->liveness.nonlive_timeouts = 0;
}

Here is the call graph for this function:

Here is the caller graph for this function:

This function is called when we get a consensus update.

It checks to see if we have changed any consensus parameters that require reallocation or discard of previous stats.

Definition at line 441 of file circuitbuild.c.

{
  int32_t num;

  /*
   * First check if we're doing adaptive timeouts at all; nothing to
   * update if we aren't.
   */

  if (!circuit_build_times_disabled()) {
    num = circuit_build_times_recent_circuit_count(ns);

    if (num > 0) {
      if (num != cbt->liveness.num_recent_circs) {
        int8_t *recent_circs;
        log_notice(LD_CIRC, "The Tor Directory Consensus has changed how many "
                   "circuits we must track to detect network failures from %d "
                   "to %d.", cbt->liveness.num_recent_circs, num);

        tor_assert(cbt->liveness.timeouts_after_firsthop ||
                   cbt->liveness.num_recent_circs == 0);

        /*
         * Technically this is a circular array that we are reallocating
         * and memcopying. However, since it only consists of either 1s
         * or 0s, and is only used in a statistical test to determine when
         * we should discard our history after a sufficient number of 1's
         * have been reached, it is fine if order is not preserved or
         * elements are lost.
         *
         * cbtrecentcount should only be changing in cases of severe network
         * distress anyway, so memory correctness here is paramount over
         * doing acrobatics to preserve the array.
         */
        recent_circs = tor_malloc_zero(sizeof(int8_t)*num);
        if (cbt->liveness.timeouts_after_firsthop &&
            cbt->liveness.num_recent_circs > 0) {
          memcpy(recent_circs, cbt->liveness.timeouts_after_firsthop,
                 sizeof(int8_t)*MIN(num, cbt->liveness.num_recent_circs));
        }

        // Adjust the index if it needs it.
        if (num < cbt->liveness.num_recent_circs) {
          cbt->liveness.after_firsthop_idx = MIN(num-1,
                  cbt->liveness.after_firsthop_idx);
        }

        tor_free(cbt->liveness.timeouts_after_firsthop);
        cbt->liveness.timeouts_after_firsthop = recent_circs;
        cbt->liveness.num_recent_circs = num;
      }
      /* else no change, nothing to do */
    } else { /* num == 0 */
      /*
       * Weird.  This probably shouldn't happen, so log a warning, but try
       * to do something sensible anyway.
       */

      log_warn(LD_CIRC,
               "The cbtrecentcircs consensus parameter came back zero!  "
               "This disables adaptive timeouts since we can't keep track of "
               "any recent circuits.");

      circuit_build_times_free_timeouts(cbt);
    }
  } else {
    /*
     * Adaptive timeouts are disabled; this might be because of the
     * LearnCircuitBuildTimes config parameter, and hence permanent, or
     * the cbtdisabled consensus parameter, so it may be a new condition.
     * Treat it like getting num == 0 above and free the circuit history
     * if we have any.
     */

    circuit_build_times_free_timeouts(cbt);
  }
}

Here is the call graph for this function:

Here is the caller graph for this function:

Load histogram from state, shuffling the resulting array after we do so.

Use this result to estimate parameters and calculate the timeout.

Return -1 on error.

Definition at line 940 of file circuitbuild.c.

{
  int tot_values = 0;
  uint32_t loaded_cnt = 0, N = 0;
  config_line_t *line;
  unsigned int i;
  build_time_t *loaded_times;
  int err = 0;
  circuit_build_times_init(cbt);

  if (circuit_build_times_disabled()) {
    return 0;
  }

  /* build_time_t 0 means uninitialized */
  loaded_times = tor_malloc_zero(sizeof(build_time_t)*state->TotalBuildTimes);

  for (line = state->BuildtimeHistogram; line; line = line->next) {
    smartlist_t *args = smartlist_new();
    smartlist_split_string(args, line->value, " ",
                           SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
    if (smartlist_len(args) < 2) {
      log_warn(LD_GENERAL, "Unable to parse circuit build times: "
                           "Too few arguments to CircuitBuildTime");
      err = 1;
      SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
      smartlist_free(args);
      break;
    } else {
      const char *ms_str = smartlist_get(args,0);
      const char *count_str = smartlist_get(args,1);
      uint32_t count, k;
      build_time_t ms;
      int ok;
      ms = (build_time_t)tor_parse_ulong(ms_str, 0, 0,
                                         CBT_BUILD_TIME_MAX, &ok, NULL);
      if (!ok) {
        log_warn(LD_GENERAL, "Unable to parse circuit build times: "
                             "Unparsable bin number");
        err = 1;
        SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
        smartlist_free(args);
        break;
      }
      count = (uint32_t)tor_parse_ulong(count_str, 0, 0,
                                        UINT32_MAX, &ok, NULL);
      if (!ok) {
        log_warn(LD_GENERAL, "Unable to parse circuit build times: "
                             "Unparsable bin count");
        err = 1;
        SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
        smartlist_free(args);
        break;
      }

      if (loaded_cnt+count+state->CircuitBuildAbandonedCount
            > state->TotalBuildTimes) {
        log_warn(LD_CIRC,
                 "Too many build times in state file. "
                 "Stopping short before %d",
                 loaded_cnt+count);
        SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
        smartlist_free(args);
        break;
      }

      for (k = 0; k < count; k++) {
        loaded_times[loaded_cnt++] = ms;
      }
      N++;
      SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
      smartlist_free(args);
    }
  }

  log_info(LD_CIRC,
           "Adding %d timeouts.", state->CircuitBuildAbandonedCount);
  for (i=0; i < state->CircuitBuildAbandonedCount; i++) {
    loaded_times[loaded_cnt++] = CBT_BUILD_ABANDONED;
  }

  if (loaded_cnt != state->TotalBuildTimes) {
    log_warn(LD_CIRC,
            "Corrupt state file? Build times count mismatch. "
            "Read %d times, but file says %d", loaded_cnt,
            state->TotalBuildTimes);
    err = 1;
    circuit_build_times_reset(cbt);
    goto done;
  }

  circuit_build_times_shuffle_and_store_array(cbt, loaded_times, loaded_cnt);

  /* Verify that we didn't overwrite any indexes */
  for (i=0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
    if (!cbt->circuit_build_times[i])
      break;
    tot_values++;
  }
  log_info(LD_CIRC,
           "Loaded %d/%d values from %d lines in circuit time histogram",
           tot_values, cbt->total_build_times, N);

  if (cbt->total_build_times != tot_values
        || cbt->total_build_times > CBT_NCIRCUITS_TO_OBSERVE) {
    log_warn(LD_CIRC,
            "Corrupt state file? Shuffled build times mismatch. "
            "Read %d times, but file says %d", tot_values,
            state->TotalBuildTimes);
    err = 1;
    circuit_build_times_reset(cbt);
    goto done;
  }

  circuit_build_times_set_timeout(cbt);

  if (!state->CircuitBuildAbandonedCount && cbt->total_build_times) {
    circuit_build_times_filter_timeouts(cbt);
  }

 done:
  tor_free(loaded_times);
  return err ? -1 : 0;
}

Here is the call graph for this function:

Here is the caller graph for this function:

Exposed function to compute a new timeout.

Dispatches events and also filters out extremely high timeout values.

Definition at line 1612 of file circuitbuild.c.

{
  long prev_timeout = tor_lround(cbt->timeout_ms/1000);
  double timeout_rate;

  /*
   * Just return if we aren't using adaptive timeouts
   */
  if (circuit_build_times_disabled())
    return;

  if (!circuit_build_times_set_timeout_worker(cbt))
    return;

  if (cbt->timeout_ms < circuit_build_times_min_timeout()) {
    log_warn(LD_CIRC, "Set buildtimeout to low value %fms. Setting to %dms",
             cbt->timeout_ms, circuit_build_times_min_timeout());
    cbt->timeout_ms = circuit_build_times_min_timeout();
    if (cbt->close_ms < cbt->timeout_ms) {
      /* This shouldn't happen because of MAX() in timeout_worker above,
       * but doing it just in case */
      cbt->close_ms = circuit_build_times_initial_timeout();
    }
  }

  control_event_buildtimeout_set(cbt, BUILDTIMEOUT_SET_EVENT_COMPUTED);

  timeout_rate = circuit_build_times_timeout_rate(cbt);

  if (prev_timeout > tor_lround(cbt->timeout_ms/1000)) {
    log_info(LD_CIRC,
               "Based on %d circuit times, it looks like we don't need to "
               "wait so long for circuits to finish. We will now assume a "
               "circuit is too slow to use after waiting %ld seconds.",
               cbt->total_build_times,
               tor_lround(cbt->timeout_ms/1000));
    log_info(LD_CIRC,
             "Circuit timeout data: %fms, %fms, Xm: %d, a: %f, r: %f",
             cbt->timeout_ms, cbt->close_ms, cbt->Xm, cbt->alpha,
             timeout_rate);
  } else if (prev_timeout < tor_lround(cbt->timeout_ms/1000)) {
    log_info(LD_CIRC,
               "Based on %d circuit times, it looks like we need to wait "
               "longer for circuits to finish. We will now assume a "
               "circuit is too slow to use after waiting %ld seconds.",
               cbt->total_build_times,
               tor_lround(cbt->timeout_ms/1000));
    log_info(LD_CIRC,
             "Circuit timeout data: %fms, %fms, Xm: %d, a: %f, r: %f",
             cbt->timeout_ms, cbt->close_ms, cbt->Xm, cbt->alpha,
             timeout_rate);
  } else {
    log_info(LD_CIRC,
             "Set circuit build timeout to %lds (%fms, %fms, Xm: %d, a: %f,"
             " r: %f) based on %d circuit times",
             tor_lround(cbt->timeout_ms/1000),
             cbt->timeout_ms, cbt->close_ms, cbt->Xm, cbt->alpha, timeout_rate,
             cbt->total_build_times);
  }
}

Here is the call graph for this function:

Here is the caller graph for this function:

Count the number of timeouts in a set of cbt data.

Definition at line 1470 of file circuitbuild.c.

{
  int i=0,timeouts=0;
  for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
    if (cbt->circuit_build_times[i] >= cbt->timeout_ms) {
       timeouts++;
    }
  }

  if (!cbt->total_build_times)
    return 0;

  return ((double)timeouts)/cbt->total_build_times;
}

Here is the caller graph for this function:

Output a histogram of current circuit build times to the or_state_t state structure.

Definition at line 814 of file circuitbuild.c.

{
  uint32_t *histogram;
  build_time_t i = 0;
  build_time_t nbins = 0;
  config_line_t **next, *line;

  histogram = circuit_build_times_create_histogram(cbt, &nbins);
  // write to state
  config_free_lines(state->BuildtimeHistogram);
  next = &state->BuildtimeHistogram;
  *next = NULL;

  state->TotalBuildTimes = cbt->total_build_times;
  state->CircuitBuildAbandonedCount = 0;

  for (i = 0; i < CBT_NCIRCUITS_TO_OBSERVE; i++) {
    if (cbt->circuit_build_times[i] == CBT_BUILD_ABANDONED)
      state->CircuitBuildAbandonedCount++;
  }

  for (i = 0; i < nbins; i++) {
    // compress the histogram by skipping the blanks
    if (histogram[i] == 0) continue;
    *next = line = tor_malloc_zero(sizeof(config_line_t));
    line->key = tor_strdup("CircuitBuildTimeBin");
    tor_asprintf(&line->value, "%d %d",
            CBT_BIN_TO_MS(i), histogram[i]);
    next = &(line->next);
  }

  if (!unit_tests) {
    if (!get_options()->AvoidDiskWrites)
      or_state_mark_dirty(get_or_state(), 0);
  }

  tor_free(histogram);
}

Here is the call graph for this function:

Here is the caller graph for this function:

origin_circuit_t* circuit_establish_circuit ( uint8_t  purpose,
extend_info_t exit,
int  flags 
)

Build a new circuit for purpose.

If exit is defined, then use that as your exit router, else choose a suitable exit node.

Also launch a connection to the first OR in the chosen path, if it's not open already.

Definition at line 1912 of file circuitbuild.c.

{
  origin_circuit_t *circ;
  int err_reason = 0;

  circ = origin_circuit_init(purpose, flags);

  if (onion_pick_cpath_exit(circ, exit) < 0 ||
      onion_populate_cpath(circ) < 0) {
    circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_NOPATH);
    return NULL;
  }

  control_event_circuit_status(circ, CIRC_EVENT_LAUNCHED, 0);

  if ((err_reason = circuit_handle_first_hop(circ)) < 0) {
    circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
    return NULL;
  }
  return circ;
}

Here is the call graph for this function:

Here is the caller graph for this function:

int circuit_extend ( cell_t cell,
circuit_t circ 
)

Take the 'extend' cell, pull out addr/port plus the onion skin and identity digest for the next hop.

If we're already connected, pass the onion skin to the next hop using a create cell; otherwise launch a new OR connection, and circ will notice when the connection succeeds or fails.

Return -1 if we want to warn and tear down the circuit, else return 0.

Definition at line 2396 of file circuitbuild.c.

{
  or_connection_t *n_conn;
  relay_header_t rh;
  char *onionskin;
  char *id_digest=NULL;
  uint32_t n_addr32;
  uint16_t n_port;
  tor_addr_t n_addr;
  const char *msg = NULL;
  int should_launch = 0;

  if (circ->n_conn) {
    log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
           "n_conn already set. Bug/attack. Closing.");
    return -1;
  }
  if (circ->n_hop) {
    log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
           "conn to next hop already launched. Bug/attack. Closing.");
    return -1;
  }

  if (!server_mode(get_options())) {
    log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
           "Got an extend cell, but running as a client. Closing.");
    return -1;
  }

  relay_header_unpack(&rh, cell->payload);

  if (rh.length < 4+2+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN) {
    log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
           "Wrong length %d on extend cell. Closing circuit.",
           rh.length);
    return -1;
  }

  n_addr32 = ntohl(get_uint32(cell->payload+RELAY_HEADER_SIZE));
  n_port = ntohs(get_uint16(cell->payload+RELAY_HEADER_SIZE+4));
  onionskin = (char*) cell->payload+RELAY_HEADER_SIZE+4+2;
  id_digest = (char*) cell->payload+RELAY_HEADER_SIZE+4+2+
    ONIONSKIN_CHALLENGE_LEN;
  tor_addr_from_ipv4h(&n_addr, n_addr32);

  if (!n_port || !n_addr32) {
    log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
           "Client asked me to extend to zero destination port or addr.");
    return -1;
  }

  /* Check if they asked us for 0000..0000. We support using
   * an empty fingerprint for the first hop (e.g. for a bridge relay),
   * but we don't want to let people send us extend cells for empty
   * fingerprints -- a) because it opens the user up to a mitm attack,
   * and b) because it lets an attacker force the relay to hold open a
   * new TLS connection for each extend request. */
  if (tor_digest_is_zero(id_digest)) {
    log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
           "Client asked me to extend without specifying an id_digest.");
    return -1;
  }

  /* Next, check if we're being asked to connect to the hop that the
   * extend cell came from. There isn't any reason for that, and it can
   * assist circular-path attacks. */
  if (tor_memeq(id_digest, TO_OR_CIRCUIT(circ)->p_conn->identity_digest,
              DIGEST_LEN)) {
    log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
           "Client asked me to extend back to the previous hop.");
    return -1;
  }

  n_conn = connection_or_get_for_extend(id_digest,
                                        &n_addr,
                                        &msg,
                                        &should_launch);

  if (!n_conn) {
    log_debug(LD_CIRC|LD_OR,"Next router (%s:%d): %s",
              fmt_addr(&n_addr), (int)n_port, msg?msg:"????");

    circ->n_hop = extend_info_alloc(NULL /*nickname*/,
                                    id_digest,
                                    NULL /*onion_key*/,
                                    &n_addr, n_port);

    circ->n_conn_onionskin = tor_malloc(ONIONSKIN_CHALLENGE_LEN);
    memcpy(circ->n_conn_onionskin, onionskin, ONIONSKIN_CHALLENGE_LEN);
    circuit_set_state(circ, CIRCUIT_STATE_OR_WAIT);

    if (should_launch) {
      /* we should try to open a connection */
      n_conn = connection_or_connect(&n_addr, n_port, id_digest);
      if (!n_conn) {
        log_info(LD_CIRC,"Launching n_conn failed. Closing circuit.");
        circuit_mark_for_close(circ, END_CIRC_REASON_CONNECTFAILED);
        return 0;
      }
      log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
    }
    /* return success. The onion/circuit/etc will be taken care of
     * automatically (may already have been) whenever n_conn reaches
     * OR_CONN_STATE_OPEN.
     */
    return 0;
  }

  tor_assert(!circ->n_hop); /* Connection is already established. */
  circ->n_conn = n_conn;
  log_debug(LD_CIRC,"n_conn is %s:%u",
            n_conn->_base.address,n_conn->_base.port);

  if (circuit_deliver_create_cell(circ, CELL_CREATE, onionskin) < 0)
    return -1;
  return 0;
}

Here is the call graph for this function:

Here is the caller graph for this function:

Take an open circ, and add a new hop at the end, based on info.

Set its state back to CIRCUIT_STATE_BUILDING, and then send the next extend cell to begin connecting to that hop.

Definition at line 3380 of file circuitbuild.c.

{
  int err_reason = 0;
  warn_if_last_router_excluded(circ, exit);
  circuit_append_new_exit(circ, exit);
  circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
  if ((err_reason = circuit_send_next_onion_skin(circ))<0) {
    log_warn(LD_CIRC, "Couldn't extend circuit to new point %s.",
             extend_info_describe(exit));
    circuit_mark_for_close(TO_CIRCUIT(circ), -err_reason);
    return -1;
  }
  return 0;
}

Here is the call graph for this function:

Here is the caller graph for this function:

int circuit_finish_handshake ( origin_circuit_t circ,
uint8_t  reply_type,
const uint8_t *  reply 
)

A created or extended cell came back to us on the circuit, and it included reply as its body.

(If reply_type is CELL_CREATED, the body contains (the second DH key, plus KH). If reply_type is CELL_CREATED_FAST, the body contains a secret y and a hash H(x|y).)

Calculate the appropriate keys and digests, make sure KH is correct, and initialize this hop of the cpath.

Return - reason if we want to mark circ for close, else return 0.

Definition at line 2685 of file circuitbuild.c.

{
  char keys[CPATH_KEY_MATERIAL_LEN];
  crypt_path_t *hop;

  if (circ->cpath->state == CPATH_STATE_AWAITING_KEYS) {
    hop = circ->cpath;
    /* Don't count cannibalized or onehop circs for path bias */
    if (!circ->has_opened && !circ->build_state->onehop_tunnel) {
      entry_guard_t *guard;

      guard = entry_guard_get_by_id_digest(
              circ->_base.n_conn->identity_digest);
      if (guard) {
        if (entry_guard_inc_first_hop_count(guard) < 0) {
          /* Bogus guard; we already warned. */
          return -END_CIRC_REASON_TORPROTOCOL;
        }
      }
    }
  } else {
    hop = onion_next_hop_in_cpath(circ->cpath);
    if (!hop) { /* got an extended when we're all done? */
      log_warn(LD_PROTOCOL,"got extended when circ already built? Closing.");
      return - END_CIRC_REASON_TORPROTOCOL;
    }
  }
  tor_assert(hop->state == CPATH_STATE_AWAITING_KEYS);

  if (reply_type == CELL_CREATED && hop->dh_handshake_state) {
    if (onion_skin_client_handshake(hop->dh_handshake_state, (char*)reply,keys,
                                    DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
      log_warn(LD_CIRC,"onion_skin_client_handshake failed.");
      return -END_CIRC_REASON_TORPROTOCOL;
    }
    /* Remember hash of g^xy */
    memcpy(hop->handshake_digest, reply+DH_KEY_LEN, DIGEST_LEN);
  } else if (reply_type == CELL_CREATED_FAST && !hop->dh_handshake_state) {
    if (fast_client_handshake(hop->fast_handshake_state, reply,
                              (uint8_t*)keys,
                              DIGEST_LEN*2+CIPHER_KEY_LEN*2) < 0) {
      log_warn(LD_CIRC,"fast_client_handshake failed.");
      return -END_CIRC_REASON_TORPROTOCOL;
    }
    memcpy(hop->handshake_digest, reply+DIGEST_LEN, DIGEST_LEN);
  } else {
    log_warn(LD_PROTOCOL,"CREATED cell type did not match CREATE cell type.");
    return -END_CIRC_REASON_TORPROTOCOL;
  }

  crypto_dh_free(hop->dh_handshake_state); /* don't need it anymore */
  hop->dh_handshake_state = NULL;

  memset(hop->fast_handshake_state, 0, sizeof(hop->fast_handshake_state));

  if (circuit_init_cpath_crypto(hop, keys, 0)<0) {
    return -END_CIRC_REASON_TORPROTOCOL;
  }

  hop->state = CPATH_STATE_OPEN;
  log_info(LD_CIRC,"Finished building %scircuit hop:",
           (reply_type == CELL_CREATED_FAST) ? "fast " : "");
  circuit_log_path(LOG_INFO,LD_CIRC,circ);
  control_event_circuit_status(circ, CIRC_EVENT_EXTENDED, 0);

  return 0;
}

Here is the call graph for this function:

Here is the caller graph for this function:

Start establishing the first hop of our circuit.

Figure out what OR we should connect to, and if necessary start the connection to it. If we're already connected, then send the 'create' cell. Return 0 for ok, -reason if circ should be marked-for-close.

Definition at line 1939 of file circuitbuild.c.

{
  crypt_path_t *firsthop;
  or_connection_t *n_conn;
  int err_reason = 0;
  const char *msg = NULL;
  int should_launch = 0;

  firsthop = onion_next_hop_in_cpath(circ->cpath);
  tor_assert(firsthop);
  tor_assert(firsthop->extend_info);

  /* now see if we're already connected to the first OR in 'route' */
  log_debug(LD_CIRC,"Looking for firsthop '%s:%u'",
            fmt_addr(&firsthop->extend_info->addr),
            firsthop->extend_info->port);

  n_conn = connection_or_get_for_extend(firsthop->extend_info->identity_digest,
                                        &firsthop->extend_info->addr,
                                        &msg,
                                        &should_launch);

  if (!n_conn) {
    /* not currently connected in a useful way. */
    log_info(LD_CIRC, "Next router is %s: %s",
             safe_str_client(extend_info_describe(firsthop->extend_info)),
             msg?msg:"???");
    circ->_base.n_hop = extend_info_dup(firsthop->extend_info);

    if (should_launch) {
      if (circ->build_state->onehop_tunnel)
        control_event_bootstrap(BOOTSTRAP_STATUS_CONN_DIR, 0);
      n_conn = connection_or_connect(&firsthop->extend_info->addr,
                                     firsthop->extend_info->port,
                                     firsthop->extend_info->identity_digest);
      if (!n_conn) { /* connect failed, forget the whole thing */
        log_info(LD_CIRC,"connect to firsthop failed. Closing.");
        return -END_CIRC_REASON_CONNECTFAILED;
      }
    }

    log_debug(LD_CIRC,"connecting in progress (or finished). Good.");
    /* return success. The onion/circuit/etc will be taken care of
     * automatically (may already have been) whenever n_conn reaches
     * OR_CONN_STATE_OPEN.
     */
    return 0;
  } else { /* it's already open. use it. */
    tor_assert(!circ->_base.n_hop);
    circ->_base.n_conn = n_conn;
    log_debug(LD_CIRC,"Conn open. Delivering first onion skin.");
    if ((err_reason = circuit_send_next_onion_skin(circ)) < 0) {
      log_info(LD_CIRC,"circuit_send_next_onion_skin failed.");
      return err_reason;
    }
  }
  return 0;
}

Here is the call graph for this function:

Here is the caller graph for this function:

int circuit_init_cpath_crypto ( crypt_path_t cpath,
const char *  key_data,
int  reverse 
)

Initialize cpath->{f|b}_{crypto|digest} from the key material in key_data.

key_data must contain CPATH_KEY_MATERIAL bytes, which are used as follows:

  • 20 to initialize f_digest
  • 20 to initialize b_digest
  • 16 to key f_crypto
  • 16 to key b_crypto

(If 'reverse' is true, then f_XX and b_XX are swapped.)

Definition at line 2525 of file circuitbuild.c.

{
  crypto_digest_t *tmp_digest;
  crypto_cipher_t *tmp_crypto;

  tor_assert(cpath);
  tor_assert(key_data);
  tor_assert(!(cpath->f_crypto || cpath->b_crypto ||
             cpath->f_digest || cpath->b_digest));

  cpath->f_digest = crypto_digest_new();
  crypto_digest_add_bytes(cpath->f_digest, key_data, DIGEST_LEN);
  cpath->b_digest = crypto_digest_new();
  crypto_digest_add_bytes(cpath->b_digest, key_data+DIGEST_LEN, DIGEST_LEN);

  if (!(cpath->f_crypto =
        crypto_cipher_new(key_data+(2*DIGEST_LEN)))) {
    log_warn(LD_BUG,"Forward cipher initialization failed.");
    return -1;
  }
  if (!(cpath->b_crypto =
        crypto_cipher_new(key_data+(2*DIGEST_LEN)+CIPHER_KEY_LEN))) {
    log_warn(LD_BUG,"Backward cipher initialization failed.");
    return -1;
  }

  if (reverse) {
    tmp_digest = cpath->f_digest;
    cpath->f_digest = cpath->b_digest;
    cpath->b_digest = tmp_digest;
    tmp_crypto = cpath->f_crypto;
    cpath->f_crypto = cpath->b_crypto;
    cpath->b_crypto = tmp_crypto;
  }

  return 0;
}

Here is the call graph for this function:

Here is the caller graph for this function:

char* circuit_list_path ( origin_circuit_t circ,
int  verbose 
)

If verbose is false, allocate and return a comma-separated list of the currently built elements of circ.

If verbose is true, also list information about link status in a more verbose format using spaces.

Definition at line 1800 of file circuitbuild.c.

{
  return circuit_list_path_impl(circ, verbose, 0);
}

Here is the call graph for this function:

Here is the caller graph for this function:

Allocate and return a comma-separated list of the currently built elements of circ, giving each as a verbose nickname.

Definition at line 1809 of file circuitbuild.c.

{
  return circuit_list_path_impl(circ, 0, 1);
}

Here is the call graph for this function:

Here is the caller graph for this function:

void circuit_log_path ( int  severity,
unsigned int  domain,
origin_circuit_t circ 
)

Log, at severity severity, the nicknames of each router in circ's cpath.

Also log the length of the cpath, and the intended exit point.

Definition at line 1819 of file circuitbuild.c.

{
  char *s = circuit_list_path(circ,1);
  tor_log(severity,domain,"%s",s);
  tor_free(s);
}

Here is the call graph for this function:

Here is the caller graph for this function:

void circuit_n_conn_done ( or_connection_t or_conn,
int  status 
)

Find any circuits that are waiting on or_conn to become open and get them to send their create cells forward.

Status is 1 if connect succeeded, or 0 if connect failed.

Definition at line 2004 of file circuitbuild.c.

{
  smartlist_t *pending_circs;
  int err_reason = 0;

  log_debug(LD_CIRC,"or_conn to %s/%s, status=%d",
            or_conn->nickname ? or_conn->nickname : "NULL",
            or_conn->_base.address, status);

  pending_circs = smartlist_new();
  circuit_get_all_pending_on_or_conn(pending_circs, or_conn);

  SMARTLIST_FOREACH_BEGIN(pending_circs, circuit_t *, circ)
    {
      /* These checks are redundant wrt get_all_pending_on_or_conn, but I'm
       * leaving them in in case it's possible for the status of a circuit to
       * change as we're going down the list. */
      if (circ->marked_for_close || circ->n_conn || !circ->n_hop ||
          circ->state != CIRCUIT_STATE_OR_WAIT)
        continue;

      if (tor_digest_is_zero(circ->n_hop->identity_digest)) {
        /* Look at addr/port. This is an unkeyed connection. */
        if (!tor_addr_eq(&circ->n_hop->addr, &or_conn->_base.addr) ||
            circ->n_hop->port != or_conn->_base.port)
          continue;
      } else {
        /* We expected a key. See if it's the right one. */
        if (tor_memneq(or_conn->identity_digest,
                   circ->n_hop->identity_digest, DIGEST_LEN))
          continue;
      }
      if (!status) { /* or_conn failed; close circ */
        log_info(LD_CIRC,"or_conn failed. Closing circ.");
        circuit_mark_for_close(circ, END_CIRC_REASON_OR_CONN_CLOSED);
        continue;
      }
      log_debug(LD_CIRC, "Found circ, sending create cell.");
      /* circuit_deliver_create_cell will set n_circ_id and add us to
       * orconn_circuid_circuit_map, so we don't need to call
       * set_circid_orconn here. */
      circ->n_conn = or_conn;
      extend_info_free(circ->n_hop);
      circ->n_hop = NULL;

      if (CIRCUIT_IS_ORIGIN(circ)) {
        if ((err_reason =
             circuit_send_next_onion_skin(TO_ORIGIN_CIRCUIT(circ))) < 0) {
          log_info(LD_CIRC,
                   "send_next_onion_skin failed; circuit marked for closing.");
          circuit_mark_for_close(circ, -err_reason);
          continue;
          /* XXX could this be bad, eg if next_onion_skin failed because conn
           *     died? */
        }
      } else {
        /* pull the create cell out of circ->onionskin, and send it */
        tor_assert(circ->n_conn_onionskin);
        if (circuit_deliver_create_cell(circ,CELL_CREATE,
                                        circ->n_conn_onionskin)<0) {
          circuit_mark_for_close(circ, END_CIRC_REASON_RESOURCELIMIT);
          continue;
        }
        tor_free(circ->n_conn_onionskin);
        circuit_set_state(circ, CIRCUIT_STATE_OPEN);
      }
    }
  SMARTLIST_FOREACH_END(circ);

  smartlist_free(pending_circs);
}

Here is the call graph for this function:

Here is the caller graph for this function:

void circuit_note_clock_jumped ( int  seconds_elapsed)

Our clock just jumped by seconds_elapsed.

Assume something has also gone wrong with our network: notify the user, and abandon all not-yet-used circuits.

Definition at line 2371 of file circuitbuild.c.

{
  int severity = server_mode(get_options()) ? LOG_WARN : LOG_NOTICE;
  tor_log(severity, LD_GENERAL, "Your system clock just jumped %d seconds %s; "
      "assuming established circuits no longer work.",
      seconds_elapsed >=0 ? seconds_elapsed : -seconds_elapsed,
      seconds_elapsed >=0 ? "forward" : "backward");
  control_event_general_status(LOG_WARN, "CLOCK_JUMPED TIME=%d",
                               seconds_elapsed);
  can_complete_circuit=0; /* so it'll log when it works again */
  control_event_client_status(severity, "CIRCUIT_NOT_ESTABLISHED REASON=%s",
                              "CLOCK_JUMPED");
  circuit_mark_all_unused_circs();
  circuit_expire_all_dirty_circs();
}

Here is the call graph for this function:

Here is the caller graph for this function:

Tell the rep(utation)hist(ory) module about the status of the links in circ.

Hops that have become OPEN are marked as successfully extended; the first hop that isn't open (if any) is marked as unable to extend.

Definition at line 1833 of file circuitbuild.c.

{
  crypt_path_t *hop;
  const char *prev_digest = NULL;
  hop = circ->cpath;
  if (!hop) /* circuit hasn't started building yet. */
    return;
  if (server_mode(get_options())) {
    const routerinfo_t *me = router_get_my_routerinfo();
    if (!me)
      return;
    prev_digest = me->cache_info.identity_digest;
  }
  do {
    const node_t *node = node_get_by_id(hop->extend_info->identity_digest);
    if (node) { /* Why do we check this?  We know the identity. -NM XXXX */
      if (prev_digest) {
        if (hop->state == CPATH_STATE_OPEN)
          rep_hist_note_extend_succeeded(prev_digest, node->identity);
        else {
          rep_hist_note_extend_failed(prev_digest, node->identity);
          break;
        }
      }
      prev_digest = node->identity;
    } else {
      prev_digest = NULL;
    }
    hop=hop->next;
  } while (hop!=circ->cpath);
}

Here is the call graph for this function:

Here is the caller graph for this function:

This is the backbone function for building circuits.

If circ's first hop is closed, then we need to build a create cell and send it forward.

Otherwise, we need to build a relay extend cell and send it forward.

Return -reason if we want to tear down circ, else return 0.

Definition at line 2196 of file circuitbuild.c.

{
  crypt_path_t *hop;
  const node_t *node;
  char payload[2+4+DIGEST_LEN+ONIONSKIN_CHALLENGE_LEN];
  char *onionskin;
  size_t payload_len;

  tor_assert(circ);

  if (circ->cpath->state == CPATH_STATE_CLOSED) {
    int fast;
    uint8_t cell_type;
    log_debug(LD_CIRC,"First skin; sending create cell.");
    if (circ->build_state->onehop_tunnel)
      control_event_bootstrap(BOOTSTRAP_STATUS_ONEHOP_CREATE, 0);
    else
      control_event_bootstrap(BOOTSTRAP_STATUS_CIRCUIT_CREATE, 0);

    node = node_get_by_id(circ->_base.n_conn->identity_digest);
    fast = should_use_create_fast_for_circuit(circ);
    if (!fast) {
      /* We are an OR and we know the right onion key: we should
       * send an old slow create cell.
       */
      cell_type = CELL_CREATE;
      if (onion_skin_create(circ->cpath->extend_info->onion_key,
                            &(circ->cpath->dh_handshake_state),
                            payload) < 0) {
        log_warn(LD_CIRC,"onion_skin_create (first hop) failed.");
        return - END_CIRC_REASON_INTERNAL;
      }
      note_request("cell: create", 1);
    } else {
      /* We are not an OR, and we're building the first hop of a circuit to a
       * new OR: we can be speedy and use CREATE_FAST to save an RSA operation
       * and a DH operation. */
      cell_type = CELL_CREATE_FAST;
      memset(payload, 0, sizeof(payload));
      crypto_rand((char*) circ->cpath->fast_handshake_state,
                  sizeof(circ->cpath->fast_handshake_state));
      memcpy(payload, circ->cpath->fast_handshake_state,
             sizeof(circ->cpath->fast_handshake_state));
      note_request("cell: create fast", 1);
    }

    if (circuit_deliver_create_cell(TO_CIRCUIT(circ), cell_type, payload) < 0)
      return - END_CIRC_REASON_RESOURCELIMIT;

    circ->cpath->state = CPATH_STATE_AWAITING_KEYS;
    circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_BUILDING);
    log_info(LD_CIRC,"First hop: finished sending %s cell to '%s'",
             fast ? "CREATE_FAST" : "CREATE",
             node ? node_describe(node) : "<unnamed>");
  } else {
    tor_assert(circ->cpath->state == CPATH_STATE_OPEN);
    tor_assert(circ->_base.state == CIRCUIT_STATE_BUILDING);
    log_debug(LD_CIRC,"starting to send subsequent skin.");
    hop = onion_next_hop_in_cpath(circ->cpath);
    if (!hop) {
      /* done building the circuit. whew. */
      circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);
      if (circuit_timeout_want_to_count_circ(circ)) {
        struct timeval end;
        long timediff;
        tor_gettimeofday(&end);
        timediff = tv_mdiff(&circ->_base.timestamp_created, &end);

        /*
         * If the circuit build time is much greater than we would have cut
         * it off at, we probably had a suspend event along this codepath,
         * and we should discard the value.
         */
        if (timediff < 0 || timediff > 2*circ_times.close_ms+1000) {
          log_notice(LD_CIRC, "Strange value for circuit build time: %ldmsec. "
                              "Assuming clock jump. Purpose %d (%s)", timediff,
                     circ->_base.purpose,
                     circuit_purpose_to_string(circ->_base.purpose));
        } else if (!circuit_build_times_disabled()) {
          /* Only count circuit times if the network is live */
          if (circuit_build_times_network_check_live(&circ_times)) {
            circuit_build_times_add_time(&circ_times, (build_time_t)timediff);
            circuit_build_times_set_timeout(&circ_times);
          }

          if (circ->_base.purpose != CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT) {
            circuit_build_times_network_circ_success(&circ_times);
          }
        }
      }
      log_info(LD_CIRC,"circuit built!");
      circuit_reset_failure_count(0);
      /* Don't count cannibalized or onehop circs for path bias */
      if (circ->build_state->onehop_tunnel || circ->has_opened) {
        control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_STATUS, 0);
      } else {
        entry_guard_t *guard =
          entry_guard_get_by_id_digest(circ->_base.n_conn->identity_digest);

        if (guard) {
          guard->circuit_successes++;

          log_info(LD_PROTOCOL, "Got success count %u/%u for guard %s=%s",
                   guard->circuit_successes, guard->first_hops,
                   guard->nickname, hex_str(guard->identity, DIGEST_LEN));

          if (guard->first_hops < guard->circuit_successes) {
            log_warn(LD_BUG, "Unexpectedly high circuit_successes (%u/%u) "
                     "for guard %s",
                     guard->circuit_successes, guard->first_hops,
                     guard->nickname);
          }
        }
      }
      if (!can_complete_circuit && !circ->build_state->onehop_tunnel) {
        const or_options_t *options = get_options();
        can_complete_circuit=1;
        /* FFFF Log a count of known routers here */
        log_notice(LD_GENERAL,
            "Tor has successfully opened a circuit. "
            "Looks like client functionality is working.");
        control_event_bootstrap(BOOTSTRAP_STATUS_DONE, 0);
        control_event_client_status(LOG_NOTICE, "CIRCUIT_ESTABLISHED");
        clear_broken_connection_map(1);
        if (server_mode(options) && !check_whether_orport_reachable()) {
          inform_testing_reachability();
          consider_testing_reachability(1, 1);
        }
      }
      circuit_rep_hist_note_result(circ);
      circuit_has_opened(circ); /* do other actions as necessary */

      /* We're done with measurement circuits here. Just close them */
      if (circ->_base.purpose == CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT)
        circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
      return 0;
    }

    if (tor_addr_family(&hop->extend_info->addr) != AF_INET) {
      log_warn(LD_BUG, "Trying to extend to a non-IPv4 address.");
      return - END_CIRC_REASON_INTERNAL;
    }

    set_uint32(payload, tor_addr_to_ipv4n(&hop->extend_info->addr));
    set_uint16(payload+4, htons(hop->extend_info->port));

    onionskin = payload+2+4;
    memcpy(payload+2+4+ONIONSKIN_CHALLENGE_LEN,
           hop->extend_info->identity_digest, DIGEST_LEN);
    payload_len = 2+4+ONIONSKIN_CHALLENGE_LEN+DIGEST_LEN;

    if (onion_skin_create(hop->extend_info->onion_key,
                          &(hop->dh_handshake_state), onionskin) < 0) {
      log_warn(LD_CIRC,"onion_skin_create failed.");
      return - END_CIRC_REASON_INTERNAL;
    }

    log_info(LD_CIRC,"Sending extend relay cell.");
    note_request("cell: extend", 1);
    /* send it to hop->prev, because it will transfer
     * it to a create cell and then send to hop */
    if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
                                     RELAY_COMMAND_EXTEND,
                                     payload, payload_len, hop->prev) < 0)
      return 0; /* circuit is closed */

    hop->state = CPATH_STATE_AWAITING_KEYS;
  }
  return 0;
}

Here is the call graph for this function:

Here is the caller graph for this function:

Return true if circ is the type of circuit we want to count timeouts from.

In particular, we want it to have not completed yet (already completing indicates we cannibalized it), and we want it to have exactly three hops.

Definition at line 2179 of file circuitbuild.c.

{
  return !circ->has_opened
          && circ->build_state->desired_path_len == DEFAULT_ROUTE_LEN;
}

Here is the caller graph for this function:

int circuit_truncated ( origin_circuit_t circ,
crypt_path_t layer 
)

We received a relay truncated cell on circ.

Since we don't ask for truncates currently, getting a truncated means that a connection broke or an extend failed. For now, just give up: for circ to close, and return 0.

Definition at line 2761 of file circuitbuild.c.

{
//  crypt_path_t *victim;
//  connection_t *stream;

  tor_assert(circ);
  tor_assert(layer);

  /* XXX Since we don't ask for truncates currently, getting a truncated
   *     means that a connection broke or an extend failed. For now,
   *     just give up.
   */
  circuit_mark_for_close(TO_CIRCUIT(circ),
          END_CIRC_REASON_FLAG_REMOTE|END_CIRC_REASON_OR_CONN_CLOSED);
  return 0;

#if 0
  while (layer->next != circ->cpath) {
    /* we need to clear out layer->next */
    victim = layer->next;
    log_debug(LD_CIRC, "Killing a layer of the cpath.");

    for (stream = circ->p_streams; stream; stream=stream->next_stream) {
      if (stream->cpath_layer == victim) {
        log_info(LD_APP, "Marking stream %d for close because of truncate.",
                 stream->stream_id);
        /* no need to send 'end' relay cells,
         * because the other side's already dead
         */
        connection_mark_unattached_ap(stream, END_STREAM_REASON_DESTROY);
      }
    }

    layer->next = victim->next;
    circuit_free_cpath_node(victim);
  }

  log_info(LD_CIRC, "finished");
  return 0;
#endif
}

Here is the call graph for this function:

Here is the caller graph for this function:

void clear_transport_list ( void  )

Initialize the pluggable transports list to empty, creating it if needed.

Definition at line 5005 of file circuitbuild.c.

Here is the call graph for this function:

Here is the caller graph for this function:

int entries_known_but_down ( const or_options_t options)

Do we know any descriptors for our bridges / entrynodes, and are all the ones we have descriptors for down?

Definition at line 5749 of file circuitbuild.c.

{
  tor_assert(entry_list_is_constrained(options));
  return entries_retry_helper(options, 0);
}

Here is the call graph for this function:

Here is the caller graph for this function:

void entries_retry_all ( const or_options_t options)

Mark all down known bridges / entrynodes up.

Definition at line 5757 of file circuitbuild.c.

Here is the call graph for this function:

Here is the caller graph for this function:

int entry_guard_register_connect_status ( const char *  digest,
int  succeeded,
int  mark_relay_status,
time_t  now 
)

Called when a connection to an OR with the identity digest digest is established (succeeded==1) or has failed (succeeded==0).

If the OR is an entry, change that entry's up/down status. Return 0 normally, or -1 if we want to tear down the new connection.

If mark_relay_status, also call router_set_status() on this relay.

XXX024 change succeeded and mark_relay_status into 'int flags'.

Definition at line 4244 of file circuitbuild.c.

{
  int changed = 0;
  int refuse_conn = 0;
  int first_contact = 0;
  entry_guard_t *entry = NULL;
  int idx = -1;
  char buf[HEX_DIGEST_LEN+1];

  if (! entry_guards)
    return 0;

  SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, e) {
    tor_assert(e);
    if (tor_memeq(e->identity, digest, DIGEST_LEN)) {
      entry = e;
      idx = e_sl_idx;
      break;
    }
  } SMARTLIST_FOREACH_END(e);

  if (!entry)
    return 0;

  base16_encode(buf, sizeof(buf), entry->identity, DIGEST_LEN);

  if (succeeded) {
    if (entry->unreachable_since) {
      log_info(LD_CIRC, "Entry guard '%s' (%s) is now reachable again. Good.",
               entry->nickname, buf);
      entry->can_retry = 0;
      entry->unreachable_since = 0;
      entry->last_attempted = now;
      control_event_guard(entry->nickname, entry->identity, "UP");
      changed = 1;
    }
    if (!entry->made_contact) {
      entry->made_contact = 1;
      first_contact = changed = 1;
    }
  } else { /* ! succeeded */
    if (!entry->made_contact) {
      /* We've never connected to this one. */
      log_info(LD_CIRC,
               "Connection to never-contacted entry guard '%s' (%s) failed. "
               "Removing from the list. %d/%d entry guards usable/new.",
               entry->nickname, buf,
               num_live_entry_guards()-1, smartlist_len(entry_guards)-1);
      control_event_guard(entry->nickname, entry->identity, "DROPPED");
      entry_guard_free(entry);
      smartlist_del_keeporder(entry_guards, idx);
      log_entry_guards(LOG_INFO);
      changed = 1;
    } else if (!entry->unreachable_since) {
      log_info(LD_CIRC, "Unable to connect to entry guard '%s' (%s). "
               "Marking as unreachable.", entry->nickname, buf);
      entry->unreachable_since = entry->last_attempted = now;
      control_event_guard(entry->nickname, entry->identity, "DOWN");
      changed = 1;
      entry->can_retry = 0; /* We gave it an early chance; no good. */
    } else {
      char tbuf[ISO_TIME_LEN+1];
      format_iso_time(tbuf, entry->unreachable_since);
      log_debug(LD_CIRC, "Failed to connect to unreachable entry guard "
                "'%s' (%s).  It has been unreachable since %s.",
                entry->nickname, buf, tbuf);
      entry->last_attempted = now;
      entry->can_retry = 0; /* We gave it an early chance; no good. */
    }
  }

  /* if the caller asked us to, also update the is_running flags for this
   * relay */
  if (mark_relay_status)
    router_set_status(digest, succeeded);

  if (first_contact) {
    /* We've just added a new long-term entry guard. Perhaps the network just
     * came back? We should give our earlier entries another try too,
     * and close this connection so we don't use it before we've given
     * the others a shot. */
    SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e, {
        if (e == entry)
          break;
        if (e->made_contact) {
          const char *msg;
          const node_t *r = entry_is_live(e, 0, 1, 1, &msg);
          if (r && e->unreachable_since) {
            refuse_conn = 1;
            e->can_retry = 1;
          }
        }
      });
    if (refuse_conn) {
      log_info(LD_CIRC,
               "Connected to new entry guard '%s' (%s). Marking earlier "
               "entry guards up. %d/%d entry guards usable/new.",
               entry->nickname, buf,
               num_live_entry_guards(), smartlist_len(entry_guards));
      log_entry_guards(LOG_INFO);
      changed = 1;
    }
  }

  if (changed)
    entry_guards_changed();
  return refuse_conn ? -1 : 0;
}

Here is the call graph for this function:

Here is the caller graph for this function:

void entry_guards_compute_status ( const or_options_t options,
time_t  now 
)

A new directory or router-status has arrived; update the down/listed status of the entry guards.

An entry is 'down' if the directory lists it as nonrunning. An entry is 'unlisted' if the directory doesn't include it.

Don't call this on startup; only on a fresh download. Otherwise we'll think that things are unlisted.

Definition at line 4178 of file circuitbuild.c.

{
  int changed = 0;
  digestmap_t *reasons;

  if (! entry_guards)
    return;

  if (options->EntryNodes) /* reshuffle the entry guard list if needed */
    entry_nodes_should_be_added();

  reasons = digestmap_new();
  SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, entry)
    {
      const node_t *r = node_get_by_id(entry->identity);
      const char *reason = NULL;
      if (entry_guard_set_status(entry, r, now, options, &reason))
        changed = 1;

      if (entry->bad_since)
        tor_assert(reason);
      if (reason)
        digestmap_set(reasons, entry->identity, (char*)reason);
    }
  SMARTLIST_FOREACH_END(entry);

  if (remove_dead_entry_guards(now))
    changed = 1;
  if (remove_obsolete_entry_guards(now))
    changed = 1;

  if (changed) {
    SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, entry) {
      const char *reason = digestmap_get(reasons, entry->identity);
      const char *live_msg = "";
      const node_t *r = entry_is_live(entry, 0, 1, 0, &live_msg);
      log_info(LD_CIRC, "Summary: Entry %s [%s] is %s, %s%s%s, and %s%s.",
               entry->nickname,
               hex_str(entry->identity, DIGEST_LEN),
               entry->unreachable_since ? "unreachable" : "reachable",
               entry->bad_since ? "unusable" : "usable",
               reason ? ", ": "",
               reason ? reason : "",
               r ? "live" : "not live / ",
               r ? "" : live_msg);
    } SMARTLIST_FOREACH_END(entry);
    log_info(LD_CIRC, "    (%d/%d entry guards are usable/new)",
             num_live_entry_guards(), smartlist_len(entry_guards));
    log_entry_guards(LOG_INFO);
    entry_guards_changed();
  }

  digestmap_free(reasons, NULL);
}

Here is the call graph for this function:

Here is the caller graph for this function:

void entry_guards_free_all ( void  )

Release all storage held by the list of entry guards and related memory structs.

Definition at line 5794 of file circuitbuild.c.

Here is the call graph for this function:

Here is the caller graph for this function:

int entry_guards_parse_state ( or_state_t state,
int  set,
char **  msg 
)

Parse state and learn about the entry guards it describes.

If set is true, and there are no errors, replace the global entry_list with what we find. On success, return 0. On failure, alloc into *msg a string describing the error, and return -1.

Definition at line 4621 of file circuitbuild.c.

{
  entry_guard_t *node = NULL;
  smartlist_t *new_entry_guards = smartlist_new();
  config_line_t *line;
  time_t now = time(NULL);
  const char *state_version = state->TorVersion;
  digestmap_t *added_by = digestmap_new();

  *msg = NULL;
  for (line = state->EntryGuards; line; line = line->next) {
    if (!strcasecmp(line->key, "EntryGuard")) {
      smartlist_t *args = smartlist_new();
      node = tor_malloc_zero(sizeof(entry_guard_t));
      /* all entry guards on disk have been contacted */
      node->made_contact = 1;
      smartlist_add(new_entry_guards, node);
      smartlist_split_string(args, line->value, " ",
                             SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
      if (smartlist_len(args)<2) {
        *msg = tor_strdup("Unable to parse entry nodes: "
                          "Too few arguments to EntryGuard");
      } else if (!is_legal_nickname(smartlist_get(args,0))) {
        *msg = tor_strdup("Unable to parse entry nodes: "
                          "Bad nickname for EntryGuard");
      } else {
        strlcpy(node->nickname, smartlist_get(args,0), MAX_NICKNAME_LEN+1);
        if (base16_decode(node->identity, DIGEST_LEN, smartlist_get(args,1),
                          strlen(smartlist_get(args,1)))<0) {
          *msg = tor_strdup("Unable to parse entry nodes: "
                            "Bad hex digest for EntryGuard");
        }
      }
      SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
      smartlist_free(args);
      if (*msg)
        break;
    } else if (!strcasecmp(line->key, "EntryGuardDownSince") ||
               !strcasecmp(line->key, "EntryGuardUnlistedSince")) {
      time_t when;
      time_t last_try = 0;
      if (!node) {
        *msg = tor_strdup("Unable to parse entry nodes: "
               "EntryGuardDownSince/UnlistedSince without EntryGuard");
        break;
      }
      if (parse_iso_time(line->value, &when)<0) {
        *msg = tor_strdup("Unable to parse entry nodes: "
                          "Bad time in EntryGuardDownSince/UnlistedSince");
        break;
      }
      if (when > now) {
        /* It's a bad idea to believe info in the future: you can wind
         * up with timeouts that aren't allowed to happen for years. */
        continue;
      }
      if (strlen(line->value) >= ISO_TIME_LEN+ISO_TIME_LEN+1) {
        /* ignore failure */
        (void) parse_iso_time(line->value+ISO_TIME_LEN+1, &last_try);
      }
      if (!strcasecmp(line->key, "EntryGuardDownSince")) {
        node->unreachable_since = when;
        node->last_attempted = last_try;
      } else {
        node->bad_since = when;
      }
    } else if (!strcasecmp(line->key, "EntryGuardAddedBy")) {
      char d[DIGEST_LEN];
      /* format is digest version date */
      if (strlen(line->value) < HEX_DIGEST_LEN+1+1+1+ISO_TIME_LEN) {
        log_warn(LD_BUG, "EntryGuardAddedBy line is not long enough.");
        continue;
      }
      if (base16_decode(d, sizeof(d), line->value, HEX_DIGEST_LEN)<0 ||
          line->value[HEX_DIGEST_LEN] != ' ') {
        log_warn(LD_BUG, "EntryGuardAddedBy line %s does not begin with "
                 "hex digest", escaped(line->value));
        continue;
      }
      digestmap_set(added_by, d, tor_strdup(line->value+HEX_DIGEST_LEN+1));
    } else if (!strcasecmp(line->key, "EntryGuardPathBias")) {
      const or_options_t *options = get_options();
      unsigned hop_cnt, success_cnt;

      if (tor_sscanf(line->value, "%u %u", &success_cnt, &hop_cnt) != 2) {
        log_warn(LD_GENERAL, "Unable to parse guard path bias info: "
                 "Misformated EntryGuardPathBias %s", escaped(line->value));
        continue;
      }

      node->first_hops = hop_cnt;
      node->circuit_successes = success_cnt;
      log_info(LD_GENERAL, "Read %u/%u path bias for node %s",
               node->circuit_successes, node->first_hops, node->nickname);
      /* Note: We rely on the < comparison here to allow us to set a 0
       * rate and disable the feature entirely. If refactoring, don't
       * change to <= */
      if (node->circuit_successes/((double)node->first_hops)
          < pathbias_get_disable_rate(options)) {
        node->path_bias_disabled = 1;
        log_info(LD_GENERAL,
                 "Path bias is too high (%u/%u); disabling node %s",
                 node->circuit_successes, node->first_hops, node->nickname);
      }

    } else {
      log_warn(LD_BUG, "Unexpected key %s", line->key);
    }
  }

  SMARTLIST_FOREACH(new_entry_guards, entry_guard_t *, e,
   {
     char *sp;
     char *val = digestmap_get(added_by, e->identity);
     if (val && (sp = strchr(val, ' '))) {
       time_t when;
       *sp++ = '\0';
       if (parse_iso_time(sp, &when)<0) {
         log_warn(LD_BUG, "Can't read time %s in EntryGuardAddedBy", sp);
       } else {
         e->chosen_by_version = tor_strdup(val);
         e->chosen_on_date = when;
       }
     } else {
       if (state_version) {
         e->chosen_by_version = tor_strdup(state_version);
         e->chosen_on_date = time(NULL) - crypto_rand_int(3600*24*30);
       }
     }
     if (node->path_bias_disabled && !node->bad_since)
       node->bad_since = time(NULL);
   });

  if (*msg || !set) {
    SMARTLIST_FOREACH(new_entry_guards, entry_guard_t *, e,
                      entry_guard_free(e));
    smartlist_free(new_entry_guards);
  } else { /* !err && set */
    if (entry_guards) {
      SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
                        entry_guard_free(e));
      smartlist_free(entry_guards);
    }
    entry_guards = new_entry_guards;
    entry_guards_dirty = 0;
    /* XXX024 hand new_entry_guards to this func, and move it up a
     * few lines, so we don't have to re-dirty it */
    if (remove_obsolete_entry_guards(now))
      entry_guards_dirty = 1;
  }
  digestmap_free(added_by, _tor_free);
  return *msg ? -1 : 0;
}

Here is the call graph for this function:

Here is the caller graph for this function:

If the entry guard info has not changed, do nothing and return.

Otherwise, free the EntryGuards piece of state and create a new one out of the global entry_guards list, and then mark state dirty so it will get saved to disk.

Definition at line 4796 of file circuitbuild.c.

{
  config_line_t **next, *line;
  if (! entry_guards_dirty)
    return;

  config_free_lines(state->EntryGuards);
  next = &state->EntryGuards;
  *next = NULL;
  if (!entry_guards)
    entry_guards = smartlist_new();
  SMARTLIST_FOREACH(entry_guards, entry_guard_t *, e,
    {
      char dbuf[HEX_DIGEST_LEN+1];
      if (!e->made_contact)
        continue; /* don't write this one to disk */
      *next = line = tor_malloc_zero(sizeof(config_line_t));
      line->key = tor_strdup("EntryGuard");
      base16_encode(dbuf, sizeof(dbuf), e->identity, DIGEST_LEN);
      tor_asprintf(&line->value, "%s %s", e->nickname, dbuf);
      next = &(line->next);
      if (e->unreachable_since) {
        *next = line = tor_malloc_zero(sizeof(config_line_t));
        line->key = tor_strdup("EntryGuardDownSince");
        line->value = tor_malloc(ISO_TIME_LEN+1+ISO_TIME_LEN+1);
        format_iso_time(line->value, e->unreachable_since);
        if (e->last_attempted) {
          line->value[ISO_TIME_LEN] = ' ';
          format_iso_time(line->value+ISO_TIME_LEN+1, e->last_attempted);
        }
        next = &(line->next);
      }
      if (e->bad_since) {
        *next = line = tor_malloc_zero(sizeof(config_line_t));
        line->key = tor_strdup("EntryGuardUnlistedSince");
        line->value = tor_malloc(ISO_TIME_LEN+1);
        format_iso_time(line->value, e->bad_since);
        next = &(line->next);
      }
      if (e->chosen_on_date && e->chosen_by_version &&
          !strchr(e->chosen_by_version, ' ')) {
        char d[HEX_DIGEST_LEN+1];
        char t[ISO_TIME_LEN+1];
        *next = line = tor_malloc_zero(sizeof(config_line_t));
        line->key = tor_strdup("EntryGuardAddedBy");
        base16_encode(d, sizeof(d), e->identity, DIGEST_LEN);
        format_iso_time(t, e->chosen_on_date);
        tor_asprintf(&line->value, "%s %s %s",
                     d, e->chosen_by_version, t);
        next = &(line->next);
      }
      if (e->first_hops) {
        *next = line = tor_malloc_zero(sizeof(config_line_t));
        line->key = tor_strdup("EntryGuardPathBias");
        tor_asprintf(&line->value, "%u %u",
                     e->circuit_successes, e->first_hops);
        next = &(line->next);
      }

    });
  if (!get_options()->AvoidDiskWrites)
    or_state_mark_dirty(get_or_state(), 0);
  entry_guards_dirty = 0;
}

Here is the call graph for this function:

Here is the caller graph for this function:

int entry_list_is_constrained ( const or_options_t options)

Return 0 if we're fine adding arbitrary routers out of the directory to our entry guard list, or return 1 if we have a list already and we must stick to it.

Definition at line 4464 of file circuitbuild.c.

{
  if (options->EntryNodes)
    return 1;
  if (options->UseBridges)
    return 1;
  return 0;
}

Here is the caller graph for this function:

void entry_nodes_should_be_added ( void  )

Called when the value of EntryNodes changes in our configuration.

Definition at line 4360 of file circuitbuild.c.

{
  log_info(LD_CIRC, "EntryNodes config option set. Putting configured "
           "relays at the front of the entry guard list.");
  should_add_entry_nodes = 1;
}

Here is the caller graph for this function:

extend_info_t* extend_info_alloc ( const char *  nickname,
const char *  digest,
crypto_pk_t onion_key,
const tor_addr_t addr,
uint16_t  port 
)

Allocate a new extend_info object based on the various arguments.

Definition at line 3645 of file circuitbuild.c.

{
  extend_info_t *info = tor_malloc_zero(sizeof(extend_info_t));
  memcpy(info->identity_digest, digest, DIGEST_LEN);
  if (nickname)
    strlcpy(info->nickname, nickname, sizeof(info->nickname));
  if (onion_key)
    info->onion_key = crypto_pk_dup_key(onion_key);
  tor_addr_copy(&info->addr, addr);
  info->port = port;
  return info;
}

Here is the call graph for this function:

Here is the caller graph for this function:

Allocate and return a new extend_info_t with the same contents as info.

Definition at line 3716 of file circuitbuild.c.

{
  extend_info_t *newinfo;
  tor_assert(info);
  newinfo = tor_malloc(sizeof(extend_info_t));
  memcpy(newinfo, info, sizeof(extend_info_t));
  if (info->onion_key)
    newinfo->onion_key = crypto_pk_dup_key(info->onion_key);
  else
    newinfo->onion_key = NULL;
  return newinfo;
}

Here is the call graph for this function:

Here is the caller graph for this function:

void extend_info_free ( extend_info_t info)

Release storage held by an extend_info_t struct.

Definition at line 3705 of file circuitbuild.c.

{
  if (!info)
    return;
  crypto_pk_free(info->onion_key);
  tor_free(info);
}

Here is the call graph for this function:

Here is the caller graph for this function:

extend_info_t* extend_info_from_node ( const node_t node,
int  for_direct_connect 
)

Allocate and return a new extend_info that can be used to build a circuit to or through the node node.

Use the primary address of the node unless for_direct_connect is true, in which case the preferred address is used instead. May return NULL if there is not enough info about node to extend to it--for example, if there is no routerinfo_t or microdesc_t.

Definition at line 3686 of file circuitbuild.c.

{
  if (node->ri) {
    return extend_info_from_router(node->ri, for_direct_connect);
  } else if (node->rs && node->md) {
    tor_addr_t addr;
    tor_addr_from_ipv4h(&addr, node->rs->addr);
    return extend_info_alloc(node->rs->nickname,
                             node->identity,
                             node->md->onion_pkey,
                             &addr,
                             node->rs->or_port);
  } else {
    return NULL;
  }
}

Here is the call graph for this function:

Here is the caller graph for this function:

extend_info_t* extend_info_from_router ( const routerinfo_t r,
int  for_direct_connect 
)

Allocate and return a new extend_info_t that can be used to build a circuit to or through the router r.

Use the primary address of the router unless for_direct_connect is true, in which case the preferred address is used instead.

Definition at line 3665 of file circuitbuild.c.

{
  tor_addr_port_t ap;
  tor_assert(r);

  if (for_direct_connect)
    router_get_pref_orport(r, &ap);
  else
    router_get_prim_orport(r, &ap);
  return extend_info_alloc(r->nickname, r->cache_info.identity_digest,
                           r->onion_pkey, &ap.addr, ap.port);
}

Here is the call graph for this function:

Here is the caller graph for this function:

void fetch_bridge_descriptors ( const or_options_t options,
time_t  now 
)

For each bridge in our list for which we don't currently have a descriptor, fetch a new copy of its descriptor -- either directly from the bridge or via a bridge authority.

Definition at line 5478 of file circuitbuild.c.

{
  int num_bridge_auths = get_n_authorities(BRIDGE_DIRINFO);
  int ask_bridge_directly;
  int can_use_bridge_authority;

  if (!bridge_list)
    return;

  /* If we still have unconfigured managed proxies, don't go and
     connect to a bridge. */
  if (pt_proxies_configuration_pending())
    return;

  SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge)
    {
      if (!download_status_is_ready(&bridge->fetch_status, now,
                                    IMPOSSIBLE_TO_DOWNLOAD))
        continue; /* don't bother, no need to retry yet */
      if (routerset_contains_bridge(options->ExcludeNodes, bridge)) {
        download_status_mark_impossible(&bridge->fetch_status);
        log_warn(LD_APP, "Not using bridge at %s: it is in ExcludeNodes.",
                 safe_str_client(fmt_addr(&bridge->addr)));
        continue;
      }

      /* schedule another fetch as if this one will fail, in case it does */
      download_status_failed(&bridge->fetch_status, 0);

      can_use_bridge_authority = !tor_digest_is_zero(bridge->identity) &&
                                 num_bridge_auths;
      ask_bridge_directly = !can_use_bridge_authority ||
                            !options->UpdateBridgesFromAuthority;
      log_debug(LD_DIR, "ask_bridge_directly=%d (%d, %d, %d)",
                ask_bridge_directly, tor_digest_is_zero(bridge->identity),
                !options->UpdateBridgesFromAuthority, !num_bridge_auths);

      if (ask_bridge_directly &&
          !fascist_firewall_allows_address_or(&bridge->addr, bridge->port)) {
        log_notice(LD_DIR, "Bridge at '%s:%d' isn't reachable by our "
                   "firewall policy. %s.", fmt_addr(&bridge->addr),
                   bridge->port,
                   can_use_bridge_authority ?
                     "Asking bridge authority instead" : "Skipping");
        if (can_use_bridge_authority)
          ask_bridge_directly = 0;
        else
          continue;
      }

      if (ask_bridge_directly) {
        /* we need to ask the bridge itself for its descriptor. */
        launch_direct_bridge_descriptor_fetch(bridge);
      } else {
        /* We have a digest and we want to ask an authority. We could
         * combine all the requests into one, but that may give more
         * hints to the bridge authority than we want to give. */
        char resource[10 + HEX_DIGEST_LEN];
        memcpy(resource, "fp/", 3);
        base16_encode(resource+3, HEX_DIGEST_LEN+1,
                      bridge->identity, DIGEST_LEN);
        memcpy(resource+3+HEX_DIGEST_LEN, ".z", 3);
        log_info(LD_DIR, "Fetching bridge info '%s' from bridge authority.",
                 resource);
        directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
                ROUTER_PURPOSE_BRIDGE, resource, 0);
      }
    }
  SMARTLIST_FOREACH_END(bridge);
}

Here is the call graph for this function:

Here is the caller graph for this function:

int find_transport_by_bridge_addrport ( const tor_addr_t addr,
uint16_t  port,
const transport_t **  transport 
)

If addr and port match the address and port of a bridge of ours that uses pluggable transports, place its transport in transport.

Return 0 on success (found a transport, or found a bridge with no transport, or found no bridge); return -1 if we should be using a transport, but the transport could not be found.

Definition at line 5404 of file circuitbuild.c.

{
  *transport = NULL;
  if (!bridge_list)
    return 0;

  SMARTLIST_FOREACH_BEGIN(bridge_list, const bridge_info_t *, bridge) {
    if (tor_addr_eq(&bridge->addr, addr) &&
        (bridge->port == port)) { /* bridge matched */
      if (bridge->transport_name) { /* it also uses pluggable transports */
        *transport = transport_get_by_name(bridge->transport_name);
        if (*transport == NULL) { /* it uses pluggable transports, but
                                     the transport could not be found! */
          return -1;
        }
        return 0;
      } else { /* bridge matched, but it doesn't use transports. */
        break;
      }
    }
  } SMARTLIST_FOREACH_END(bridge);

  *transport = NULL;
  return 0;
}

Here is the call graph for this function:

Here is the caller graph for this function:

const char* find_transport_name_by_bridge_addrport ( const tor_addr_t addr,
uint16_t  port 
)

Definition at line 5381 of file circuitbuild.c.

{
  if (!bridge_list)
    return NULL;

  SMARTLIST_FOREACH_BEGIN(bridge_list, const bridge_info_t *, bridge) {
    if (tor_addr_eq(&bridge->addr, addr) &&
        (bridge->port == port))
      return bridge->transport_name;
  } SMARTLIST_FOREACH_END(bridge);

  return NULL;
}

Here is the caller graph for this function:

int getinfo_helper_entry_guards ( control_connection_t conn,
const char *  question,
char **  answer,
const char **  errmsg 
)

If question is the string "entry-guards", then dump to *answer a newly allocated string describing all of the nodes in the global entry_guards list.

See control-spec.txt for details. For backward compatibility, we also handle the string "helper-nodes".

Definition at line 4868 of file circuitbuild.c.

{
  (void) conn;
  (void) errmsg;

  if (!strcmp(question,"entry-guards") ||
      !strcmp(question,"helper-nodes")) {
    smartlist_t *sl = smartlist_new();
    char tbuf[ISO_TIME_LEN+1];
    char nbuf[MAX_VERBOSE_NICKNAME_LEN+1];
    if (!entry_guards)
      entry_guards = smartlist_new();
    SMARTLIST_FOREACH_BEGIN(entry_guards, entry_guard_t *, e) {
        const char *status = NULL;
        time_t when = 0;
        const node_t *node;

        if (!e->made_contact) {
          status = "never-connected";
        } else if (e->bad_since) {
          when = e->bad_since;
          status = "unusable";
        } else {
          status = "up";
        }

        node = node_get_by_id(e->identity);
        if (node) {
          node_get_verbose_nickname(node, nbuf);
        } else {
          nbuf[0] = '$';
          base16_encode(nbuf+1, sizeof(nbuf)-1, e->identity, DIGEST_LEN);
          /* e->nickname field is not very reliable if we don't know about
           * this router any longer; don't include it. */
        }

        if (when) {
          format_iso_time(tbuf, when);
          smartlist_add_asprintf(sl, "%s %s %s\n", nbuf, status, tbuf);
        } else {
          smartlist_add_asprintf(sl, "%s %s\n", nbuf, status);
        }
    } SMARTLIST_FOREACH_END(e);
    *answer = smartlist_join_strings(sl, "", 0, NULL);
    SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
    smartlist_free(sl);
  }
  return 0;
}

Here is the call graph for this function:

We've decided to start our reachability testing.

If all is set, log this to the user. Return 1 if we did, or 0 if we chose not to log anything.

Definition at line 2123 of file circuitbuild.c.

{
  char dirbuf[128];
  const routerinfo_t *me = router_get_my_routerinfo();
  if (!me)
    return 0;
  control_event_server_status(LOG_NOTICE,
                              "CHECKING_REACHABILITY ORADDRESS=%s:%d",
                              me->address, me->or_port);
  if (me->dir_port) {
    tor_snprintf(dirbuf, sizeof(dirbuf), " and DirPort %s:%d",
                 me->address, me->dir_port);
    control_event_server_status(LOG_NOTICE,
                                "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
                                me->address, me->dir_port);
  }
  log_notice(LD_OR, "Now checking whether ORPort %s:%d%s %s reachable... "
                         "(this may take up to %d minutes -- look for log "
                         "messages indicating success)",
      me->address, me->or_port,
      me->dir_port ? dirbuf : "",
      me->dir_port ? "are" : "is",
      TIMEOUT_UNTIL_UNREACHABILITY_COMPLAINT/60);

  return 1;
}

Here is the call graph for this function:

Here is the caller graph for this function:

void learned_bridge_descriptor ( routerinfo_t ri,
int  from_cache 
)

We just learned a descriptor for a bridge.

See if that digest is in our entry guard list, and add it if not.

Definition at line 5637 of file circuitbuild.c.

{
  tor_assert(ri);
  tor_assert(ri->purpose == ROUTER_PURPOSE_BRIDGE);
  if (get_options()->UseBridges) {
    int first = !any_bridge_descriptors_known();
    bridge_info_t *bridge = get_configured_bridge_by_routerinfo(ri);
    time_t now = time(NULL);
    router_set_status(ri->cache_info.identity_digest, 1);

    if (bridge) { /* if we actually want to use this one */
      node_t *node;
      /* it's here; schedule its re-fetch for a long time from now. */
      if (!from_cache)
        download_status_reset(&bridge->fetch_status);

      node = node_get_mutable_by_id(ri->cache_info.identity_digest);
      tor_assert(node);
      rewrite_node_address_for_bridge(bridge, node);
      add_an_entry_guard(node, 1, 1);

      log_notice(LD_DIR, "new bridge descriptor '%s' (%s): %s", ri->nickname,
                 from_cache ? "cached" : "fresh", router_describe(ri));
      /* set entry->made_contact so if it goes down we don't drop it from
       * our entry node list */
      entry_guard_register_connect_status(ri->cache_info.identity_digest,
                                          1, 0, now);
      if (first)
        routerlist_retry_directory_downloads(now);
    }
  }
}

Here is the call graph for this function:

Here is the caller graph for this function:

void learned_router_identity ( const tor_addr_t addr,
uint16_t  port,
const char *  digest 
)

We made a connection to a router at addr:port without knowing its digest.

Its digest turned out to be digest. If it was a bridge, and we still don't know its digest, record it.

Definition at line 5245 of file circuitbuild.c.

{
  bridge_info_t *bridge =
    get_configured_bridge_by_addr_port_digest(addr, port, digest);
  if (bridge && tor_digest_is_zero(bridge->identity)) {
    memcpy(bridge->identity, digest, DIGEST_LEN);
    log_notice(LD_DIR, "Learned fingerprint %s for bridge %s:%d",
               hex_str(digest, DIGEST_LEN), fmt_addr(addr), port);
  }
}

Here is the call graph for this function:

Here is the caller graph for this function:

void mark_bridge_list ( void  )

Mark every entry of the bridge list to be removed on our next call to sweep_bridge_list unless it has first been un-marked.

Definition at line 4929 of file circuitbuild.c.

Here is the call graph for this function:

Here is the caller graph for this function:

void mark_transport_list ( void  )

Mark every entry of the transport list to be removed on our next call to sweep_transport_list unless it has first been un-marked.

Definition at line 4979 of file circuitbuild.c.

Here is the call graph for this function:

Here is the caller graph for this function:

int node_is_a_configured_bridge ( const node_t node)

Return 1 if node is one of our configured bridges, else 0.

Definition at line 5211 of file circuitbuild.c.

{
  int retval = 0;               /* Negative.  */
  smartlist_t *orports = NULL;

  if (!node)
    goto out;

  orports = node_get_all_orports(node);
  if (orports == NULL)
    goto out;

  SMARTLIST_FOREACH_BEGIN(orports, tor_addr_port_t *, orport) {
    if (get_configured_bridge_by_addr_port_digest(&orport->addr, orport->port,
                                                  node->identity) != NULL) {
      retval = 1;
      goto out;
    }
  } SMARTLIST_FOREACH_END(orport);

 out:
  if (orports != NULL) {
    SMARTLIST_FOREACH(orports, tor_addr_port_t *, p, tor_free(p));
    smartlist_free(orports);
    orports = NULL;
  }
  return retval;
}

Here is the call graph for this function:

Here is the caller graph for this function:

void onion_append_to_cpath ( crypt_path_t **  head_ptr,
crypt_path_t new_hop 
)

Add new_hop to the end of the doubly-linked-list head_ptr.

This function is used to extend cpath by another hop.

Definition at line 3431 of file circuitbuild.c.

{
  if (*head_ptr) {
    new_hop->next = (*head_ptr);
    new_hop->prev = (*head_ptr)->prev;
    (*head_ptr)->prev->next = new_hop;
    (*head_ptr)->prev = new_hop;
  } else {
    *head_ptr = new_hop;
    new_hop->prev = new_hop->next = new_hop;
  }
}

Here is the caller graph for this function:

int onionskin_answer ( or_circuit_t circ,
uint8_t  cell_type,
const char *  payload,
const char *  keys 
)

Given a response payload and keys, initialize, then send a created cell back.

Definition at line 2807 of file circuitbuild.c.

{
  cell_t cell;
  crypt_path_t *tmp_cpath;

  tmp_cpath = tor_malloc_zero(sizeof(crypt_path_t));
  tmp_cpath->magic = CRYPT_PATH_MAGIC;

  memset(&cell, 0, sizeof(cell_t));
  cell.command = cell_type;
  cell.circ_id = circ->p_circ_id;

  circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OPEN);

  memcpy(cell.payload, payload,
         cell_type == CELL_CREATED ? ONIONSKIN_REPLY_LEN : DIGEST_LEN*2);

  log_debug(LD_CIRC,"init digest forward 0x%.8x, backward 0x%.8x.",
            (unsigned int)get_uint32(keys),
            (unsigned int)get_uint32(keys+20));
  if (circuit_init_cpath_crypto(tmp_cpath, keys, 0)<0) {
    log_warn(LD_BUG,"Circuit initialization failed");
    tor_free(tmp_cpath);
    return -1;
  }
  circ->n_digest = tmp_cpath->f_digest;
  circ->n_crypto = tmp_cpath->f_crypto;
  circ->p_digest = tmp_cpath->b_digest;
  circ->p_crypto = tmp_cpath->b_crypto;
  tmp_cpath->magic = 0;
  tor_free(tmp_cpath);

  if (cell_type == CELL_CREATED)
    memcpy(circ->handshake_digest, cell.payload+DH_KEY_LEN, DIGEST_LEN);
  else
    memcpy(circ->handshake_digest, cell.payload+DIGEST_LEN, DIGEST_LEN);

  circ->is_first_hop = (cell_type == CELL_CREATED_FAST);

  append_cell_to_circuit_queue(TO_CIRCUIT(circ),
                               circ->p_conn, &cell, CELL_DIRECTION_IN, 0);
  log_debug(LD_CIRC,"Finished sending '%s' cell.",
            circ->is_first_hop ? "created_fast" : "created");

  if (!is_local_addr(&circ->p_conn->_base.addr) &&
      !connection_or_nonopen_was_started_here(circ->p_conn)) {
    /* record that we could process create cells from a non-local conn
     * that we didn't initiate; presumably this means that create cells
     * can reach us too. */
    router_orport_found_reachable();
  }

  return 0;
}

Here is the call graph for this function:

Here is the caller graph for this function:

origin_circuit_t* origin_circuit_init ( uint8_t  purpose,
int  flags 
)

Create and return a new origin circuit.

Initialize its purpose and build-state based on our arguments. The flags argument is a bitfield of CIRCLAUNCH_* flags.

Definition at line 1886 of file circuitbuild.c.

{
  /* sets circ->p_circ_id and circ->p_conn */
  origin_circuit_t *circ = origin_circuit_new();
  circuit_set_state(TO_CIRCUIT(circ), CIRCUIT_STATE_OR_WAIT);
  circ->build_state = tor_malloc_zero(sizeof(cpath_build_state_t));
  circ->build_state->onehop_tunnel =
    ((flags & CIRCLAUNCH_ONEHOP_TUNNEL) ? 1 : 0);
  circ->build_state->need_uptime =
    ((flags & CIRCLAUNCH_NEED_UPTIME) ? 1 : 0);
  circ->build_state->need_capacity =
    ((flags & CIRCLAUNCH_NEED_CAPACITY) ? 1 : 0);
  circ->build_state->is_internal =
    ((flags & CIRCLAUNCH_IS_INTERNAL) ? 1 : 0);
  circ->_base.purpose = purpose;
  return circ;
}

Here is the call graph for this function:

Here is the caller graph for this function:

void retry_bridge_descriptor_fetch_directly ( const char *  digest)

Fetching the bridge descriptor from the bridge authority returned a "not found".

Fall back to trying a direct fetch.

Definition at line 5465 of file circuitbuild.c.

{
  bridge_info_t *bridge = find_bridge_by_digest(digest);
  if (!bridge)
    return; /* not found? oh well. */

  launch_direct_bridge_descriptor_fetch(bridge);
}

Here is the call graph for this function:

Here is the caller graph for this function:

Return 1 if ri is one of our known bridges, else 0.

Definition at line 5204 of file circuitbuild.c.

{
  return get_configured_bridge_by_routerinfo(ri) ? 1 : 0;
}

Here is the call graph for this function:

Here is the caller graph for this function:

void sweep_bridge_list ( void  )

Remove every entry of the bridge list that was marked with mark_bridge_list if it has not subsequently been un-marked.

Definition at line 4940 of file circuitbuild.c.

Here is the call graph for this function:

Here is the caller graph for this function:

void sweep_transport_list ( void  )

Remove every entry of the transport list that was marked with mark_transport_list if it has not subsequently been un-marked.

Definition at line 4990 of file circuitbuild.c.

Here is the call graph for this function:

Here is the caller graph for this function:

int transport_add ( transport_t t)

Add transport t to the internal list of pluggable transports.

Returns 0 if the transport was added correctly, 1 if the same transport was already registered (in this case the caller must free the transport) and -1 if there was an error.

Definition at line 5119 of file circuitbuild.c.

{
  int r;
  tor_assert(t);

  r = transport_resolve_conflicts(t);

  switch (r) {
  case 0: /* should register transport */
    if (!transport_list)
      transport_list = smartlist_new();
    smartlist_add(transport_list, t);
    return 0;
  default: /* let our caller know the return code */
    return r;
  }
}

Here is the call graph for this function:

Here is the caller graph for this function:

int transport_add_from_config ( const tor_addr_t addr,
uint16_t  port,
const char *  name,
int  socks_ver 
)

Remember a new pluggable transport proxy at addr:port.

name is set to the name of the protocol this proxy uses. socks_ver is set to the SOCKS version of the proxy.

Definition at line 5141 of file circuitbuild.c.

{
  transport_t *t = transport_new(addr, port, name, socks_ver);

  int r = transport_add(t);

  switch (r) {
  case -1:
  default:
    log_notice(LD_GENERAL, "Could not add transport %s at %s:%u. Skipping.",
               t->name, fmt_addr(&t->addr), t->port);
    transport_free(t);
    return -1;
  case 1:
    log_info(LD_GENERAL, "Succesfully registered transport %s at %s:%u.",
             t->name, fmt_addr(&t->addr), t->port);
     transport_free(t); /* falling */
     return 0;
  case 0:
    log_info(LD_GENERAL, "Succesfully registered transport %s at %s:%u.",
             t->name, fmt_addr(&t->addr), t->port);
    return 0;
  }
}

Here is the call graph for this function:

Here is the caller graph for this function:

void transport_free ( transport_t transport)

Free the pluggable transport struct transport.

Definition at line 5015 of file circuitbuild.c.

{
  if (!transport)
    return;

  tor_free(transport->name);
  tor_free(transport);
}

Here is the caller graph for this function:

transport_t* transport_get_by_name ( const char *  name)

Returns the transport in our transport list that has the name name.

Else returns NULL.

Definition at line 5027 of file circuitbuild.c.

{
  tor_assert(name);

  if (!transport_list)
    return NULL;

  SMARTLIST_FOREACH_BEGIN(transport_list, transport_t *, transport) {
    if (!strcmp(transport->name, name))
      return transport;
  } SMARTLIST_FOREACH_END(transport);

  return NULL;
}

Here is the caller graph for this function:

transport_t* transport_new ( const tor_addr_t addr,
uint16_t  port,
const char *  name,
int  socks_ver 
)

Returns a transport_t struct for a transport proxy supporting the protocol name listening at addr:port using SOCKS version socks_ver.

Definition at line 5046 of file circuitbuild.c.

{
  transport_t *t = tor_malloc_zero(sizeof(transport_t));

  tor_addr_copy(&t->addr, addr);
  t->port = port;
  t->name = tor_strdup(name);
  t->socks_version = socks_ver;

  return t;
}

Here is the call graph for this function:

Here is the caller graph for this function:


Variable Documentation

Global list of circuit build times.

Definition at line 53 of file circuitbuild.c.