node_select.c 41 KB

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