nodelist.c 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223
  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-2017, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file nodelist.c
  8. *
  9. * \brief Structures and functions for tracking what we know about the routers
  10. * on the Tor network, and correlating information from networkstatus,
  11. * routerinfo, and microdescs.
  12. *
  13. * The key structure here is node_t: that's the canonical way to refer
  14. * to a Tor relay that we might want to build a circuit through. Every
  15. * node_t has either a routerinfo_t, or a routerstatus_t from the current
  16. * networkstatus consensus. If it has a routerstatus_t, it will also
  17. * need to have a microdesc_t before you can use it for circuits.
  18. *
  19. * The nodelist_t is a global singleton that maps identities to node_t
  20. * objects. Access them with the node_get_*() functions. The nodelist_t
  21. * is maintained by calls throughout the codebase
  22. *
  23. * Generally, other code should not have to reach inside a node_t to
  24. * see what information it has. Instead, you should call one of the
  25. * many accessor functions that works on a generic node_t. If there
  26. * isn't one that does what you need, it's better to make such a function,
  27. * and then use it.
  28. *
  29. * For historical reasons, some of the functions that select a node_t
  30. * from the list of all usable node_t objects are in the routerlist.c
  31. * module, since they originally selected a routerinfo_t. (TODO: They
  32. * should move!)
  33. *
  34. * (TODO: Perhaps someday we should abstract the remaining ways of
  35. * talking about a relay to also be node_t instances. Those would be
  36. * routerstatus_t as used for directory requests, and dir_server_t as
  37. * used for authorities and fallback directories.)
  38. */
  39. #include "or.h"
  40. #include "address.h"
  41. #include "config.h"
  42. #include "control.h"
  43. #include "dirserv.h"
  44. #include "entrynodes.h"
  45. #include "geoip.h"
  46. #include "hs_common.h"
  47. #include "main.h"
  48. #include "microdesc.h"
  49. #include "networkstatus.h"
  50. #include "nodelist.h"
  51. #include "policies.h"
  52. #include "protover.h"
  53. #include "rendservice.h"
  54. #include "router.h"
  55. #include "routerlist.h"
  56. #include "routerparse.h"
  57. #include "routerset.h"
  58. #include "torcert.h"
  59. #include <string.h>
  60. static void nodelist_drop_node(node_t *node, int remove_from_ht);
  61. static void node_free(node_t *node);
  62. /** count_usable_descriptors counts descriptors with these flag(s)
  63. */
  64. typedef enum {
  65. /* All descriptors regardless of flags */
  66. USABLE_DESCRIPTOR_ALL = 0,
  67. /* Only descriptors with the Exit flag */
  68. USABLE_DESCRIPTOR_EXIT_ONLY = 1
  69. } usable_descriptor_t;
  70. static void count_usable_descriptors(int *num_present,
  71. int *num_usable,
  72. smartlist_t *descs_out,
  73. const networkstatus_t *consensus,
  74. time_t now,
  75. routerset_t *in_set,
  76. usable_descriptor_t exit_only);
  77. static void update_router_have_minimum_dir_info(void);
  78. static double get_frac_paths_needed_for_circs(const or_options_t *options,
  79. const networkstatus_t *ns);
  80. /** A nodelist_t holds a node_t object for every router we're "willing to use
  81. * for something". Specifically, it should hold a node_t for every node that
  82. * is currently in the routerlist, or currently in the consensus we're using.
  83. */
  84. typedef struct nodelist_t {
  85. /* A list of all the nodes. */
  86. smartlist_t *nodes;
  87. /* Hash table to map from node ID digest to node. */
  88. HT_HEAD(nodelist_map, node_t) nodes_by_id;
  89. } nodelist_t;
  90. static inline unsigned int
  91. node_id_hash(const node_t *node)
  92. {
  93. return (unsigned) siphash24g(node->identity, DIGEST_LEN);
  94. }
  95. static inline unsigned int
  96. node_id_eq(const node_t *node1, const node_t *node2)
  97. {
  98. return tor_memeq(node1->identity, node2->identity, DIGEST_LEN);
  99. }
  100. HT_PROTOTYPE(nodelist_map, node_t, ht_ent, node_id_hash, node_id_eq)
  101. HT_GENERATE2(nodelist_map, node_t, ht_ent, node_id_hash, node_id_eq,
  102. 0.6, tor_reallocarray_, tor_free_)
  103. /** The global nodelist. */
  104. static nodelist_t *the_nodelist=NULL;
  105. /** Create an empty nodelist if we haven't done so already. */
  106. static void
  107. init_nodelist(void)
  108. {
  109. if (PREDICT_UNLIKELY(the_nodelist == NULL)) {
  110. the_nodelist = tor_malloc_zero(sizeof(nodelist_t));
  111. HT_INIT(nodelist_map, &the_nodelist->nodes_by_id);
  112. the_nodelist->nodes = smartlist_new();
  113. }
  114. }
  115. /** As node_get_by_id, but returns a non-const pointer */
  116. node_t *
  117. node_get_mutable_by_id(const char *identity_digest)
  118. {
  119. node_t search, *node;
  120. if (PREDICT_UNLIKELY(the_nodelist == NULL))
  121. return NULL;
  122. memcpy(&search.identity, identity_digest, DIGEST_LEN);
  123. node = HT_FIND(nodelist_map, &the_nodelist->nodes_by_id, &search);
  124. return node;
  125. }
  126. /** Return the node_t whose identity is <b>identity_digest</b>, or NULL
  127. * if no such node exists. */
  128. MOCK_IMPL(const node_t *,
  129. node_get_by_id,(const char *identity_digest))
  130. {
  131. return node_get_mutable_by_id(identity_digest);
  132. }
  133. /** Internal: return the node_t whose identity_digest is
  134. * <b>identity_digest</b>. If none exists, create a new one, add it to the
  135. * nodelist, and return it.
  136. *
  137. * Requires that the nodelist be initialized.
  138. */
  139. static node_t *
  140. node_get_or_create(const char *identity_digest)
  141. {
  142. node_t *node;
  143. if ((node = node_get_mutable_by_id(identity_digest)))
  144. return node;
  145. node = tor_malloc_zero(sizeof(node_t));
  146. memcpy(node->identity, identity_digest, DIGEST_LEN);
  147. HT_INSERT(nodelist_map, &the_nodelist->nodes_by_id, node);
  148. smartlist_add(the_nodelist->nodes, node);
  149. node->nodelist_idx = smartlist_len(the_nodelist->nodes) - 1;
  150. node->hsdir_index = tor_malloc_zero(sizeof(hsdir_index_t));
  151. node->country = -1;
  152. return node;
  153. }
  154. /* For a given <b>node</b> for the consensus <b>ns</b>, set the hsdir index
  155. * for the node, both current and next if possible. This can only fails if the
  156. * node_t ed25519 identity key can't be found which would be a bug. */
  157. static void
  158. node_set_hsdir_index(node_t *node, const networkstatus_t *ns)
  159. {
  160. time_t now = approx_time();
  161. const ed25519_public_key_t *node_identity_pk;
  162. uint8_t *next_hsdir_index_srv = NULL, *current_hsdir_index_srv = NULL;
  163. uint64_t next_time_period_num, current_time_period_num;
  164. tor_assert(node);
  165. tor_assert(ns);
  166. if (!networkstatus_is_live(ns, now)) {
  167. log_info(LD_GENERAL, "Not setting hsdir index with a non-live consensus.");
  168. goto done;
  169. }
  170. node_identity_pk = node_get_ed25519_id(node);
  171. if (node_identity_pk == NULL) {
  172. log_debug(LD_GENERAL, "ed25519 identity public key not found when "
  173. "trying to build the hsdir indexes for node %s",
  174. node_describe(node));
  175. goto done;
  176. }
  177. /* Get the current and next time period number, we might use them both. */
  178. current_time_period_num = hs_get_time_period_num(now);
  179. next_time_period_num = hs_get_next_time_period_num(now);
  180. if (hs_overlap_mode_is_active(ns, now)) {
  181. /* We are in overlap mode, this means that our consensus has just cycled
  182. * from current SRV to previous SRV so for the _next_ upcoming time
  183. * period, we have to use the current SRV and use the previous SRV for the
  184. * current time period. If the current or previous SRV can't be found, the
  185. * disaster one is returned. */
  186. next_hsdir_index_srv = hs_get_current_srv(next_time_period_num, ns);
  187. /* The following can be confusing so again, in overlap mode, we use our
  188. * previous SRV for our _current_ hsdir index. */
  189. current_hsdir_index_srv = hs_get_previous_srv(current_time_period_num, ns);
  190. } else {
  191. /* If NOT in overlap mode, we only need to compute the current hsdir index
  192. * for the ongoing time period and thus the current SRV. If it can't be
  193. * found, the disaster one is returned. */
  194. current_hsdir_index_srv = hs_get_current_srv(current_time_period_num, ns);
  195. }
  196. /* Build the current hsdir index. */
  197. hs_build_hsdir_index(node_identity_pk, current_hsdir_index_srv,
  198. current_time_period_num, node->hsdir_index->current);
  199. if (next_hsdir_index_srv) {
  200. /* Build the next hsdir index if we have a next SRV that we can use. */
  201. hs_build_hsdir_index(node_identity_pk, next_hsdir_index_srv,
  202. next_time_period_num, node->hsdir_index->next);
  203. } else {
  204. memset(node->hsdir_index->next, 0, sizeof(node->hsdir_index->next));
  205. }
  206. done:
  207. tor_free(current_hsdir_index_srv);
  208. tor_free(next_hsdir_index_srv);
  209. return;
  210. }
  211. /** Recompute all node hsdir indices. */
  212. void
  213. nodelist_recompute_all_hsdir_indices(void)
  214. {
  215. networkstatus_t *consensus;
  216. if (!the_nodelist) {
  217. return;
  218. }
  219. /* Get a live consensus. Abort if not found */
  220. consensus = networkstatus_get_live_consensus(approx_time());
  221. if (!consensus) {
  222. return;
  223. }
  224. /* Recompute all hsdir indices */
  225. SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) {
  226. node_set_hsdir_index(node, consensus);
  227. } SMARTLIST_FOREACH_END(node);
  228. }
  229. /** Called when a node's address changes. */
  230. static void
  231. node_addrs_changed(node_t *node)
  232. {
  233. node->last_reachable = node->last_reachable6 = 0;
  234. node->country = -1;
  235. }
  236. /** Add <b>ri</b> to an appropriate node in the nodelist. If we replace an
  237. * old routerinfo, and <b>ri_old_out</b> is not NULL, set *<b>ri_old_out</b>
  238. * to the previous routerinfo.
  239. */
  240. node_t *
  241. nodelist_set_routerinfo(routerinfo_t *ri, routerinfo_t **ri_old_out)
  242. {
  243. node_t *node;
  244. const char *id_digest;
  245. int had_router = 0;
  246. tor_assert(ri);
  247. init_nodelist();
  248. id_digest = ri->cache_info.identity_digest;
  249. node = node_get_or_create(id_digest);
  250. if (node->ri) {
  251. if (!routers_have_same_or_addrs(node->ri, ri)) {
  252. node_addrs_changed(node);
  253. }
  254. had_router = 1;
  255. if (ri_old_out)
  256. *ri_old_out = node->ri;
  257. } else {
  258. if (ri_old_out)
  259. *ri_old_out = NULL;
  260. }
  261. node->ri = ri;
  262. if (node->country == -1)
  263. node_set_country(node);
  264. if (authdir_mode(get_options()) && !had_router) {
  265. const char *discard=NULL;
  266. uint32_t status = dirserv_router_get_status(ri, &discard, LOG_INFO);
  267. dirserv_set_node_flags_from_authoritative_status(node, status);
  268. }
  269. /* Setting the HSDir index requires the ed25519 identity key which can
  270. * only be found either in the ri or md. This is why this is called here.
  271. * Only nodes supporting HSDir=2 protocol version needs this index. */
  272. if (node->rs && node->rs->supports_v3_hsdir) {
  273. node_set_hsdir_index(node,
  274. networkstatus_get_latest_consensus());
  275. }
  276. return node;
  277. }
  278. /** Set the appropriate node_t to use <b>md</b> as its microdescriptor.
  279. *
  280. * Called when a new microdesc has arrived and the usable consensus flavor
  281. * is "microdesc".
  282. **/
  283. node_t *
  284. nodelist_add_microdesc(microdesc_t *md)
  285. {
  286. networkstatus_t *ns =
  287. networkstatus_get_latest_consensus_by_flavor(FLAV_MICRODESC);
  288. const routerstatus_t *rs;
  289. node_t *node;
  290. if (ns == NULL)
  291. return NULL;
  292. init_nodelist();
  293. /* Microdescriptors don't carry an identity digest, so we need to figure
  294. * it out by looking up the routerstatus. */
  295. rs = router_get_consensus_status_by_descriptor_digest(ns, md->digest);
  296. if (rs == NULL)
  297. return NULL;
  298. node = node_get_mutable_by_id(rs->identity_digest);
  299. if (node) {
  300. if (node->md)
  301. node->md->held_by_nodes--;
  302. node->md = md;
  303. md->held_by_nodes++;
  304. /* Setting the HSDir index requires the ed25519 identity key which can
  305. * only be found either in the ri or md. This is why this is called here.
  306. * Only nodes supporting HSDir=2 protocol version needs this index. */
  307. if (rs->supports_v3_hsdir) {
  308. node_set_hsdir_index(node, ns);
  309. }
  310. }
  311. return node;
  312. }
  313. /** Tell the nodelist that the current usable consensus is <b>ns</b>.
  314. * This makes the nodelist change all of the routerstatus entries for
  315. * the nodes, drop nodes that no longer have enough info to get used,
  316. * and grab microdescriptors into nodes as appropriate.
  317. */
  318. void
  319. nodelist_set_consensus(networkstatus_t *ns)
  320. {
  321. const or_options_t *options = get_options();
  322. int authdir = authdir_mode_v3(options);
  323. init_nodelist();
  324. if (ns->flavor == FLAV_MICRODESC)
  325. (void) get_microdesc_cache(); /* Make sure it exists first. */
  326. SMARTLIST_FOREACH(the_nodelist->nodes, node_t *, node,
  327. node->rs = NULL);
  328. SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, routerstatus_t *, rs) {
  329. node_t *node = node_get_or_create(rs->identity_digest);
  330. node->rs = rs;
  331. if (ns->flavor == FLAV_MICRODESC) {
  332. if (node->md == NULL ||
  333. tor_memneq(node->md->digest,rs->descriptor_digest,DIGEST256_LEN)) {
  334. if (node->md)
  335. node->md->held_by_nodes--;
  336. node->md = microdesc_cache_lookup_by_digest256(NULL,
  337. rs->descriptor_digest);
  338. if (node->md)
  339. node->md->held_by_nodes++;
  340. }
  341. }
  342. if (rs->supports_v3_hsdir) {
  343. node_set_hsdir_index(node, ns);
  344. }
  345. node_set_country(node);
  346. /* If we're not an authdir, believe others. */
  347. if (!authdir) {
  348. node->is_valid = rs->is_valid;
  349. node->is_running = rs->is_flagged_running;
  350. node->is_fast = rs->is_fast;
  351. node->is_stable = rs->is_stable;
  352. node->is_possible_guard = rs->is_possible_guard;
  353. node->is_exit = rs->is_exit;
  354. node->is_bad_exit = rs->is_bad_exit;
  355. node->is_hs_dir = rs->is_hs_dir;
  356. node->ipv6_preferred = 0;
  357. if (fascist_firewall_prefer_ipv6_orport(options) &&
  358. (tor_addr_is_null(&rs->ipv6_addr) == 0 ||
  359. (node->md && tor_addr_is_null(&node->md->ipv6_addr) == 0)))
  360. node->ipv6_preferred = 1;
  361. }
  362. } SMARTLIST_FOREACH_END(rs);
  363. nodelist_purge();
  364. if (! authdir) {
  365. SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) {
  366. /* We have no routerstatus for this router. Clear flags so we can skip
  367. * it, maybe.*/
  368. if (!node->rs) {
  369. tor_assert(node->ri); /* if it had only an md, or nothing, purge
  370. * would have removed it. */
  371. if (node->ri->purpose == ROUTER_PURPOSE_GENERAL) {
  372. /* Clear all flags. */
  373. node->is_valid = node->is_running = node->is_hs_dir =
  374. node->is_fast = node->is_stable =
  375. node->is_possible_guard = node->is_exit =
  376. node->is_bad_exit = node->ipv6_preferred = 0;
  377. }
  378. }
  379. } SMARTLIST_FOREACH_END(node);
  380. }
  381. }
  382. /** Helper: return true iff a node has a usable amount of information*/
  383. static inline int
  384. node_is_usable(const node_t *node)
  385. {
  386. return (node->rs) || (node->ri);
  387. }
  388. /** Tell the nodelist that <b>md</b> is no longer a microdescriptor for the
  389. * node with <b>identity_digest</b>. */
  390. void
  391. nodelist_remove_microdesc(const char *identity_digest, microdesc_t *md)
  392. {
  393. node_t *node = node_get_mutable_by_id(identity_digest);
  394. if (node && node->md == md) {
  395. node->md = NULL;
  396. md->held_by_nodes--;
  397. }
  398. }
  399. /** Tell the nodelist that <b>ri</b> is no longer in the routerlist. */
  400. void
  401. nodelist_remove_routerinfo(routerinfo_t *ri)
  402. {
  403. node_t *node = node_get_mutable_by_id(ri->cache_info.identity_digest);
  404. if (node && node->ri == ri) {
  405. node->ri = NULL;
  406. if (! node_is_usable(node)) {
  407. nodelist_drop_node(node, 1);
  408. node_free(node);
  409. }
  410. }
  411. }
  412. /** Remove <b>node</b> from the nodelist. (Asserts that it was there to begin
  413. * with.) */
  414. static void
  415. nodelist_drop_node(node_t *node, int remove_from_ht)
  416. {
  417. node_t *tmp;
  418. int idx;
  419. if (remove_from_ht) {
  420. tmp = HT_REMOVE(nodelist_map, &the_nodelist->nodes_by_id, node);
  421. tor_assert(tmp == node);
  422. }
  423. idx = node->nodelist_idx;
  424. tor_assert(idx >= 0);
  425. tor_assert(node == smartlist_get(the_nodelist->nodes, idx));
  426. smartlist_del(the_nodelist->nodes, idx);
  427. if (idx < smartlist_len(the_nodelist->nodes)) {
  428. tmp = smartlist_get(the_nodelist->nodes, idx);
  429. tmp->nodelist_idx = idx;
  430. }
  431. node->nodelist_idx = -1;
  432. }
  433. /** Return a newly allocated smartlist of the nodes that have <b>md</b> as
  434. * their microdescriptor. */
  435. smartlist_t *
  436. nodelist_find_nodes_with_microdesc(const microdesc_t *md)
  437. {
  438. smartlist_t *result = smartlist_new();
  439. if (the_nodelist == NULL)
  440. return result;
  441. SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) {
  442. if (node->md == md) {
  443. smartlist_add(result, node);
  444. }
  445. } SMARTLIST_FOREACH_END(node);
  446. return result;
  447. }
  448. /** Release storage held by <b>node</b> */
  449. static void
  450. node_free(node_t *node)
  451. {
  452. if (!node)
  453. return;
  454. if (node->md)
  455. node->md->held_by_nodes--;
  456. tor_assert(node->nodelist_idx == -1);
  457. tor_free(node->hsdir_index);
  458. tor_free(node);
  459. }
  460. /** Remove all entries from the nodelist that don't have enough info to be
  461. * usable for anything. */
  462. void
  463. nodelist_purge(void)
  464. {
  465. node_t **iter;
  466. if (PREDICT_UNLIKELY(the_nodelist == NULL))
  467. return;
  468. /* Remove the non-usable nodes. */
  469. for (iter = HT_START(nodelist_map, &the_nodelist->nodes_by_id); iter; ) {
  470. node_t *node = *iter;
  471. if (node->md && !node->rs) {
  472. /* An md is only useful if there is an rs. */
  473. node->md->held_by_nodes--;
  474. node->md = NULL;
  475. }
  476. if (node_is_usable(node)) {
  477. iter = HT_NEXT(nodelist_map, &the_nodelist->nodes_by_id, iter);
  478. } else {
  479. iter = HT_NEXT_RMV(nodelist_map, &the_nodelist->nodes_by_id, iter);
  480. nodelist_drop_node(node, 0);
  481. node_free(node);
  482. }
  483. }
  484. nodelist_assert_ok();
  485. }
  486. /** Release all storage held by the nodelist. */
  487. void
  488. nodelist_free_all(void)
  489. {
  490. if (PREDICT_UNLIKELY(the_nodelist == NULL))
  491. return;
  492. HT_CLEAR(nodelist_map, &the_nodelist->nodes_by_id);
  493. SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) {
  494. node->nodelist_idx = -1;
  495. node_free(node);
  496. } SMARTLIST_FOREACH_END(node);
  497. smartlist_free(the_nodelist->nodes);
  498. tor_free(the_nodelist);
  499. }
  500. /** Check that the nodelist is internally consistent, and consistent with
  501. * the directory info it's derived from.
  502. */
  503. void
  504. nodelist_assert_ok(void)
  505. {
  506. routerlist_t *rl = router_get_routerlist();
  507. networkstatus_t *ns = networkstatus_get_latest_consensus();
  508. digestmap_t *dm;
  509. if (!the_nodelist)
  510. return;
  511. dm = digestmap_new();
  512. /* every routerinfo in rl->routers should be in the nodelist. */
  513. if (rl) {
  514. SMARTLIST_FOREACH_BEGIN(rl->routers, routerinfo_t *, ri) {
  515. const node_t *node = node_get_by_id(ri->cache_info.identity_digest);
  516. tor_assert(node && node->ri == ri);
  517. tor_assert(fast_memeq(ri->cache_info.identity_digest,
  518. node->identity, DIGEST_LEN));
  519. tor_assert(! digestmap_get(dm, node->identity));
  520. digestmap_set(dm, node->identity, (void*)node);
  521. } SMARTLIST_FOREACH_END(ri);
  522. }
  523. /* every routerstatus in ns should be in the nodelist */
  524. if (ns) {
  525. SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, routerstatus_t *, rs) {
  526. const node_t *node = node_get_by_id(rs->identity_digest);
  527. tor_assert(node && node->rs == rs);
  528. tor_assert(fast_memeq(rs->identity_digest, node->identity, DIGEST_LEN));
  529. digestmap_set(dm, node->identity, (void*)node);
  530. if (ns->flavor == FLAV_MICRODESC) {
  531. /* If it's a microdesc consensus, every entry that has a
  532. * microdescriptor should be in the nodelist.
  533. */
  534. microdesc_t *md =
  535. microdesc_cache_lookup_by_digest256(NULL, rs->descriptor_digest);
  536. tor_assert(md == node->md);
  537. if (md)
  538. tor_assert(md->held_by_nodes >= 1);
  539. }
  540. } SMARTLIST_FOREACH_END(rs);
  541. }
  542. /* The nodelist should have no other entries, and its entries should be
  543. * well-formed. */
  544. SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) {
  545. tor_assert(digestmap_get(dm, node->identity) != NULL);
  546. tor_assert(node_sl_idx == node->nodelist_idx);
  547. } SMARTLIST_FOREACH_END(node);
  548. tor_assert((long)smartlist_len(the_nodelist->nodes) ==
  549. (long)HT_SIZE(&the_nodelist->nodes_by_id));
  550. digestmap_free(dm, NULL);
  551. }
  552. /** Return a list of a node_t * for every node we know about. The caller
  553. * MUST NOT modify the list. (You can set and clear flags in the nodes if
  554. * you must, but you must not add or remove nodes.) */
  555. MOCK_IMPL(smartlist_t *,
  556. nodelist_get_list,(void))
  557. {
  558. init_nodelist();
  559. return the_nodelist->nodes;
  560. }
  561. /** Given a hex-encoded nickname of the format DIGEST, $DIGEST, $DIGEST=name,
  562. * or $DIGEST~name, return the node with the matching identity digest and
  563. * nickname (if any). Return NULL if no such node exists, or if <b>hex_id</b>
  564. * is not well-formed. */
  565. const node_t *
  566. node_get_by_hex_id(const char *hex_id)
  567. {
  568. char digest_buf[DIGEST_LEN];
  569. char nn_buf[MAX_NICKNAME_LEN+1];
  570. char nn_char='\0';
  571. if (hex_digest_nickname_decode(hex_id, digest_buf, &nn_char, nn_buf)==0) {
  572. const node_t *node = node_get_by_id(digest_buf);
  573. if (!node)
  574. return NULL;
  575. if (nn_char) {
  576. const char *real_name = node_get_nickname(node);
  577. if (!real_name || strcasecmp(real_name, nn_buf))
  578. return NULL;
  579. if (nn_char == '=') {
  580. const char *named_id =
  581. networkstatus_get_router_digest_by_nickname(nn_buf);
  582. if (!named_id || tor_memneq(named_id, digest_buf, DIGEST_LEN))
  583. return NULL;
  584. }
  585. }
  586. return node;
  587. }
  588. return NULL;
  589. }
  590. /** Given a nickname (possibly verbose, possibly a hexadecimal digest), return
  591. * the corresponding node_t, or NULL if none exists. Warn the user if
  592. * <b>warn_if_unnamed</b> is set, and they have specified a router by
  593. * nickname, but the Named flag isn't set for that router. */
  594. MOCK_IMPL(const node_t *,
  595. node_get_by_nickname,(const char *nickname, int warn_if_unnamed))
  596. {
  597. if (!the_nodelist)
  598. return NULL;
  599. /* Handle these cases: DIGEST, $DIGEST, $DIGEST=name, $DIGEST~name. */
  600. {
  601. const node_t *node;
  602. if ((node = node_get_by_hex_id(nickname)) != NULL)
  603. return node;
  604. }
  605. if (!strcasecmp(nickname, UNNAMED_ROUTER_NICKNAME))
  606. return NULL;
  607. /* Okay, so if we get here, the nickname is just a nickname. Is there
  608. * a binding for it in the consensus? */
  609. {
  610. const char *named_id =
  611. networkstatus_get_router_digest_by_nickname(nickname);
  612. if (named_id)
  613. return node_get_by_id(named_id);
  614. }
  615. /* Is it marked as owned-by-someone-else? */
  616. if (networkstatus_nickname_is_unnamed(nickname)) {
  617. log_info(LD_GENERAL, "The name %s is listed as Unnamed: there is some "
  618. "router that holds it, but not one listed in the current "
  619. "consensus.", escaped(nickname));
  620. return NULL;
  621. }
  622. /* Okay, so the name is not canonical for anybody. */
  623. {
  624. smartlist_t *matches = smartlist_new();
  625. const node_t *choice = NULL;
  626. SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) {
  627. if (!strcasecmp(node_get_nickname(node), nickname))
  628. smartlist_add(matches, node);
  629. } SMARTLIST_FOREACH_END(node);
  630. if (smartlist_len(matches)>1 && warn_if_unnamed) {
  631. int any_unwarned = 0;
  632. SMARTLIST_FOREACH_BEGIN(matches, node_t *, node) {
  633. if (!node->name_lookup_warned) {
  634. node->name_lookup_warned = 1;
  635. any_unwarned = 1;
  636. }
  637. } SMARTLIST_FOREACH_END(node);
  638. if (any_unwarned) {
  639. log_warn(LD_CONFIG, "There are multiple matches for the name %s, "
  640. "but none is listed as Named in the directory consensus. "
  641. "Choosing one arbitrarily.", nickname);
  642. }
  643. } else if (smartlist_len(matches)==1 && warn_if_unnamed) {
  644. char fp[HEX_DIGEST_LEN+1];
  645. node_t *node = smartlist_get(matches, 0);
  646. if (! node->name_lookup_warned) {
  647. base16_encode(fp, sizeof(fp), node->identity, DIGEST_LEN);
  648. log_warn(LD_CONFIG,
  649. "You specified a relay \"%s\" by name, but nicknames can be "
  650. "used by any relay, not just the one you meant. "
  651. "To make sure you get the same relay in the future, refer "
  652. "to it by key, as \"$%s\".", nickname, fp);
  653. node->name_lookup_warned = 1;
  654. }
  655. }
  656. if (smartlist_len(matches))
  657. choice = smartlist_get(matches, 0);
  658. smartlist_free(matches);
  659. return choice;
  660. }
  661. }
  662. /** Return the Ed25519 identity key for the provided node, or NULL if it
  663. * doesn't have one. */
  664. const ed25519_public_key_t *
  665. node_get_ed25519_id(const node_t *node)
  666. {
  667. if (node->ri) {
  668. if (node->ri->cache_info.signing_key_cert) {
  669. const ed25519_public_key_t *pk =
  670. &node->ri->cache_info.signing_key_cert->signing_key;
  671. if (BUG(ed25519_public_key_is_zero(pk)))
  672. goto try_the_md;
  673. return pk;
  674. }
  675. }
  676. try_the_md:
  677. if (node->md) {
  678. if (node->md->ed25519_identity_pkey) {
  679. return node->md->ed25519_identity_pkey;
  680. }
  681. }
  682. return NULL;
  683. }
  684. /** Return true iff this node's Ed25519 identity matches <b>id</b>.
  685. * (An absent Ed25519 identity matches NULL or zero.) */
  686. int
  687. node_ed25519_id_matches(const node_t *node, const ed25519_public_key_t *id)
  688. {
  689. const ed25519_public_key_t *node_id = node_get_ed25519_id(node);
  690. if (node_id == NULL || ed25519_public_key_is_zero(node_id)) {
  691. return id == NULL || ed25519_public_key_is_zero(id);
  692. } else {
  693. return id && ed25519_pubkey_eq(node_id, id);
  694. }
  695. }
  696. /** Return true iff <b>node</b> supports authenticating itself
  697. * by ed25519 ID during the link handshake in a way that we can understand
  698. * when we probe it. */
  699. int
  700. node_supports_ed25519_link_authentication(const node_t *node)
  701. {
  702. /* XXXX Oh hm. What if some day in the future there are link handshake
  703. * versions that aren't 3 but which are ed25519 */
  704. if (! node_get_ed25519_id(node))
  705. return 0;
  706. if (node->ri) {
  707. const char *protos = node->ri->protocol_list;
  708. if (protos == NULL)
  709. return 0;
  710. return protocol_list_supports_protocol(protos, PRT_LINKAUTH, 3);
  711. }
  712. if (node->rs) {
  713. return node->rs->supports_ed25519_link_handshake;
  714. }
  715. tor_assert_nonfatal_unreached_once();
  716. return 0;
  717. }
  718. /** Return true iff <b>node</b> supports the hidden service directory version
  719. * 3 protocol (proposal 224). */
  720. int
  721. node_supports_v3_hsdir(const node_t *node)
  722. {
  723. tor_assert(node);
  724. if (node->rs) {
  725. return node->rs->supports_v3_hsdir;
  726. }
  727. if (node->ri) {
  728. if (node->ri->protocol_list == NULL) {
  729. return 0;
  730. }
  731. /* Bug #22447 forces us to filter on tor version:
  732. * If platform is a Tor version, and older than 0.3.0.8, return False.
  733. * Else, obey the protocol list. */
  734. if (node->ri->platform) {
  735. if (!strcmpstart(node->ri->platform, "Tor ") &&
  736. !tor_version_as_new_as(node->ri->platform, "0.3.0.8")) {
  737. return 0;
  738. }
  739. }
  740. return protocol_list_supports_protocol(node->ri->protocol_list,
  741. PRT_HSDIR, PROTOVER_HSDIR_V3);
  742. }
  743. tor_assert_nonfatal_unreached_once();
  744. return 0;
  745. }
  746. /** Return true iff <b>node</b> supports ed25519 authentication as an hidden
  747. * service introduction point.*/
  748. int
  749. node_supports_ed25519_hs_intro(const node_t *node)
  750. {
  751. tor_assert(node);
  752. if (node->rs) {
  753. return node->rs->supports_ed25519_hs_intro;
  754. }
  755. if (node->ri) {
  756. if (node->ri->protocol_list == NULL) {
  757. return 0;
  758. }
  759. return protocol_list_supports_protocol(node->ri->protocol_list,
  760. PRT_HSINTRO, PROTOVER_HS_INTRO_V3);
  761. }
  762. tor_assert_nonfatal_unreached_once();
  763. return 0;
  764. }
  765. /** Return true iff <b>node</b> supports to be a rendezvous point for hidden
  766. * service version 3 (HSRend=2). */
  767. int
  768. node_supports_v3_rendezvous_point(const node_t *node)
  769. {
  770. tor_assert(node);
  771. if (node->rs) {
  772. return node->rs->supports_v3_rendezvous_point;
  773. }
  774. if (node->ri) {
  775. if (node->ri->protocol_list == NULL) {
  776. return 0;
  777. }
  778. return protocol_list_supports_protocol(node->ri->protocol_list,
  779. PRT_HSREND,
  780. PROTOVER_HS_RENDEZVOUS_POINT_V3);
  781. }
  782. tor_assert_nonfatal_unreached_once();
  783. return 0;
  784. }
  785. /** Return the RSA ID key's SHA1 digest for the provided node. */
  786. const uint8_t *
  787. node_get_rsa_id_digest(const node_t *node)
  788. {
  789. tor_assert(node);
  790. return (const uint8_t*)node->identity;
  791. }
  792. /** Return the nickname of <b>node</b>, or NULL if we can't find one. */
  793. const char *
  794. node_get_nickname(const node_t *node)
  795. {
  796. tor_assert(node);
  797. if (node->rs)
  798. return node->rs->nickname;
  799. else if (node->ri)
  800. return node->ri->nickname;
  801. else
  802. return NULL;
  803. }
  804. /** Return true iff the nickname of <b>node</b> is canonical, based on the
  805. * latest consensus. */
  806. int
  807. node_is_named(const node_t *node)
  808. {
  809. const char *named_id;
  810. const char *nickname = node_get_nickname(node);
  811. if (!nickname)
  812. return 0;
  813. named_id = networkstatus_get_router_digest_by_nickname(nickname);
  814. if (!named_id)
  815. return 0;
  816. return tor_memeq(named_id, node->identity, DIGEST_LEN);
  817. }
  818. /** Return true iff <b>node</b> appears to be a directory authority or
  819. * directory cache */
  820. int
  821. node_is_dir(const node_t *node)
  822. {
  823. if (node->rs) {
  824. routerstatus_t * rs = node->rs;
  825. /* This is true if supports_tunnelled_dir_requests is true which
  826. * indicates that we support directory request tunnelled or through the
  827. * DirPort. */
  828. return rs->is_v2_dir;
  829. } else if (node->ri) {
  830. routerinfo_t * ri = node->ri;
  831. /* Both tunnelled request is supported or DirPort is set. */
  832. return ri->supports_tunnelled_dir_requests;
  833. } else {
  834. return 0;
  835. }
  836. }
  837. /** Return true iff <b>node</b> has either kind of usable descriptor -- that
  838. * is, a routerdescriptor or a microdescriptor. */
  839. int
  840. node_has_descriptor(const node_t *node)
  841. {
  842. return (node->ri ||
  843. (node->rs && node->md));
  844. }
  845. /** Return the router_purpose of <b>node</b>. */
  846. int
  847. node_get_purpose(const node_t *node)
  848. {
  849. if (node->ri)
  850. return node->ri->purpose;
  851. else
  852. return ROUTER_PURPOSE_GENERAL;
  853. }
  854. /** Compute the verbose ("extended") nickname of <b>node</b> and store it
  855. * into the MAX_VERBOSE_NICKNAME_LEN+1 character buffer at
  856. * <b>verbose_name_out</b> */
  857. void
  858. node_get_verbose_nickname(const node_t *node,
  859. char *verbose_name_out)
  860. {
  861. const char *nickname = node_get_nickname(node);
  862. int is_named = node_is_named(node);
  863. verbose_name_out[0] = '$';
  864. base16_encode(verbose_name_out+1, HEX_DIGEST_LEN+1, node->identity,
  865. DIGEST_LEN);
  866. if (!nickname)
  867. return;
  868. verbose_name_out[1+HEX_DIGEST_LEN] = is_named ? '=' : '~';
  869. strlcpy(verbose_name_out+1+HEX_DIGEST_LEN+1, nickname, MAX_NICKNAME_LEN+1);
  870. }
  871. /** Compute the verbose ("extended") nickname of node with
  872. * given <b>id_digest</b> and store it into the MAX_VERBOSE_NICKNAME_LEN+1
  873. * character buffer at <b>verbose_name_out</b>
  874. *
  875. * If node_get_by_id() returns NULL, base 16 encoding of
  876. * <b>id_digest</b> is returned instead. */
  877. void
  878. node_get_verbose_nickname_by_id(const char *id_digest,
  879. char *verbose_name_out)
  880. {
  881. const node_t *node = node_get_by_id(id_digest);
  882. if (!node) {
  883. verbose_name_out[0] = '$';
  884. base16_encode(verbose_name_out+1, HEX_DIGEST_LEN+1, id_digest, DIGEST_LEN);
  885. } else {
  886. node_get_verbose_nickname(node, verbose_name_out);
  887. }
  888. }
  889. /** Return true iff it seems that <b>node</b> allows circuits to exit
  890. * through it directlry from the client. */
  891. int
  892. node_allows_single_hop_exits(const node_t *node)
  893. {
  894. if (node && node->ri)
  895. return node->ri->allow_single_hop_exits;
  896. else
  897. return 0;
  898. }
  899. /** Return true iff it seems that <b>node</b> has an exit policy that doesn't
  900. * actually permit anything to exit, or we don't know its exit policy */
  901. int
  902. node_exit_policy_rejects_all(const node_t *node)
  903. {
  904. if (node->rejects_all)
  905. return 1;
  906. if (node->ri)
  907. return node->ri->policy_is_reject_star;
  908. else if (node->md)
  909. return node->md->exit_policy == NULL ||
  910. short_policy_is_reject_star(node->md->exit_policy);
  911. else
  912. return 1;
  913. }
  914. /** Return true iff the exit policy for <b>node</b> is such that we can treat
  915. * rejecting an address of type <b>family</b> unexpectedly as a sign of that
  916. * node's failure. */
  917. int
  918. node_exit_policy_is_exact(const node_t *node, sa_family_t family)
  919. {
  920. if (family == AF_UNSPEC) {
  921. return 1; /* Rejecting an address but not telling us what address
  922. * is a bad sign. */
  923. } else if (family == AF_INET) {
  924. return node->ri != NULL;
  925. } else if (family == AF_INET6) {
  926. return 0;
  927. }
  928. tor_fragile_assert();
  929. return 1;
  930. }
  931. /* Check if the "addr" and port_field fields from r are a valid non-listening
  932. * address/port. If so, set valid to true and add a newly allocated
  933. * tor_addr_port_t containing "addr" and port_field to sl.
  934. * "addr" is an IPv4 host-order address and port_field is a uint16_t.
  935. * r is typically a routerinfo_t or routerstatus_t.
  936. */
  937. #define SL_ADD_NEW_IPV4_AP(r, port_field, sl, valid) \
  938. STMT_BEGIN \
  939. if (tor_addr_port_is_valid_ipv4h((r)->addr, (r)->port_field, 0)) { \
  940. valid = 1; \
  941. tor_addr_port_t *ap = tor_malloc(sizeof(tor_addr_port_t)); \
  942. tor_addr_from_ipv4h(&ap->addr, (r)->addr); \
  943. ap->port = (r)->port_field; \
  944. smartlist_add((sl), ap); \
  945. } \
  946. STMT_END
  947. /* Check if the "addr" and port_field fields from r are a valid non-listening
  948. * address/port. If so, set valid to true and add a newly allocated
  949. * tor_addr_port_t containing "addr" and port_field to sl.
  950. * "addr" is a tor_addr_t and port_field is a uint16_t.
  951. * r is typically a routerinfo_t or routerstatus_t.
  952. */
  953. #define SL_ADD_NEW_IPV6_AP(r, port_field, sl, valid) \
  954. STMT_BEGIN \
  955. if (tor_addr_port_is_valid(&(r)->ipv6_addr, (r)->port_field, 0)) { \
  956. valid = 1; \
  957. tor_addr_port_t *ap = tor_malloc(sizeof(tor_addr_port_t)); \
  958. tor_addr_copy(&ap->addr, &(r)->ipv6_addr); \
  959. ap->port = (r)->port_field; \
  960. smartlist_add((sl), ap); \
  961. } \
  962. STMT_END
  963. /** Return list of tor_addr_port_t with all OR ports (in the sense IP
  964. * addr + TCP port) for <b>node</b>. Caller must free all elements
  965. * using tor_free() and free the list using smartlist_free().
  966. *
  967. * XXX this is potentially a memory fragmentation hog -- if on
  968. * critical path consider the option of having the caller allocate the
  969. * memory
  970. */
  971. smartlist_t *
  972. node_get_all_orports(const node_t *node)
  973. {
  974. smartlist_t *sl = smartlist_new();
  975. int valid = 0;
  976. /* Find a valid IPv4 address and port */
  977. if (node->ri != NULL) {
  978. SL_ADD_NEW_IPV4_AP(node->ri, or_port, sl, valid);
  979. }
  980. /* If we didn't find a valid address/port in the ri, try the rs */
  981. if (!valid && node->rs != NULL) {
  982. SL_ADD_NEW_IPV4_AP(node->rs, or_port, sl, valid);
  983. }
  984. /* Find a valid IPv6 address and port */
  985. valid = 0;
  986. if (node->ri != NULL) {
  987. SL_ADD_NEW_IPV6_AP(node->ri, ipv6_orport, sl, valid);
  988. }
  989. if (!valid && node->rs != NULL) {
  990. SL_ADD_NEW_IPV6_AP(node->rs, ipv6_orport, sl, valid);
  991. }
  992. if (!valid && node->md != NULL) {
  993. SL_ADD_NEW_IPV6_AP(node->md, ipv6_orport, sl, valid);
  994. }
  995. return sl;
  996. }
  997. #undef SL_ADD_NEW_IPV4_AP
  998. #undef SL_ADD_NEW_IPV6_AP
  999. /** Wrapper around node_get_prim_orport for backward
  1000. compatibility. */
  1001. void
  1002. node_get_addr(const node_t *node, tor_addr_t *addr_out)
  1003. {
  1004. tor_addr_port_t ap;
  1005. node_get_prim_orport(node, &ap);
  1006. tor_addr_copy(addr_out, &ap.addr);
  1007. }
  1008. /** Return the host-order IPv4 address for <b>node</b>, or 0 if it doesn't
  1009. * seem to have one. */
  1010. uint32_t
  1011. node_get_prim_addr_ipv4h(const node_t *node)
  1012. {
  1013. /* Don't check the ORPort or DirPort, as this function isn't port-specific,
  1014. * and the node might have a valid IPv4 address, yet have a zero
  1015. * ORPort or DirPort.
  1016. */
  1017. if (node->ri && tor_addr_is_valid_ipv4h(node->ri->addr, 0)) {
  1018. return node->ri->addr;
  1019. } else if (node->rs && tor_addr_is_valid_ipv4h(node->rs->addr, 0)) {
  1020. return node->rs->addr;
  1021. }
  1022. return 0;
  1023. }
  1024. /** Copy a string representation of an IP address for <b>node</b> into
  1025. * the <b>len</b>-byte buffer at <b>buf</b>. */
  1026. void
  1027. node_get_address_string(const node_t *node, char *buf, size_t len)
  1028. {
  1029. uint32_t ipv4_addr = node_get_prim_addr_ipv4h(node);
  1030. if (tor_addr_is_valid_ipv4h(ipv4_addr, 0)) {
  1031. tor_addr_t addr;
  1032. tor_addr_from_ipv4h(&addr, ipv4_addr);
  1033. tor_addr_to_str(buf, &addr, len, 0);
  1034. } else if (len > 0) {
  1035. buf[0] = '\0';
  1036. }
  1037. }
  1038. /** Return <b>node</b>'s declared uptime, or -1 if it doesn't seem to have
  1039. * one. */
  1040. long
  1041. node_get_declared_uptime(const node_t *node)
  1042. {
  1043. if (node->ri)
  1044. return node->ri->uptime;
  1045. else
  1046. return -1;
  1047. }
  1048. /** Return <b>node</b>'s platform string, or NULL if we don't know it. */
  1049. const char *
  1050. node_get_platform(const node_t *node)
  1051. {
  1052. /* If we wanted, we could record the version in the routerstatus_t, since
  1053. * the consensus lists it. We don't, though, so this function just won't
  1054. * work with microdescriptors. */
  1055. if (node->ri)
  1056. return node->ri->platform;
  1057. else
  1058. return NULL;
  1059. }
  1060. /** Return true iff <b>node</b> is one representing this router. */
  1061. int
  1062. node_is_me(const node_t *node)
  1063. {
  1064. return router_digest_is_me(node->identity);
  1065. }
  1066. /** Return <b>node</b> declared family (as a list of names), or NULL if
  1067. * the node didn't declare a family. */
  1068. const smartlist_t *
  1069. node_get_declared_family(const node_t *node)
  1070. {
  1071. if (node->ri && node->ri->declared_family)
  1072. return node->ri->declared_family;
  1073. else if (node->md && node->md->family)
  1074. return node->md->family;
  1075. else
  1076. return NULL;
  1077. }
  1078. /* Does this node have a valid IPv6 address?
  1079. * Prefer node_has_ipv6_orport() or node_has_ipv6_dirport() for
  1080. * checking specific ports. */
  1081. int
  1082. node_has_ipv6_addr(const node_t *node)
  1083. {
  1084. /* Don't check the ORPort or DirPort, as this function isn't port-specific,
  1085. * and the node might have a valid IPv6 address, yet have a zero
  1086. * ORPort or DirPort.
  1087. */
  1088. if (node->ri && tor_addr_is_valid(&node->ri->ipv6_addr, 0))
  1089. return 1;
  1090. if (node->rs && tor_addr_is_valid(&node->rs->ipv6_addr, 0))
  1091. return 1;
  1092. if (node->md && tor_addr_is_valid(&node->md->ipv6_addr, 0))
  1093. return 1;
  1094. return 0;
  1095. }
  1096. /* Does this node have a valid IPv6 ORPort? */
  1097. int
  1098. node_has_ipv6_orport(const node_t *node)
  1099. {
  1100. tor_addr_port_t ipv6_orport;
  1101. node_get_pref_ipv6_orport(node, &ipv6_orport);
  1102. return tor_addr_port_is_valid_ap(&ipv6_orport, 0);
  1103. }
  1104. /* Does this node have a valid IPv6 DirPort? */
  1105. int
  1106. node_has_ipv6_dirport(const node_t *node)
  1107. {
  1108. tor_addr_port_t ipv6_dirport;
  1109. node_get_pref_ipv6_dirport(node, &ipv6_dirport);
  1110. return tor_addr_port_is_valid_ap(&ipv6_dirport, 0);
  1111. }
  1112. /** Return 1 if we prefer the IPv6 address and OR TCP port of
  1113. * <b>node</b>, else 0.
  1114. *
  1115. * We prefer the IPv6 address if the router has an IPv6 address,
  1116. * and we can use IPv6 addresses, and:
  1117. * i) the node_t says that it prefers IPv6
  1118. * or
  1119. * ii) the router has no IPv4 OR address.
  1120. *
  1121. * If you don't have a node, consider looking it up.
  1122. * If there is no node, use fascist_firewall_prefer_ipv6_orport().
  1123. */
  1124. int
  1125. node_ipv6_or_preferred(const node_t *node)
  1126. {
  1127. const or_options_t *options = get_options();
  1128. tor_addr_port_t ipv4_addr;
  1129. node_assert_ok(node);
  1130. /* XX/teor - node->ipv6_preferred is set from
  1131. * fascist_firewall_prefer_ipv6_orport() each time the consensus is loaded.
  1132. */
  1133. if (!fascist_firewall_use_ipv6(options)) {
  1134. return 0;
  1135. } else if (node->ipv6_preferred || node_get_prim_orport(node, &ipv4_addr)) {
  1136. return node_has_ipv6_orport(node);
  1137. }
  1138. return 0;
  1139. }
  1140. #define RETURN_IPV4_AP(r, port_field, ap_out) \
  1141. STMT_BEGIN \
  1142. if (r && tor_addr_port_is_valid_ipv4h((r)->addr, (r)->port_field, 0)) { \
  1143. tor_addr_from_ipv4h(&(ap_out)->addr, (r)->addr); \
  1144. (ap_out)->port = (r)->port_field; \
  1145. return 0; \
  1146. } \
  1147. STMT_END
  1148. /** Copy the primary (IPv4) OR port (IP address and TCP port) for
  1149. * <b>node</b> into *<b>ap_out</b>. Return 0 if a valid address and
  1150. * port was copied, else return non-zero.*/
  1151. int
  1152. node_get_prim_orport(const node_t *node, tor_addr_port_t *ap_out)
  1153. {
  1154. node_assert_ok(node);
  1155. tor_assert(ap_out);
  1156. /* Check ri first, because rewrite_node_address_for_bridge() updates
  1157. * node->ri with the configured bridge address. */
  1158. RETURN_IPV4_AP(node->ri, or_port, ap_out);
  1159. RETURN_IPV4_AP(node->rs, or_port, ap_out);
  1160. /* Microdescriptors only have an IPv6 address */
  1161. return -1;
  1162. }
  1163. /** Copy the preferred OR port (IP address and TCP port) for
  1164. * <b>node</b> into *<b>ap_out</b>. */
  1165. void
  1166. node_get_pref_orport(const node_t *node, tor_addr_port_t *ap_out)
  1167. {
  1168. tor_assert(ap_out);
  1169. if (node_ipv6_or_preferred(node)) {
  1170. node_get_pref_ipv6_orport(node, ap_out);
  1171. } else {
  1172. /* the primary ORPort is always on IPv4 */
  1173. node_get_prim_orport(node, ap_out);
  1174. }
  1175. }
  1176. /** Copy the preferred IPv6 OR port (IP address and TCP port) for
  1177. * <b>node</b> into *<b>ap_out</b>. */
  1178. void
  1179. node_get_pref_ipv6_orport(const node_t *node, tor_addr_port_t *ap_out)
  1180. {
  1181. node_assert_ok(node);
  1182. tor_assert(ap_out);
  1183. /* Check ri first, because rewrite_node_address_for_bridge() updates
  1184. * node->ri with the configured bridge address.
  1185. * Prefer rs over md for consistency with the fascist_firewall_* functions.
  1186. * Check if the address or port are valid, and try another alternative
  1187. * if they are not. */
  1188. if (node->ri && tor_addr_port_is_valid(&node->ri->ipv6_addr,
  1189. node->ri->ipv6_orport, 0)) {
  1190. tor_addr_copy(&ap_out->addr, &node->ri->ipv6_addr);
  1191. ap_out->port = node->ri->ipv6_orport;
  1192. } else if (node->rs && tor_addr_port_is_valid(&node->rs->ipv6_addr,
  1193. node->rs->ipv6_orport, 0)) {
  1194. tor_addr_copy(&ap_out->addr, &node->rs->ipv6_addr);
  1195. ap_out->port = node->rs->ipv6_orport;
  1196. } else if (node->md && tor_addr_port_is_valid(&node->md->ipv6_addr,
  1197. node->md->ipv6_orport, 0)) {
  1198. tor_addr_copy(&ap_out->addr, &node->md->ipv6_addr);
  1199. ap_out->port = node->md->ipv6_orport;
  1200. } else {
  1201. tor_addr_make_null(&ap_out->addr, AF_INET6);
  1202. ap_out->port = 0;
  1203. }
  1204. }
  1205. /** Return 1 if we prefer the IPv6 address and Dir TCP port of
  1206. * <b>node</b>, else 0.
  1207. *
  1208. * We prefer the IPv6 address if the router has an IPv6 address,
  1209. * and we can use IPv6 addresses, and:
  1210. * i) the router has no IPv4 Dir address.
  1211. * or
  1212. * ii) our preference is for IPv6 Dir addresses.
  1213. *
  1214. * If there is no node, use fascist_firewall_prefer_ipv6_dirport().
  1215. */
  1216. int
  1217. node_ipv6_dir_preferred(const node_t *node)
  1218. {
  1219. const or_options_t *options = get_options();
  1220. tor_addr_port_t ipv4_addr;
  1221. node_assert_ok(node);
  1222. /* node->ipv6_preferred is set from fascist_firewall_prefer_ipv6_orport(),
  1223. * so we can't use it to determine DirPort IPv6 preference.
  1224. * This means that bridge clients will use IPv4 DirPorts by default.
  1225. */
  1226. if (!fascist_firewall_use_ipv6(options)) {
  1227. return 0;
  1228. } else if (node_get_prim_dirport(node, &ipv4_addr)
  1229. || fascist_firewall_prefer_ipv6_dirport(get_options())) {
  1230. return node_has_ipv6_dirport(node);
  1231. }
  1232. return 0;
  1233. }
  1234. /** Copy the primary (IPv4) Dir port (IP address and TCP port) for
  1235. * <b>node</b> into *<b>ap_out</b>. Return 0 if a valid address and
  1236. * port was copied, else return non-zero.*/
  1237. int
  1238. node_get_prim_dirport(const node_t *node, tor_addr_port_t *ap_out)
  1239. {
  1240. node_assert_ok(node);
  1241. tor_assert(ap_out);
  1242. /* Check ri first, because rewrite_node_address_for_bridge() updates
  1243. * node->ri with the configured bridge address. */
  1244. RETURN_IPV4_AP(node->ri, dir_port, ap_out);
  1245. RETURN_IPV4_AP(node->rs, dir_port, ap_out);
  1246. /* Microdescriptors only have an IPv6 address */
  1247. return -1;
  1248. }
  1249. #undef RETURN_IPV4_AP
  1250. /** Copy the preferred Dir port (IP address and TCP port) for
  1251. * <b>node</b> into *<b>ap_out</b>. */
  1252. void
  1253. node_get_pref_dirport(const node_t *node, tor_addr_port_t *ap_out)
  1254. {
  1255. tor_assert(ap_out);
  1256. if (node_ipv6_dir_preferred(node)) {
  1257. node_get_pref_ipv6_dirport(node, ap_out);
  1258. } else {
  1259. /* the primary DirPort is always on IPv4 */
  1260. node_get_prim_dirport(node, ap_out);
  1261. }
  1262. }
  1263. /** Copy the preferred IPv6 Dir port (IP address and TCP port) for
  1264. * <b>node</b> into *<b>ap_out</b>. */
  1265. void
  1266. node_get_pref_ipv6_dirport(const node_t *node, tor_addr_port_t *ap_out)
  1267. {
  1268. node_assert_ok(node);
  1269. tor_assert(ap_out);
  1270. /* Check ri first, because rewrite_node_address_for_bridge() updates
  1271. * node->ri with the configured bridge address.
  1272. * Prefer rs over md for consistency with the fascist_firewall_* functions.
  1273. * Check if the address or port are valid, and try another alternative
  1274. * if they are not. */
  1275. /* Assume IPv4 and IPv6 dirports are the same */
  1276. if (node->ri && tor_addr_port_is_valid(&node->ri->ipv6_addr,
  1277. node->ri->dir_port, 0)) {
  1278. tor_addr_copy(&ap_out->addr, &node->ri->ipv6_addr);
  1279. ap_out->port = node->ri->dir_port;
  1280. } else if (node->rs && tor_addr_port_is_valid(&node->rs->ipv6_addr,
  1281. node->rs->dir_port, 0)) {
  1282. tor_addr_copy(&ap_out->addr, &node->rs->ipv6_addr);
  1283. ap_out->port = node->rs->dir_port;
  1284. } else {
  1285. tor_addr_make_null(&ap_out->addr, AF_INET6);
  1286. ap_out->port = 0;
  1287. }
  1288. }
  1289. /** Return true iff <b>md</b> has a curve25519 onion key.
  1290. * Use node_has_curve25519_onion_key() instead of calling this directly. */
  1291. static int
  1292. microdesc_has_curve25519_onion_key(const microdesc_t *md)
  1293. {
  1294. if (!md) {
  1295. return 0;
  1296. }
  1297. if (!md->onion_curve25519_pkey) {
  1298. return 0;
  1299. }
  1300. if (tor_mem_is_zero((const char*)md->onion_curve25519_pkey->public_key,
  1301. CURVE25519_PUBKEY_LEN)) {
  1302. return 0;
  1303. }
  1304. return 1;
  1305. }
  1306. /** Return true iff <b>node</b> has a curve25519 onion key. */
  1307. int
  1308. node_has_curve25519_onion_key(const node_t *node)
  1309. {
  1310. if (!node)
  1311. return 0;
  1312. if (node->ri)
  1313. return routerinfo_has_curve25519_onion_key(node->ri);
  1314. else if (node->md)
  1315. return microdesc_has_curve25519_onion_key(node->md);
  1316. else
  1317. return 0;
  1318. }
  1319. /** Refresh the country code of <b>ri</b>. This function MUST be called on
  1320. * each router when the GeoIP database is reloaded, and on all new routers. */
  1321. void
  1322. node_set_country(node_t *node)
  1323. {
  1324. tor_addr_t addr = TOR_ADDR_NULL;
  1325. /* XXXXipv6 */
  1326. if (node->rs)
  1327. tor_addr_from_ipv4h(&addr, node->rs->addr);
  1328. else if (node->ri)
  1329. tor_addr_from_ipv4h(&addr, node->ri->addr);
  1330. node->country = geoip_get_country_by_addr(&addr);
  1331. }
  1332. /** Set the country code of all routers in the routerlist. */
  1333. void
  1334. nodelist_refresh_countries(void)
  1335. {
  1336. smartlist_t *nodes = nodelist_get_list();
  1337. SMARTLIST_FOREACH(nodes, node_t *, node,
  1338. node_set_country(node));
  1339. }
  1340. /** Return true iff router1 and router2 have similar enough network addresses
  1341. * that we should treat them as being in the same family */
  1342. int
  1343. addrs_in_same_network_family(const tor_addr_t *a1,
  1344. const tor_addr_t *a2)
  1345. {
  1346. return 0 == tor_addr_compare_masked(a1, a2, 16, CMP_SEMANTIC);
  1347. }
  1348. /** Return true if <b>node</b>'s nickname matches <b>nickname</b>
  1349. * (case-insensitive), or if <b>node's</b> identity key digest
  1350. * matches a hexadecimal value stored in <b>nickname</b>. Return
  1351. * false otherwise. */
  1352. static int
  1353. node_nickname_matches(const node_t *node, const char *nickname)
  1354. {
  1355. const char *n = node_get_nickname(node);
  1356. if (n && nickname[0]!='$' && !strcasecmp(n, nickname))
  1357. return 1;
  1358. return hex_digest_nickname_matches(nickname,
  1359. node->identity,
  1360. n,
  1361. node_is_named(node));
  1362. }
  1363. /** Return true iff <b>node</b> is named by some nickname in <b>lst</b>. */
  1364. static inline int
  1365. node_in_nickname_smartlist(const smartlist_t *lst, const node_t *node)
  1366. {
  1367. if (!lst) return 0;
  1368. SMARTLIST_FOREACH(lst, const char *, name, {
  1369. if (node_nickname_matches(node, name))
  1370. return 1;
  1371. });
  1372. return 0;
  1373. }
  1374. /** Return true iff r1 and r2 are in the same family, but not the same
  1375. * router. */
  1376. int
  1377. nodes_in_same_family(const node_t *node1, const node_t *node2)
  1378. {
  1379. const or_options_t *options = get_options();
  1380. /* Are they in the same family because of their addresses? */
  1381. if (options->EnforceDistinctSubnets) {
  1382. tor_addr_t a1, a2;
  1383. node_get_addr(node1, &a1);
  1384. node_get_addr(node2, &a2);
  1385. if (addrs_in_same_network_family(&a1, &a2))
  1386. return 1;
  1387. }
  1388. /* Are they in the same family because the agree they are? */
  1389. {
  1390. const smartlist_t *f1, *f2;
  1391. f1 = node_get_declared_family(node1);
  1392. f2 = node_get_declared_family(node2);
  1393. if (f1 && f2 &&
  1394. node_in_nickname_smartlist(f1, node2) &&
  1395. node_in_nickname_smartlist(f2, node1))
  1396. return 1;
  1397. }
  1398. /* Are they in the same option because the user says they are? */
  1399. if (options->NodeFamilySets) {
  1400. SMARTLIST_FOREACH(options->NodeFamilySets, const routerset_t *, rs, {
  1401. if (routerset_contains_node(rs, node1) &&
  1402. routerset_contains_node(rs, node2))
  1403. return 1;
  1404. });
  1405. }
  1406. return 0;
  1407. }
  1408. /**
  1409. * Add all the family of <b>node</b>, including <b>node</b> itself, to
  1410. * the smartlist <b>sl</b>.
  1411. *
  1412. * This is used to make sure we don't pick siblings in a single path, or
  1413. * pick more than one relay from a family for our entry guard list.
  1414. * Note that a node may be added to <b>sl</b> more than once if it is
  1415. * part of <b>node</b>'s family for more than one reason.
  1416. */
  1417. void
  1418. nodelist_add_node_and_family(smartlist_t *sl, const node_t *node)
  1419. {
  1420. const smartlist_t *all_nodes = nodelist_get_list();
  1421. const smartlist_t *declared_family;
  1422. const or_options_t *options = get_options();
  1423. tor_assert(node);
  1424. declared_family = node_get_declared_family(node);
  1425. /* Let's make sure that we have the node itself, if it's a real node. */
  1426. {
  1427. const node_t *real_node = node_get_by_id(node->identity);
  1428. if (real_node)
  1429. smartlist_add(sl, (node_t*)real_node);
  1430. }
  1431. /* First, add any nodes with similar network addresses. */
  1432. if (options->EnforceDistinctSubnets) {
  1433. tor_addr_t node_addr;
  1434. node_get_addr(node, &node_addr);
  1435. SMARTLIST_FOREACH_BEGIN(all_nodes, const node_t *, node2) {
  1436. tor_addr_t a;
  1437. node_get_addr(node2, &a);
  1438. if (addrs_in_same_network_family(&a, &node_addr))
  1439. smartlist_add(sl, (void*)node2);
  1440. } SMARTLIST_FOREACH_END(node2);
  1441. }
  1442. /* Now, add all nodes in the declared_family of this node, if they
  1443. * also declare this node to be in their family. */
  1444. if (declared_family) {
  1445. /* Add every r such that router declares familyness with node, and node
  1446. * declares familyhood with router. */
  1447. SMARTLIST_FOREACH_BEGIN(declared_family, const char *, name) {
  1448. const node_t *node2;
  1449. const smartlist_t *family2;
  1450. if (!(node2 = node_get_by_nickname(name, 0)))
  1451. continue;
  1452. if (!(family2 = node_get_declared_family(node2)))
  1453. continue;
  1454. SMARTLIST_FOREACH_BEGIN(family2, const char *, name2) {
  1455. if (node_nickname_matches(node, name2)) {
  1456. smartlist_add(sl, (void*)node2);
  1457. break;
  1458. }
  1459. } SMARTLIST_FOREACH_END(name2);
  1460. } SMARTLIST_FOREACH_END(name);
  1461. }
  1462. /* If the user declared any families locally, honor those too. */
  1463. if (options->NodeFamilySets) {
  1464. SMARTLIST_FOREACH(options->NodeFamilySets, const routerset_t *, rs, {
  1465. if (routerset_contains_node(rs, node)) {
  1466. routerset_get_all_nodes(sl, rs, NULL, 0);
  1467. }
  1468. });
  1469. }
  1470. }
  1471. /** Find a router that's up, that has this IP address, and
  1472. * that allows exit to this address:port, or return NULL if there
  1473. * isn't a good one.
  1474. * Don't exit enclave to excluded relays -- it wouldn't actually
  1475. * hurt anything, but this way there are fewer confused users.
  1476. */
  1477. const node_t *
  1478. router_find_exact_exit_enclave(const char *address, uint16_t port)
  1479. {/*XXXX MOVE*/
  1480. uint32_t addr;
  1481. struct in_addr in;
  1482. tor_addr_t a;
  1483. const or_options_t *options = get_options();
  1484. if (!tor_inet_aton(address, &in))
  1485. return NULL; /* it's not an IP already */
  1486. addr = ntohl(in.s_addr);
  1487. tor_addr_from_ipv4h(&a, addr);
  1488. SMARTLIST_FOREACH(nodelist_get_list(), const node_t *, node, {
  1489. if (node_get_addr_ipv4h(node) == addr &&
  1490. node->is_running &&
  1491. compare_tor_addr_to_node_policy(&a, port, node) ==
  1492. ADDR_POLICY_ACCEPTED &&
  1493. !routerset_contains_node(options->ExcludeExitNodesUnion_, node))
  1494. return node;
  1495. });
  1496. return NULL;
  1497. }
  1498. /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
  1499. * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
  1500. * If <b>need_capacity</b> is non-zero, we require a minimum advertised
  1501. * bandwidth.
  1502. * If <b>need_guard</b>, we require that the router is a possible entry guard.
  1503. */
  1504. int
  1505. node_is_unreliable(const node_t *node, int need_uptime,
  1506. int need_capacity, int need_guard)
  1507. {
  1508. if (need_uptime && !node->is_stable)
  1509. return 1;
  1510. if (need_capacity && !node->is_fast)
  1511. return 1;
  1512. if (need_guard && !node->is_possible_guard)
  1513. return 1;
  1514. return 0;
  1515. }
  1516. /** Return 1 if all running sufficiently-stable routers we can use will reject
  1517. * addr:port. Return 0 if any might accept it. */
  1518. int
  1519. router_exit_policy_all_nodes_reject(const tor_addr_t *addr, uint16_t port,
  1520. int need_uptime)
  1521. {
  1522. addr_policy_result_t r;
  1523. SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), const node_t *, node) {
  1524. if (node->is_running &&
  1525. !node_is_unreliable(node, need_uptime, 0, 0)) {
  1526. r = compare_tor_addr_to_node_policy(addr, port, node);
  1527. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  1528. return 0; /* this one could be ok. good enough. */
  1529. }
  1530. } SMARTLIST_FOREACH_END(node);
  1531. return 1; /* all will reject. */
  1532. }
  1533. /** Mark the router with ID <b>digest</b> as running or non-running
  1534. * in our routerlist. */
  1535. void
  1536. router_set_status(const char *digest, int up)
  1537. {
  1538. node_t *node;
  1539. tor_assert(digest);
  1540. SMARTLIST_FOREACH(router_get_fallback_dir_servers(),
  1541. dir_server_t *, d,
  1542. if (tor_memeq(d->digest, digest, DIGEST_LEN))
  1543. d->is_running = up);
  1544. SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
  1545. dir_server_t *, d,
  1546. if (tor_memeq(d->digest, digest, DIGEST_LEN))
  1547. d->is_running = up);
  1548. node = node_get_mutable_by_id(digest);
  1549. if (node) {
  1550. #if 0
  1551. log_debug(LD_DIR,"Marking router %s as %s.",
  1552. node_describe(node), up ? "up" : "down");
  1553. #endif
  1554. if (!up && node_is_me(node) && !net_is_disabled())
  1555. log_warn(LD_NET, "We just marked ourself as down. Are your external "
  1556. "addresses reachable?");
  1557. if (bool_neq(node->is_running, up))
  1558. router_dir_info_changed();
  1559. node->is_running = up;
  1560. }
  1561. }
  1562. /** True iff, the last time we checked whether we had enough directory info
  1563. * to build circuits, the answer was "yes". If there are no exits in the
  1564. * consensus, we act as if we have 100% of the exit directory info. */
  1565. static int have_min_dir_info = 0;
  1566. /** Does the consensus contain nodes that can exit? */
  1567. static consensus_path_type_t have_consensus_path = CONSENSUS_PATH_UNKNOWN;
  1568. /** True iff enough has changed since the last time we checked whether we had
  1569. * enough directory info to build circuits that our old answer can no longer
  1570. * be trusted. */
  1571. static int need_to_update_have_min_dir_info = 1;
  1572. /** String describing what we're missing before we have enough directory
  1573. * info. */
  1574. static char dir_info_status[512] = "";
  1575. /** Return true iff we have enough consensus information to
  1576. * start building circuits. Right now, this means "a consensus that's
  1577. * less than a day old, and at least 60% of router descriptors (configurable),
  1578. * weighted by bandwidth. Treat the exit fraction as 100% if there are
  1579. * no exits in the consensus."
  1580. * To obtain the final weighted bandwidth, we multiply the
  1581. * weighted bandwidth fraction for each position (guard, middle, exit). */
  1582. MOCK_IMPL(int,
  1583. router_have_minimum_dir_info,(void))
  1584. {
  1585. static int logged_delay=0;
  1586. const char *delay_fetches_msg = NULL;
  1587. if (should_delay_dir_fetches(get_options(), &delay_fetches_msg)) {
  1588. if (!logged_delay)
  1589. log_notice(LD_DIR, "Delaying directory fetches: %s", delay_fetches_msg);
  1590. logged_delay=1;
  1591. strlcpy(dir_info_status, delay_fetches_msg, sizeof(dir_info_status));
  1592. return 0;
  1593. }
  1594. logged_delay = 0; /* reset it if we get this far */
  1595. if (PREDICT_UNLIKELY(need_to_update_have_min_dir_info)) {
  1596. update_router_have_minimum_dir_info();
  1597. }
  1598. return have_min_dir_info;
  1599. }
  1600. /** Set to CONSENSUS_PATH_EXIT if there is at least one exit node
  1601. * in the consensus. We update this flag in compute_frac_paths_available if
  1602. * there is at least one relay that has an Exit flag in the consensus.
  1603. * Used to avoid building exit circuits when they will almost certainly fail.
  1604. * Set to CONSENSUS_PATH_INTERNAL if there are no exits in the consensus.
  1605. * (This situation typically occurs during bootstrap of a test network.)
  1606. * Set to CONSENSUS_PATH_UNKNOWN if we have never checked, or have
  1607. * reason to believe our last known value was invalid or has expired.
  1608. * If we're in a network with TestingDirAuthVoteExit set,
  1609. * this can cause router_have_consensus_path() to be set to
  1610. * CONSENSUS_PATH_EXIT, even if there are no nodes with accept exit policies.
  1611. */
  1612. MOCK_IMPL(consensus_path_type_t,
  1613. router_have_consensus_path, (void))
  1614. {
  1615. return have_consensus_path;
  1616. }
  1617. /** Called when our internal view of the directory has changed. This can be
  1618. * when the authorities change, networkstatuses change, the list of routerdescs
  1619. * changes, or number of running routers changes.
  1620. */
  1621. void
  1622. router_dir_info_changed(void)
  1623. {
  1624. need_to_update_have_min_dir_info = 1;
  1625. rend_hsdir_routers_changed();
  1626. hs_hsdir_set_changed_consider_reupload();
  1627. }
  1628. /** Return a string describing what we're missing before we have enough
  1629. * directory info. */
  1630. const char *
  1631. get_dir_info_status_string(void)
  1632. {
  1633. return dir_info_status;
  1634. }
  1635. /** Iterate over the servers listed in <b>consensus</b>, and count how many of
  1636. * them seem like ones we'd use (store this in *<b>num_usable</b>), and how
  1637. * many of <em>those</em> we have descriptors for (store this in
  1638. * *<b>num_present</b>).
  1639. *
  1640. * If <b>in_set</b> is non-NULL, only consider those routers in <b>in_set</b>.
  1641. * If <b>exit_only</b> is USABLE_DESCRIPTOR_EXIT_ONLY, only consider nodes
  1642. * with the Exit flag.
  1643. * If *<b>descs_out</b> is present, add a node_t for each usable descriptor
  1644. * to it.
  1645. */
  1646. static void
  1647. count_usable_descriptors(int *num_present, int *num_usable,
  1648. smartlist_t *descs_out,
  1649. const networkstatus_t *consensus,
  1650. time_t now,
  1651. routerset_t *in_set,
  1652. usable_descriptor_t exit_only)
  1653. {
  1654. const int md = (consensus->flavor == FLAV_MICRODESC);
  1655. *num_present = 0, *num_usable = 0;
  1656. SMARTLIST_FOREACH_BEGIN(consensus->routerstatus_list, routerstatus_t *, rs)
  1657. {
  1658. const node_t *node = node_get_by_id(rs->identity_digest);
  1659. if (!node)
  1660. continue; /* This would be a bug: every entry in the consensus is
  1661. * supposed to have a node. */
  1662. if (exit_only == USABLE_DESCRIPTOR_EXIT_ONLY && ! rs->is_exit)
  1663. continue;
  1664. if (in_set && ! routerset_contains_routerstatus(in_set, rs, -1))
  1665. continue;
  1666. if (client_would_use_router(rs, now)) {
  1667. const char * const digest = rs->descriptor_digest;
  1668. int present;
  1669. ++*num_usable; /* the consensus says we want it. */
  1670. if (md)
  1671. present = NULL != microdesc_cache_lookup_by_digest256(NULL, digest);
  1672. else
  1673. present = NULL != router_get_by_descriptor_digest(digest);
  1674. if (present) {
  1675. /* we have the descriptor listed in the consensus. */
  1676. ++*num_present;
  1677. }
  1678. if (descs_out)
  1679. smartlist_add(descs_out, (node_t*)node);
  1680. }
  1681. }
  1682. SMARTLIST_FOREACH_END(rs);
  1683. log_debug(LD_DIR, "%d usable, %d present (%s%s).",
  1684. *num_usable, *num_present,
  1685. md ? "microdesc" : "desc",
  1686. exit_only == USABLE_DESCRIPTOR_EXIT_ONLY ? " exits" : "s");
  1687. }
  1688. /** Return an estimate of which fraction of usable paths through the Tor
  1689. * network we have available for use. Count how many routers seem like ones
  1690. * we'd use (store this in *<b>num_usable_out</b>), and how many of
  1691. * <em>those</em> we have descriptors for (store this in
  1692. * *<b>num_present_out</b>.)
  1693. *
  1694. * If **<b>status_out</b> is present, allocate a new string and print the
  1695. * available percentages of guard, middle, and exit nodes to it, noting
  1696. * whether there are exits in the consensus.
  1697. * If there are no exits in the consensus, we treat the exit fraction as 100%,
  1698. * but set router_have_consensus_path() so that we can only build internal
  1699. * paths. */
  1700. static double
  1701. compute_frac_paths_available(const networkstatus_t *consensus,
  1702. const or_options_t *options, time_t now,
  1703. int *num_present_out, int *num_usable_out,
  1704. char **status_out)
  1705. {
  1706. smartlist_t *guards = smartlist_new();
  1707. smartlist_t *mid = smartlist_new();
  1708. smartlist_t *exits = smartlist_new();
  1709. double f_guard, f_mid, f_exit;
  1710. double f_path = 0.0;
  1711. /* Used to determine whether there are any exits in the consensus */
  1712. int np = 0;
  1713. /* Used to determine whether there are any exits with descriptors */
  1714. int nu = 0;
  1715. const int authdir = authdir_mode_v3(options);
  1716. count_usable_descriptors(num_present_out, num_usable_out,
  1717. mid, consensus, now, NULL,
  1718. USABLE_DESCRIPTOR_ALL);
  1719. if (options->EntryNodes) {
  1720. count_usable_descriptors(&np, &nu, guards, consensus, now,
  1721. options->EntryNodes, USABLE_DESCRIPTOR_ALL);
  1722. } else {
  1723. SMARTLIST_FOREACH(mid, const node_t *, node, {
  1724. if (authdir) {
  1725. if (node->rs && node->rs->is_possible_guard)
  1726. smartlist_add(guards, (node_t*)node);
  1727. } else {
  1728. if (node->is_possible_guard)
  1729. smartlist_add(guards, (node_t*)node);
  1730. }
  1731. });
  1732. }
  1733. /* All nodes with exit flag
  1734. * If we're in a network with TestingDirAuthVoteExit set,
  1735. * this can cause false positives on have_consensus_path,
  1736. * incorrectly setting it to CONSENSUS_PATH_EXIT. This is
  1737. * an unavoidable feature of forcing authorities to declare
  1738. * certain nodes as exits.
  1739. */
  1740. count_usable_descriptors(&np, &nu, exits, consensus, now,
  1741. NULL, USABLE_DESCRIPTOR_EXIT_ONLY);
  1742. log_debug(LD_NET,
  1743. "%s: %d present, %d usable",
  1744. "exits",
  1745. np,
  1746. nu);
  1747. /* We need at least 1 exit present in the consensus to consider
  1748. * building exit paths */
  1749. /* Update our understanding of whether the consensus has exits */
  1750. consensus_path_type_t old_have_consensus_path = have_consensus_path;
  1751. have_consensus_path = ((nu > 0) ?
  1752. CONSENSUS_PATH_EXIT :
  1753. CONSENSUS_PATH_INTERNAL);
  1754. if (have_consensus_path == CONSENSUS_PATH_INTERNAL
  1755. && old_have_consensus_path != have_consensus_path) {
  1756. log_notice(LD_NET,
  1757. "The current consensus has no exit nodes. "
  1758. "Tor can only build internal paths, "
  1759. "such as paths to hidden services.");
  1760. /* However, exit nodes can reachability self-test using this consensus,
  1761. * join the network, and appear in a later consensus. This will allow
  1762. * the network to build exit paths, such as paths for world wide web
  1763. * browsing (as distinct from hidden service web browsing). */
  1764. }
  1765. f_guard = frac_nodes_with_descriptors(guards, WEIGHT_FOR_GUARD);
  1766. f_mid = frac_nodes_with_descriptors(mid, WEIGHT_FOR_MID);
  1767. f_exit = frac_nodes_with_descriptors(exits, WEIGHT_FOR_EXIT);
  1768. log_debug(LD_NET,
  1769. "f_guard: %.2f, f_mid: %.2f, f_exit: %.2f",
  1770. f_guard,
  1771. f_mid,
  1772. f_exit);
  1773. smartlist_free(guards);
  1774. smartlist_free(mid);
  1775. smartlist_free(exits);
  1776. if (options->ExitNodes) {
  1777. double f_myexit, f_myexit_unflagged;
  1778. smartlist_t *myexits= smartlist_new();
  1779. smartlist_t *myexits_unflagged = smartlist_new();
  1780. /* All nodes with exit flag in ExitNodes option */
  1781. count_usable_descriptors(&np, &nu, myexits, consensus, now,
  1782. options->ExitNodes, USABLE_DESCRIPTOR_EXIT_ONLY);
  1783. log_debug(LD_NET,
  1784. "%s: %d present, %d usable",
  1785. "myexits",
  1786. np,
  1787. nu);
  1788. /* Now compute the nodes in the ExitNodes option where which we don't know
  1789. * what their exit policy is, or we know it permits something. */
  1790. count_usable_descriptors(&np, &nu, myexits_unflagged,
  1791. consensus, now,
  1792. options->ExitNodes, USABLE_DESCRIPTOR_ALL);
  1793. log_debug(LD_NET,
  1794. "%s: %d present, %d usable",
  1795. "myexits_unflagged (initial)",
  1796. np,
  1797. nu);
  1798. SMARTLIST_FOREACH_BEGIN(myexits_unflagged, const node_t *, node) {
  1799. if (node_has_descriptor(node) && node_exit_policy_rejects_all(node)) {
  1800. SMARTLIST_DEL_CURRENT(myexits_unflagged, node);
  1801. /* this node is not actually an exit */
  1802. np--;
  1803. /* this node is unusable as an exit */
  1804. nu--;
  1805. }
  1806. } SMARTLIST_FOREACH_END(node);
  1807. log_debug(LD_NET,
  1808. "%s: %d present, %d usable",
  1809. "myexits_unflagged (final)",
  1810. np,
  1811. nu);
  1812. f_myexit= frac_nodes_with_descriptors(myexits,WEIGHT_FOR_EXIT);
  1813. f_myexit_unflagged=
  1814. frac_nodes_with_descriptors(myexits_unflagged,WEIGHT_FOR_EXIT);
  1815. log_debug(LD_NET,
  1816. "f_exit: %.2f, f_myexit: %.2f, f_myexit_unflagged: %.2f",
  1817. f_exit,
  1818. f_myexit,
  1819. f_myexit_unflagged);
  1820. /* If our ExitNodes list has eliminated every possible Exit node, and there
  1821. * were some possible Exit nodes, then instead consider nodes that permit
  1822. * exiting to some ports. */
  1823. if (smartlist_len(myexits) == 0 &&
  1824. smartlist_len(myexits_unflagged)) {
  1825. f_myexit = f_myexit_unflagged;
  1826. }
  1827. smartlist_free(myexits);
  1828. smartlist_free(myexits_unflagged);
  1829. /* This is a tricky point here: we don't want to make it easy for a
  1830. * directory to trickle exits to us until it learns which exits we have
  1831. * configured, so require that we have a threshold both of total exits
  1832. * and usable exits. */
  1833. if (f_myexit < f_exit)
  1834. f_exit = f_myexit;
  1835. }
  1836. /* if the consensus has no exits, treat the exit fraction as 100% */
  1837. if (router_have_consensus_path() != CONSENSUS_PATH_EXIT) {
  1838. f_exit = 1.0;
  1839. }
  1840. f_path = f_guard * f_mid * f_exit;
  1841. if (status_out)
  1842. tor_asprintf(status_out,
  1843. "%d%% of guards bw, "
  1844. "%d%% of midpoint bw, and "
  1845. "%d%% of exit bw%s = "
  1846. "%d%% of path bw",
  1847. (int)(f_guard*100),
  1848. (int)(f_mid*100),
  1849. (int)(f_exit*100),
  1850. (router_have_consensus_path() == CONSENSUS_PATH_EXIT ?
  1851. "" :
  1852. " (no exits in consensus)"),
  1853. (int)(f_path*100));
  1854. return f_path;
  1855. }
  1856. /** We just fetched a new set of descriptors. Compute how far through
  1857. * the "loading descriptors" bootstrapping phase we are, so we can inform
  1858. * the controller of our progress. */
  1859. int
  1860. count_loading_descriptors_progress(void)
  1861. {
  1862. int num_present = 0, num_usable=0;
  1863. time_t now = time(NULL);
  1864. const or_options_t *options = get_options();
  1865. const networkstatus_t *consensus =
  1866. networkstatus_get_reasonably_live_consensus(now,usable_consensus_flavor());
  1867. double paths, fraction;
  1868. if (!consensus)
  1869. return 0; /* can't count descriptors if we have no list of them */
  1870. paths = compute_frac_paths_available(consensus, options, now,
  1871. &num_present, &num_usable,
  1872. NULL);
  1873. fraction = paths / get_frac_paths_needed_for_circs(options,consensus);
  1874. if (fraction > 1.0)
  1875. return 0; /* it's not the number of descriptors holding us back */
  1876. return BOOTSTRAP_STATUS_LOADING_DESCRIPTORS + (int)
  1877. (fraction*(BOOTSTRAP_STATUS_CONN_OR-1 -
  1878. BOOTSTRAP_STATUS_LOADING_DESCRIPTORS));
  1879. }
  1880. /** Return the fraction of paths needed before we're willing to build
  1881. * circuits, as configured in <b>options</b>, or in the consensus <b>ns</b>. */
  1882. static double
  1883. get_frac_paths_needed_for_circs(const or_options_t *options,
  1884. const networkstatus_t *ns)
  1885. {
  1886. #define DFLT_PCT_USABLE_NEEDED 60
  1887. if (options->PathsNeededToBuildCircuits >= 0.0) {
  1888. return options->PathsNeededToBuildCircuits;
  1889. } else {
  1890. return networkstatus_get_param(ns, "min_paths_for_circs_pct",
  1891. DFLT_PCT_USABLE_NEEDED,
  1892. 25, 95)/100.0;
  1893. }
  1894. }
  1895. /** Change the value of have_min_dir_info, setting it true iff we have enough
  1896. * network and router information to build circuits. Clear the value of
  1897. * need_to_update_have_min_dir_info. */
  1898. static void
  1899. update_router_have_minimum_dir_info(void)
  1900. {
  1901. time_t now = time(NULL);
  1902. int res;
  1903. const or_options_t *options = get_options();
  1904. const networkstatus_t *consensus =
  1905. networkstatus_get_reasonably_live_consensus(now,usable_consensus_flavor());
  1906. int using_md;
  1907. if (!consensus) {
  1908. if (!networkstatus_get_latest_consensus())
  1909. strlcpy(dir_info_status, "We have no usable consensus.",
  1910. sizeof(dir_info_status));
  1911. else
  1912. strlcpy(dir_info_status, "We have no recent usable consensus.",
  1913. sizeof(dir_info_status));
  1914. res = 0;
  1915. goto done;
  1916. }
  1917. using_md = consensus->flavor == FLAV_MICRODESC;
  1918. if (! entry_guards_have_enough_dir_info_to_build_circuits()) {
  1919. strlcpy(dir_info_status, "We're missing descriptors for some of our "
  1920. "primary entry guards", sizeof(dir_info_status));
  1921. res = 0;
  1922. goto done;
  1923. }
  1924. /* Check fraction of available paths */
  1925. {
  1926. char *status = NULL;
  1927. int num_present=0, num_usable=0;
  1928. double paths = compute_frac_paths_available(consensus, options, now,
  1929. &num_present, &num_usable,
  1930. &status);
  1931. if (paths < get_frac_paths_needed_for_circs(options,consensus)) {
  1932. tor_snprintf(dir_info_status, sizeof(dir_info_status),
  1933. "We need more %sdescriptors: we have %d/%d, and "
  1934. "can only build %d%% of likely paths. (We have %s.)",
  1935. using_md?"micro":"", num_present, num_usable,
  1936. (int)(paths*100), status);
  1937. tor_free(status);
  1938. res = 0;
  1939. control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS, 0);
  1940. goto done;
  1941. }
  1942. tor_free(status);
  1943. res = 1;
  1944. }
  1945. done:
  1946. /* If paths have just become available in this update. */
  1947. if (res && !have_min_dir_info) {
  1948. control_event_client_status(LOG_NOTICE, "ENOUGH_DIR_INFO");
  1949. if (control_event_bootstrap(BOOTSTRAP_STATUS_CONN_OR, 0) == 0) {
  1950. log_notice(LD_DIR,
  1951. "We now have enough directory information to build circuits.");
  1952. }
  1953. }
  1954. /* If paths have just become unavailable in this update. */
  1955. if (!res && have_min_dir_info) {
  1956. int quiet = directory_too_idle_to_fetch_descriptors(options, now);
  1957. tor_log(quiet ? LOG_INFO : LOG_NOTICE, LD_DIR,
  1958. "Our directory information is no longer up-to-date "
  1959. "enough to build circuits: %s", dir_info_status);
  1960. /* a) make us log when we next complete a circuit, so we know when Tor
  1961. * is back up and usable, and b) disable some activities that Tor
  1962. * should only do while circuits are working, like reachability tests
  1963. * and fetching bridge descriptors only over circuits. */
  1964. note_that_we_maybe_cant_complete_circuits();
  1965. have_consensus_path = CONSENSUS_PATH_UNKNOWN;
  1966. control_event_client_status(LOG_NOTICE, "NOT_ENOUGH_DIR_INFO");
  1967. }
  1968. have_min_dir_info = res;
  1969. need_to_update_have_min_dir_info = 0;
  1970. }