tor

The Tor anonymity network
git clone https://git.dasho.dev/tor.git
Log | Files | Refs | README | LICENSE

bridges.c (39316B)


      1 /* Copyright (c) 2001 Matej Pfajfar.
      2 * Copyright (c) 2001-2004, Roger Dingledine.
      3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
      4 * Copyright (c) 2007-2021, The Tor Project, Inc. */
      5 /* See LICENSE for licensing information */
      6 
      7 /**
      8 * \file bridges.c
      9 * \brief Code to manage bridges and bridge selection.
     10 *
     11 * Bridges are fixed entry nodes, used for censorship circumvention.
     12 **/
     13 
     14 #define TOR_BRIDGES_PRIVATE
     15 
     16 #include "core/or/or.h"
     17 #include "app/config/config.h"
     18 #include "core/mainloop/connection.h"
     19 #include "core/or/circuitbuild.h"
     20 #include "core/or/policies.h"
     21 #include "feature/client/bridges.h"
     22 #include "feature/client/entrynodes.h"
     23 #include "feature/client/transports.h"
     24 #include "feature/dirclient/dirclient.h"
     25 #include "feature/dirclient/dlstatus.h"
     26 #include "feature/dircommon/directory.h"
     27 #include "feature/nodelist/describe.h"
     28 #include "feature/nodelist/dirlist.h"
     29 #include "feature/nodelist/nodelist.h"
     30 #include "feature/nodelist/routerinfo.h"
     31 #include "feature/nodelist/routerlist.h"
     32 #include "feature/nodelist/routerset.h"
     33 
     34 #include "core/or/extend_info_st.h"
     35 #include "feature/nodelist/node_st.h"
     36 #include "feature/nodelist/routerinfo_st.h"
     37 #include "feature/nodelist/routerstatus_st.h"
     38 #include "feature/nodelist/microdesc_st.h"
     39 
     40 /** Information about a configured bridge. Currently this just matches the
     41 * ones in the torrc file, but one day we may be able to learn about new
     42 * bridges on our own, and remember them in the state file. */
     43 struct bridge_info_t {
     44  /** Address and port of the bridge, as configured by the user.*/
     45  tor_addr_port_t addrport_configured;
     46  /** Address of the bridge. */
     47  tor_addr_t addr;
     48  /** TLS port for the bridge. */
     49  uint16_t port;
     50  /** Boolean: We are re-parsing our bridge list, and we are going to remove
     51   * this one if we don't find it in the list of configured bridges. */
     52  unsigned marked_for_removal : 1;
     53  /** Expected identity digest, or all zero bytes if we don't know what the
     54   * digest should be. */
     55  char identity[DIGEST_LEN];
     56 
     57  /** Name of pluggable transport protocol taken from its config line. */
     58  char *transport_name;
     59 
     60  /** When should we next try to fetch a descriptor for this bridge? */
     61  download_status_t fetch_status;
     62 
     63  /** A smartlist of k=v values to be passed to the SOCKS proxy, if
     64      transports are used for this bridge. */
     65  smartlist_t *socks_args;
     66 };
     67 
     68 #define bridge_free(bridge) \
     69  FREE_AND_NULL(bridge_info_t, bridge_free_, (bridge))
     70 
     71 static void bridge_free_(bridge_info_t *bridge);
     72 static void rewrite_node_address_for_bridge(const bridge_info_t *bridge,
     73                                            node_t *node);
     74 
     75 /** A list of configured bridges. Whenever we actually get a descriptor
     76 * for one, we add it as an entry guard.  Note that the order of bridges
     77 * in this list does not necessarily correspond to the order of bridges
     78 * in the torrc. */
     79 static smartlist_t *bridge_list = NULL;
     80 
     81 /** Mark every entry of the bridge list to be removed on our next call to
     82 * sweep_bridge_list unless it has first been un-marked. */
     83 void
     84 mark_bridge_list(void)
     85 {
     86  if (!bridge_list)
     87    bridge_list = smartlist_new();
     88  SMARTLIST_FOREACH(bridge_list, bridge_info_t *, b,
     89                    b->marked_for_removal = 1);
     90 }
     91 
     92 /** Remove every entry of the bridge list that was marked with
     93 * mark_bridge_list if it has not subsequently been un-marked. */
     94 void
     95 sweep_bridge_list(void)
     96 {
     97  if (!bridge_list)
     98    bridge_list = smartlist_new();
     99  SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, b) {
    100    if (b->marked_for_removal) {
    101      SMARTLIST_DEL_CURRENT(bridge_list, b);
    102      bridge_free(b);
    103    }
    104  } SMARTLIST_FOREACH_END(b);
    105 }
    106 
    107 /** Initialize the bridge list to empty, creating it if needed. */
    108 STATIC void
    109 clear_bridge_list(void)
    110 {
    111  if (!bridge_list)
    112    bridge_list = smartlist_new();
    113  SMARTLIST_FOREACH(bridge_list, bridge_info_t *, b, bridge_free(b));
    114  smartlist_clear(bridge_list);
    115 }
    116 
    117 /** Free the bridge <b>bridge</b>. */
    118 static void
    119 bridge_free_(bridge_info_t *bridge)
    120 {
    121  if (!bridge)
    122    return;
    123 
    124  tor_free(bridge->transport_name);
    125  if (bridge->socks_args) {
    126    SMARTLIST_FOREACH(bridge->socks_args, char*, s, tor_free(s));
    127    smartlist_free(bridge->socks_args);
    128  }
    129 
    130  tor_free(bridge);
    131 }
    132 
    133 /** Return a list of all the configured bridges, as bridge_info_t pointers. */
    134 const smartlist_t *
    135 bridge_list_get(void)
    136 {
    137  if (!bridge_list)
    138    bridge_list = smartlist_new();
    139  return bridge_list;
    140 }
    141 
    142 /**
    143 * Returns true if there are enough bridges to make a conflux set
    144 * without re-using the same bridge.
    145 */
    146 bool
    147 conflux_can_exclude_used_bridges(void)
    148 {
    149  if (smartlist_len(bridge_list_get()) == 1) {
    150    static bool warned_once = false;
    151    bridge_info_t *bridge = smartlist_get(bridge_list_get(), 0);
    152    tor_assert(bridge);
    153 
    154    /* Snowflake is a special case. With one snowflake bridge,
    155     * you are load balanced among many back-end bridges.
    156     * So we do not need to warn the user for it. */
    157    if (bridge->transport_name &&
    158        strcasecmp(bridge->transport_name, "snowflake") == 0) {
    159      return false;
    160    }
    161 
    162    if (!warned_once) {
    163      log_warn(LD_CIRC, "Only one bridge (transport: '%s') is configured. "
    164                        "You should have at least two for conflux, "
    165                        "for any transport that is not 'snowflake'.",
    166                        bridge->transport_name ?
    167                          bridge->transport_name : "vanilla");
    168      warned_once = true;
    169    }
    170 
    171    return false;
    172  }
    173 
    174  return true;
    175 }
    176 
    177 /**
    178 * Given a <b>bridge</b>, return a pointer to its RSA identity digest, or
    179 * NULL if we don't know one for it.
    180 */
    181 const uint8_t *
    182 bridge_get_rsa_id_digest(const bridge_info_t *bridge)
    183 {
    184  tor_assert(bridge);
    185  if (tor_digest_is_zero(bridge->identity))
    186    return NULL;
    187  else
    188    return (const uint8_t *) bridge->identity;
    189 }
    190 
    191 /**
    192 * Given a <b>bridge</b>, return a pointer to its configured addr:port
    193 * combination.
    194 */
    195 const tor_addr_port_t *
    196 bridge_get_addr_port(const bridge_info_t *bridge)
    197 {
    198  tor_assert(bridge);
    199  return &bridge->addrport_configured;
    200 }
    201 
    202 /**
    203 * Given a <b>bridge</b>, return the transport name. If none were configured,
    204 * NULL is returned.
    205 */
    206 const char *
    207 bridget_get_transport_name(const bridge_info_t *bridge)
    208 {
    209  tor_assert(bridge);
    210  return bridge->transport_name;
    211 }
    212 
    213 /**
    214 * Return true if @a bridge has a transport name for which we don't actually
    215 * know a transport.
    216 */
    217 bool
    218 bridge_has_invalid_transport(const bridge_info_t *bridge)
    219 {
    220  const char *tname = bridget_get_transport_name(bridge);
    221  return tname && transport_get_by_name(tname) == NULL;
    222 }
    223 
    224 /** If we have a bridge configured whose digest matches <b>digest</b>, or a
    225 * bridge with no known digest whose address matches any of the
    226 * tor_addr_port_t's in <b>orports</b>, return that bridge.  Else return
    227 * NULL. */
    228 STATIC bridge_info_t *
    229 get_configured_bridge_by_orports_digest(const char *digest,
    230                                        const smartlist_t *orports)
    231 {
    232  if (!bridge_list)
    233    return NULL;
    234  SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge)
    235    {
    236      if (tor_digest_is_zero(bridge->identity)) {
    237        SMARTLIST_FOREACH_BEGIN(orports, tor_addr_port_t *, ap)
    238          {
    239            if (tor_addr_compare(&bridge->addr, &ap->addr, CMP_EXACT) == 0 &&
    240                bridge->port == ap->port)
    241              return bridge;
    242          }
    243        SMARTLIST_FOREACH_END(ap);
    244      }
    245      if (digest && tor_memeq(bridge->identity, digest, DIGEST_LEN))
    246        return bridge;
    247    }
    248  SMARTLIST_FOREACH_END(bridge);
    249  return NULL;
    250 }
    251 
    252 /** If we have a bridge configured whose digest matches <b>digest</b>, or a
    253 * bridge with no known digest whose address matches <b>addr</b>:<b>port</b>,
    254 * return that bridge.  Else return NULL. If <b>digest</b> is NULL, check for
    255 * address/port matches only. */
    256 bridge_info_t *
    257 get_configured_bridge_by_addr_port_digest(const tor_addr_t *addr,
    258                                          uint16_t port,
    259                                          const char *digest)
    260 {
    261  if (!bridge_list)
    262    return NULL;
    263  SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge)
    264    {
    265      if ((tor_digest_is_zero(bridge->identity) || digest == NULL) &&
    266          !tor_addr_compare(&bridge->addr, addr, CMP_EXACT) &&
    267          bridge->port == port)
    268        return bridge;
    269      if (digest && tor_memeq(bridge->identity, digest, DIGEST_LEN))
    270        return bridge;
    271    }
    272  SMARTLIST_FOREACH_END(bridge);
    273  return NULL;
    274 }
    275 
    276 /**
    277 * As get_configured_bridge_by_addr_port, but require that the
    278 * address match <b>addr</b>:<b>port</b>, and that the ID digest match
    279 * <b>digest</b>.  (The other function will ignore the address if the
    280 * digest matches.)
    281 */
    282 bridge_info_t *
    283 get_configured_bridge_by_exact_addr_port_digest(const tor_addr_t *addr,
    284                                                uint16_t port,
    285                                                const char *digest)
    286 {
    287  if (!bridge_list)
    288    return NULL;
    289  SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge) {
    290    if (!tor_addr_compare(&bridge->addr, addr, CMP_EXACT) &&
    291        bridge->port == port) {
    292 
    293      if (digest && tor_memeq(bridge->identity, digest, DIGEST_LEN))
    294        return bridge;
    295      else if (!digest || tor_digest_is_zero(bridge->identity))
    296        return bridge;
    297    }
    298 
    299  } SMARTLIST_FOREACH_END(bridge);
    300  return NULL;
    301 }
    302 
    303 /** If we have a bridge configured whose digest matches <b>digest</b>, or a
    304 * bridge with no known digest whose address matches <b>addr</b>:<b>port</b>,
    305 * return 1.  Else return 0. If <b>digest</b> is NULL, check for
    306 * address/port matches only. */
    307 int
    308 addr_is_a_configured_bridge(const tor_addr_t *addr,
    309                            uint16_t port,
    310                            const char *digest)
    311 {
    312  tor_assert(addr);
    313  return get_configured_bridge_by_addr_port_digest(addr, port, digest) ? 1 : 0;
    314 }
    315 
    316 /** If we have a bridge configured whose digest matches
    317 * <b>ei->identity_digest</b>, or a bridge with no known digest whose address
    318 * matches <b>ei->addr</b>:<b>ei->port</b>, return 1.  Else return 0.
    319 * If <b>ei</b> has no onion key configured, check for address/port matches
    320 * only.
    321 *
    322 * Note that if the extend_info_t contains multiple addresses, we return true
    323 * only if _every_ address is a bridge.
    324 */
    325 int
    326 extend_info_is_a_configured_bridge(const extend_info_t *ei)
    327 {
    328  const char *digest = curve25519_public_key_is_ok(&ei->curve25519_onion_key)
    329    ? ei->identity_digest : NULL;
    330  const tor_addr_port_t *ap1 = NULL, *ap2 = NULL;
    331  if (! tor_addr_is_null(&ei->orports[0].addr))
    332    ap1 = &ei->orports[0];
    333  if (! tor_addr_is_null(&ei->orports[1].addr))
    334    ap2 = &ei->orports[1];
    335  IF_BUG_ONCE(ap1 == NULL) {
    336    return 0;
    337  }
    338  return addr_is_a_configured_bridge(&ap1->addr, ap1->port, digest) &&
    339    (ap2 == NULL ||
    340     addr_is_a_configured_bridge(&ap2->addr, ap2->port, digest));
    341 }
    342 
    343 /** Wrapper around get_configured_bridge_by_addr_port_digest() to look
    344 * it up via router descriptor <b>ri</b>. */
    345 static bridge_info_t *
    346 get_configured_bridge_by_routerinfo(const routerinfo_t *ri)
    347 {
    348  bridge_info_t *bi = NULL;
    349  smartlist_t *orports = router_get_all_orports(ri);
    350  bi = get_configured_bridge_by_orports_digest(ri->cache_info.identity_digest,
    351                                               orports);
    352  SMARTLIST_FOREACH(orports, tor_addr_port_t *, p, tor_free(p));
    353  smartlist_free(orports);
    354  return bi;
    355 }
    356 
    357 /** Return 1 if <b>ri</b> is one of our known bridges, else 0. */
    358 int
    359 routerinfo_is_a_configured_bridge(const routerinfo_t *ri)
    360 {
    361  return get_configured_bridge_by_routerinfo(ri) ? 1 : 0;
    362 }
    363 
    364 /**
    365 * Return 1 iff <b>bridge_list</b> contains entry matching given
    366 * <b>addr</b> and <b>port</b> (and no identity digest) OR
    367 * it contains an  entry whose identity matches <b>digest</b>.
    368 * Otherwise, return 0.
    369 */
    370 static int
    371 bridge_exists_with_addr_and_port(const tor_addr_t *addr,
    372                                 const uint16_t port,
    373                                 const char *digest)
    374 {
    375  if (!tor_addr_port_is_valid(addr, port, 0))
    376    return 0;
    377 
    378  bridge_info_t *bridge =
    379   get_configured_bridge_by_addr_port_digest(addr, port, digest);
    380 
    381  return (bridge != NULL);
    382 }
    383 
    384 /** Return 1 if <b>node</b> is one of our configured bridges, else 0.
    385 * More specifically, return 1 iff: a bridge_info_t object exists in
    386 * <b>bridge_list</b> such that: 1) It's identity is equal to node
    387 * identity OR 2) It's identity digest is zero, but it matches
    388 * address and port of any ORPort in the node.
    389 */
    390 int
    391 node_is_a_configured_bridge(const node_t *node)
    392 {
    393  /* First, let's try searching for a bridge with matching identity. */
    394  if (BUG(fast_mem_is_zero(node->identity, DIGEST_LEN)))
    395    return 0;
    396 
    397  if (find_bridge_by_digest(node->identity) != NULL)
    398    return 1;
    399 
    400  /* At this point, we have established that no bridge exists with
    401   * matching identity digest. However, we still pass it into
    402   * bridge_exists_* functions because we want further code to
    403   * check for absence of identity digest in a bridge.
    404   */
    405  if (node->ri) {
    406    if (bridge_exists_with_addr_and_port(&node->ri->ipv4_addr,
    407                                         node->ri->ipv4_orport,
    408                                         node->identity))
    409      return 1;
    410 
    411    if (bridge_exists_with_addr_and_port(&node->ri->ipv6_addr,
    412                                         node->ri->ipv6_orport,
    413                                         node->identity))
    414      return 1;
    415  } else if (node->rs) {
    416    if (bridge_exists_with_addr_and_port(&node->rs->ipv4_addr,
    417                                         node->rs->ipv4_orport,
    418                                         node->identity))
    419      return 1;
    420 
    421    if (bridge_exists_with_addr_and_port(&node->rs->ipv6_addr,
    422                                         node->rs->ipv6_orport,
    423                                         node->identity))
    424      return 1;
    425  }  else if (node->md) {
    426    if (bridge_exists_with_addr_and_port(&node->md->ipv6_addr,
    427                                         node->md->ipv6_orport,
    428                                         node->identity))
    429      return 1;
    430  }
    431 
    432  return 0;
    433 }
    434 
    435 /** We made a connection to a router at <b>addr</b>:<b>port</b>
    436 * without knowing its digest. Its digest turned out to be <b>digest</b>.
    437 * If it was a bridge, and we still don't know its digest, record it.
    438 */
    439 void
    440 learned_router_identity(const tor_addr_t *addr, uint16_t port,
    441                        const char *digest,
    442                        const ed25519_public_key_t *ed_id)
    443 {
    444  // XXXX prop220 use ed_id here, once there is some way to specify
    445  (void)ed_id;
    446  int learned = 0;
    447  bridge_info_t *bridge =
    448    get_configured_bridge_by_exact_addr_port_digest(addr, port, digest);
    449  if (bridge && tor_digest_is_zero(bridge->identity)) {
    450    memcpy(bridge->identity, digest, DIGEST_LEN);
    451    learned = 1;
    452  }
    453  /* XXXX prop220 remember bridge ed25519 identities -- add a field */
    454 #if 0
    455  if (bridge && ed_id &&
    456      ed25519_public_key_is_zero(&bridge->ed25519_identity) &&
    457      !ed25519_public_key_is_zero(ed_id)) {
    458    memcpy(&bridge->ed25519_identity, ed_id, sizeof(*ed_id));
    459    learned = 1;
    460  }
    461 #endif /* 0 */
    462  if (learned) {
    463    char *transport_info = NULL;
    464    const char *transport_name =
    465      find_transport_name_by_bridge_addrport(addr, port);
    466    if (transport_name)
    467      tor_asprintf(&transport_info, " (with transport '%s')", transport_name);
    468 
    469    // XXXX prop220 log both fingerprints.
    470    log_notice(LD_DIR, "Learned fingerprint %s for bridge %s%s.",
    471               hex_str(digest, DIGEST_LEN), fmt_addrport(addr, port),
    472               transport_info ? transport_info : "");
    473    tor_free(transport_info);
    474    entry_guard_learned_bridge_identity(&bridge->addrport_configured,
    475                                        (const uint8_t *)digest);
    476  }
    477 }
    478 
    479 /** Return true if <b>bridge</b> has the same identity digest as
    480 *  <b>digest</b>. If <b>digest</b> is NULL, it matches
    481 *  bridges with unspecified identity digests. */
    482 static int
    483 bridge_has_digest(const bridge_info_t *bridge, const char *digest)
    484 {
    485  if (digest)
    486    return tor_memeq(digest, bridge->identity, DIGEST_LEN);
    487  else
    488    return tor_digest_is_zero(bridge->identity);
    489 }
    490 
    491 /** We are about to add a new bridge at <b>addr</b>:<b>port</b>, with optional
    492 * <b>digest</b> and <b>transport_name</b>. Mark for removal any previously
    493 * existing bridge with the same address and port, and warn the user as
    494 * appropriate.
    495 */
    496 STATIC void
    497 bridge_resolve_conflicts(const tor_addr_t *addr, uint16_t port,
    498                         const char *digest, const char *transport_name)
    499 {
    500  /* Iterate the already-registered bridge list:
    501 
    502     If you find a bridge with the same address and port, mark it for
    503     removal. It doesn't make sense to have two active bridges with
    504     the same IP:PORT. If the bridge in question has a different
    505     digest or transport than <b>digest</b>/<b>transport_name</b>,
    506     it's probably a misconfiguration and we should warn the user.
    507  */
    508  SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge) {
    509    if (bridge->marked_for_removal)
    510      continue;
    511 
    512    if (tor_addr_eq(&bridge->addr, addr) && (bridge->port == port)) {
    513 
    514      bridge->marked_for_removal = 1;
    515 
    516      if (!bridge_has_digest(bridge, digest) ||
    517          strcmp_opt(bridge->transport_name, transport_name)) {
    518        /* warn the user */
    519        char *bridge_description_new, *bridge_description_old;
    520        tor_asprintf(&bridge_description_new, "%s:%s:%s",
    521                     fmt_addrport(addr, port),
    522                     digest ? hex_str(digest, DIGEST_LEN) : "",
    523                     transport_name ? transport_name : "");
    524        tor_asprintf(&bridge_description_old, "%s:%s:%s",
    525                     fmt_addrport(&bridge->addr, bridge->port),
    526                     tor_digest_is_zero(bridge->identity) ?
    527                     "" : hex_str(bridge->identity,DIGEST_LEN),
    528                     bridge->transport_name ? bridge->transport_name : "");
    529 
    530        log_warn(LD_GENERAL,"Tried to add bridge '%s', but we found a conflict"
    531                 " with the already registered bridge '%s'. We will discard"
    532                 " the old bridge and keep '%s'. If this is not what you"
    533                 " wanted, please change your configuration file accordingly.",
    534                 bridge_description_new, bridge_description_old,
    535                 bridge_description_new);
    536 
    537        tor_free(bridge_description_new);
    538        tor_free(bridge_description_old);
    539      }
    540    }
    541  } SMARTLIST_FOREACH_END(bridge);
    542 }
    543 
    544 /** Return True if we have a bridge that uses a transport with name
    545 *  <b>transport_name</b>. */
    546 MOCK_IMPL(int,
    547 transport_is_needed, (const char *transport_name))
    548 {
    549  if (!bridge_list)
    550    return 0;
    551 
    552  SMARTLIST_FOREACH_BEGIN(bridge_list, const bridge_info_t *, bridge) {
    553    if (bridge->transport_name &&
    554        !strcmp(bridge->transport_name, transport_name))
    555      return 1;
    556  } SMARTLIST_FOREACH_END(bridge);
    557 
    558  return 0;
    559 }
    560 
    561 /** Register the bridge information in <b>bridge_line</b> to the
    562 *  bridge subsystem. Steals reference of <b>bridge_line</b>. */
    563 void
    564 bridge_add_from_config(bridge_line_t *bridge_line)
    565 {
    566  bridge_info_t *b;
    567 
    568  // XXXX prop220 add a way to specify ed25519 ID to bridge_line_t.
    569 
    570  { /* Log the bridge we are about to register: */
    571    log_debug(LD_GENERAL, "Registering bridge at %s (transport: %s) (%s)",
    572              fmt_addrport(&bridge_line->addr, bridge_line->port),
    573              bridge_line->transport_name ?
    574              bridge_line->transport_name : "no transport",
    575              tor_digest_is_zero(bridge_line->digest) ?
    576              "no key listed" : hex_str(bridge_line->digest, DIGEST_LEN));
    577 
    578    if (bridge_line->socks_args) { /* print socks arguments */
    579      int i = 0;
    580 
    581      tor_assert(smartlist_len(bridge_line->socks_args) > 0);
    582 
    583      log_debug(LD_GENERAL, "Bridge uses %d SOCKS arguments:",
    584                smartlist_len(bridge_line->socks_args));
    585      SMARTLIST_FOREACH(bridge_line->socks_args, const char *, arg,
    586                        log_debug(LD_CONFIG, "%d: %s", ++i, arg));
    587    }
    588  }
    589 
    590  bridge_resolve_conflicts(&bridge_line->addr,
    591                           bridge_line->port,
    592                           bridge_line->digest,
    593                           bridge_line->transport_name);
    594 
    595  b = tor_malloc_zero(sizeof(bridge_info_t));
    596  tor_addr_copy(&b->addrport_configured.addr, &bridge_line->addr);
    597  b->addrport_configured.port = bridge_line->port;
    598  tor_addr_copy(&b->addr, &bridge_line->addr);
    599  b->port = bridge_line->port;
    600  memcpy(b->identity, bridge_line->digest, DIGEST_LEN);
    601  if (bridge_line->transport_name)
    602    b->transport_name = bridge_line->transport_name;
    603  b->fetch_status.schedule = DL_SCHED_BRIDGE;
    604  b->fetch_status.increment_on = DL_SCHED_INCREMENT_ATTEMPT;
    605  /* We can't reset the bridge's download status here, because UseBridges
    606   * might be 0 now, and it might be changed to 1 much later. */
    607  b->socks_args = bridge_line->socks_args;
    608  if (!bridge_list)
    609    bridge_list = smartlist_new();
    610 
    611  tor_free(bridge_line); /* Deallocate bridge_line now. */
    612 
    613  smartlist_add(bridge_list, b);
    614 }
    615 
    616 /** If <b>digest</b> is one of our known bridges, return it. */
    617 STATIC bridge_info_t *
    618 find_bridge_by_digest(const char *digest)
    619 {
    620  if (! bridge_list)
    621    return NULL;
    622  SMARTLIST_FOREACH(bridge_list, bridge_info_t *, bridge,
    623    {
    624      if (tor_memeq(bridge->identity, digest, DIGEST_LEN))
    625        return bridge;
    626    });
    627  return NULL;
    628 }
    629 
    630 /** Given the <b>addr</b> and <b>port</b> of a bridge, if that bridge
    631 *  supports a pluggable transport, return its name. Otherwise, return
    632 *  NULL. */
    633 const char *
    634 find_transport_name_by_bridge_addrport(const tor_addr_t *addr, uint16_t port)
    635 {
    636  if (!bridge_list)
    637    return NULL;
    638 
    639  SMARTLIST_FOREACH_BEGIN(bridge_list, const bridge_info_t *, bridge) {
    640    if (tor_addr_eq(&bridge->addr, addr) &&
    641        (bridge->port == port))
    642      return bridge->transport_name;
    643  } SMARTLIST_FOREACH_END(bridge);
    644 
    645  return NULL;
    646 }
    647 
    648 /** If <b>addr</b> and <b>port</b> match the address and port of a
    649 * bridge of ours that uses pluggable transports, place its transport
    650 * in <b>transport</b>.
    651 *
    652 * Return 0 on success (found a transport, or found a bridge with no
    653 * transport, or found no bridge); return -1 if we should be using a
    654 * transport, but the transport could not be found.
    655 */
    656 int
    657 get_transport_by_bridge_addrport(const tor_addr_t *addr, uint16_t port,
    658                                 const transport_t **transport)
    659 {
    660  *transport = NULL;
    661  if (!bridge_list)
    662    return 0;
    663 
    664  SMARTLIST_FOREACH_BEGIN(bridge_list, const bridge_info_t *, bridge) {
    665    if (tor_addr_eq(&bridge->addr, addr) &&
    666        (bridge->port == port)) { /* bridge matched */
    667      if (bridge->transport_name) { /* it also uses pluggable transports */
    668        *transport = transport_get_by_name(bridge->transport_name);
    669        if (*transport == NULL) { /* it uses pluggable transports, but
    670                                     the transport could not be found! */
    671          return -1;
    672        }
    673        return 0;
    674      } else { /* bridge matched, but it doesn't use transports. */
    675        break;
    676      }
    677    }
    678  } SMARTLIST_FOREACH_END(bridge);
    679 
    680  *transport = NULL;
    681  return 0;
    682 }
    683 
    684 /** Return a smartlist containing all the SOCKS arguments that we
    685 *  should pass to the SOCKS proxy. */
    686 const smartlist_t *
    687 get_socks_args_by_bridge_addrport(const tor_addr_t *addr, uint16_t port)
    688 {
    689  bridge_info_t *bridge = get_configured_bridge_by_addr_port_digest(addr,
    690                                                                    port,
    691                                                                    NULL);
    692  return bridge ? bridge->socks_args : NULL;
    693 }
    694 
    695 /** We need to ask <b>bridge</b> for its server descriptor. */
    696 static void
    697 launch_direct_bridge_descriptor_fetch(bridge_info_t *bridge)
    698 {
    699  const or_options_t *options = get_options();
    700  circuit_guard_state_t *guard_state = NULL;
    701 
    702  if (connection_get_by_type_addr_port_purpose(
    703      CONN_TYPE_DIR, &bridge->addr, bridge->port,
    704      DIR_PURPOSE_FETCH_SERVERDESC))
    705    return; /* it's already on the way */
    706 
    707  if (bridge_has_invalid_transport(bridge)) {
    708    download_status_mark_impossible(&bridge->fetch_status);
    709    log_warn(LD_CONFIG, "Can't use bridge at %s: there is no configured "
    710             "transport called \"%s\".",
    711             safe_str_client(fmt_and_decorate_addr(&bridge->addr)),
    712             bridget_get_transport_name(bridge));
    713    return; /* Can't use this bridge; it has not */
    714  }
    715 
    716  if (routerset_contains_bridge(options->ExcludeNodes, bridge)) {
    717    download_status_mark_impossible(&bridge->fetch_status);
    718    log_warn(LD_APP, "Not using bridge at %s: it is in ExcludeNodes.",
    719             safe_str_client(fmt_and_decorate_addr(&bridge->addr)));
    720    return;
    721  }
    722 
    723  /* Until we get a descriptor for the bridge, we only know one address for
    724   * it. */
    725  if (!reachable_addr_allows_addr(&bridge->addr, bridge->port,
    726                                            FIREWALL_OR_CONNECTION, 0, 0)) {
    727    log_notice(LD_CONFIG, "Tried to fetch a descriptor directly from a "
    728               "bridge, but that bridge is not reachable through our "
    729               "firewall.");
    730    return;
    731  }
    732 
    733  /* If we already have a node_t for this bridge, rewrite its address now. */
    734  node_t *node = node_get_mutable_by_id(bridge->identity);
    735  if (node) {
    736    rewrite_node_address_for_bridge(bridge, node);
    737  }
    738 
    739  tor_addr_port_t bridge_addrport;
    740  memcpy(&bridge_addrport.addr, &bridge->addr, sizeof(tor_addr_t));
    741  bridge_addrport.port = bridge->port;
    742 
    743  guard_state = get_guard_state_for_bridge_desc_fetch(bridge->identity);
    744 
    745  directory_request_t *req =
    746    directory_request_new(DIR_PURPOSE_FETCH_SERVERDESC);
    747  directory_request_set_or_addr_port(req, &bridge_addrport);
    748  directory_request_set_directory_id_digest(req, bridge->identity);
    749  directory_request_set_router_purpose(req, ROUTER_PURPOSE_BRIDGE);
    750  directory_request_set_resource(req, "authority.z");
    751  if (guard_state) {
    752    directory_request_set_guard_state(req, guard_state);
    753  }
    754  directory_initiate_request(req);
    755  directory_request_free(req);
    756 }
    757 
    758 /** Fetching the bridge descriptor from the bridge authority returned a
    759 * "not found". Fall back to trying a direct fetch. */
    760 void
    761 retry_bridge_descriptor_fetch_directly(const char *digest)
    762 {
    763  bridge_info_t *bridge = find_bridge_by_digest(digest);
    764  if (!bridge)
    765    return; /* not found? oh well. */
    766 
    767  launch_direct_bridge_descriptor_fetch(bridge);
    768 }
    769 
    770 /** For each bridge in our list for which we don't currently have a
    771 * descriptor, fetch a new copy of its descriptor -- either directly
    772 * from the bridge or via a bridge authority. */
    773 void
    774 fetch_bridge_descriptors(const or_options_t *options, time_t now)
    775 {
    776  int num_bridge_auths = get_n_authorities(BRIDGE_DIRINFO);
    777  int ask_bridge_directly;
    778  int can_use_bridge_authority;
    779 
    780  if (!bridge_list)
    781    return;
    782 
    783  /* If we still have unconfigured managed proxies, don't go and
    784     connect to a bridge. */
    785  if (pt_proxies_configuration_pending())
    786    return;
    787 
    788  SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge)
    789    {
    790      /* This resets the download status on first use */
    791      if (!download_status_is_ready(&bridge->fetch_status, now))
    792        continue; /* don't bother, no need to retry yet */
    793      if (routerset_contains_bridge(options->ExcludeNodes, bridge)) {
    794        download_status_mark_impossible(&bridge->fetch_status);
    795        log_warn(LD_APP, "Not using bridge at %s: it is in ExcludeNodes.",
    796                 safe_str_client(fmt_and_decorate_addr(&bridge->addr)));
    797        continue;
    798      }
    799 
    800      /* schedule the next attempt
    801       * we can't increment after a failure, because sometimes we use the
    802       * bridge authority, and sometimes we use the bridge direct */
    803      download_status_increment_attempt(
    804                        &bridge->fetch_status,
    805                        safe_str_client(fmt_and_decorate_addr(&bridge->addr)),
    806                        now);
    807 
    808      can_use_bridge_authority = !tor_digest_is_zero(bridge->identity) &&
    809                                 num_bridge_auths;
    810      ask_bridge_directly = !can_use_bridge_authority ||
    811                            !options->UpdateBridgesFromAuthority;
    812      log_debug(LD_DIR, "ask_bridge_directly=%d (%d, %d, %d)",
    813                ask_bridge_directly, tor_digest_is_zero(bridge->identity),
    814                !options->UpdateBridgesFromAuthority, !num_bridge_auths);
    815 
    816      if (ask_bridge_directly &&
    817          !reachable_addr_allows_addr(&bridge->addr, bridge->port,
    818                                                FIREWALL_OR_CONNECTION, 0,
    819                                                0)) {
    820        log_notice(LD_DIR, "Bridge at '%s' isn't reachable by our "
    821                   "firewall policy. %s.",
    822                   fmt_addrport(&bridge->addr, bridge->port),
    823                   can_use_bridge_authority ?
    824                     "Asking bridge authority instead" : "Skipping");
    825        if (can_use_bridge_authority)
    826          ask_bridge_directly = 0;
    827        else
    828          continue;
    829      }
    830 
    831      if (ask_bridge_directly) {
    832        /* we need to ask the bridge itself for its descriptor. */
    833        launch_direct_bridge_descriptor_fetch(bridge);
    834      } else {
    835        /* We have a digest and we want to ask an authority. We could
    836         * combine all the requests into one, but that may give more
    837         * hints to the bridge authority than we want to give. */
    838        char resource[10 + HEX_DIGEST_LEN];
    839        memcpy(resource, "fp/", 3);
    840        base16_encode(resource+3, HEX_DIGEST_LEN+1,
    841                      bridge->identity, DIGEST_LEN);
    842        memcpy(resource+3+HEX_DIGEST_LEN, ".z", 3);
    843        log_info(LD_DIR, "Fetching bridge info '%s' from bridge authority.",
    844                 resource);
    845        directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
    846                ROUTER_PURPOSE_BRIDGE, resource, 0, DL_WANT_AUTHORITY);
    847      }
    848    }
    849  SMARTLIST_FOREACH_END(bridge);
    850 }
    851 
    852 /** If our <b>bridge</b> is configured to be a different address than
    853 * the bridge gives in <b>node</b>, rewrite the routerinfo
    854 * we received to use the address we meant to use. Now we handle
    855 * multihomed bridges better.
    856 */
    857 static void
    858 rewrite_node_address_for_bridge(const bridge_info_t *bridge, node_t *node)
    859 {
    860  /* XXXX move this function. */
    861  /* XXXX overridden addresses should really live in the node_t, so that the
    862   *   routerinfo_t and the microdesc_t can be immutable.  But we can only
    863   *   do that safely if we know that no function that connects to an OR
    864   *   does so through an address from any source other than node_get_addr().
    865   */
    866  const or_options_t *options = get_options();
    867 
    868  if (node->ri) {
    869    routerinfo_t *ri = node->ri;
    870    if ((!tor_addr_compare(&bridge->addr, &ri->ipv4_addr, CMP_EXACT) &&
    871         bridge->port == ri->ipv4_orport) ||
    872        (!tor_addr_compare(&bridge->addr, &ri->ipv6_addr, CMP_EXACT) &&
    873         bridge->port == ri->ipv6_orport)) {
    874      /* they match, so no need to do anything */
    875    } else {
    876      if (tor_addr_family(&bridge->addr) == AF_INET) {
    877        tor_addr_copy(&ri->ipv4_addr, &bridge->addr);
    878        ri->ipv4_orport = bridge->port;
    879        log_info(LD_DIR,
    880                 "Adjusted bridge routerinfo for '%s' to match configured "
    881                 "address %s:%d.",
    882                 ri->nickname, fmt_addr(&ri->ipv4_addr), ri->ipv4_orport);
    883      } else if (tor_addr_family(&bridge->addr) == AF_INET6) {
    884        tor_addr_copy(&ri->ipv6_addr, &bridge->addr);
    885        ri->ipv6_orport = bridge->port;
    886        log_info(LD_DIR,
    887                 "Adjusted bridge routerinfo for '%s' to match configured "
    888                 "address %s.",
    889                 ri->nickname, fmt_addrport(&ri->ipv6_addr, ri->ipv6_orport));
    890      } else {
    891        log_err(LD_BUG, "Address family not supported: %d.",
    892                tor_addr_family(&bridge->addr));
    893        return;
    894      }
    895    }
    896 
    897    if (options->ClientPreferIPv6ORPort == -1) {
    898      /* Mark which address to use based on which bridge_t we got. */
    899      node->ipv6_preferred = (tor_addr_family(&bridge->addr) == AF_INET6 &&
    900                              !tor_addr_is_null(&node->ri->ipv6_addr));
    901    } else {
    902      /* Mark which address to use based on user preference */
    903      node->ipv6_preferred = (reachable_addr_prefer_ipv6_orport(options) &&
    904                              !tor_addr_is_null(&node->ri->ipv6_addr));
    905    }
    906 
    907    /* XXXipv6 we lack support for falling back to another address for
    908       the same relay, warn the user */
    909    if (!tor_addr_is_null(&ri->ipv6_addr)) {
    910      tor_addr_port_t ap;
    911      node_get_pref_orport(node, &ap);
    912      log_notice(LD_CONFIG,
    913                 "Bridge '%s' has both an IPv4 and an IPv6 address.  "
    914                 "Will prefer using its %s address (%s) based on %s.",
    915                 ri->nickname,
    916                 node->ipv6_preferred ? "IPv6" : "IPv4",
    917                 fmt_addrport(&ap.addr, ap.port),
    918                 options->ClientPreferIPv6ORPort == -1 ?
    919                 "the configured Bridge address" :
    920                 "ClientPreferIPv6ORPort");
    921    }
    922  }
    923  if (node->rs) {
    924    routerstatus_t *rs = node->rs;
    925 
    926    if ((!tor_addr_compare(&bridge->addr, &rs->ipv4_addr, CMP_EXACT) &&
    927        bridge->port == rs->ipv4_orport) ||
    928       (!tor_addr_compare(&bridge->addr, &rs->ipv6_addr, CMP_EXACT) &&
    929        bridge->port == rs->ipv6_orport)) {
    930      /* they match, so no need to do anything */
    931    } else {
    932      if (tor_addr_family(&bridge->addr) == AF_INET) {
    933        tor_addr_copy(&rs->ipv4_addr, &bridge->addr);
    934        rs->ipv4_orport = bridge->port;
    935        log_info(LD_DIR,
    936                 "Adjusted bridge routerstatus for '%s' to match "
    937                 "configured address %s.",
    938                 rs->nickname, fmt_addrport(&bridge->addr, rs->ipv4_orport));
    939      /* set IPv6 preferences even if there is no ri */
    940      } else if (tor_addr_family(&bridge->addr) == AF_INET6) {
    941        tor_addr_copy(&rs->ipv6_addr, &bridge->addr);
    942        rs->ipv6_orport = bridge->port;
    943        log_info(LD_DIR,
    944                 "Adjusted bridge routerstatus for '%s' to match configured"
    945                 " address %s.",
    946                 rs->nickname, fmt_addrport(&rs->ipv6_addr, rs->ipv6_orport));
    947      } else {
    948        log_err(LD_BUG, "Address family not supported: %d.",
    949                tor_addr_family(&bridge->addr));
    950        return;
    951      }
    952    }
    953 
    954    if (options->ClientPreferIPv6ORPort == -1) {
    955      /* Mark which address to use based on which bridge_t we got. */
    956      node->ipv6_preferred = (tor_addr_family(&bridge->addr) == AF_INET6 &&
    957                              !tor_addr_is_null(&node->rs->ipv6_addr));
    958    } else {
    959      /* Mark which address to use based on user preference */
    960      node->ipv6_preferred = (reachable_addr_prefer_ipv6_orport(options) &&
    961                              !tor_addr_is_null(&node->rs->ipv6_addr));
    962    }
    963 
    964    /* XXXipv6 we lack support for falling back to another address for
    965    the same relay, warn the user */
    966    if (!tor_addr_is_null(&rs->ipv6_addr)) {
    967      tor_addr_port_t ap;
    968      node_get_pref_orport(node, &ap);
    969      log_notice(LD_CONFIG,
    970                 "Bridge '%s' has both an IPv4 and an IPv6 address.  "
    971                 "Will prefer using its %s address (%s) based on %s.",
    972                 rs->nickname,
    973                 node->ipv6_preferred ? "IPv6" : "IPv4",
    974                 fmt_addrport(&ap.addr, ap.port),
    975                 options->ClientPreferIPv6ORPort == -1 ?
    976                 "the configured Bridge address" :
    977                 "ClientPreferIPv6ORPort");
    978    }
    979  }
    980 }
    981 
    982 /** We just learned a descriptor for a bridge. See if that
    983 * digest is in our entry guard list, and add it if not. Schedule the
    984 * next fetch for a long time from now, and initiate any follow-up
    985 * activities like continuing to bootstrap.
    986 *
    987 * <b>from_cache</b> * tells us whether we fetched it from disk (else
    988 * the network)
    989 *
    990 * <b>desc_is_new</b> tells us if we preferred it to the old version we
    991 * had, if any. */
    992 void
    993 learned_bridge_descriptor(routerinfo_t *ri, int from_cache, int desc_is_new)
    994 {
    995  tor_assert(ri);
    996  tor_assert(ri->purpose == ROUTER_PURPOSE_BRIDGE);
    997  if (get_options()->UseBridges) {
    998    /* Retry directory downloads whenever we get a bridge descriptor:
    999     * - when bootstrapping, and
   1000     * - when we aren't sure if any of our bridges are reachable.
   1001     * Keep on retrying until we have at least one reachable bridge. */
   1002    int first = num_bridges_usable(0) < 1;
   1003    bridge_info_t *bridge = get_configured_bridge_by_routerinfo(ri);
   1004    time_t now = time(NULL);
   1005    router_set_status(ri->cache_info.identity_digest, 1);
   1006 
   1007    if (bridge) { /* if we actually want to use this one */
   1008      node_t *node;
   1009      if (!from_cache) {
   1010        /* This schedules the re-fetch at a constant interval, which produces
   1011         * a pattern of bridge traffic. But it's better than trying all
   1012         * configured bridges several times in the first few minutes. */
   1013        download_status_reset(&bridge->fetch_status);
   1014        /* it's here; schedule its re-fetch for a long time from now. */
   1015        bridge->fetch_status.next_attempt_at +=
   1016          get_options()->TestingBridgeDownloadInitialDelay;
   1017      }
   1018 
   1019      node = node_get_mutable_by_id(ri->cache_info.identity_digest);
   1020      tor_assert(node);
   1021      rewrite_node_address_for_bridge(bridge, node);
   1022      if (tor_digest_is_zero(bridge->identity)) {
   1023        memcpy(bridge->identity,ri->cache_info.identity_digest, DIGEST_LEN);
   1024        log_notice(LD_DIR, "Learned identity %s for bridge at %s:%d",
   1025                   hex_str(bridge->identity, DIGEST_LEN),
   1026                   fmt_and_decorate_addr(&bridge->addr),
   1027                   (int) bridge->port);
   1028      }
   1029      entry_guard_learned_bridge_identity(&bridge->addrport_configured,
   1030                              (const uint8_t*)ri->cache_info.identity_digest);
   1031 
   1032      if (desc_is_new)
   1033        log_notice(LD_DIR, "new bridge descriptor '%s' (%s): %s",
   1034                   ri->nickname,
   1035                   from_cache ? "cached" : "fresh", router_describe(ri));
   1036      /* If we didn't have a reachable bridge before this one, try directory
   1037       * documents again. */
   1038      if (first) {
   1039        routerlist_retry_directory_downloads(now);
   1040      }
   1041    }
   1042  }
   1043 }
   1044 
   1045 /** Return a smartlist containing all bridge identity digests */
   1046 MOCK_IMPL(smartlist_t *,
   1047 list_bridge_identities, (void))
   1048 {
   1049  smartlist_t *result = NULL;
   1050  char *digest_tmp;
   1051 
   1052  if (get_options()->UseBridges && bridge_list) {
   1053    result = smartlist_new();
   1054 
   1055    SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, b) {
   1056      digest_tmp = tor_malloc(DIGEST_LEN);
   1057      memcpy(digest_tmp, b->identity, DIGEST_LEN);
   1058      smartlist_add(result, digest_tmp);
   1059    } SMARTLIST_FOREACH_END(b);
   1060  }
   1061 
   1062  return result;
   1063 }
   1064 
   1065 /** Get the download status for a bridge descriptor given its identity */
   1066 MOCK_IMPL(download_status_t *,
   1067 get_bridge_dl_status_by_id, (const char *digest))
   1068 {
   1069  download_status_t *dl = NULL;
   1070 
   1071  if (digest && get_options()->UseBridges && bridge_list) {
   1072    SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, b) {
   1073      if (tor_memeq(digest, b->identity, DIGEST_LEN)) {
   1074        dl = &(b->fetch_status);
   1075        break;
   1076      }
   1077    } SMARTLIST_FOREACH_END(b);
   1078  }
   1079 
   1080  return dl;
   1081 }
   1082 
   1083 /** Release all storage held in bridges.c */
   1084 void
   1085 bridges_free_all(void)
   1086 {
   1087  clear_bridge_list();
   1088  smartlist_free(bridge_list);
   1089  bridge_list = NULL;
   1090 }