node_select.c 41 KB

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