node_select.c 41 KB

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