node_select.c 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110
  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-2018, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file node_select.c
  8. * \brief Code to choose nodes randomly based on restrictions and
  9. * weighted probabilities.
  10. **/
  11. #define NODE_SELECT_PRIVATE
  12. #include "core/or/or.h"
  13. #include "app/config/config.h"
  14. #include "core/mainloop/connection.h"
  15. #include "core/or/policies.h"
  16. #include "core/or/reasons.h"
  17. #include "feature/client/entrynodes.h"
  18. #include "feature/dircommon/directory.h"
  19. #include "feature/dirclient/dirclient.h"
  20. #include "feature/nodelist/dirlist.h"
  21. #include "feature/nodelist/microdesc.h"
  22. #include "feature/nodelist/networkstatus.h"
  23. #include "feature/nodelist/node_select.h"
  24. #include "feature/nodelist/nodelist.h"
  25. #include "feature/nodelist/routerlist.h"
  26. #include "feature/nodelist/routerset.h"
  27. #include "feature/relay/router.h"
  28. #include "feature/relay/routermode.h"
  29. #include "lib/crypt_ops/crypto_rand.h"
  30. #include "lib/math/fp.h"
  31. #include "feature/dirclient/dir_server_st.h"
  32. #include "feature/nodelist/networkstatus_st.h"
  33. #include "feature/nodelist/node_st.h"
  34. #include "feature/nodelist/routerinfo_st.h"
  35. #include "feature/nodelist/routerstatus_st.h"
  36. static int compute_weighted_bandwidths(const smartlist_t *sl,
  37. bandwidth_weight_rule_t rule,
  38. double **bandwidths_out,
  39. double *total_bandwidth_out);
  40. static const routerstatus_t *router_pick_trusteddirserver_impl(
  41. const smartlist_t *sourcelist, dirinfo_type_t auth,
  42. int flags, int *n_busy_out);
  43. static const routerstatus_t *router_pick_dirserver_generic(
  44. smartlist_t *sourcelist,
  45. dirinfo_type_t type, int flags);
  46. /** Try to find a running dirserver that supports operations of <b>type</b>.
  47. *
  48. * If there are no running dirservers in our routerlist and the
  49. * <b>PDS_RETRY_IF_NO_SERVERS</b> flag is set, set all the fallback ones
  50. * (including authorities) as running again, and pick one.
  51. *
  52. * If the <b>PDS_IGNORE_FASCISTFIREWALL</b> flag is set, then include
  53. * dirservers that we can't reach.
  54. *
  55. * If the <b>PDS_ALLOW_SELF</b> flag is not set, then don't include ourself
  56. * (if we're a dirserver).
  57. *
  58. * Don't pick a fallback directory mirror if any non-fallback is viable;
  59. * (the fallback directory mirrors include the authorities)
  60. * try to avoid using servers that have returned 503 recently.
  61. */
  62. const routerstatus_t *
  63. router_pick_directory_server(dirinfo_type_t type, int flags)
  64. {
  65. int busy = 0;
  66. const routerstatus_t *choice;
  67. choice = router_pick_directory_server_impl(type, flags, &busy);
  68. if (choice || !(flags & PDS_RETRY_IF_NO_SERVERS))
  69. return choice;
  70. if (busy) {
  71. /* If the reason that we got no server is that servers are "busy",
  72. * we must be excluding good servers because we already have serverdesc
  73. * fetches with them. Do not mark down servers up because of this. */
  74. tor_assert((flags & (PDS_NO_EXISTING_SERVERDESC_FETCH|
  75. PDS_NO_EXISTING_MICRODESC_FETCH)));
  76. return NULL;
  77. }
  78. log_info(LD_DIR,
  79. "No reachable router entries for dirservers. "
  80. "Trying them all again.");
  81. /* mark all fallback directory mirrors as up again */
  82. router_reset_status_download_failures();
  83. /* try again */
  84. choice = router_pick_directory_server_impl(type, flags, NULL);
  85. return choice;
  86. }
  87. /** Try to find a running fallback directory. Flags are as for
  88. * router_pick_directory_server.
  89. */
  90. const routerstatus_t *
  91. router_pick_dirserver_generic(smartlist_t *sourcelist,
  92. dirinfo_type_t type, int flags)
  93. {
  94. const routerstatus_t *choice;
  95. int busy = 0;
  96. if (smartlist_len(sourcelist) == 1) {
  97. /* If there's only one choice, then we should disable the logic that
  98. * would otherwise prevent us from choosing ourself. */
  99. flags |= PDS_ALLOW_SELF;
  100. }
  101. choice = router_pick_trusteddirserver_impl(sourcelist, type, flags, &busy);
  102. if (choice || !(flags & PDS_RETRY_IF_NO_SERVERS))
  103. return choice;
  104. if (busy) {
  105. /* If the reason that we got no server is that servers are "busy",
  106. * we must be excluding good servers because we already have serverdesc
  107. * fetches with them. Do not mark down servers up because of this. */
  108. tor_assert((flags & (PDS_NO_EXISTING_SERVERDESC_FETCH|
  109. PDS_NO_EXISTING_MICRODESC_FETCH)));
  110. return NULL;
  111. }
  112. log_info(LD_DIR,
  113. "No dirservers are reachable. Trying them all again.");
  114. mark_all_dirservers_up(sourcelist);
  115. return router_pick_trusteddirserver_impl(sourcelist, type, flags, NULL);
  116. }
  117. /* Common retry code for router_pick_directory_server_impl and
  118. * router_pick_trusteddirserver_impl. Retry with the non-preferred IP version.
  119. * Must be called before RETRY_WITHOUT_EXCLUDE().
  120. *
  121. * If we got no result, and we are applying IP preferences, and we are a
  122. * client that could use an alternate IP version, try again with the
  123. * opposite preferences. */
  124. #define RETRY_ALTERNATE_IP_VERSION(retry_label) \
  125. STMT_BEGIN \
  126. if (result == NULL && try_ip_pref && options->ClientUseIPv4 \
  127. && fascist_firewall_use_ipv6(options) && !server_mode(options) \
  128. && !n_busy) { \
  129. n_excluded = 0; \
  130. n_busy = 0; \
  131. try_ip_pref = 0; \
  132. goto retry_label; \
  133. } \
  134. STMT_END \
  135. /* Common retry code for router_pick_directory_server_impl and
  136. * router_pick_trusteddirserver_impl. Retry without excluding nodes, but with
  137. * the preferred IP version. Must be called after RETRY_ALTERNATE_IP_VERSION().
  138. *
  139. * If we got no result, and we are excluding nodes, and StrictNodes is
  140. * not set, try again without excluding nodes. */
  141. #define RETRY_WITHOUT_EXCLUDE(retry_label) \
  142. STMT_BEGIN \
  143. if (result == NULL && try_excluding && !options->StrictNodes \
  144. && n_excluded && !n_busy) { \
  145. try_excluding = 0; \
  146. n_excluded = 0; \
  147. n_busy = 0; \
  148. try_ip_pref = 1; \
  149. goto retry_label; \
  150. } \
  151. STMT_END
  152. /* Common code used in the loop within router_pick_directory_server_impl and
  153. * router_pick_trusteddirserver_impl.
  154. *
  155. * Check if the given <b>identity</b> supports extrainfo. If not, skip further
  156. * checks.
  157. */
  158. #define SKIP_MISSING_TRUSTED_EXTRAINFO(type, identity) \
  159. STMT_BEGIN \
  160. int is_trusted_extrainfo = router_digest_is_trusted_dir_type( \
  161. (identity), EXTRAINFO_DIRINFO); \
  162. if (((type) & EXTRAINFO_DIRINFO) && \
  163. !router_supports_extrainfo((identity), is_trusted_extrainfo)) \
  164. continue; \
  165. STMT_END
  166. #ifndef LOG_FALSE_POSITIVES_DURING_BOOTSTRAP
  167. #define LOG_FALSE_POSITIVES_DURING_BOOTSTRAP 0
  168. #endif
  169. /* Log a message if rs is not found or not a preferred address */
  170. static void
  171. router_picked_poor_directory_log(const routerstatus_t *rs)
  172. {
  173. const networkstatus_t *usable_consensus;
  174. usable_consensus = networkstatus_get_reasonably_live_consensus(time(NULL),
  175. usable_consensus_flavor());
  176. #if !LOG_FALSE_POSITIVES_DURING_BOOTSTRAP
  177. /* Don't log early in the bootstrap process, it's normal to pick from a
  178. * small pool of nodes. Of course, this won't help if we're trying to
  179. * diagnose bootstrap issues. */
  180. if (!smartlist_len(nodelist_get_list()) || !usable_consensus
  181. || !router_have_minimum_dir_info()) {
  182. return;
  183. }
  184. #endif /* !LOG_FALSE_POSITIVES_DURING_BOOTSTRAP */
  185. /* We couldn't find a node, or the one we have doesn't fit our preferences.
  186. * Sometimes this is normal, sometimes it can be a reachability issue. */
  187. if (!rs) {
  188. /* This happens a lot, so it's at debug level */
  189. log_debug(LD_DIR, "Wanted to make an outgoing directory connection, but "
  190. "we couldn't find a directory that fit our criteria. "
  191. "Perhaps we will succeed next time with less strict criteria.");
  192. } else if (!fascist_firewall_allows_rs(rs, FIREWALL_OR_CONNECTION, 1)
  193. && !fascist_firewall_allows_rs(rs, FIREWALL_DIR_CONNECTION, 1)
  194. ) {
  195. /* This is rare, and might be interesting to users trying to diagnose
  196. * connection issues on dual-stack machines. */
  197. log_info(LD_DIR, "Selected a directory %s with non-preferred OR and Dir "
  198. "addresses for launching an outgoing connection: "
  199. "IPv4 %s OR %d Dir %d IPv6 %s OR %d Dir %d",
  200. routerstatus_describe(rs),
  201. fmt_addr32(rs->addr), rs->or_port,
  202. rs->dir_port, fmt_addr(&rs->ipv6_addr),
  203. rs->ipv6_orport, rs->dir_port);
  204. }
  205. }
  206. #undef LOG_FALSE_POSITIVES_DURING_BOOTSTRAP
  207. /* Check if we already have a directory fetch from ap, for serverdesc
  208. * (including extrainfo) or microdesc documents.
  209. * If so, return 1, if not, return 0.
  210. * Also returns 0 if addr is NULL, tor_addr_is_null(addr), or dir_port is 0.
  211. */
  212. STATIC int
  213. router_is_already_dir_fetching(const tor_addr_port_t *ap, int serverdesc,
  214. int microdesc)
  215. {
  216. if (!ap || tor_addr_is_null(&ap->addr) || !ap->port) {
  217. return 0;
  218. }
  219. /* XX/teor - we're not checking tunnel connections here, see #17848
  220. */
  221. if (serverdesc && (
  222. connection_get_by_type_addr_port_purpose(
  223. CONN_TYPE_DIR, &ap->addr, ap->port, DIR_PURPOSE_FETCH_SERVERDESC)
  224. || connection_get_by_type_addr_port_purpose(
  225. CONN_TYPE_DIR, &ap->addr, ap->port, DIR_PURPOSE_FETCH_EXTRAINFO))) {
  226. return 1;
  227. }
  228. if (microdesc && (
  229. connection_get_by_type_addr_port_purpose(
  230. CONN_TYPE_DIR, &ap->addr, ap->port, DIR_PURPOSE_FETCH_MICRODESC))) {
  231. return 1;
  232. }
  233. return 0;
  234. }
  235. /* Check if we already have a directory fetch from the ipv4 or ipv6
  236. * router, for serverdesc (including extrainfo) or microdesc documents.
  237. * If so, return 1, if not, return 0.
  238. */
  239. static int
  240. router_is_already_dir_fetching_(uint32_t ipv4_addr,
  241. const tor_addr_t *ipv6_addr,
  242. uint16_t dir_port,
  243. int serverdesc,
  244. int microdesc)
  245. {
  246. tor_addr_port_t ipv4_dir_ap, ipv6_dir_ap;
  247. /* Assume IPv6 DirPort is the same as IPv4 DirPort */
  248. tor_addr_from_ipv4h(&ipv4_dir_ap.addr, ipv4_addr);
  249. ipv4_dir_ap.port = dir_port;
  250. tor_addr_copy(&ipv6_dir_ap.addr, ipv6_addr);
  251. ipv6_dir_ap.port = dir_port;
  252. return (router_is_already_dir_fetching(&ipv4_dir_ap, serverdesc, microdesc)
  253. || router_is_already_dir_fetching(&ipv6_dir_ap, serverdesc, microdesc));
  254. }
  255. /** Pick a random running valid directory server/mirror from our
  256. * routerlist. Arguments are as for router_pick_directory_server(), except:
  257. *
  258. * If <b>n_busy_out</b> is provided, set *<b>n_busy_out</b> to the number of
  259. * directories that we excluded for no other reason than
  260. * PDS_NO_EXISTING_SERVERDESC_FETCH or PDS_NO_EXISTING_MICRODESC_FETCH.
  261. */
  262. STATIC const routerstatus_t *
  263. router_pick_directory_server_impl(dirinfo_type_t type, int flags,
  264. int *n_busy_out)
  265. {
  266. const or_options_t *options = get_options();
  267. const node_t *result;
  268. smartlist_t *direct, *tunnel;
  269. smartlist_t *trusted_direct, *trusted_tunnel;
  270. smartlist_t *overloaded_direct, *overloaded_tunnel;
  271. time_t now = time(NULL);
  272. const networkstatus_t *consensus = networkstatus_get_latest_consensus();
  273. const int requireother = ! (flags & PDS_ALLOW_SELF);
  274. const int fascistfirewall = ! (flags & PDS_IGNORE_FASCISTFIREWALL);
  275. const int no_serverdesc_fetching =(flags & PDS_NO_EXISTING_SERVERDESC_FETCH);
  276. const int no_microdesc_fetching = (flags & PDS_NO_EXISTING_MICRODESC_FETCH);
  277. int try_excluding = 1, n_excluded = 0, n_busy = 0;
  278. int try_ip_pref = 1;
  279. if (!consensus)
  280. return NULL;
  281. retry_search:
  282. direct = smartlist_new();
  283. tunnel = smartlist_new();
  284. trusted_direct = smartlist_new();
  285. trusted_tunnel = smartlist_new();
  286. overloaded_direct = smartlist_new();
  287. overloaded_tunnel = smartlist_new();
  288. const int skip_or_fw = router_skip_or_reachability(options, try_ip_pref);
  289. const int skip_dir_fw = router_skip_dir_reachability(options, try_ip_pref);
  290. const int must_have_or = directory_must_use_begindir(options);
  291. /* Find all the running dirservers we know about. */
  292. SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), const node_t *, node) {
  293. int is_trusted;
  294. int is_overloaded;
  295. const routerstatus_t *status = node->rs;
  296. const country_t country = node->country;
  297. if (!status)
  298. continue;
  299. if (!node->is_running || !node_is_dir(node) || !node->is_valid)
  300. continue;
  301. if (requireother && router_digest_is_me(node->identity))
  302. continue;
  303. SKIP_MISSING_TRUSTED_EXTRAINFO(type, node->identity);
  304. if (try_excluding &&
  305. routerset_contains_routerstatus(options->ExcludeNodes, status,
  306. country)) {
  307. ++n_excluded;
  308. continue;
  309. }
  310. if (router_is_already_dir_fetching_(status->addr,
  311. &status->ipv6_addr,
  312. status->dir_port,
  313. no_serverdesc_fetching,
  314. no_microdesc_fetching)) {
  315. ++n_busy;
  316. continue;
  317. }
  318. is_overloaded = status->last_dir_503_at + DIR_503_TIMEOUT > now;
  319. is_trusted = router_digest_is_trusted_dir(node->identity);
  320. /* Clients use IPv6 addresses if the server has one and the client
  321. * prefers IPv6.
  322. * Add the router if its preferred address and port are reachable.
  323. * If we don't get any routers, we'll try again with the non-preferred
  324. * address for each router (if any). (To ensure correct load-balancing
  325. * we try routers that only have one address both times.)
  326. */
  327. if (!fascistfirewall || skip_or_fw ||
  328. fascist_firewall_allows_node(node, FIREWALL_OR_CONNECTION,
  329. try_ip_pref))
  330. smartlist_add(is_trusted ? trusted_tunnel :
  331. is_overloaded ? overloaded_tunnel : tunnel, (void*)node);
  332. else if (!must_have_or && (skip_dir_fw ||
  333. fascist_firewall_allows_node(node, FIREWALL_DIR_CONNECTION,
  334. try_ip_pref)))
  335. smartlist_add(is_trusted ? trusted_direct :
  336. is_overloaded ? overloaded_direct : direct, (void*)node);
  337. } SMARTLIST_FOREACH_END(node);
  338. if (smartlist_len(tunnel)) {
  339. result = node_sl_choose_by_bandwidth(tunnel, WEIGHT_FOR_DIR);
  340. } else if (smartlist_len(overloaded_tunnel)) {
  341. result = node_sl_choose_by_bandwidth(overloaded_tunnel,
  342. WEIGHT_FOR_DIR);
  343. } else if (smartlist_len(trusted_tunnel)) {
  344. /* FFFF We don't distinguish between trusteds and overloaded trusteds
  345. * yet. Maybe one day we should. */
  346. /* FFFF We also don't load balance over authorities yet. I think this
  347. * is a feature, but it could easily be a bug. -RD */
  348. result = smartlist_choose(trusted_tunnel);
  349. } else if (smartlist_len(direct)) {
  350. result = node_sl_choose_by_bandwidth(direct, WEIGHT_FOR_DIR);
  351. } else if (smartlist_len(overloaded_direct)) {
  352. result = node_sl_choose_by_bandwidth(overloaded_direct,
  353. WEIGHT_FOR_DIR);
  354. } else {
  355. result = smartlist_choose(trusted_direct);
  356. }
  357. smartlist_free(direct);
  358. smartlist_free(tunnel);
  359. smartlist_free(trusted_direct);
  360. smartlist_free(trusted_tunnel);
  361. smartlist_free(overloaded_direct);
  362. smartlist_free(overloaded_tunnel);
  363. RETRY_ALTERNATE_IP_VERSION(retry_search);
  364. RETRY_WITHOUT_EXCLUDE(retry_search);
  365. if (n_busy_out)
  366. *n_busy_out = n_busy;
  367. router_picked_poor_directory_log(result ? result->rs : NULL);
  368. return result ? result->rs : NULL;
  369. }
  370. /** Given an array of double/uint64_t unions that are currently being used as
  371. * doubles, convert them to uint64_t, and try to scale them linearly so as to
  372. * much of the range of uint64_t. If <b>total_out</b> is provided, set it to
  373. * the sum of all elements in the array _before_ scaling. */
  374. STATIC void
  375. scale_array_elements_to_u64(uint64_t *entries_out, const double *entries_in,
  376. int n_entries,
  377. uint64_t *total_out)
  378. {
  379. double total = 0.0;
  380. double scale_factor = 0.0;
  381. int i;
  382. for (i = 0; i < n_entries; ++i)
  383. total += entries_in[i];
  384. if (total > 0.0) {
  385. scale_factor = ((double)INT64_MAX) / total;
  386. scale_factor /= 4.0; /* make sure we're very far away from overflowing */
  387. }
  388. for (i = 0; i < n_entries; ++i)
  389. entries_out[i] = tor_llround(entries_in[i] * scale_factor);
  390. if (total_out)
  391. *total_out = (uint64_t) total;
  392. }
  393. /** Pick a random element of <b>n_entries</b>-element array <b>entries</b>,
  394. * choosing each element with a probability proportional to its (uint64_t)
  395. * value, and return the index of that element. If all elements are 0, choose
  396. * an index at random. Return -1 on error.
  397. */
  398. STATIC int
  399. choose_array_element_by_weight(const uint64_t *entries, int n_entries)
  400. {
  401. int i;
  402. uint64_t rand_val;
  403. uint64_t total = 0;
  404. for (i = 0; i < n_entries; ++i)
  405. total += entries[i];
  406. if (n_entries < 1)
  407. return -1;
  408. if (total == 0)
  409. return crypto_rand_int(n_entries);
  410. tor_assert(total < INT64_MAX);
  411. rand_val = crypto_rand_uint64(total);
  412. return select_array_member_cumulative_timei(
  413. entries, n_entries, total, rand_val);
  414. }
  415. /** Return bw*1000, unless bw*1000 would overflow, in which case return
  416. * INT32_MAX. */
  417. static inline int32_t
  418. kb_to_bytes(uint32_t bw)
  419. {
  420. return (bw > (INT32_MAX/1000)) ? INT32_MAX : bw*1000;
  421. }
  422. /** Helper function:
  423. * choose a random element of smartlist <b>sl</b> of nodes, weighted by
  424. * the advertised bandwidth of each element using the consensus
  425. * bandwidth weights.
  426. *
  427. * If <b>rule</b>==WEIGHT_FOR_EXIT. we're picking an exit node: consider all
  428. * nodes' bandwidth equally regardless of their Exit status, since there may
  429. * be some in the list because they exit to obscure ports. If
  430. * <b>rule</b>==NO_WEIGHTING, we're picking a non-exit node: weight
  431. * exit-node's bandwidth less depending on the smallness of the fraction of
  432. * Exit-to-total bandwidth. If <b>rule</b>==WEIGHT_FOR_GUARD, we're picking a
  433. * guard node: consider all guard's bandwidth equally. Otherwise, weight
  434. * guards proportionally less.
  435. */
  436. static const node_t *
  437. smartlist_choose_node_by_bandwidth_weights(const smartlist_t *sl,
  438. bandwidth_weight_rule_t rule)
  439. {
  440. double *bandwidths_dbl=NULL;
  441. uint64_t *bandwidths_u64=NULL;
  442. if (compute_weighted_bandwidths(sl, rule, &bandwidths_dbl, NULL) < 0)
  443. return NULL;
  444. bandwidths_u64 = tor_calloc(smartlist_len(sl), sizeof(uint64_t));
  445. scale_array_elements_to_u64(bandwidths_u64, bandwidths_dbl,
  446. smartlist_len(sl), NULL);
  447. {
  448. int idx = choose_array_element_by_weight(bandwidths_u64,
  449. smartlist_len(sl));
  450. tor_free(bandwidths_dbl);
  451. tor_free(bandwidths_u64);
  452. return idx < 0 ? NULL : smartlist_get(sl, idx);
  453. }
  454. }
  455. /** When weighting bridges, enforce these values as lower and upper
  456. * bound for believable bandwidth, because there is no way for us
  457. * to verify a bridge's bandwidth currently. */
  458. #define BRIDGE_MIN_BELIEVABLE_BANDWIDTH 20000 /* 20 kB/sec */
  459. #define BRIDGE_MAX_BELIEVABLE_BANDWIDTH 100000 /* 100 kB/sec */
  460. /** Return the smaller of the router's configured BandwidthRate
  461. * and its advertised capacity, making sure to stay within the
  462. * interval between bridge-min-believe-bw and
  463. * bridge-max-believe-bw. */
  464. static uint32_t
  465. bridge_get_advertised_bandwidth_bounded(routerinfo_t *router)
  466. {
  467. uint32_t result = router->bandwidthcapacity;
  468. if (result > router->bandwidthrate)
  469. result = router->bandwidthrate;
  470. if (result > BRIDGE_MAX_BELIEVABLE_BANDWIDTH)
  471. result = BRIDGE_MAX_BELIEVABLE_BANDWIDTH;
  472. else if (result < BRIDGE_MIN_BELIEVABLE_BANDWIDTH)
  473. result = BRIDGE_MIN_BELIEVABLE_BANDWIDTH;
  474. return result;
  475. }
  476. /** Given a list of routers and a weighting rule as in
  477. * smartlist_choose_node_by_bandwidth_weights, compute weighted bandwidth
  478. * values for each node and store them in a freshly allocated
  479. * *<b>bandwidths_out</b> of the same length as <b>sl</b>, and holding results
  480. * as doubles. If <b>total_bandwidth_out</b> is non-NULL, set it to the total
  481. * of all the bandwidths.
  482. * Return 0 on success, -1 on failure. */
  483. static int
  484. compute_weighted_bandwidths(const smartlist_t *sl,
  485. bandwidth_weight_rule_t rule,
  486. double **bandwidths_out,
  487. double *total_bandwidth_out)
  488. {
  489. int64_t weight_scale;
  490. double Wg = -1, Wm = -1, We = -1, Wd = -1;
  491. double Wgb = -1, Wmb = -1, Web = -1, Wdb = -1;
  492. guardfraction_bandwidth_t guardfraction_bw;
  493. double *bandwidths = NULL;
  494. double total_bandwidth = 0.0;
  495. tor_assert(sl);
  496. tor_assert(bandwidths_out);
  497. /* Can't choose exit and guard at same time */
  498. tor_assert(rule == NO_WEIGHTING ||
  499. rule == WEIGHT_FOR_EXIT ||
  500. rule == WEIGHT_FOR_GUARD ||
  501. rule == WEIGHT_FOR_MID ||
  502. rule == WEIGHT_FOR_DIR);
  503. *bandwidths_out = NULL;
  504. if (total_bandwidth_out) {
  505. *total_bandwidth_out = 0.0;
  506. }
  507. if (smartlist_len(sl) == 0) {
  508. log_info(LD_CIRC,
  509. "Empty routerlist passed in to consensus weight node "
  510. "selection for rule %s",
  511. bandwidth_weight_rule_to_string(rule));
  512. return -1;
  513. }
  514. weight_scale = networkstatus_get_weight_scale_param(NULL);
  515. if (rule == WEIGHT_FOR_GUARD) {
  516. Wg = networkstatus_get_bw_weight(NULL, "Wgg", -1);
  517. Wm = networkstatus_get_bw_weight(NULL, "Wgm", -1); /* Bridges */
  518. We = 0;
  519. Wd = networkstatus_get_bw_weight(NULL, "Wgd", -1);
  520. Wgb = networkstatus_get_bw_weight(NULL, "Wgb", -1);
  521. Wmb = networkstatus_get_bw_weight(NULL, "Wmb", -1);
  522. Web = networkstatus_get_bw_weight(NULL, "Web", -1);
  523. Wdb = networkstatus_get_bw_weight(NULL, "Wdb", -1);
  524. } else if (rule == WEIGHT_FOR_MID) {
  525. Wg = networkstatus_get_bw_weight(NULL, "Wmg", -1);
  526. Wm = networkstatus_get_bw_weight(NULL, "Wmm", -1);
  527. We = networkstatus_get_bw_weight(NULL, "Wme", -1);
  528. Wd = networkstatus_get_bw_weight(NULL, "Wmd", -1);
  529. Wgb = networkstatus_get_bw_weight(NULL, "Wgb", -1);
  530. Wmb = networkstatus_get_bw_weight(NULL, "Wmb", -1);
  531. Web = networkstatus_get_bw_weight(NULL, "Web", -1);
  532. Wdb = networkstatus_get_bw_weight(NULL, "Wdb", -1);
  533. } else if (rule == WEIGHT_FOR_EXIT) {
  534. // Guards CAN be exits if they have weird exit policies
  535. // They are d then I guess...
  536. We = networkstatus_get_bw_weight(NULL, "Wee", -1);
  537. Wm = networkstatus_get_bw_weight(NULL, "Wem", -1); /* Odd exit policies */
  538. Wd = networkstatus_get_bw_weight(NULL, "Wed", -1);
  539. Wg = networkstatus_get_bw_weight(NULL, "Weg", -1); /* Odd exit policies */
  540. Wgb = networkstatus_get_bw_weight(NULL, "Wgb", -1);
  541. Wmb = networkstatus_get_bw_weight(NULL, "Wmb", -1);
  542. Web = networkstatus_get_bw_weight(NULL, "Web", -1);
  543. Wdb = networkstatus_get_bw_weight(NULL, "Wdb", -1);
  544. } else if (rule == WEIGHT_FOR_DIR) {
  545. We = networkstatus_get_bw_weight(NULL, "Wbe", -1);
  546. Wm = networkstatus_get_bw_weight(NULL, "Wbm", -1);
  547. Wd = networkstatus_get_bw_weight(NULL, "Wbd", -1);
  548. Wg = networkstatus_get_bw_weight(NULL, "Wbg", -1);
  549. Wgb = Wmb = Web = Wdb = weight_scale;
  550. } else if (rule == NO_WEIGHTING) {
  551. Wg = Wm = We = Wd = weight_scale;
  552. Wgb = Wmb = Web = Wdb = weight_scale;
  553. }
  554. if (Wg < 0 || Wm < 0 || We < 0 || Wd < 0 || Wgb < 0 || Wmb < 0 || Wdb < 0
  555. || Web < 0) {
  556. log_debug(LD_CIRC,
  557. "Got negative bandwidth weights. Defaulting to naive selection"
  558. " algorithm.");
  559. Wg = Wm = We = Wd = weight_scale;
  560. Wgb = Wmb = Web = Wdb = weight_scale;
  561. }
  562. Wg /= weight_scale;
  563. Wm /= weight_scale;
  564. We /= weight_scale;
  565. Wd /= weight_scale;
  566. Wgb /= weight_scale;
  567. Wmb /= weight_scale;
  568. Web /= weight_scale;
  569. Wdb /= weight_scale;
  570. bandwidths = tor_calloc(smartlist_len(sl), sizeof(double));
  571. // Cycle through smartlist and total the bandwidth.
  572. static int warned_missing_bw = 0;
  573. SMARTLIST_FOREACH_BEGIN(sl, const node_t *, node) {
  574. int is_exit = 0, is_guard = 0, is_dir = 0, this_bw = 0;
  575. double weight = 1;
  576. double weight_without_guard_flag = 0; /* Used for guardfraction */
  577. double final_weight = 0;
  578. is_exit = node->is_exit && ! node->is_bad_exit;
  579. is_guard = node->is_possible_guard;
  580. is_dir = node_is_dir(node);
  581. if (node->rs) {
  582. if (!node->rs->has_bandwidth) {
  583. /* This should never happen, unless all the authorities downgrade
  584. * to 0.2.0 or rogue routerstatuses get inserted into our consensus. */
  585. if (! warned_missing_bw) {
  586. log_warn(LD_BUG,
  587. "Consensus is missing some bandwidths. Using a naive "
  588. "router selection algorithm");
  589. warned_missing_bw = 1;
  590. }
  591. this_bw = 30000; /* Chosen arbitrarily */
  592. } else {
  593. this_bw = kb_to_bytes(node->rs->bandwidth_kb);
  594. }
  595. } else if (node->ri) {
  596. /* bridge or other descriptor not in our consensus */
  597. this_bw = bridge_get_advertised_bandwidth_bounded(node->ri);
  598. } else {
  599. /* We can't use this one. */
  600. continue;
  601. }
  602. if (is_guard && is_exit) {
  603. weight = (is_dir ? Wdb*Wd : Wd);
  604. weight_without_guard_flag = (is_dir ? Web*We : We);
  605. } else if (is_guard) {
  606. weight = (is_dir ? Wgb*Wg : Wg);
  607. weight_without_guard_flag = (is_dir ? Wmb*Wm : Wm);
  608. } else if (is_exit) {
  609. weight = (is_dir ? Web*We : We);
  610. } else { // middle
  611. weight = (is_dir ? Wmb*Wm : Wm);
  612. }
  613. /* These should be impossible; but overflows here would be bad, so let's
  614. * make sure. */
  615. if (this_bw < 0)
  616. this_bw = 0;
  617. if (weight < 0.0)
  618. weight = 0.0;
  619. if (weight_without_guard_flag < 0.0)
  620. weight_without_guard_flag = 0.0;
  621. /* If guardfraction information is available in the consensus, we
  622. * want to calculate this router's bandwidth according to its
  623. * guardfraction. Quoting from proposal236:
  624. *
  625. * Let Wpf denote the weight from the 'bandwidth-weights' line a
  626. * client would apply to N for position p if it had the guard
  627. * flag, Wpn the weight if it did not have the guard flag, and B the
  628. * measured bandwidth of N in the consensus. Then instead of choosing
  629. * N for position p proportionally to Wpf*B or Wpn*B, clients should
  630. * choose N proportionally to F*Wpf*B + (1-F)*Wpn*B.
  631. */
  632. if (node->rs && node->rs->has_guardfraction && rule != WEIGHT_FOR_GUARD) {
  633. /* XXX The assert should actually check for is_guard. However,
  634. * that crashes dirauths because of #13297. This should be
  635. * equivalent: */
  636. tor_assert(node->rs->is_possible_guard);
  637. guard_get_guardfraction_bandwidth(&guardfraction_bw,
  638. this_bw,
  639. node->rs->guardfraction_percentage);
  640. /* Calculate final_weight = F*Wpf*B + (1-F)*Wpn*B */
  641. final_weight =
  642. guardfraction_bw.guard_bw * weight +
  643. guardfraction_bw.non_guard_bw * weight_without_guard_flag;
  644. log_debug(LD_GENERAL, "%s: Guardfraction weight %f instead of %f (%s)",
  645. node->rs->nickname, final_weight, weight*this_bw,
  646. bandwidth_weight_rule_to_string(rule));
  647. } else { /* no guardfraction information. calculate the weight normally. */
  648. final_weight = weight*this_bw;
  649. }
  650. bandwidths[node_sl_idx] = final_weight;
  651. total_bandwidth += final_weight;
  652. } SMARTLIST_FOREACH_END(node);
  653. log_debug(LD_CIRC, "Generated weighted bandwidths for rule %s based "
  654. "on weights "
  655. "Wg=%f Wm=%f We=%f Wd=%f with total bw %f",
  656. bandwidth_weight_rule_to_string(rule),
  657. Wg, Wm, We, Wd, total_bandwidth);
  658. *bandwidths_out = bandwidths;
  659. if (total_bandwidth_out) {
  660. *total_bandwidth_out = total_bandwidth;
  661. }
  662. return 0;
  663. }
  664. /** For all nodes in <b>sl</b>, return the fraction of those nodes, weighted
  665. * by their weighted bandwidths with rule <b>rule</b>, for which we have
  666. * descriptors.
  667. *
  668. * If <b>for_direct_connect</b> is true, we intend to connect to the node
  669. * directly, as the first hop of a circuit; otherwise, we intend to connect
  670. * to it indirectly, or use it as if we were connecting to it indirectly. */
  671. double
  672. frac_nodes_with_descriptors(const smartlist_t *sl,
  673. bandwidth_weight_rule_t rule,
  674. int for_direct_conn)
  675. {
  676. double *bandwidths = NULL;
  677. double total, present;
  678. if (smartlist_len(sl) == 0)
  679. return 0.0;
  680. if (compute_weighted_bandwidths(sl, rule, &bandwidths, &total) < 0 ||
  681. total <= 0.0) {
  682. int n_with_descs = 0;
  683. SMARTLIST_FOREACH(sl, const node_t *, node, {
  684. if (node_has_preferred_descriptor(node, for_direct_conn))
  685. n_with_descs++;
  686. });
  687. tor_free(bandwidths);
  688. return ((double)n_with_descs) / smartlist_len(sl);
  689. }
  690. present = 0.0;
  691. SMARTLIST_FOREACH_BEGIN(sl, const node_t *, node) {
  692. if (node_has_preferred_descriptor(node, for_direct_conn))
  693. present += bandwidths[node_sl_idx];
  694. } SMARTLIST_FOREACH_END(node);
  695. tor_free(bandwidths);
  696. return present / total;
  697. }
  698. /** Choose a random element of status list <b>sl</b>, weighted by
  699. * the advertised bandwidth of each node */
  700. const node_t *
  701. node_sl_choose_by_bandwidth(const smartlist_t *sl,
  702. bandwidth_weight_rule_t rule)
  703. { /*XXXX MOVE */
  704. return smartlist_choose_node_by_bandwidth_weights(sl, rule);
  705. }
  706. /** Given a <b>router</b>, add every node_t in its family (including the
  707. * node itself!) to <b>sl</b>.
  708. *
  709. * Note the type mismatch: This function takes a routerinfo, but adds nodes
  710. * to the smartlist!
  711. */
  712. static void
  713. routerlist_add_node_and_family(smartlist_t *sl, const routerinfo_t *router)
  714. {
  715. /* XXXX MOVE ? */
  716. node_t fake_node;
  717. const node_t *node = node_get_by_id(router->cache_info.identity_digest);
  718. if (node == NULL) {
  719. memset(&fake_node, 0, sizeof(fake_node));
  720. fake_node.ri = (routerinfo_t *)router;
  721. memcpy(fake_node.identity, router->cache_info.identity_digest, DIGEST_LEN);
  722. node = &fake_node;
  723. }
  724. nodelist_add_node_and_family(sl, node);
  725. }
  726. /** Return a random running node from the nodelist. Never
  727. * pick a node that is in
  728. * <b>excludedsmartlist</b>, or which matches <b>excludedset</b>,
  729. * even if they are the only nodes available.
  730. * If <b>CRN_NEED_UPTIME</b> is set in flags and any router has more than
  731. * a minimum uptime, return one of those.
  732. * If <b>CRN_NEED_CAPACITY</b> is set in flags, weight your choice by the
  733. * advertised capacity of each router.
  734. * If <b>CRN_NEED_GUARD</b> is set in flags, consider only Guard routers.
  735. * If <b>CRN_WEIGHT_AS_EXIT</b> is set in flags, we weight bandwidths as if
  736. * picking an exit node, otherwise we weight bandwidths for picking a relay
  737. * node (that is, possibly discounting exit nodes).
  738. * If <b>CRN_NEED_DESC</b> is set in flags, we only consider nodes that
  739. * have a routerinfo or microdescriptor -- that is, enough info to be
  740. * used to build a circuit.
  741. * If <b>CRN_PREF_ADDR</b> is set in flags, we only consider nodes that
  742. * have an address that is preferred by the ClientPreferIPv6ORPort setting
  743. * (regardless of this flag, we exclude nodes that aren't allowed by the
  744. * firewall, including ClientUseIPv4 0 and fascist_firewall_use_ipv6() == 0).
  745. */
  746. const node_t *
  747. router_choose_random_node(smartlist_t *excludedsmartlist,
  748. routerset_t *excludedset,
  749. router_crn_flags_t flags)
  750. { /* XXXX MOVE */
  751. const int need_uptime = (flags & CRN_NEED_UPTIME) != 0;
  752. const int need_capacity = (flags & CRN_NEED_CAPACITY) != 0;
  753. const int need_guard = (flags & CRN_NEED_GUARD) != 0;
  754. const int weight_for_exit = (flags & CRN_WEIGHT_AS_EXIT) != 0;
  755. const int need_desc = (flags & CRN_NEED_DESC) != 0;
  756. const int pref_addr = (flags & CRN_PREF_ADDR) != 0;
  757. const int direct_conn = (flags & CRN_DIRECT_CONN) != 0;
  758. const int rendezvous_v3 = (flags & CRN_RENDEZVOUS_V3) != 0;
  759. smartlist_t *sl=smartlist_new(),
  760. *excludednodes=smartlist_new();
  761. const node_t *choice = NULL;
  762. const routerinfo_t *r;
  763. bandwidth_weight_rule_t rule;
  764. tor_assert(!(weight_for_exit && need_guard));
  765. rule = weight_for_exit ? WEIGHT_FOR_EXIT :
  766. (need_guard ? WEIGHT_FOR_GUARD : WEIGHT_FOR_MID);
  767. SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), node_t *, node) {
  768. if (node_allows_single_hop_exits(node)) {
  769. /* Exclude relays that allow single hop exit circuits. This is an
  770. * obsolete option since 0.2.9.2-alpha and done by default in
  771. * 0.3.1.0-alpha. */
  772. smartlist_add(excludednodes, node);
  773. } else if (rendezvous_v3 &&
  774. !node_supports_v3_rendezvous_point(node)) {
  775. /* Exclude relays that do not support to rendezvous for a hidden service
  776. * version 3. */
  777. smartlist_add(excludednodes, node);
  778. }
  779. } SMARTLIST_FOREACH_END(node);
  780. /* If the node_t is not found we won't be to exclude ourself but we
  781. * won't be able to pick ourself in router_choose_random_node() so
  782. * this is fine to at least try with our routerinfo_t object. */
  783. if ((r = router_get_my_routerinfo()))
  784. routerlist_add_node_and_family(excludednodes, r);
  785. router_add_running_nodes_to_smartlist(sl, need_uptime, need_capacity,
  786. need_guard, need_desc, pref_addr,
  787. direct_conn);
  788. log_debug(LD_CIRC,
  789. "We found %d running nodes.",
  790. smartlist_len(sl));
  791. smartlist_subtract(sl,excludednodes);
  792. log_debug(LD_CIRC,
  793. "We removed %d excludednodes, leaving %d nodes.",
  794. smartlist_len(excludednodes),
  795. smartlist_len(sl));
  796. if (excludedsmartlist) {
  797. smartlist_subtract(sl,excludedsmartlist);
  798. log_debug(LD_CIRC,
  799. "We removed %d excludedsmartlist, leaving %d nodes.",
  800. smartlist_len(excludedsmartlist),
  801. smartlist_len(sl));
  802. }
  803. if (excludedset) {
  804. routerset_subtract_nodes(sl,excludedset);
  805. log_debug(LD_CIRC,
  806. "We removed excludedset, leaving %d nodes.",
  807. smartlist_len(sl));
  808. }
  809. // Always weight by bandwidth
  810. choice = node_sl_choose_by_bandwidth(sl, rule);
  811. smartlist_free(sl);
  812. if (!choice && (need_uptime || need_capacity || need_guard || pref_addr)) {
  813. /* try once more -- recurse but with fewer restrictions. */
  814. log_info(LD_CIRC,
  815. "We couldn't find any live%s%s%s routers; falling back "
  816. "to list of all routers.",
  817. need_capacity?", fast":"",
  818. need_uptime?", stable":"",
  819. need_guard?", guard":"");
  820. flags &= ~ (CRN_NEED_UPTIME|CRN_NEED_CAPACITY|CRN_NEED_GUARD|
  821. CRN_PREF_ADDR);
  822. choice = router_choose_random_node(
  823. excludedsmartlist, excludedset, flags);
  824. }
  825. smartlist_free(excludednodes);
  826. if (!choice) {
  827. log_warn(LD_CIRC,
  828. "No available nodes when trying to choose node. Failing.");
  829. }
  830. return choice;
  831. }
  832. /** Try to find a running directory authority. Flags are as for
  833. * router_pick_directory_server.
  834. */
  835. const routerstatus_t *
  836. router_pick_trusteddirserver(dirinfo_type_t type, int flags)
  837. {
  838. return router_pick_dirserver_generic(
  839. router_get_trusted_dir_servers_mutable(),
  840. type, flags);
  841. }
  842. /** Try to find a running fallback directory. Flags are as for
  843. * router_pick_directory_server.
  844. */
  845. const routerstatus_t *
  846. router_pick_fallback_dirserver(dirinfo_type_t type, int flags)
  847. {
  848. return router_pick_dirserver_generic(
  849. router_get_fallback_dir_servers_mutable(),
  850. type, flags);
  851. }
  852. /** Pick a random element from a list of dir_server_t, weighting by their
  853. * <b>weight</b> field. */
  854. static const dir_server_t *
  855. dirserver_choose_by_weight(const smartlist_t *servers, double authority_weight)
  856. {
  857. int n = smartlist_len(servers);
  858. int i;
  859. double *weights_dbl;
  860. uint64_t *weights_u64;
  861. const dir_server_t *ds;
  862. weights_dbl = tor_calloc(n, sizeof(double));
  863. weights_u64 = tor_calloc(n, sizeof(uint64_t));
  864. for (i = 0; i < n; ++i) {
  865. ds = smartlist_get(servers, i);
  866. weights_dbl[i] = ds->weight;
  867. if (ds->is_authority)
  868. weights_dbl[i] *= authority_weight;
  869. }
  870. scale_array_elements_to_u64(weights_u64, weights_dbl, n, NULL);
  871. i = choose_array_element_by_weight(weights_u64, n);
  872. tor_free(weights_dbl);
  873. tor_free(weights_u64);
  874. return (i < 0) ? NULL : smartlist_get(servers, i);
  875. }
  876. /** Choose randomly from among the dir_server_ts in sourcelist that
  877. * are up. Flags are as for router_pick_directory_server_impl().
  878. */
  879. static const routerstatus_t *
  880. router_pick_trusteddirserver_impl(const smartlist_t *sourcelist,
  881. dirinfo_type_t type, int flags,
  882. int *n_busy_out)
  883. {
  884. const or_options_t *options = get_options();
  885. smartlist_t *direct, *tunnel;
  886. smartlist_t *overloaded_direct, *overloaded_tunnel;
  887. const routerinfo_t *me = router_get_my_routerinfo();
  888. const routerstatus_t *result = NULL;
  889. time_t now = time(NULL);
  890. const int requireother = ! (flags & PDS_ALLOW_SELF);
  891. const int fascistfirewall = ! (flags & PDS_IGNORE_FASCISTFIREWALL);
  892. const int no_serverdesc_fetching =(flags & PDS_NO_EXISTING_SERVERDESC_FETCH);
  893. const int no_microdesc_fetching =(flags & PDS_NO_EXISTING_MICRODESC_FETCH);
  894. const double auth_weight =
  895. (sourcelist == router_get_fallback_dir_servers()) ?
  896. options->DirAuthorityFallbackRate : 1.0;
  897. smartlist_t *pick_from;
  898. int n_busy = 0;
  899. int try_excluding = 1, n_excluded = 0;
  900. int try_ip_pref = 1;
  901. if (!sourcelist)
  902. return NULL;
  903. retry_search:
  904. direct = smartlist_new();
  905. tunnel = smartlist_new();
  906. overloaded_direct = smartlist_new();
  907. overloaded_tunnel = smartlist_new();
  908. const int skip_or_fw = router_skip_or_reachability(options, try_ip_pref);
  909. const int skip_dir_fw = router_skip_dir_reachability(options, try_ip_pref);
  910. const int must_have_or = directory_must_use_begindir(options);
  911. SMARTLIST_FOREACH_BEGIN(sourcelist, const dir_server_t *, d)
  912. {
  913. int is_overloaded =
  914. d->fake_status.last_dir_503_at + DIR_503_TIMEOUT > now;
  915. if (!d->is_running) continue;
  916. if ((type & d->type) == 0)
  917. continue;
  918. SKIP_MISSING_TRUSTED_EXTRAINFO(type, d->digest);
  919. if (requireother && me && router_digest_is_me(d->digest))
  920. continue;
  921. if (try_excluding &&
  922. routerset_contains_routerstatus(options->ExcludeNodes,
  923. &d->fake_status, -1)) {
  924. ++n_excluded;
  925. continue;
  926. }
  927. if (router_is_already_dir_fetching_(d->addr,
  928. &d->ipv6_addr,
  929. d->dir_port,
  930. no_serverdesc_fetching,
  931. no_microdesc_fetching)) {
  932. ++n_busy;
  933. continue;
  934. }
  935. /* Clients use IPv6 addresses if the server has one and the client
  936. * prefers IPv6.
  937. * Add the router if its preferred address and port are reachable.
  938. * If we don't get any routers, we'll try again with the non-preferred
  939. * address for each router (if any). (To ensure correct load-balancing
  940. * we try routers that only have one address both times.)
  941. */
  942. if (!fascistfirewall || skip_or_fw ||
  943. fascist_firewall_allows_dir_server(d, FIREWALL_OR_CONNECTION,
  944. try_ip_pref))
  945. smartlist_add(is_overloaded ? overloaded_tunnel : tunnel, (void*)d);
  946. else if (!must_have_or && (skip_dir_fw ||
  947. fascist_firewall_allows_dir_server(d, FIREWALL_DIR_CONNECTION,
  948. try_ip_pref)))
  949. smartlist_add(is_overloaded ? overloaded_direct : direct, (void*)d);
  950. }
  951. SMARTLIST_FOREACH_END(d);
  952. if (smartlist_len(tunnel)) {
  953. pick_from = tunnel;
  954. } else if (smartlist_len(overloaded_tunnel)) {
  955. pick_from = overloaded_tunnel;
  956. } else if (smartlist_len(direct)) {
  957. pick_from = direct;
  958. } else {
  959. pick_from = overloaded_direct;
  960. }
  961. {
  962. const dir_server_t *selection =
  963. dirserver_choose_by_weight(pick_from, auth_weight);
  964. if (selection)
  965. result = &selection->fake_status;
  966. }
  967. smartlist_free(direct);
  968. smartlist_free(tunnel);
  969. smartlist_free(overloaded_direct);
  970. smartlist_free(overloaded_tunnel);
  971. RETRY_ALTERNATE_IP_VERSION(retry_search);
  972. RETRY_WITHOUT_EXCLUDE(retry_search);
  973. router_picked_poor_directory_log(result);
  974. if (n_busy_out)
  975. *n_busy_out = n_busy;
  976. return result;
  977. }