nodelist.c 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770
  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-2019, 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. #define NODELIST_PRIVATE
  40. #include "core/or/or.h"
  41. #include "app/config/config.h"
  42. #include "core/mainloop/mainloop.h"
  43. #include "core/mainloop/netstatus.h"
  44. #include "core/or/address_set.h"
  45. #include "core/or/policies.h"
  46. #include "core/or/protover.h"
  47. #include "feature/client/bridges.h"
  48. #include "feature/client/entrynodes.h"
  49. #include "feature/control/control_events.h"
  50. #include "feature/dirauth/process_descs.h"
  51. #include "feature/dircache/dirserv.h"
  52. #include "feature/hs/hs_client.h"
  53. #include "feature/hs/hs_common.h"
  54. #include "feature/nodelist/describe.h"
  55. #include "feature/nodelist/dirlist.h"
  56. #include "feature/nodelist/microdesc.h"
  57. #include "feature/nodelist/networkstatus.h"
  58. #include "feature/nodelist/node_select.h"
  59. #include "feature/nodelist/nodefamily.h"
  60. #include "feature/nodelist/nodelist.h"
  61. #include "feature/nodelist/routerlist.h"
  62. #include "feature/nodelist/routerset.h"
  63. #include "feature/nodelist/torcert.h"
  64. #include "feature/rend/rendservice.h"
  65. #include "lib/encoding/binascii.h"
  66. #include "lib/err/backtrace.h"
  67. #include "lib/geoip/geoip.h"
  68. #include "lib/net/address.h"
  69. #include <string.h>
  70. #include "feature/dirauth/authmode.h"
  71. #include "feature/dirclient/dir_server_st.h"
  72. #include "feature/nodelist/microdesc_st.h"
  73. #include "feature/nodelist/networkstatus_st.h"
  74. #include "feature/nodelist/node_st.h"
  75. #include "feature/nodelist/routerinfo_st.h"
  76. #include "feature/nodelist/routerlist_st.h"
  77. #include "feature/nodelist/routerstatus_st.h"
  78. static void nodelist_drop_node(node_t *node, int remove_from_ht);
  79. #define node_free(val) \
  80. FREE_AND_NULL(node_t, node_free_, (val))
  81. static void node_free_(node_t *node);
  82. /** count_usable_descriptors counts descriptors with these flag(s)
  83. */
  84. typedef enum {
  85. /* All descriptors regardless of flags or exit policies */
  86. USABLE_DESCRIPTOR_ALL = 0U,
  87. /* Only count descriptors with an exit policy that allows at least one port
  88. */
  89. USABLE_DESCRIPTOR_EXIT_POLICY = 1U << 0,
  90. /* Only count descriptors for relays that have the exit flag in the
  91. * consensus */
  92. USABLE_DESCRIPTOR_EXIT_FLAG = 1U << 1,
  93. /* Only count descriptors for relays that have the policy and the flag */
  94. USABLE_DESCRIPTOR_EXIT_POLICY_AND_FLAG = (USABLE_DESCRIPTOR_EXIT_POLICY |
  95. USABLE_DESCRIPTOR_EXIT_FLAG)
  96. } usable_descriptor_t;
  97. static void count_usable_descriptors(int *num_present,
  98. int *num_usable,
  99. smartlist_t *descs_out,
  100. const networkstatus_t *consensus,
  101. time_t now,
  102. routerset_t *in_set,
  103. usable_descriptor_t exit_only);
  104. static void update_router_have_minimum_dir_info(void);
  105. static double get_frac_paths_needed_for_circs(const or_options_t *options,
  106. const networkstatus_t *ns);
  107. static void node_add_to_address_set(const node_t *node);
  108. /** A nodelist_t holds a node_t object for every router we're "willing to use
  109. * for something". Specifically, it should hold a node_t for every node that
  110. * is currently in the routerlist, or currently in the consensus we're using.
  111. */
  112. typedef struct nodelist_t {
  113. /* A list of all the nodes. */
  114. smartlist_t *nodes;
  115. /* Hash table to map from node ID digest to node. */
  116. HT_HEAD(nodelist_map, node_t) nodes_by_id;
  117. /* Hash table to map from node Ed25519 ID to node.
  118. *
  119. * Whenever a node's routerinfo or microdescriptor is about to change,
  120. * you should remove it from this map with node_remove_from_ed25519_map().
  121. * Whenever a node's routerinfo or microdescriptor has just chaned,
  122. * you should add it to this map with node_add_to_ed25519_map().
  123. */
  124. HT_HEAD(nodelist_ed_map, node_t) nodes_by_ed_id;
  125. /* Set of addresses that belong to nodes we believe in. */
  126. address_set_t *node_addrs;
  127. /* The valid-after time of the last live consensus that initialized the
  128. * nodelist. We use this to detect outdated nodelists that need to be
  129. * rebuilt using a newer consensus. */
  130. time_t live_consensus_valid_after;
  131. } nodelist_t;
  132. static inline unsigned int
  133. node_id_hash(const node_t *node)
  134. {
  135. return (unsigned) siphash24g(node->identity, DIGEST_LEN);
  136. }
  137. static inline unsigned int
  138. node_id_eq(const node_t *node1, const node_t *node2)
  139. {
  140. return tor_memeq(node1->identity, node2->identity, DIGEST_LEN);
  141. }
  142. HT_PROTOTYPE(nodelist_map, node_t, ht_ent, node_id_hash, node_id_eq)
  143. HT_GENERATE2(nodelist_map, node_t, ht_ent, node_id_hash, node_id_eq,
  144. 0.6, tor_reallocarray_, tor_free_)
  145. static inline unsigned int
  146. node_ed_id_hash(const node_t *node)
  147. {
  148. return (unsigned) siphash24g(node->ed25519_id.pubkey, ED25519_PUBKEY_LEN);
  149. }
  150. static inline unsigned int
  151. node_ed_id_eq(const node_t *node1, const node_t *node2)
  152. {
  153. return ed25519_pubkey_eq(&node1->ed25519_id, &node2->ed25519_id);
  154. }
  155. HT_PROTOTYPE(nodelist_ed_map, node_t, ed_ht_ent, node_ed_id_hash,
  156. node_ed_id_eq)
  157. HT_GENERATE2(nodelist_ed_map, node_t, ed_ht_ent, node_ed_id_hash,
  158. node_ed_id_eq, 0.6, tor_reallocarray_, tor_free_)
  159. /** The global nodelist. */
  160. static nodelist_t *the_nodelist=NULL;
  161. /** Create an empty nodelist if we haven't done so already. */
  162. static void
  163. init_nodelist(void)
  164. {
  165. if (PREDICT_UNLIKELY(the_nodelist == NULL)) {
  166. the_nodelist = tor_malloc_zero(sizeof(nodelist_t));
  167. HT_INIT(nodelist_map, &the_nodelist->nodes_by_id);
  168. HT_INIT(nodelist_ed_map, &the_nodelist->nodes_by_ed_id);
  169. the_nodelist->nodes = smartlist_new();
  170. }
  171. }
  172. /** As node_get_by_id, but returns a non-const pointer */
  173. MOCK_IMPL(node_t *,
  174. node_get_mutable_by_id,(const char *identity_digest))
  175. {
  176. node_t search, *node;
  177. if (PREDICT_UNLIKELY(the_nodelist == NULL))
  178. return NULL;
  179. memcpy(&search.identity, identity_digest, DIGEST_LEN);
  180. node = HT_FIND(nodelist_map, &the_nodelist->nodes_by_id, &search);
  181. return node;
  182. }
  183. /** As node_get_by_ed25519_id, but returns a non-const pointer */
  184. node_t *
  185. node_get_mutable_by_ed25519_id(const ed25519_public_key_t *ed_id)
  186. {
  187. node_t search, *node;
  188. if (PREDICT_UNLIKELY(the_nodelist == NULL))
  189. return NULL;
  190. if (BUG(ed_id == NULL) || BUG(ed25519_public_key_is_zero(ed_id)))
  191. return NULL;
  192. memcpy(&search.ed25519_id, ed_id, sizeof(search.ed25519_id));
  193. node = HT_FIND(nodelist_ed_map, &the_nodelist->nodes_by_ed_id, &search);
  194. return node;
  195. }
  196. /** Return the node_t whose identity is <b>identity_digest</b>, or NULL
  197. * if no such node exists. */
  198. MOCK_IMPL(const node_t *,
  199. node_get_by_id,(const char *identity_digest))
  200. {
  201. return node_get_mutable_by_id(identity_digest);
  202. }
  203. /** Return the node_t whose ed25519 identity is <b>ed_id</b>, or NULL
  204. * if no such node exists. */
  205. MOCK_IMPL(const node_t *,
  206. node_get_by_ed25519_id,(const ed25519_public_key_t *ed_id))
  207. {
  208. return node_get_mutable_by_ed25519_id(ed_id);
  209. }
  210. /** Internal: return the node_t whose identity_digest is
  211. * <b>identity_digest</b>. If none exists, create a new one, add it to the
  212. * nodelist, and return it.
  213. *
  214. * Requires that the nodelist be initialized.
  215. */
  216. static node_t *
  217. node_get_or_create(const char *identity_digest)
  218. {
  219. node_t *node;
  220. if ((node = node_get_mutable_by_id(identity_digest)))
  221. return node;
  222. node = tor_malloc_zero(sizeof(node_t));
  223. memcpy(node->identity, identity_digest, DIGEST_LEN);
  224. HT_INSERT(nodelist_map, &the_nodelist->nodes_by_id, node);
  225. smartlist_add(the_nodelist->nodes, node);
  226. node->nodelist_idx = smartlist_len(the_nodelist->nodes) - 1;
  227. node->country = -1;
  228. return node;
  229. }
  230. /** Remove <b>node</b> from the ed25519 map (if it present), and
  231. * set its ed25519_id field to zero. */
  232. static int
  233. node_remove_from_ed25519_map(node_t *node)
  234. {
  235. tor_assert(the_nodelist);
  236. tor_assert(node);
  237. if (ed25519_public_key_is_zero(&node->ed25519_id)) {
  238. return 0;
  239. }
  240. int rv = 0;
  241. node_t *search =
  242. HT_FIND(nodelist_ed_map, &the_nodelist->nodes_by_ed_id, node);
  243. if (BUG(search != node)) {
  244. goto clear_and_return;
  245. }
  246. search = HT_REMOVE(nodelist_ed_map, &the_nodelist->nodes_by_ed_id, node);
  247. tor_assert(search == node);
  248. rv = 1;
  249. clear_and_return:
  250. memset(&node->ed25519_id, 0, sizeof(node->ed25519_id));
  251. return rv;
  252. }
  253. /** Helper function to log details of duplicated ed2559_ids */
  254. static void
  255. node_log_dup_ed_id(const node_t *old, const node_t *node, const char *ed_id)
  256. {
  257. char *s;
  258. char *olddesc = tor_strdup(node_describe(old));
  259. tor_asprintf(&s, "Reused ed25519_id %s: old %s new %s", ed_id,
  260. olddesc, node_describe(node));
  261. log_backtrace(LOG_NOTICE, LD_DIR, s);
  262. tor_free(olddesc);
  263. tor_free(s);
  264. }
  265. /** If <b>node</b> has an ed25519 id, and it is not already in the ed25519 id
  266. * map, set its ed25519_id field, and add it to the ed25519 map.
  267. */
  268. static int
  269. node_add_to_ed25519_map(node_t *node)
  270. {
  271. tor_assert(the_nodelist);
  272. tor_assert(node);
  273. if (! ed25519_public_key_is_zero(&node->ed25519_id)) {
  274. return 0;
  275. }
  276. const ed25519_public_key_t *key = node_get_ed25519_id(node);
  277. if (!key) {
  278. return 0;
  279. }
  280. node_t *old;
  281. memcpy(&node->ed25519_id, key, sizeof(node->ed25519_id));
  282. old = HT_FIND(nodelist_ed_map, &the_nodelist->nodes_by_ed_id, node);
  283. if (old) {
  284. char ed_id[BASE32_BUFSIZE(sizeof(key->pubkey))];
  285. base32_encode(ed_id, sizeof(ed_id), (const char *)key->pubkey,
  286. sizeof(key->pubkey));
  287. if (BUG(old == node)) {
  288. /* Actual bug: all callers of this function call
  289. * node_remove_from_ed25519_map first. */
  290. log_err(LD_BUG,
  291. "Unexpectedly found deleted node with ed25519_id %s", ed_id);
  292. } else {
  293. /* Distinct nodes sharing a ed25519 id, possibly due to relay
  294. * misconfiguration. The key pinning might not catch this,
  295. * possibly due to downloading a missing descriptor during
  296. * consensus voting. */
  297. node_log_dup_ed_id(old, node, ed_id);
  298. memset(&node->ed25519_id, 0, sizeof(node->ed25519_id));
  299. }
  300. return 0;
  301. }
  302. HT_INSERT(nodelist_ed_map, &the_nodelist->nodes_by_ed_id, node);
  303. return 1;
  304. }
  305. /* For a given <b>node</b> for the consensus <b>ns</b>, set the hsdir index
  306. * for the node, both current and next if possible. This can only fails if the
  307. * node_t ed25519 identity key can't be found which would be a bug. */
  308. STATIC void
  309. node_set_hsdir_index(node_t *node, const networkstatus_t *ns)
  310. {
  311. time_t now = approx_time();
  312. const ed25519_public_key_t *node_identity_pk;
  313. uint8_t *fetch_srv = NULL, *store_first_srv = NULL, *store_second_srv = NULL;
  314. uint64_t next_time_period_num, current_time_period_num;
  315. uint64_t fetch_tp, store_first_tp, store_second_tp;
  316. tor_assert(node);
  317. tor_assert(ns);
  318. if (!networkstatus_is_live(ns, now)) {
  319. static struct ratelim_t live_consensus_ratelim = RATELIM_INIT(30 * 60);
  320. log_fn_ratelim(&live_consensus_ratelim, LOG_INFO, LD_GENERAL,
  321. "Not setting hsdir index with a non-live consensus.");
  322. goto done;
  323. }
  324. node_identity_pk = node_get_ed25519_id(node);
  325. if (node_identity_pk == NULL) {
  326. log_debug(LD_GENERAL, "ed25519 identity public key not found when "
  327. "trying to build the hsdir indexes for node %s",
  328. node_describe(node));
  329. goto done;
  330. }
  331. /* Get the current and next time period number. */
  332. current_time_period_num = hs_get_time_period_num(0);
  333. next_time_period_num = hs_get_next_time_period_num(0);
  334. /* We always use the current time period for fetching descs */
  335. fetch_tp = current_time_period_num;
  336. /* Now extract the needed SRVs and time periods for building hsdir indices */
  337. if (hs_in_period_between_tp_and_srv(ns, now)) {
  338. fetch_srv = hs_get_current_srv(fetch_tp, ns);
  339. store_first_tp = hs_get_previous_time_period_num(0);
  340. store_second_tp = current_time_period_num;
  341. } else {
  342. fetch_srv = hs_get_previous_srv(fetch_tp, ns);
  343. store_first_tp = current_time_period_num;
  344. store_second_tp = next_time_period_num;
  345. }
  346. /* We always use the old SRV for storing the first descriptor and the latest
  347. * SRV for storing the second descriptor */
  348. store_first_srv = hs_get_previous_srv(store_first_tp, ns);
  349. store_second_srv = hs_get_current_srv(store_second_tp, ns);
  350. /* Build the fetch index. */
  351. hs_build_hsdir_index(node_identity_pk, fetch_srv, fetch_tp,
  352. node->hsdir_index.fetch);
  353. /* If we are in the time segment between SRV#N and TP#N, the fetch index is
  354. the same as the first store index */
  355. if (!hs_in_period_between_tp_and_srv(ns, now)) {
  356. memcpy(node->hsdir_index.store_first, node->hsdir_index.fetch,
  357. sizeof(node->hsdir_index.store_first));
  358. } else {
  359. hs_build_hsdir_index(node_identity_pk, store_first_srv, store_first_tp,
  360. node->hsdir_index.store_first);
  361. }
  362. /* If we are in the time segment between TP#N and SRV#N+1, the fetch index is
  363. the same as the second store index */
  364. if (hs_in_period_between_tp_and_srv(ns, now)) {
  365. memcpy(node->hsdir_index.store_second, node->hsdir_index.fetch,
  366. sizeof(node->hsdir_index.store_second));
  367. } else {
  368. hs_build_hsdir_index(node_identity_pk, store_second_srv, store_second_tp,
  369. node->hsdir_index.store_second);
  370. }
  371. done:
  372. tor_free(fetch_srv);
  373. tor_free(store_first_srv);
  374. tor_free(store_second_srv);
  375. return;
  376. }
  377. /** Called when a node's address changes. */
  378. static void
  379. node_addrs_changed(node_t *node)
  380. {
  381. node->last_reachable = node->last_reachable6 = 0;
  382. node->country = -1;
  383. }
  384. /** Add all address information about <b>node</b> to the current address
  385. * set (if there is one).
  386. */
  387. static void
  388. node_add_to_address_set(const node_t *node)
  389. {
  390. if (!the_nodelist || !the_nodelist->node_addrs)
  391. return;
  392. /* These various address sources can be redundant, but it's likely faster
  393. * to add them all than to compare them all for equality. */
  394. if (node->rs) {
  395. if (node->rs->addr)
  396. address_set_add_ipv4h(the_nodelist->node_addrs, node->rs->addr);
  397. if (!tor_addr_is_null(&node->rs->ipv6_addr))
  398. address_set_add(the_nodelist->node_addrs, &node->rs->ipv6_addr);
  399. }
  400. if (node->ri) {
  401. if (node->ri->addr)
  402. address_set_add_ipv4h(the_nodelist->node_addrs, node->ri->addr);
  403. if (!tor_addr_is_null(&node->ri->ipv6_addr))
  404. address_set_add(the_nodelist->node_addrs, &node->ri->ipv6_addr);
  405. }
  406. if (node->md) {
  407. if (!tor_addr_is_null(&node->md->ipv6_addr))
  408. address_set_add(the_nodelist->node_addrs, &node->md->ipv6_addr);
  409. }
  410. }
  411. /** Return true if <b>addr</b> is the address of some node in the nodelist.
  412. * If not, probably return false. */
  413. int
  414. nodelist_probably_contains_address(const tor_addr_t *addr)
  415. {
  416. if (BUG(!addr))
  417. return 0;
  418. if (!the_nodelist || !the_nodelist->node_addrs)
  419. return 0;
  420. return address_set_probably_contains(the_nodelist->node_addrs, addr);
  421. }
  422. /** Add <b>ri</b> to an appropriate node in the nodelist. If we replace an
  423. * old routerinfo, and <b>ri_old_out</b> is not NULL, set *<b>ri_old_out</b>
  424. * to the previous routerinfo.
  425. */
  426. node_t *
  427. nodelist_set_routerinfo(routerinfo_t *ri, routerinfo_t **ri_old_out)
  428. {
  429. node_t *node;
  430. const char *id_digest;
  431. int had_router = 0;
  432. tor_assert(ri);
  433. init_nodelist();
  434. id_digest = ri->cache_info.identity_digest;
  435. node = node_get_or_create(id_digest);
  436. node_remove_from_ed25519_map(node);
  437. if (node->ri) {
  438. if (!routers_have_same_or_addrs(node->ri, ri)) {
  439. node_addrs_changed(node);
  440. }
  441. had_router = 1;
  442. if (ri_old_out)
  443. *ri_old_out = node->ri;
  444. } else {
  445. if (ri_old_out)
  446. *ri_old_out = NULL;
  447. }
  448. node->ri = ri;
  449. node_add_to_ed25519_map(node);
  450. if (node->country == -1)
  451. node_set_country(node);
  452. if (authdir_mode(get_options()) && !had_router) {
  453. const char *discard=NULL;
  454. uint32_t status = dirserv_router_get_status(ri, &discard, LOG_INFO);
  455. dirserv_set_node_flags_from_authoritative_status(node, status);
  456. }
  457. /* Setting the HSDir index requires the ed25519 identity key which can
  458. * only be found either in the ri or md. This is why this is called here.
  459. * Only nodes supporting HSDir=2 protocol version needs this index. */
  460. if (node->rs && node->rs->pv.supports_v3_hsdir) {
  461. node_set_hsdir_index(node,
  462. networkstatus_get_latest_consensus());
  463. }
  464. node_add_to_address_set(node);
  465. return node;
  466. }
  467. /** Set the appropriate node_t to use <b>md</b> as its microdescriptor.
  468. *
  469. * Called when a new microdesc has arrived and the usable consensus flavor
  470. * is "microdesc".
  471. **/
  472. node_t *
  473. nodelist_add_microdesc(microdesc_t *md)
  474. {
  475. networkstatus_t *ns =
  476. networkstatus_get_latest_consensus_by_flavor(FLAV_MICRODESC);
  477. const routerstatus_t *rs;
  478. node_t *node;
  479. if (ns == NULL)
  480. return NULL;
  481. init_nodelist();
  482. /* Microdescriptors don't carry an identity digest, so we need to figure
  483. * it out by looking up the routerstatus. */
  484. rs = router_get_consensus_status_by_descriptor_digest(ns, md->digest);
  485. if (rs == NULL)
  486. return NULL;
  487. node = node_get_mutable_by_id(rs->identity_digest);
  488. if (node == NULL)
  489. return NULL;
  490. node_remove_from_ed25519_map(node);
  491. if (node->md)
  492. node->md->held_by_nodes--;
  493. node->md = md;
  494. md->held_by_nodes++;
  495. /* Setting the HSDir index requires the ed25519 identity key which can
  496. * only be found either in the ri or md. This is why this is called here.
  497. * Only nodes supporting HSDir=2 protocol version needs this index. */
  498. if (rs->pv.supports_v3_hsdir) {
  499. node_set_hsdir_index(node, ns);
  500. }
  501. node_add_to_ed25519_map(node);
  502. node_add_to_address_set(node);
  503. return node;
  504. }
  505. /* Default value. */
  506. #define ESTIMATED_ADDRESS_PER_NODE 2
  507. /* Return the estimated number of address per node_t. This is used for the
  508. * size of the bloom filter in the nodelist (node_addrs). */
  509. MOCK_IMPL(int,
  510. get_estimated_address_per_node, (void))
  511. {
  512. return ESTIMATED_ADDRESS_PER_NODE;
  513. }
  514. /** Tell the nodelist that the current usable consensus is <b>ns</b>.
  515. * This makes the nodelist change all of the routerstatus entries for
  516. * the nodes, drop nodes that no longer have enough info to get used,
  517. * and grab microdescriptors into nodes as appropriate.
  518. */
  519. void
  520. nodelist_set_consensus(networkstatus_t *ns)
  521. {
  522. const or_options_t *options = get_options();
  523. int authdir = authdir_mode_v3(options);
  524. init_nodelist();
  525. if (ns->flavor == FLAV_MICRODESC)
  526. (void) get_microdesc_cache(); /* Make sure it exists first. */
  527. SMARTLIST_FOREACH(the_nodelist->nodes, node_t *, node,
  528. node->rs = NULL);
  529. /* Conservatively estimate that every node will have 2 addresses. */
  530. const int estimated_addresses = smartlist_len(ns->routerstatus_list) *
  531. get_estimated_address_per_node();
  532. address_set_free(the_nodelist->node_addrs);
  533. the_nodelist->node_addrs = address_set_new(estimated_addresses);
  534. SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, routerstatus_t *, rs) {
  535. node_t *node = node_get_or_create(rs->identity_digest);
  536. node->rs = rs;
  537. if (ns->flavor == FLAV_MICRODESC) {
  538. if (node->md == NULL ||
  539. tor_memneq(node->md->digest,rs->descriptor_digest,DIGEST256_LEN)) {
  540. node_remove_from_ed25519_map(node);
  541. if (node->md)
  542. node->md->held_by_nodes--;
  543. node->md = microdesc_cache_lookup_by_digest256(NULL,
  544. rs->descriptor_digest);
  545. if (node->md)
  546. node->md->held_by_nodes++;
  547. node_add_to_ed25519_map(node);
  548. }
  549. }
  550. if (rs->pv.supports_v3_hsdir) {
  551. node_set_hsdir_index(node, ns);
  552. }
  553. node_set_country(node);
  554. /* If we're not an authdir, believe others. */
  555. if (!authdir) {
  556. node->is_valid = rs->is_valid;
  557. node->is_running = rs->is_flagged_running;
  558. node->is_fast = rs->is_fast;
  559. node->is_stable = rs->is_stable;
  560. node->is_possible_guard = rs->is_possible_guard;
  561. node->is_exit = rs->is_exit;
  562. node->is_bad_exit = rs->is_bad_exit;
  563. node->is_hs_dir = rs->is_hs_dir;
  564. node->ipv6_preferred = 0;
  565. if (fascist_firewall_prefer_ipv6_orport(options) &&
  566. (tor_addr_is_null(&rs->ipv6_addr) == 0 ||
  567. (node->md && tor_addr_is_null(&node->md->ipv6_addr) == 0)))
  568. node->ipv6_preferred = 1;
  569. }
  570. } SMARTLIST_FOREACH_END(rs);
  571. nodelist_purge();
  572. /* Now add all the nodes we have to the address set. */
  573. SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) {
  574. node_add_to_address_set(node);
  575. } SMARTLIST_FOREACH_END(node);
  576. if (! authdir) {
  577. SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) {
  578. /* We have no routerstatus for this router. Clear flags so we can skip
  579. * it, maybe.*/
  580. if (!node->rs) {
  581. tor_assert(node->ri); /* if it had only an md, or nothing, purge
  582. * would have removed it. */
  583. if (node->ri->purpose == ROUTER_PURPOSE_GENERAL) {
  584. /* Clear all flags. */
  585. node->is_valid = node->is_running = node->is_hs_dir =
  586. node->is_fast = node->is_stable =
  587. node->is_possible_guard = node->is_exit =
  588. node->is_bad_exit = node->ipv6_preferred = 0;
  589. }
  590. }
  591. } SMARTLIST_FOREACH_END(node);
  592. }
  593. /* If the consensus is live, note down the consensus valid-after that formed
  594. * the nodelist. */
  595. if (networkstatus_is_live(ns, approx_time())) {
  596. the_nodelist->live_consensus_valid_after = ns->valid_after;
  597. }
  598. }
  599. /** Return 1 iff <b>node</b> has Exit flag and no BadExit flag.
  600. * Otherwise, return 0.
  601. */
  602. int
  603. node_is_good_exit(const node_t *node)
  604. {
  605. return node->is_exit && ! node->is_bad_exit;
  606. }
  607. /** Helper: return true iff a node has a usable amount of information*/
  608. static inline int
  609. node_is_usable(const node_t *node)
  610. {
  611. return (node->rs) || (node->ri);
  612. }
  613. /** Tell the nodelist that <b>md</b> is no longer a microdescriptor for the
  614. * node with <b>identity_digest</b>. */
  615. void
  616. nodelist_remove_microdesc(const char *identity_digest, microdesc_t *md)
  617. {
  618. node_t *node = node_get_mutable_by_id(identity_digest);
  619. if (node && node->md == md) {
  620. node->md = NULL;
  621. md->held_by_nodes--;
  622. if (! node_get_ed25519_id(node)) {
  623. node_remove_from_ed25519_map(node);
  624. }
  625. }
  626. }
  627. /** Tell the nodelist that <b>ri</b> is no longer in the routerlist. */
  628. void
  629. nodelist_remove_routerinfo(routerinfo_t *ri)
  630. {
  631. node_t *node = node_get_mutable_by_id(ri->cache_info.identity_digest);
  632. if (node && node->ri == ri) {
  633. node->ri = NULL;
  634. if (! node_is_usable(node)) {
  635. nodelist_drop_node(node, 1);
  636. node_free(node);
  637. }
  638. }
  639. }
  640. /** Remove <b>node</b> from the nodelist. (Asserts that it was there to begin
  641. * with.) */
  642. static void
  643. nodelist_drop_node(node_t *node, int remove_from_ht)
  644. {
  645. node_t *tmp;
  646. int idx;
  647. if (remove_from_ht) {
  648. tmp = HT_REMOVE(nodelist_map, &the_nodelist->nodes_by_id, node);
  649. tor_assert(tmp == node);
  650. }
  651. node_remove_from_ed25519_map(node);
  652. idx = node->nodelist_idx;
  653. tor_assert(idx >= 0);
  654. tor_assert(node == smartlist_get(the_nodelist->nodes, idx));
  655. smartlist_del(the_nodelist->nodes, idx);
  656. if (idx < smartlist_len(the_nodelist->nodes)) {
  657. tmp = smartlist_get(the_nodelist->nodes, idx);
  658. tmp->nodelist_idx = idx;
  659. }
  660. node->nodelist_idx = -1;
  661. }
  662. /** Return a newly allocated smartlist of the nodes that have <b>md</b> as
  663. * their microdescriptor. */
  664. smartlist_t *
  665. nodelist_find_nodes_with_microdesc(const microdesc_t *md)
  666. {
  667. smartlist_t *result = smartlist_new();
  668. if (the_nodelist == NULL)
  669. return result;
  670. SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) {
  671. if (node->md == md) {
  672. smartlist_add(result, node);
  673. }
  674. } SMARTLIST_FOREACH_END(node);
  675. return result;
  676. }
  677. /** Release storage held by <b>node</b> */
  678. static void
  679. node_free_(node_t *node)
  680. {
  681. if (!node)
  682. return;
  683. if (node->md)
  684. node->md->held_by_nodes--;
  685. tor_assert(node->nodelist_idx == -1);
  686. tor_free(node);
  687. }
  688. /** Remove all entries from the nodelist that don't have enough info to be
  689. * usable for anything. */
  690. void
  691. nodelist_purge(void)
  692. {
  693. node_t **iter;
  694. if (PREDICT_UNLIKELY(the_nodelist == NULL))
  695. return;
  696. /* Remove the non-usable nodes. */
  697. for (iter = HT_START(nodelist_map, &the_nodelist->nodes_by_id); iter; ) {
  698. node_t *node = *iter;
  699. if (node->md && !node->rs) {
  700. /* An md is only useful if there is an rs. */
  701. node->md->held_by_nodes--;
  702. node->md = NULL;
  703. }
  704. if (node_is_usable(node)) {
  705. iter = HT_NEXT(nodelist_map, &the_nodelist->nodes_by_id, iter);
  706. } else {
  707. iter = HT_NEXT_RMV(nodelist_map, &the_nodelist->nodes_by_id, iter);
  708. nodelist_drop_node(node, 0);
  709. node_free(node);
  710. }
  711. }
  712. nodelist_assert_ok();
  713. }
  714. /** Release all storage held by the nodelist. */
  715. void
  716. nodelist_free_all(void)
  717. {
  718. if (PREDICT_UNLIKELY(the_nodelist == NULL))
  719. return;
  720. HT_CLEAR(nodelist_map, &the_nodelist->nodes_by_id);
  721. HT_CLEAR(nodelist_ed_map, &the_nodelist->nodes_by_ed_id);
  722. SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) {
  723. node->nodelist_idx = -1;
  724. node_free(node);
  725. } SMARTLIST_FOREACH_END(node);
  726. smartlist_free(the_nodelist->nodes);
  727. address_set_free(the_nodelist->node_addrs);
  728. the_nodelist->node_addrs = NULL;
  729. tor_free(the_nodelist);
  730. }
  731. /** Check that the nodelist is internally consistent, and consistent with
  732. * the directory info it's derived from.
  733. */
  734. void
  735. nodelist_assert_ok(void)
  736. {
  737. routerlist_t *rl = router_get_routerlist();
  738. networkstatus_t *ns = networkstatus_get_latest_consensus();
  739. digestmap_t *dm;
  740. if (!the_nodelist)
  741. return;
  742. dm = digestmap_new();
  743. /* every routerinfo in rl->routers should be in the nodelist. */
  744. if (rl) {
  745. SMARTLIST_FOREACH_BEGIN(rl->routers, routerinfo_t *, ri) {
  746. const node_t *node = node_get_by_id(ri->cache_info.identity_digest);
  747. tor_assert(node && node->ri == ri);
  748. tor_assert(fast_memeq(ri->cache_info.identity_digest,
  749. node->identity, DIGEST_LEN));
  750. tor_assert(! digestmap_get(dm, node->identity));
  751. digestmap_set(dm, node->identity, (void*)node);
  752. } SMARTLIST_FOREACH_END(ri);
  753. }
  754. /* every routerstatus in ns should be in the nodelist */
  755. if (ns) {
  756. SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, routerstatus_t *, rs) {
  757. const node_t *node = node_get_by_id(rs->identity_digest);
  758. tor_assert(node && node->rs == rs);
  759. tor_assert(fast_memeq(rs->identity_digest, node->identity, DIGEST_LEN));
  760. digestmap_set(dm, node->identity, (void*)node);
  761. if (ns->flavor == FLAV_MICRODESC) {
  762. /* If it's a microdesc consensus, every entry that has a
  763. * microdescriptor should be in the nodelist.
  764. */
  765. microdesc_t *md =
  766. microdesc_cache_lookup_by_digest256(NULL, rs->descriptor_digest);
  767. tor_assert(md == node->md);
  768. if (md)
  769. tor_assert(md->held_by_nodes >= 1);
  770. }
  771. } SMARTLIST_FOREACH_END(rs);
  772. }
  773. /* The nodelist should have no other entries, and its entries should be
  774. * well-formed. */
  775. SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) {
  776. tor_assert(digestmap_get(dm, node->identity) != NULL);
  777. tor_assert(node_sl_idx == node->nodelist_idx);
  778. } SMARTLIST_FOREACH_END(node);
  779. /* Every node listed with an ed25519 identity should be listed by that
  780. * identity.
  781. */
  782. SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) {
  783. if (!ed25519_public_key_is_zero(&node->ed25519_id)) {
  784. tor_assert(node == node_get_by_ed25519_id(&node->ed25519_id));
  785. }
  786. } SMARTLIST_FOREACH_END(node);
  787. node_t **idx;
  788. HT_FOREACH(idx, nodelist_ed_map, &the_nodelist->nodes_by_ed_id) {
  789. node_t *node = *idx;
  790. tor_assert(node == node_get_by_ed25519_id(&node->ed25519_id));
  791. }
  792. tor_assert((long)smartlist_len(the_nodelist->nodes) ==
  793. (long)HT_SIZE(&the_nodelist->nodes_by_id));
  794. tor_assert((long)smartlist_len(the_nodelist->nodes) >=
  795. (long)HT_SIZE(&the_nodelist->nodes_by_ed_id));
  796. digestmap_free(dm, NULL);
  797. }
  798. /** Ensure that the nodelist has been created with the most recent consensus.
  799. * If that's not the case, make it so. */
  800. void
  801. nodelist_ensure_freshness(networkstatus_t *ns)
  802. {
  803. tor_assert(ns);
  804. /* We don't even have a nodelist: this is a NOP. */
  805. if (!the_nodelist) {
  806. return;
  807. }
  808. if (the_nodelist->live_consensus_valid_after != ns->valid_after) {
  809. log_info(LD_GENERAL, "Nodelist was not fresh: rebuilding. (%d / %d)",
  810. (int) the_nodelist->live_consensus_valid_after,
  811. (int) ns->valid_after);
  812. nodelist_set_consensus(ns);
  813. }
  814. }
  815. /** Return a list of a node_t * for every node we know about. The caller
  816. * MUST NOT modify the list. (You can set and clear flags in the nodes if
  817. * you must, but you must not add or remove nodes.) */
  818. MOCK_IMPL(const smartlist_t *,
  819. nodelist_get_list,(void))
  820. {
  821. init_nodelist();
  822. return the_nodelist->nodes;
  823. }
  824. /** Given a hex-encoded nickname of the format DIGEST, $DIGEST, $DIGEST=name,
  825. * or $DIGEST~name, return the node with the matching identity digest and
  826. * nickname (if any). Return NULL if no such node exists, or if <b>hex_id</b>
  827. * is not well-formed. DOCDOC flags */
  828. const node_t *
  829. node_get_by_hex_id(const char *hex_id, unsigned flags)
  830. {
  831. char digest_buf[DIGEST_LEN];
  832. char nn_buf[MAX_NICKNAME_LEN+1];
  833. char nn_char='\0';
  834. (void) flags; // XXXX
  835. if (hex_digest_nickname_decode(hex_id, digest_buf, &nn_char, nn_buf)==0) {
  836. const node_t *node = node_get_by_id(digest_buf);
  837. if (!node)
  838. return NULL;
  839. if (nn_char == '=') {
  840. /* "=" indicates a Named relay, but there aren't any of those now. */
  841. return NULL;
  842. }
  843. return node;
  844. }
  845. return NULL;
  846. }
  847. /** Given a nickname (possibly verbose, possibly a hexadecimal digest), return
  848. * the corresponding node_t, or NULL if none exists. Warn the user if they
  849. * have specified a router by nickname, unless the NNF_NO_WARN_UNNAMED bit is
  850. * set in <b>flags</b>. */
  851. MOCK_IMPL(const node_t *,
  852. node_get_by_nickname,(const char *nickname, unsigned flags))
  853. {
  854. const int warn_if_unnamed = !(flags & NNF_NO_WARN_UNNAMED);
  855. if (!the_nodelist)
  856. return NULL;
  857. /* Handle these cases: DIGEST, $DIGEST, $DIGEST=name, $DIGEST~name. */
  858. {
  859. const node_t *node;
  860. if ((node = node_get_by_hex_id(nickname, flags)) != NULL)
  861. return node;
  862. }
  863. if (!strcasecmp(nickname, UNNAMED_ROUTER_NICKNAME))
  864. return NULL;
  865. /* Okay, so the name is not canonical for anybody. */
  866. {
  867. smartlist_t *matches = smartlist_new();
  868. const node_t *choice = NULL;
  869. SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) {
  870. if (!strcasecmp(node_get_nickname(node), nickname))
  871. smartlist_add(matches, node);
  872. } SMARTLIST_FOREACH_END(node);
  873. if (smartlist_len(matches)>1 && warn_if_unnamed) {
  874. int any_unwarned = 0;
  875. SMARTLIST_FOREACH_BEGIN(matches, node_t *, node) {
  876. if (!node->name_lookup_warned) {
  877. node->name_lookup_warned = 1;
  878. any_unwarned = 1;
  879. }
  880. } SMARTLIST_FOREACH_END(node);
  881. if (any_unwarned) {
  882. log_warn(LD_CONFIG, "There are multiple matches for the name %s. "
  883. "Choosing one arbitrarily.", nickname);
  884. }
  885. } else if (smartlist_len(matches)==1 && warn_if_unnamed) {
  886. char fp[HEX_DIGEST_LEN+1];
  887. node_t *node = smartlist_get(matches, 0);
  888. if (! node->name_lookup_warned) {
  889. base16_encode(fp, sizeof(fp), node->identity, DIGEST_LEN);
  890. log_warn(LD_CONFIG,
  891. "You specified a relay \"%s\" by name, but nicknames can be "
  892. "used by any relay, not just the one you meant. "
  893. "To make sure you get the same relay in the future, refer "
  894. "to it by key, as \"$%s\".", nickname, fp);
  895. node->name_lookup_warned = 1;
  896. }
  897. }
  898. if (smartlist_len(matches))
  899. choice = smartlist_get(matches, 0);
  900. smartlist_free(matches);
  901. return choice;
  902. }
  903. }
  904. /** Return the Ed25519 identity key for the provided node, or NULL if it
  905. * doesn't have one. */
  906. const ed25519_public_key_t *
  907. node_get_ed25519_id(const node_t *node)
  908. {
  909. const ed25519_public_key_t *ri_pk = NULL;
  910. const ed25519_public_key_t *md_pk = NULL;
  911. if (node->ri) {
  912. if (node->ri->cache_info.signing_key_cert) {
  913. ri_pk = &node->ri->cache_info.signing_key_cert->signing_key;
  914. /* Checking whether routerinfo ed25519 is all zero.
  915. * Our descriptor parser should make sure this never happens. */
  916. if (BUG(ed25519_public_key_is_zero(ri_pk)))
  917. ri_pk = NULL;
  918. }
  919. }
  920. if (node->md) {
  921. if (node->md->ed25519_identity_pkey) {
  922. md_pk = node->md->ed25519_identity_pkey;
  923. /* Checking whether microdesc ed25519 is all zero.
  924. * Our descriptor parser should make sure this never happens. */
  925. if (BUG(ed25519_public_key_is_zero(md_pk)))
  926. md_pk = NULL;
  927. }
  928. }
  929. if (ri_pk && md_pk) {
  930. if (ed25519_pubkey_eq(ri_pk, md_pk)) {
  931. return ri_pk;
  932. } else {
  933. /* This can happen if the relay gets flagged NoEdConsensus which will be
  934. * triggered on all relays of the network. Thus a protocol warning. */
  935. log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
  936. "Inconsistent ed25519 identities in the nodelist");
  937. return NULL;
  938. }
  939. } else if (ri_pk) {
  940. return ri_pk;
  941. } else {
  942. return md_pk;
  943. }
  944. }
  945. /** Return true iff this node's Ed25519 identity matches <b>id</b>.
  946. * (An absent Ed25519 identity matches NULL or zero.) */
  947. int
  948. node_ed25519_id_matches(const node_t *node, const ed25519_public_key_t *id)
  949. {
  950. const ed25519_public_key_t *node_id = node_get_ed25519_id(node);
  951. if (node_id == NULL || ed25519_public_key_is_zero(node_id)) {
  952. return id == NULL || ed25519_public_key_is_zero(id);
  953. } else {
  954. return id && ed25519_pubkey_eq(node_id, id);
  955. }
  956. }
  957. /** Dummy object that should be unreturnable. Used to ensure that
  958. * node_get_protover_summary_flags() always returns non-NULL. */
  959. static const protover_summary_flags_t zero_protover_flags = {
  960. 0,0,0,0,0,0,0,0,0
  961. };
  962. /** Return the protover_summary_flags for a given node. */
  963. static const protover_summary_flags_t *
  964. node_get_protover_summary_flags(const node_t *node)
  965. {
  966. if (node->rs) {
  967. return &node->rs->pv;
  968. } else if (node->ri) {
  969. return &node->ri->pv;
  970. } else {
  971. /* This should be impossible: every node should have a routerstatus or a
  972. * router descriptor or both. But just in case we've messed up somehow,
  973. * return a nice empty set of flags to indicate "this node supports
  974. * nothing." */
  975. tor_assert_nonfatal_unreached_once();
  976. return &zero_protover_flags;
  977. }
  978. }
  979. /** Return true iff <b>node</b> supports authenticating itself
  980. * by ed25519 ID during the link handshake. If <b>compatible_with_us</b>,
  981. * it needs to be using a link authentication method that we understand.
  982. * If not, any plausible link authentication method will do. */
  983. int
  984. node_supports_ed25519_link_authentication(const node_t *node,
  985. int compatible_with_us)
  986. {
  987. if (! node_get_ed25519_id(node))
  988. return 0;
  989. const protover_summary_flags_t *pv = node_get_protover_summary_flags(node);
  990. if (compatible_with_us)
  991. return pv->supports_ed25519_link_handshake_compat;
  992. else
  993. return pv->supports_ed25519_link_handshake_any;
  994. }
  995. /** Return true iff <b>node</b> supports the hidden service directory version
  996. * 3 protocol (proposal 224). */
  997. int
  998. node_supports_v3_hsdir(const node_t *node)
  999. {
  1000. tor_assert(node);
  1001. return node_get_protover_summary_flags(node)->supports_v3_hsdir;
  1002. }
  1003. /** Return true iff <b>node</b> supports ed25519 authentication as an hidden
  1004. * service introduction point.*/
  1005. int
  1006. node_supports_ed25519_hs_intro(const node_t *node)
  1007. {
  1008. tor_assert(node);
  1009. return node_get_protover_summary_flags(node)->supports_ed25519_hs_intro;
  1010. }
  1011. /** Return true iff <b>node</b> supports the DoS ESTABLISH_INTRO cell
  1012. * extenstion. */
  1013. int
  1014. node_supports_establish_intro_dos_extension(const node_t *node)
  1015. {
  1016. tor_assert(node);
  1017. return node_get_protover_summary_flags(node)->
  1018. supports_establish_intro_dos_extension;
  1019. }
  1020. /** Return true iff <b>node</b> supports to be a rendezvous point for hidden
  1021. * service version 3 (HSRend=2). */
  1022. int
  1023. node_supports_v3_rendezvous_point(const node_t *node)
  1024. {
  1025. tor_assert(node);
  1026. /* We can't use a v3 rendezvous point without the curve25519 onion pk. */
  1027. if (!node_get_curve25519_onion_key(node)) {
  1028. return 0;
  1029. }
  1030. return node_get_protover_summary_flags(node)->supports_v3_rendezvous_point;
  1031. }
  1032. /** Return the RSA ID key's SHA1 digest for the provided node. */
  1033. const uint8_t *
  1034. node_get_rsa_id_digest(const node_t *node)
  1035. {
  1036. tor_assert(node);
  1037. return (const uint8_t*)node->identity;
  1038. }
  1039. /* Returns a new smartlist with all possible link specifiers from node:
  1040. * - legacy ID is mandatory thus MUST be present in node;
  1041. * - include ed25519 link specifier if present in the node, and the node
  1042. * supports ed25519 link authentication, and:
  1043. * - if direct_conn is true, its link versions are compatible with us,
  1044. * - if direct_conn is false, regardless of its link versions;
  1045. * - include IPv4 link specifier, if the primary address is not IPv4, log a
  1046. * BUG() warning, and return an empty smartlist;
  1047. * - include IPv6 link specifier if present in the node.
  1048. *
  1049. * If node is NULL, returns an empty smartlist.
  1050. *
  1051. * The smartlist must be freed using link_specifier_smartlist_free(). */
  1052. smartlist_t *
  1053. node_get_link_specifier_smartlist(const node_t *node, bool direct_conn)
  1054. {
  1055. link_specifier_t *ls;
  1056. tor_addr_port_t ap;
  1057. smartlist_t *lspecs = smartlist_new();
  1058. if (!node)
  1059. return lspecs;
  1060. /* Get the relay's IPv4 address. */
  1061. node_get_prim_orport(node, &ap);
  1062. /* We expect the node's primary address to be a valid IPv4 address.
  1063. * This conforms to the protocol, which requires either an IPv4 or IPv6
  1064. * address (or both). */
  1065. if (BUG(!tor_addr_is_v4(&ap.addr)) ||
  1066. BUG(!tor_addr_port_is_valid_ap(&ap, 0))) {
  1067. return lspecs;
  1068. }
  1069. ls = link_specifier_new();
  1070. link_specifier_set_ls_type(ls, LS_IPV4);
  1071. link_specifier_set_un_ipv4_addr(ls, tor_addr_to_ipv4h(&ap.addr));
  1072. link_specifier_set_un_ipv4_port(ls, ap.port);
  1073. /* Four bytes IPv4 and two bytes port. */
  1074. link_specifier_set_ls_len(ls, sizeof(ap.addr.addr.in_addr) +
  1075. sizeof(ap.port));
  1076. smartlist_add(lspecs, ls);
  1077. /* Legacy ID is mandatory and will always be present in node. */
  1078. ls = link_specifier_new();
  1079. link_specifier_set_ls_type(ls, LS_LEGACY_ID);
  1080. memcpy(link_specifier_getarray_un_legacy_id(ls), node->identity,
  1081. link_specifier_getlen_un_legacy_id(ls));
  1082. link_specifier_set_ls_len(ls, link_specifier_getlen_un_legacy_id(ls));
  1083. smartlist_add(lspecs, ls);
  1084. /* ed25519 ID is only included if the node has it, and the node declares a
  1085. protocol version that supports ed25519 link authentication.
  1086. If direct_conn is true, we also require that the node's link version is
  1087. compatible with us. (Otherwise, we will be sending the ed25519 key
  1088. to another tor, which may support different link versions.) */
  1089. if (!ed25519_public_key_is_zero(&node->ed25519_id) &&
  1090. node_supports_ed25519_link_authentication(node, direct_conn)) {
  1091. ls = link_specifier_new();
  1092. link_specifier_set_ls_type(ls, LS_ED25519_ID);
  1093. memcpy(link_specifier_getarray_un_ed25519_id(ls), &node->ed25519_id,
  1094. link_specifier_getlen_un_ed25519_id(ls));
  1095. link_specifier_set_ls_len(ls, link_specifier_getlen_un_ed25519_id(ls));
  1096. smartlist_add(lspecs, ls);
  1097. }
  1098. /* Check for IPv6. If so, include it as well. */
  1099. if (node_has_ipv6_orport(node)) {
  1100. ls = link_specifier_new();
  1101. node_get_pref_ipv6_orport(node, &ap);
  1102. link_specifier_set_ls_type(ls, LS_IPV6);
  1103. size_t addr_len = link_specifier_getlen_un_ipv6_addr(ls);
  1104. const uint8_t *in6_addr = tor_addr_to_in6_addr8(&ap.addr);
  1105. uint8_t *ipv6_array = link_specifier_getarray_un_ipv6_addr(ls);
  1106. memcpy(ipv6_array, in6_addr, addr_len);
  1107. link_specifier_set_un_ipv6_port(ls, ap.port);
  1108. /* Sixteen bytes IPv6 and two bytes port. */
  1109. link_specifier_set_ls_len(ls, addr_len + sizeof(ap.port));
  1110. smartlist_add(lspecs, ls);
  1111. }
  1112. return lspecs;
  1113. }
  1114. /* Free a link specifier list. */
  1115. void
  1116. link_specifier_smartlist_free_(smartlist_t *ls_list)
  1117. {
  1118. if (!ls_list)
  1119. return;
  1120. SMARTLIST_FOREACH(ls_list, link_specifier_t *, lspec,
  1121. link_specifier_free(lspec));
  1122. smartlist_free(ls_list);
  1123. }
  1124. /** Return the nickname of <b>node</b>, or NULL if we can't find one. */
  1125. const char *
  1126. node_get_nickname(const node_t *node)
  1127. {
  1128. tor_assert(node);
  1129. if (node->rs)
  1130. return node->rs->nickname;
  1131. else if (node->ri)
  1132. return node->ri->nickname;
  1133. else
  1134. return NULL;
  1135. }
  1136. /** Return true iff <b>node</b> appears to be a directory authority or
  1137. * directory cache */
  1138. int
  1139. node_is_dir(const node_t *node)
  1140. {
  1141. if (node->rs) {
  1142. routerstatus_t * rs = node->rs;
  1143. /* This is true if supports_tunnelled_dir_requests is true which
  1144. * indicates that we support directory request tunnelled or through the
  1145. * DirPort. */
  1146. return rs->is_v2_dir;
  1147. } else if (node->ri) {
  1148. routerinfo_t * ri = node->ri;
  1149. /* Both tunnelled request is supported or DirPort is set. */
  1150. return ri->supports_tunnelled_dir_requests;
  1151. } else {
  1152. return 0;
  1153. }
  1154. }
  1155. /** Return true iff <b>node</b> has either kind of descriptor -- that
  1156. * is, a routerdescriptor or a microdescriptor.
  1157. *
  1158. * You should probably use node_has_preferred_descriptor() instead.
  1159. **/
  1160. int
  1161. node_has_any_descriptor(const node_t *node)
  1162. {
  1163. return (node->ri ||
  1164. (node->rs && node->md));
  1165. }
  1166. /** Return true iff <b>node</b> has the kind of descriptor we would prefer to
  1167. * use for it, given our configuration and how we intend to use the node.
  1168. *
  1169. * If <b>for_direct_connect</b> is true, we intend to connect to the node
  1170. * directly, as the first hop of a circuit; otherwise, we intend to connect to
  1171. * it indirectly, or use it as if we were connecting to it indirectly. */
  1172. int
  1173. node_has_preferred_descriptor(const node_t *node,
  1174. int for_direct_connect)
  1175. {
  1176. const int is_bridge = node_is_a_configured_bridge(node);
  1177. const int we_use_mds = we_use_microdescriptors_for_circuits(get_options());
  1178. if ((is_bridge && for_direct_connect) || !we_use_mds) {
  1179. /* We need an ri in this case. */
  1180. if (!node->ri)
  1181. return 0;
  1182. } else {
  1183. /* Otherwise we need an rs and an md. */
  1184. if (node->rs == NULL || node->md == NULL)
  1185. return 0;
  1186. }
  1187. return 1;
  1188. }
  1189. /** Return the router_purpose of <b>node</b>. */
  1190. int
  1191. node_get_purpose(const node_t *node)
  1192. {
  1193. if (node->ri)
  1194. return node->ri->purpose;
  1195. else
  1196. return ROUTER_PURPOSE_GENERAL;
  1197. }
  1198. /** Compute the verbose ("extended") nickname of <b>node</b> and store it
  1199. * into the MAX_VERBOSE_NICKNAME_LEN+1 character buffer at
  1200. * <b>verbose_name_out</b> */
  1201. void
  1202. node_get_verbose_nickname(const node_t *node,
  1203. char *verbose_name_out)
  1204. {
  1205. const char *nickname = node_get_nickname(node);
  1206. verbose_name_out[0] = '$';
  1207. base16_encode(verbose_name_out+1, HEX_DIGEST_LEN+1, node->identity,
  1208. DIGEST_LEN);
  1209. if (!nickname)
  1210. return;
  1211. verbose_name_out[1+HEX_DIGEST_LEN] = '~';
  1212. strlcpy(verbose_name_out+1+HEX_DIGEST_LEN+1, nickname, MAX_NICKNAME_LEN+1);
  1213. }
  1214. /** Compute the verbose ("extended") nickname of node with
  1215. * given <b>id_digest</b> and store it into the MAX_VERBOSE_NICKNAME_LEN+1
  1216. * character buffer at <b>verbose_name_out</b>
  1217. *
  1218. * If node_get_by_id() returns NULL, base 16 encoding of
  1219. * <b>id_digest</b> is returned instead. */
  1220. void
  1221. node_get_verbose_nickname_by_id(const char *id_digest,
  1222. char *verbose_name_out)
  1223. {
  1224. const node_t *node = node_get_by_id(id_digest);
  1225. if (!node) {
  1226. verbose_name_out[0] = '$';
  1227. base16_encode(verbose_name_out+1, HEX_DIGEST_LEN+1, id_digest, DIGEST_LEN);
  1228. } else {
  1229. node_get_verbose_nickname(node, verbose_name_out);
  1230. }
  1231. }
  1232. /** Return true iff it seems that <b>node</b> allows circuits to exit
  1233. * through it directlry from the client. */
  1234. int
  1235. node_allows_single_hop_exits(const node_t *node)
  1236. {
  1237. if (node && node->ri)
  1238. return node->ri->allow_single_hop_exits;
  1239. else
  1240. return 0;
  1241. }
  1242. /** Return true iff it seems that <b>node</b> has an exit policy that doesn't
  1243. * actually permit anything to exit, or we don't know its exit policy */
  1244. int
  1245. node_exit_policy_rejects_all(const node_t *node)
  1246. {
  1247. if (node->rejects_all)
  1248. return 1;
  1249. if (node->ri)
  1250. return node->ri->policy_is_reject_star;
  1251. else if (node->md)
  1252. return node->md->policy_is_reject_star;
  1253. else
  1254. return 1;
  1255. }
  1256. /** Return true iff the exit policy for <b>node</b> is such that we can treat
  1257. * rejecting an address of type <b>family</b> unexpectedly as a sign of that
  1258. * node's failure. */
  1259. int
  1260. node_exit_policy_is_exact(const node_t *node, sa_family_t family)
  1261. {
  1262. if (family == AF_UNSPEC) {
  1263. return 1; /* Rejecting an address but not telling us what address
  1264. * is a bad sign. */
  1265. } else if (family == AF_INET) {
  1266. return node->ri != NULL;
  1267. } else if (family == AF_INET6) {
  1268. return 0;
  1269. }
  1270. tor_fragile_assert();
  1271. return 1;
  1272. }
  1273. /* Check if the "addr" and port_field fields from r are a valid non-listening
  1274. * address/port. If so, set valid to true and add a newly allocated
  1275. * tor_addr_port_t containing "addr" and port_field to sl.
  1276. * "addr" is an IPv4 host-order address and port_field is a uint16_t.
  1277. * r is typically a routerinfo_t or routerstatus_t.
  1278. */
  1279. #define SL_ADD_NEW_IPV4_AP(r, port_field, sl, valid) \
  1280. STMT_BEGIN \
  1281. if (tor_addr_port_is_valid_ipv4h((r)->addr, (r)->port_field, 0)) { \
  1282. valid = 1; \
  1283. tor_addr_port_t *ap = tor_malloc(sizeof(tor_addr_port_t)); \
  1284. tor_addr_from_ipv4h(&ap->addr, (r)->addr); \
  1285. ap->port = (r)->port_field; \
  1286. smartlist_add((sl), ap); \
  1287. } \
  1288. STMT_END
  1289. /* Check if the "addr" and port_field fields from r are a valid non-listening
  1290. * address/port. If so, set valid to true and add a newly allocated
  1291. * tor_addr_port_t containing "addr" and port_field to sl.
  1292. * "addr" is a tor_addr_t and port_field is a uint16_t.
  1293. * r is typically a routerinfo_t or routerstatus_t.
  1294. */
  1295. #define SL_ADD_NEW_IPV6_AP(r, port_field, sl, valid) \
  1296. STMT_BEGIN \
  1297. if (tor_addr_port_is_valid(&(r)->ipv6_addr, (r)->port_field, 0)) { \
  1298. valid = 1; \
  1299. tor_addr_port_t *ap = tor_malloc(sizeof(tor_addr_port_t)); \
  1300. tor_addr_copy(&ap->addr, &(r)->ipv6_addr); \
  1301. ap->port = (r)->port_field; \
  1302. smartlist_add((sl), ap); \
  1303. } \
  1304. STMT_END
  1305. /** Return list of tor_addr_port_t with all OR ports (in the sense IP
  1306. * addr + TCP port) for <b>node</b>. Caller must free all elements
  1307. * using tor_free() and free the list using smartlist_free().
  1308. *
  1309. * XXX this is potentially a memory fragmentation hog -- if on
  1310. * critical path consider the option of having the caller allocate the
  1311. * memory
  1312. */
  1313. smartlist_t *
  1314. node_get_all_orports(const node_t *node)
  1315. {
  1316. smartlist_t *sl = smartlist_new();
  1317. int valid = 0;
  1318. /* Find a valid IPv4 address and port */
  1319. if (node->ri != NULL) {
  1320. SL_ADD_NEW_IPV4_AP(node->ri, or_port, sl, valid);
  1321. }
  1322. /* If we didn't find a valid address/port in the ri, try the rs */
  1323. if (!valid && node->rs != NULL) {
  1324. SL_ADD_NEW_IPV4_AP(node->rs, or_port, sl, valid);
  1325. }
  1326. /* Find a valid IPv6 address and port */
  1327. valid = 0;
  1328. if (node->ri != NULL) {
  1329. SL_ADD_NEW_IPV6_AP(node->ri, ipv6_orport, sl, valid);
  1330. }
  1331. if (!valid && node->rs != NULL) {
  1332. SL_ADD_NEW_IPV6_AP(node->rs, ipv6_orport, sl, valid);
  1333. }
  1334. if (!valid && node->md != NULL) {
  1335. SL_ADD_NEW_IPV6_AP(node->md, ipv6_orport, sl, valid);
  1336. }
  1337. return sl;
  1338. }
  1339. #undef SL_ADD_NEW_IPV4_AP
  1340. #undef SL_ADD_NEW_IPV6_AP
  1341. /** Wrapper around node_get_prim_orport for backward
  1342. compatibility. */
  1343. void
  1344. node_get_addr(const node_t *node, tor_addr_t *addr_out)
  1345. {
  1346. tor_addr_port_t ap;
  1347. node_get_prim_orport(node, &ap);
  1348. tor_addr_copy(addr_out, &ap.addr);
  1349. }
  1350. /** Return the host-order IPv4 address for <b>node</b>, or 0 if it doesn't
  1351. * seem to have one. */
  1352. uint32_t
  1353. node_get_prim_addr_ipv4h(const node_t *node)
  1354. {
  1355. /* Don't check the ORPort or DirPort, as this function isn't port-specific,
  1356. * and the node might have a valid IPv4 address, yet have a zero
  1357. * ORPort or DirPort.
  1358. */
  1359. if (node->ri && tor_addr_is_valid_ipv4h(node->ri->addr, 0)) {
  1360. return node->ri->addr;
  1361. } else if (node->rs && tor_addr_is_valid_ipv4h(node->rs->addr, 0)) {
  1362. return node->rs->addr;
  1363. }
  1364. return 0;
  1365. }
  1366. /** Copy a string representation of an IP address for <b>node</b> into
  1367. * the <b>len</b>-byte buffer at <b>buf</b>. */
  1368. void
  1369. node_get_address_string(const node_t *node, char *buf, size_t len)
  1370. {
  1371. uint32_t ipv4_addr = node_get_prim_addr_ipv4h(node);
  1372. if (tor_addr_is_valid_ipv4h(ipv4_addr, 0)) {
  1373. tor_addr_t addr;
  1374. tor_addr_from_ipv4h(&addr, ipv4_addr);
  1375. tor_addr_to_str(buf, &addr, len, 0);
  1376. } else if (len > 0) {
  1377. buf[0] = '\0';
  1378. }
  1379. }
  1380. /** Return <b>node</b>'s declared uptime, or -1 if it doesn't seem to have
  1381. * one. */
  1382. long
  1383. node_get_declared_uptime(const node_t *node)
  1384. {
  1385. if (node->ri)
  1386. return node->ri->uptime;
  1387. else
  1388. return -1;
  1389. }
  1390. /** Return <b>node</b>'s platform string, or NULL if we don't know it. */
  1391. const char *
  1392. node_get_platform(const node_t *node)
  1393. {
  1394. /* If we wanted, we could record the version in the routerstatus_t, since
  1395. * the consensus lists it. We don't, though, so this function just won't
  1396. * work with microdescriptors. */
  1397. if (node->ri)
  1398. return node->ri->platform;
  1399. else
  1400. return NULL;
  1401. }
  1402. /** Return true iff <b>node</b> is one representing this router. */
  1403. int
  1404. node_is_me(const node_t *node)
  1405. {
  1406. return router_digest_is_me(node->identity);
  1407. }
  1408. /* Does this node have a valid IPv6 address?
  1409. * Prefer node_has_ipv6_orport() or node_has_ipv6_dirport() for
  1410. * checking specific ports. */
  1411. int
  1412. node_has_ipv6_addr(const node_t *node)
  1413. {
  1414. /* Don't check the ORPort or DirPort, as this function isn't port-specific,
  1415. * and the node might have a valid IPv6 address, yet have a zero
  1416. * ORPort or DirPort.
  1417. */
  1418. if (node->ri && tor_addr_is_valid(&node->ri->ipv6_addr, 0))
  1419. return 1;
  1420. if (node->rs && tor_addr_is_valid(&node->rs->ipv6_addr, 0))
  1421. return 1;
  1422. if (node->md && tor_addr_is_valid(&node->md->ipv6_addr, 0))
  1423. return 1;
  1424. return 0;
  1425. }
  1426. /* Does this node have a valid IPv6 ORPort? */
  1427. int
  1428. node_has_ipv6_orport(const node_t *node)
  1429. {
  1430. tor_addr_port_t ipv6_orport;
  1431. node_get_pref_ipv6_orport(node, &ipv6_orport);
  1432. return tor_addr_port_is_valid_ap(&ipv6_orport, 0);
  1433. }
  1434. /* Does this node have a valid IPv6 DirPort? */
  1435. int
  1436. node_has_ipv6_dirport(const node_t *node)
  1437. {
  1438. tor_addr_port_t ipv6_dirport;
  1439. node_get_pref_ipv6_dirport(node, &ipv6_dirport);
  1440. return tor_addr_port_is_valid_ap(&ipv6_dirport, 0);
  1441. }
  1442. /** Return 1 if we prefer the IPv6 address and OR TCP port of
  1443. * <b>node</b>, else 0.
  1444. *
  1445. * We prefer the IPv6 address if the router has an IPv6 address,
  1446. * and we can use IPv6 addresses, and:
  1447. * i) the node_t says that it prefers IPv6
  1448. * or
  1449. * ii) the router has no IPv4 OR address.
  1450. *
  1451. * If you don't have a node, consider looking it up.
  1452. * If there is no node, use fascist_firewall_prefer_ipv6_orport().
  1453. */
  1454. int
  1455. node_ipv6_or_preferred(const node_t *node)
  1456. {
  1457. const or_options_t *options = get_options();
  1458. tor_addr_port_t ipv4_addr;
  1459. node_assert_ok(node);
  1460. /* XX/teor - node->ipv6_preferred is set from
  1461. * fascist_firewall_prefer_ipv6_orport() each time the consensus is loaded.
  1462. */
  1463. node_get_prim_orport(node, &ipv4_addr);
  1464. if (!fascist_firewall_use_ipv6(options)) {
  1465. return 0;
  1466. } else if (node->ipv6_preferred ||
  1467. !tor_addr_port_is_valid_ap(&ipv4_addr, 0)) {
  1468. return node_has_ipv6_orport(node);
  1469. }
  1470. return 0;
  1471. }
  1472. #define RETURN_IPV4_AP(r, port_field, ap_out) \
  1473. STMT_BEGIN \
  1474. if (r && tor_addr_port_is_valid_ipv4h((r)->addr, (r)->port_field, 0)) { \
  1475. tor_addr_from_ipv4h(&(ap_out)->addr, (r)->addr); \
  1476. (ap_out)->port = (r)->port_field; \
  1477. } \
  1478. STMT_END
  1479. /** Copy the primary (IPv4) OR port (IP address and TCP port) for <b>node</b>
  1480. * into *<b>ap_out</b>. */
  1481. void
  1482. node_get_prim_orport(const node_t *node, tor_addr_port_t *ap_out)
  1483. {
  1484. node_assert_ok(node);
  1485. tor_assert(ap_out);
  1486. /* Clear the address, as a safety precaution if calling functions ignore the
  1487. * return value */
  1488. tor_addr_make_null(&ap_out->addr, AF_INET);
  1489. ap_out->port = 0;
  1490. /* Check ri first, because rewrite_node_address_for_bridge() updates
  1491. * node->ri with the configured bridge address. */
  1492. RETURN_IPV4_AP(node->ri, or_port, ap_out);
  1493. RETURN_IPV4_AP(node->rs, or_port, ap_out);
  1494. /* Microdescriptors only have an IPv6 address */
  1495. }
  1496. /** Copy the preferred OR port (IP address and TCP port) for
  1497. * <b>node</b> into *<b>ap_out</b>. */
  1498. void
  1499. node_get_pref_orport(const node_t *node, tor_addr_port_t *ap_out)
  1500. {
  1501. tor_assert(ap_out);
  1502. if (node_ipv6_or_preferred(node)) {
  1503. node_get_pref_ipv6_orport(node, ap_out);
  1504. } else {
  1505. /* the primary ORPort is always on IPv4 */
  1506. node_get_prim_orport(node, ap_out);
  1507. }
  1508. }
  1509. /** Copy the preferred IPv6 OR port (IP address and TCP port) for
  1510. * <b>node</b> into *<b>ap_out</b>. */
  1511. void
  1512. node_get_pref_ipv6_orport(const node_t *node, tor_addr_port_t *ap_out)
  1513. {
  1514. node_assert_ok(node);
  1515. tor_assert(ap_out);
  1516. memset(ap_out, 0, sizeof(*ap_out));
  1517. /* Check ri first, because rewrite_node_address_for_bridge() updates
  1518. * node->ri with the configured bridge address.
  1519. * Prefer rs over md for consistency with the fascist_firewall_* functions.
  1520. * Check if the address or port are valid, and try another alternative
  1521. * if they are not. */
  1522. if (node->ri && tor_addr_port_is_valid(&node->ri->ipv6_addr,
  1523. node->ri->ipv6_orport, 0)) {
  1524. tor_addr_copy(&ap_out->addr, &node->ri->ipv6_addr);
  1525. ap_out->port = node->ri->ipv6_orport;
  1526. } else if (node->rs && tor_addr_port_is_valid(&node->rs->ipv6_addr,
  1527. node->rs->ipv6_orport, 0)) {
  1528. tor_addr_copy(&ap_out->addr, &node->rs->ipv6_addr);
  1529. ap_out->port = node->rs->ipv6_orport;
  1530. } else if (node->md && tor_addr_port_is_valid(&node->md->ipv6_addr,
  1531. node->md->ipv6_orport, 0)) {
  1532. tor_addr_copy(&ap_out->addr, &node->md->ipv6_addr);
  1533. ap_out->port = node->md->ipv6_orport;
  1534. } else {
  1535. tor_addr_make_null(&ap_out->addr, AF_INET6);
  1536. ap_out->port = 0;
  1537. }
  1538. }
  1539. /** Return 1 if we prefer the IPv6 address and Dir TCP port of
  1540. * <b>node</b>, else 0.
  1541. *
  1542. * We prefer the IPv6 address if the router has an IPv6 address,
  1543. * and we can use IPv6 addresses, and:
  1544. * i) the router has no IPv4 Dir address.
  1545. * or
  1546. * ii) our preference is for IPv6 Dir addresses.
  1547. *
  1548. * If there is no node, use fascist_firewall_prefer_ipv6_dirport().
  1549. */
  1550. int
  1551. node_ipv6_dir_preferred(const node_t *node)
  1552. {
  1553. const or_options_t *options = get_options();
  1554. tor_addr_port_t ipv4_addr;
  1555. node_assert_ok(node);
  1556. /* node->ipv6_preferred is set from fascist_firewall_prefer_ipv6_orport(),
  1557. * so we can't use it to determine DirPort IPv6 preference.
  1558. * This means that bridge clients will use IPv4 DirPorts by default.
  1559. */
  1560. node_get_prim_dirport(node, &ipv4_addr);
  1561. if (!fascist_firewall_use_ipv6(options)) {
  1562. return 0;
  1563. } else if (!tor_addr_port_is_valid_ap(&ipv4_addr, 0)
  1564. || fascist_firewall_prefer_ipv6_dirport(get_options())) {
  1565. return node_has_ipv6_dirport(node);
  1566. }
  1567. return 0;
  1568. }
  1569. /** Copy the primary (IPv4) Dir port (IP address and TCP port) for <b>node</b>
  1570. * into *<b>ap_out</b>. */
  1571. void
  1572. node_get_prim_dirport(const node_t *node, tor_addr_port_t *ap_out)
  1573. {
  1574. node_assert_ok(node);
  1575. tor_assert(ap_out);
  1576. /* Clear the address, as a safety precaution if calling functions ignore the
  1577. * return value */
  1578. tor_addr_make_null(&ap_out->addr, AF_INET);
  1579. ap_out->port = 0;
  1580. /* Check ri first, because rewrite_node_address_for_bridge() updates
  1581. * node->ri with the configured bridge address. */
  1582. RETURN_IPV4_AP(node->ri, dir_port, ap_out);
  1583. RETURN_IPV4_AP(node->rs, dir_port, ap_out);
  1584. /* Microdescriptors only have an IPv6 address */
  1585. }
  1586. #undef RETURN_IPV4_AP
  1587. /** Copy the preferred Dir port (IP address and TCP port) for
  1588. * <b>node</b> into *<b>ap_out</b>. */
  1589. void
  1590. node_get_pref_dirport(const node_t *node, tor_addr_port_t *ap_out)
  1591. {
  1592. tor_assert(ap_out);
  1593. if (node_ipv6_dir_preferred(node)) {
  1594. node_get_pref_ipv6_dirport(node, ap_out);
  1595. } else {
  1596. /* the primary DirPort is always on IPv4 */
  1597. node_get_prim_dirport(node, ap_out);
  1598. }
  1599. }
  1600. /** Copy the preferred IPv6 Dir port (IP address and TCP port) for
  1601. * <b>node</b> into *<b>ap_out</b>. */
  1602. void
  1603. node_get_pref_ipv6_dirport(const node_t *node, tor_addr_port_t *ap_out)
  1604. {
  1605. node_assert_ok(node);
  1606. tor_assert(ap_out);
  1607. /* Check ri first, because rewrite_node_address_for_bridge() updates
  1608. * node->ri with the configured bridge address.
  1609. * Prefer rs over md for consistency with the fascist_firewall_* functions.
  1610. * Check if the address or port are valid, and try another alternative
  1611. * if they are not. */
  1612. /* Assume IPv4 and IPv6 dirports are the same */
  1613. if (node->ri && tor_addr_port_is_valid(&node->ri->ipv6_addr,
  1614. node->ri->dir_port, 0)) {
  1615. tor_addr_copy(&ap_out->addr, &node->ri->ipv6_addr);
  1616. ap_out->port = node->ri->dir_port;
  1617. } else if (node->rs && tor_addr_port_is_valid(&node->rs->ipv6_addr,
  1618. node->rs->dir_port, 0)) {
  1619. tor_addr_copy(&ap_out->addr, &node->rs->ipv6_addr);
  1620. ap_out->port = node->rs->dir_port;
  1621. } else {
  1622. tor_addr_make_null(&ap_out->addr, AF_INET6);
  1623. ap_out->port = 0;
  1624. }
  1625. }
  1626. /** Return true iff <b>md</b> has a curve25519 onion key.
  1627. * Use node_has_curve25519_onion_key() instead of calling this directly. */
  1628. static int
  1629. microdesc_has_curve25519_onion_key(const microdesc_t *md)
  1630. {
  1631. if (!md) {
  1632. return 0;
  1633. }
  1634. if (!md->onion_curve25519_pkey) {
  1635. return 0;
  1636. }
  1637. if (fast_mem_is_zero((const char*)md->onion_curve25519_pkey->public_key,
  1638. CURVE25519_PUBKEY_LEN)) {
  1639. return 0;
  1640. }
  1641. return 1;
  1642. }
  1643. /** Return true iff <b>node</b> has a curve25519 onion key. */
  1644. int
  1645. node_has_curve25519_onion_key(const node_t *node)
  1646. {
  1647. return node_get_curve25519_onion_key(node) != NULL;
  1648. }
  1649. /** Return the curve25519 key of <b>node</b>, or NULL if none. */
  1650. const curve25519_public_key_t *
  1651. node_get_curve25519_onion_key(const node_t *node)
  1652. {
  1653. if (!node)
  1654. return NULL;
  1655. if (routerinfo_has_curve25519_onion_key(node->ri))
  1656. return node->ri->onion_curve25519_pkey;
  1657. else if (microdesc_has_curve25519_onion_key(node->md))
  1658. return node->md->onion_curve25519_pkey;
  1659. else
  1660. return NULL;
  1661. }
  1662. /* Return a newly allocacted RSA onion public key taken from the given node.
  1663. *
  1664. * Return NULL if node is NULL or no RSA onion public key can be found. It is
  1665. * the caller responsability to free the returned object. */
  1666. crypto_pk_t *
  1667. node_get_rsa_onion_key(const node_t *node)
  1668. {
  1669. crypto_pk_t *pk = NULL;
  1670. const char *onion_pkey;
  1671. size_t onion_pkey_len;
  1672. if (!node) {
  1673. goto end;
  1674. }
  1675. if (node->ri) {
  1676. onion_pkey = node->ri->onion_pkey;
  1677. onion_pkey_len = node->ri->onion_pkey_len;
  1678. } else if (node->rs && node->md) {
  1679. onion_pkey = node->md->onion_pkey;
  1680. onion_pkey_len = node->md->onion_pkey_len;
  1681. } else {
  1682. /* No descriptor or microdescriptor. */
  1683. goto end;
  1684. }
  1685. pk = router_get_rsa_onion_pkey(onion_pkey, onion_pkey_len);
  1686. end:
  1687. return pk;
  1688. }
  1689. /** Refresh the country code of <b>ri</b>. This function MUST be called on
  1690. * each router when the GeoIP database is reloaded, and on all new routers. */
  1691. void
  1692. node_set_country(node_t *node)
  1693. {
  1694. tor_addr_t addr = TOR_ADDR_NULL;
  1695. /* XXXXipv6 */
  1696. if (node->rs)
  1697. tor_addr_from_ipv4h(&addr, node->rs->addr);
  1698. else if (node->ri)
  1699. tor_addr_from_ipv4h(&addr, node->ri->addr);
  1700. node->country = geoip_get_country_by_addr(&addr);
  1701. }
  1702. /** Set the country code of all routers in the routerlist. */
  1703. void
  1704. nodelist_refresh_countries(void)
  1705. {
  1706. const smartlist_t *nodes = nodelist_get_list();
  1707. SMARTLIST_FOREACH(nodes, node_t *, node,
  1708. node_set_country(node));
  1709. }
  1710. /** Return true iff router1 and router2 have similar enough network addresses
  1711. * that we should treat them as being in the same family */
  1712. int
  1713. addrs_in_same_network_family(const tor_addr_t *a1,
  1714. const tor_addr_t *a2)
  1715. {
  1716. if (tor_addr_is_null(a1) || tor_addr_is_null(a2))
  1717. return 0;
  1718. switch (tor_addr_family(a1)) {
  1719. case AF_INET:
  1720. return 0 == tor_addr_compare_masked(a1, a2, 16, CMP_SEMANTIC);
  1721. case AF_INET6:
  1722. return 0 == tor_addr_compare_masked(a1, a2, 32, CMP_SEMANTIC);
  1723. default:
  1724. /* If not IPv4 or IPv6, return 0. */
  1725. return 0;
  1726. }
  1727. }
  1728. /** Return true if <b>node</b>'s nickname matches <b>nickname</b>
  1729. * (case-insensitive), or if <b>node's</b> identity key digest
  1730. * matches a hexadecimal value stored in <b>nickname</b>. Return
  1731. * false otherwise. */
  1732. STATIC int
  1733. node_nickname_matches(const node_t *node, const char *nickname)
  1734. {
  1735. const char *n = node_get_nickname(node);
  1736. if (n && nickname[0]!='$' && !strcasecmp(n, nickname))
  1737. return 1;
  1738. return hex_digest_nickname_matches(nickname,
  1739. node->identity,
  1740. n);
  1741. }
  1742. /** Return true iff <b>node</b> is named by some nickname in <b>lst</b>. */
  1743. STATIC int
  1744. node_in_nickname_smartlist(const smartlist_t *lst, const node_t *node)
  1745. {
  1746. if (!lst) return 0;
  1747. SMARTLIST_FOREACH(lst, const char *, name, {
  1748. if (node_nickname_matches(node, name))
  1749. return 1;
  1750. });
  1751. return 0;
  1752. }
  1753. /** Return true iff n1's declared family contains n2. */
  1754. STATIC int
  1755. node_family_contains(const node_t *n1, const node_t *n2)
  1756. {
  1757. if (n1->ri && n1->ri->declared_family) {
  1758. return node_in_nickname_smartlist(n1->ri->declared_family, n2);
  1759. } else if (n1->md) {
  1760. return nodefamily_contains_node(n1->md->family, n2);
  1761. } else {
  1762. return 0;
  1763. }
  1764. }
  1765. /**
  1766. * Return true iff <b>node</b> has declared a nonempty family.
  1767. **/
  1768. STATIC bool
  1769. node_has_declared_family(const node_t *node)
  1770. {
  1771. if (node->ri && node->ri->declared_family &&
  1772. smartlist_len(node->ri->declared_family)) {
  1773. return true;
  1774. }
  1775. if (node->md && node->md->family) {
  1776. return true;
  1777. }
  1778. return false;
  1779. }
  1780. /**
  1781. * Add to <b>out</b> every node_t that is listed by <b>node</b> as being in
  1782. * its family. (Note that these nodes are not in node's family unless they
  1783. * also agree that node is in their family.)
  1784. **/
  1785. STATIC void
  1786. node_lookup_declared_family(smartlist_t *out, const node_t *node)
  1787. {
  1788. if (node->ri && node->ri->declared_family &&
  1789. smartlist_len(node->ri->declared_family)) {
  1790. SMARTLIST_FOREACH_BEGIN(node->ri->declared_family, const char *, name) {
  1791. const node_t *n2 = node_get_by_nickname(name, NNF_NO_WARN_UNNAMED);
  1792. if (n2) {
  1793. smartlist_add(out, (node_t *)n2);
  1794. }
  1795. } SMARTLIST_FOREACH_END(name);
  1796. return;
  1797. }
  1798. if (node->md && node->md->family) {
  1799. nodefamily_add_nodes_to_smartlist(node->md->family, out);
  1800. }
  1801. }
  1802. /** Return true iff r1 and r2 are in the same family, but not the same
  1803. * router. */
  1804. int
  1805. nodes_in_same_family(const node_t *node1, const node_t *node2)
  1806. {
  1807. const or_options_t *options = get_options();
  1808. /* Are they in the same family because of their addresses? */
  1809. if (options->EnforceDistinctSubnets) {
  1810. tor_addr_t a1, a2;
  1811. node_get_addr(node1, &a1);
  1812. node_get_addr(node2, &a2);
  1813. tor_addr_port_t ap6_1, ap6_2;
  1814. node_get_pref_ipv6_orport(node1, &ap6_1);
  1815. node_get_pref_ipv6_orport(node2, &ap6_2);
  1816. if (addrs_in_same_network_family(&a1, &a2) ||
  1817. addrs_in_same_network_family(&ap6_1.addr, &ap6_2.addr))
  1818. return 1;
  1819. }
  1820. /* Are they in the same family because the agree they are? */
  1821. if (node_family_contains(node1, node2) &&
  1822. node_family_contains(node2, node1)) {
  1823. return 1;
  1824. }
  1825. /* Are they in the same family because the user says they are? */
  1826. if (options->NodeFamilySets) {
  1827. SMARTLIST_FOREACH(options->NodeFamilySets, const routerset_t *, rs, {
  1828. if (routerset_contains_node(rs, node1) &&
  1829. routerset_contains_node(rs, node2))
  1830. return 1;
  1831. });
  1832. }
  1833. return 0;
  1834. }
  1835. /**
  1836. * Add all the family of <b>node</b>, including <b>node</b> itself, to
  1837. * the smartlist <b>sl</b>.
  1838. *
  1839. * This is used to make sure we don't pick siblings in a single path, or
  1840. * pick more than one relay from a family for our entry guard list.
  1841. * Note that a node may be added to <b>sl</b> more than once if it is
  1842. * part of <b>node</b>'s family for more than one reason.
  1843. */
  1844. void
  1845. nodelist_add_node_and_family(smartlist_t *sl, const node_t *node)
  1846. {
  1847. const smartlist_t *all_nodes = nodelist_get_list();
  1848. const or_options_t *options = get_options();
  1849. tor_assert(node);
  1850. /* Let's make sure that we have the node itself, if it's a real node. */
  1851. {
  1852. const node_t *real_node = node_get_by_id(node->identity);
  1853. if (real_node)
  1854. smartlist_add(sl, (node_t*)real_node);
  1855. }
  1856. /* First, add any nodes with similar network addresses. */
  1857. if (options->EnforceDistinctSubnets) {
  1858. tor_addr_t node_addr;
  1859. tor_addr_port_t node_ap6;
  1860. node_get_addr(node, &node_addr);
  1861. node_get_pref_ipv6_orport(node, &node_ap6);
  1862. SMARTLIST_FOREACH_BEGIN(all_nodes, const node_t *, node2) {
  1863. tor_addr_t a;
  1864. tor_addr_port_t ap6;
  1865. node_get_addr(node2, &a);
  1866. node_get_pref_ipv6_orport(node2, &ap6);
  1867. if (addrs_in_same_network_family(&a, &node_addr) ||
  1868. addrs_in_same_network_family(&ap6.addr, &node_ap6.addr))
  1869. smartlist_add(sl, (void*)node2);
  1870. } SMARTLIST_FOREACH_END(node2);
  1871. }
  1872. /* Now, add all nodes in the declared family of this node, if they
  1873. * also declare this node to be in their family. */
  1874. if (node_has_declared_family(node)) {
  1875. smartlist_t *declared_family = smartlist_new();
  1876. node_lookup_declared_family(declared_family, node);
  1877. /* Add every r such that router declares familyness with node, and node
  1878. * declares familyhood with router. */
  1879. SMARTLIST_FOREACH_BEGIN(declared_family, const node_t *, node2) {
  1880. if (node_family_contains(node2, node)) {
  1881. smartlist_add(sl, (void*)node2);
  1882. }
  1883. } SMARTLIST_FOREACH_END(node2);
  1884. smartlist_free(declared_family);
  1885. }
  1886. /* If the user declared any families locally, honor those too. */
  1887. if (options->NodeFamilySets) {
  1888. SMARTLIST_FOREACH(options->NodeFamilySets, const routerset_t *, rs, {
  1889. if (routerset_contains_node(rs, node)) {
  1890. routerset_get_all_nodes(sl, rs, NULL, 0);
  1891. }
  1892. });
  1893. }
  1894. }
  1895. /** Find a router that's up, that has this IP address, and
  1896. * that allows exit to this address:port, or return NULL if there
  1897. * isn't a good one.
  1898. * Don't exit enclave to excluded relays -- it wouldn't actually
  1899. * hurt anything, but this way there are fewer confused users.
  1900. */
  1901. const node_t *
  1902. router_find_exact_exit_enclave(const char *address, uint16_t port)
  1903. {/*XXXX MOVE*/
  1904. uint32_t addr;
  1905. struct in_addr in;
  1906. tor_addr_t a;
  1907. const or_options_t *options = get_options();
  1908. if (!tor_inet_aton(address, &in))
  1909. return NULL; /* it's not an IP already */
  1910. addr = ntohl(in.s_addr);
  1911. tor_addr_from_ipv4h(&a, addr);
  1912. SMARTLIST_FOREACH(nodelist_get_list(), const node_t *, node, {
  1913. if (node_get_addr_ipv4h(node) == addr &&
  1914. node->is_running &&
  1915. compare_tor_addr_to_node_policy(&a, port, node) ==
  1916. ADDR_POLICY_ACCEPTED &&
  1917. !routerset_contains_node(options->ExcludeExitNodesUnion_, node))
  1918. return node;
  1919. });
  1920. return NULL;
  1921. }
  1922. /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
  1923. * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
  1924. * If <b>need_capacity</b> is non-zero, we require a minimum advertised
  1925. * bandwidth.
  1926. * If <b>need_guard</b>, we require that the router is a possible entry guard.
  1927. */
  1928. int
  1929. node_is_unreliable(const node_t *node, int need_uptime,
  1930. int need_capacity, int need_guard)
  1931. {
  1932. if (need_uptime && !node->is_stable)
  1933. return 1;
  1934. if (need_capacity && !node->is_fast)
  1935. return 1;
  1936. if (need_guard && !node->is_possible_guard)
  1937. return 1;
  1938. return 0;
  1939. }
  1940. /** Return 1 if all running sufficiently-stable routers we can use will reject
  1941. * addr:port. Return 0 if any might accept it. */
  1942. int
  1943. router_exit_policy_all_nodes_reject(const tor_addr_t *addr, uint16_t port,
  1944. int need_uptime)
  1945. {
  1946. addr_policy_result_t r;
  1947. SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), const node_t *, node) {
  1948. if (node->is_running &&
  1949. !node_is_unreliable(node, need_uptime, 0, 0)) {
  1950. r = compare_tor_addr_to_node_policy(addr, port, node);
  1951. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  1952. return 0; /* this one could be ok. good enough. */
  1953. }
  1954. } SMARTLIST_FOREACH_END(node);
  1955. return 1; /* all will reject. */
  1956. }
  1957. /** Mark the router with ID <b>digest</b> as running or non-running
  1958. * in our routerlist. */
  1959. void
  1960. router_set_status(const char *digest, int up)
  1961. {
  1962. node_t *node;
  1963. tor_assert(digest);
  1964. SMARTLIST_FOREACH(router_get_fallback_dir_servers(),
  1965. dir_server_t *, d,
  1966. if (tor_memeq(d->digest, digest, DIGEST_LEN))
  1967. d->is_running = up);
  1968. SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
  1969. dir_server_t *, d,
  1970. if (tor_memeq(d->digest, digest, DIGEST_LEN))
  1971. d->is_running = up);
  1972. node = node_get_mutable_by_id(digest);
  1973. if (node) {
  1974. #if 0
  1975. log_debug(LD_DIR,"Marking router %s as %s.",
  1976. node_describe(node), up ? "up" : "down");
  1977. #endif
  1978. if (!up && node_is_me(node) && !net_is_disabled())
  1979. log_warn(LD_NET, "We just marked ourself as down. Are your external "
  1980. "addresses reachable?");
  1981. if (bool_neq(node->is_running, up))
  1982. router_dir_info_changed();
  1983. node->is_running = up;
  1984. }
  1985. }
  1986. /** True iff, the last time we checked whether we had enough directory info
  1987. * to build circuits, the answer was "yes". If there are no exits in the
  1988. * consensus, we act as if we have 100% of the exit directory info. */
  1989. static int have_min_dir_info = 0;
  1990. /** Does the consensus contain nodes that can exit? */
  1991. static consensus_path_type_t have_consensus_path = CONSENSUS_PATH_UNKNOWN;
  1992. /** True iff enough has changed since the last time we checked whether we had
  1993. * enough directory info to build circuits that our old answer can no longer
  1994. * be trusted. */
  1995. static int need_to_update_have_min_dir_info = 1;
  1996. /** String describing what we're missing before we have enough directory
  1997. * info. */
  1998. static char dir_info_status[512] = "";
  1999. /** Return true iff we have enough consensus information to
  2000. * start building circuits. Right now, this means "a consensus that's
  2001. * less than a day old, and at least 60% of router descriptors (configurable),
  2002. * weighted by bandwidth. Treat the exit fraction as 100% if there are
  2003. * no exits in the consensus."
  2004. * To obtain the final weighted bandwidth, we multiply the
  2005. * weighted bandwidth fraction for each position (guard, middle, exit). */
  2006. MOCK_IMPL(int,
  2007. router_have_minimum_dir_info,(void))
  2008. {
  2009. static int logged_delay=0;
  2010. const char *delay_fetches_msg = NULL;
  2011. if (should_delay_dir_fetches(get_options(), &delay_fetches_msg)) {
  2012. if (!logged_delay)
  2013. log_notice(LD_DIR, "Delaying directory fetches: %s", delay_fetches_msg);
  2014. logged_delay=1;
  2015. strlcpy(dir_info_status, delay_fetches_msg, sizeof(dir_info_status));
  2016. return 0;
  2017. }
  2018. logged_delay = 0; /* reset it if we get this far */
  2019. if (PREDICT_UNLIKELY(need_to_update_have_min_dir_info)) {
  2020. update_router_have_minimum_dir_info();
  2021. }
  2022. return have_min_dir_info;
  2023. }
  2024. /** Set to CONSENSUS_PATH_EXIT if there is at least one exit node
  2025. * in the consensus. We update this flag in compute_frac_paths_available if
  2026. * there is at least one relay that has an Exit flag in the consensus.
  2027. * Used to avoid building exit circuits when they will almost certainly fail.
  2028. * Set to CONSENSUS_PATH_INTERNAL if there are no exits in the consensus.
  2029. * (This situation typically occurs during bootstrap of a test network.)
  2030. * Set to CONSENSUS_PATH_UNKNOWN if we have never checked, or have
  2031. * reason to believe our last known value was invalid or has expired.
  2032. * If we're in a network with TestingDirAuthVoteExit set,
  2033. * this can cause router_have_consensus_path() to be set to
  2034. * CONSENSUS_PATH_EXIT, even if there are no nodes with accept exit policies.
  2035. */
  2036. MOCK_IMPL(consensus_path_type_t,
  2037. router_have_consensus_path, (void))
  2038. {
  2039. return have_consensus_path;
  2040. }
  2041. /** Called when our internal view of the directory has changed. This can be
  2042. * when the authorities change, networkstatuses change, the list of routerdescs
  2043. * changes, or number of running routers changes.
  2044. */
  2045. void
  2046. router_dir_info_changed(void)
  2047. {
  2048. need_to_update_have_min_dir_info = 1;
  2049. rend_hsdir_routers_changed();
  2050. hs_service_dir_info_changed();
  2051. hs_client_dir_info_changed();
  2052. }
  2053. /** Return a string describing what we're missing before we have enough
  2054. * directory info. */
  2055. const char *
  2056. get_dir_info_status_string(void)
  2057. {
  2058. return dir_info_status;
  2059. }
  2060. /** Iterate over the servers listed in <b>consensus</b>, and count how many of
  2061. * them seem like ones we'd use (store this in *<b>num_usable</b>), and how
  2062. * many of <em>those</em> we have descriptors for (store this in
  2063. * *<b>num_present</b>).
  2064. *
  2065. * If <b>in_set</b> is non-NULL, only consider those routers in <b>in_set</b>.
  2066. * If <b>exit_only</b> & USABLE_DESCRIPTOR_EXIT_POLICY, only consider nodes
  2067. * present if they have an exit policy that accepts at least one port.
  2068. * If <b>exit_only</b> & USABLE_DESCRIPTOR_EXIT_FLAG, only consider nodes
  2069. * usable if they have the exit flag in the consensus.
  2070. *
  2071. * If *<b>descs_out</b> is present, add a node_t for each usable descriptor
  2072. * to it.
  2073. */
  2074. static void
  2075. count_usable_descriptors(int *num_present, int *num_usable,
  2076. smartlist_t *descs_out,
  2077. const networkstatus_t *consensus,
  2078. time_t now,
  2079. routerset_t *in_set,
  2080. usable_descriptor_t exit_only)
  2081. {
  2082. const int md = (consensus->flavor == FLAV_MICRODESC);
  2083. *num_present = 0, *num_usable = 0;
  2084. SMARTLIST_FOREACH_BEGIN(consensus->routerstatus_list, routerstatus_t *, rs)
  2085. {
  2086. const node_t *node = node_get_by_id(rs->identity_digest);
  2087. if (!node)
  2088. continue; /* This would be a bug: every entry in the consensus is
  2089. * supposed to have a node. */
  2090. if ((exit_only & USABLE_DESCRIPTOR_EXIT_FLAG) && ! rs->is_exit)
  2091. continue;
  2092. if (in_set && ! routerset_contains_routerstatus(in_set, rs, -1))
  2093. continue;
  2094. if (client_would_use_router(rs, now)) {
  2095. const char * const digest = rs->descriptor_digest;
  2096. int present;
  2097. ++*num_usable; /* the consensus says we want it. */
  2098. if (md)
  2099. present = NULL != microdesc_cache_lookup_by_digest256(NULL, digest);
  2100. else
  2101. present = NULL != router_get_by_descriptor_digest(digest);
  2102. if (present) {
  2103. /* Do the policy check last, because it requires a descriptor,
  2104. * and is potentially expensive */
  2105. if ((exit_only & USABLE_DESCRIPTOR_EXIT_POLICY) &&
  2106. node_exit_policy_rejects_all(node)) {
  2107. continue;
  2108. }
  2109. /* we have the descriptor listed in the consensus, and it
  2110. * satisfies our exit constraints (if any) */
  2111. ++*num_present;
  2112. }
  2113. if (descs_out)
  2114. smartlist_add(descs_out, (node_t*)node);
  2115. }
  2116. }
  2117. SMARTLIST_FOREACH_END(rs);
  2118. log_debug(LD_DIR, "%d usable, %d present (%s%s%s%s%s).",
  2119. *num_usable, *num_present,
  2120. md ? "microdesc" : "desc",
  2121. (exit_only & USABLE_DESCRIPTOR_EXIT_POLICY_AND_FLAG) ?
  2122. " exit" : "s",
  2123. (exit_only & USABLE_DESCRIPTOR_EXIT_POLICY) ?
  2124. " policies" : "" ,
  2125. (exit_only == USABLE_DESCRIPTOR_EXIT_POLICY_AND_FLAG) ?
  2126. " and" : "" ,
  2127. (exit_only & USABLE_DESCRIPTOR_EXIT_FLAG) ?
  2128. " flags" : "" );
  2129. }
  2130. /** Return an estimate of which fraction of usable paths through the Tor
  2131. * network we have available for use. Count how many routers seem like ones
  2132. * we'd use (store this in *<b>num_usable_out</b>), and how many of
  2133. * <em>those</em> we have descriptors for (store this in
  2134. * *<b>num_present_out</b>.)
  2135. *
  2136. * If **<b>status_out</b> is present, allocate a new string and print the
  2137. * available percentages of guard, middle, and exit nodes to it, noting
  2138. * whether there are exits in the consensus.
  2139. * If there are no exits in the consensus, we treat the exit fraction as 100%,
  2140. * but set router_have_consensus_path() so that we can only build internal
  2141. * paths. */
  2142. static double
  2143. compute_frac_paths_available(const networkstatus_t *consensus,
  2144. const or_options_t *options, time_t now,
  2145. int *num_present_out, int *num_usable_out,
  2146. char **status_out)
  2147. {
  2148. smartlist_t *guards = smartlist_new();
  2149. smartlist_t *mid = smartlist_new();
  2150. smartlist_t *exits = smartlist_new();
  2151. double f_guard, f_mid, f_exit;
  2152. double f_path = 0.0;
  2153. /* Used to determine whether there are any exits in the consensus */
  2154. int np = 0;
  2155. /* Used to determine whether there are any exits with descriptors */
  2156. int nu = 0;
  2157. const int authdir = authdir_mode_v3(options);
  2158. count_usable_descriptors(num_present_out, num_usable_out,
  2159. mid, consensus, now, options->MiddleNodes,
  2160. USABLE_DESCRIPTOR_ALL);
  2161. log_debug(LD_NET,
  2162. "%s: %d present, %d usable",
  2163. "mid",
  2164. np,
  2165. nu);
  2166. if (options->EntryNodes) {
  2167. count_usable_descriptors(&np, &nu, guards, consensus, now,
  2168. options->EntryNodes, USABLE_DESCRIPTOR_ALL);
  2169. log_debug(LD_NET,
  2170. "%s: %d present, %d usable",
  2171. "guard",
  2172. np,
  2173. nu);
  2174. } else {
  2175. SMARTLIST_FOREACH(mid, const node_t *, node, {
  2176. if (authdir) {
  2177. if (node->rs && node->rs->is_possible_guard)
  2178. smartlist_add(guards, (node_t*)node);
  2179. } else {
  2180. if (node->is_possible_guard)
  2181. smartlist_add(guards, (node_t*)node);
  2182. }
  2183. });
  2184. log_debug(LD_NET,
  2185. "%s: %d possible",
  2186. "guard",
  2187. smartlist_len(guards));
  2188. }
  2189. /* All nodes with exit policy and flag */
  2190. count_usable_descriptors(&np, &nu, exits, consensus, now,
  2191. NULL, USABLE_DESCRIPTOR_EXIT_POLICY_AND_FLAG);
  2192. log_debug(LD_NET,
  2193. "%s: %d present, %d usable",
  2194. "exits",
  2195. np,
  2196. nu);
  2197. /* We need at least 1 exit (flag and policy) in the consensus to consider
  2198. * building exit paths */
  2199. /* Update our understanding of whether the consensus has exits */
  2200. consensus_path_type_t old_have_consensus_path = have_consensus_path;
  2201. have_consensus_path = ((np > 0) ?
  2202. CONSENSUS_PATH_EXIT :
  2203. CONSENSUS_PATH_INTERNAL);
  2204. if (old_have_consensus_path != have_consensus_path) {
  2205. if (have_consensus_path == CONSENSUS_PATH_INTERNAL) {
  2206. log_notice(LD_NET,
  2207. "The current consensus has no exit nodes. "
  2208. "Tor can only build internal paths, "
  2209. "such as paths to onion services.");
  2210. /* However, exit nodes can reachability self-test using this consensus,
  2211. * join the network, and appear in a later consensus. This will allow
  2212. * the network to build exit paths, such as paths for world wide web
  2213. * browsing (as distinct from hidden service web browsing). */
  2214. } else if (old_have_consensus_path == CONSENSUS_PATH_INTERNAL) {
  2215. log_notice(LD_NET,
  2216. "The current consensus contains exit nodes. "
  2217. "Tor can build exit and internal paths.");
  2218. }
  2219. }
  2220. f_guard = frac_nodes_with_descriptors(guards, WEIGHT_FOR_GUARD, 1);
  2221. f_mid = frac_nodes_with_descriptors(mid, WEIGHT_FOR_MID, 0);
  2222. f_exit = frac_nodes_with_descriptors(exits, WEIGHT_FOR_EXIT, 0);
  2223. /* If we are using bridges and have at least one bridge with a full
  2224. * descriptor, assume f_guard is 1.0. */
  2225. if (options->UseBridges && num_bridges_usable(0) > 0)
  2226. f_guard = 1.0;
  2227. log_debug(LD_NET,
  2228. "f_guard: %.2f, f_mid: %.2f, f_exit: %.2f",
  2229. f_guard,
  2230. f_mid,
  2231. f_exit);
  2232. smartlist_free(guards);
  2233. smartlist_free(mid);
  2234. smartlist_free(exits);
  2235. if (options->ExitNodes) {
  2236. double f_myexit, f_myexit_unflagged;
  2237. smartlist_t *myexits= smartlist_new();
  2238. smartlist_t *myexits_unflagged = smartlist_new();
  2239. /* All nodes with exit policy and flag in ExitNodes option */
  2240. count_usable_descriptors(&np, &nu, myexits, consensus, now,
  2241. options->ExitNodes,
  2242. USABLE_DESCRIPTOR_EXIT_POLICY_AND_FLAG);
  2243. log_debug(LD_NET,
  2244. "%s: %d present, %d usable",
  2245. "myexits",
  2246. np,
  2247. nu);
  2248. /* Now compute the nodes in the ExitNodes option where we know their exit
  2249. * policy permits something. */
  2250. count_usable_descriptors(&np, &nu, myexits_unflagged,
  2251. consensus, now,
  2252. options->ExitNodes,
  2253. USABLE_DESCRIPTOR_EXIT_POLICY);
  2254. log_debug(LD_NET,
  2255. "%s: %d present, %d usable",
  2256. "myexits_unflagged (initial)",
  2257. np,
  2258. nu);
  2259. f_myexit= frac_nodes_with_descriptors(myexits,WEIGHT_FOR_EXIT, 0);
  2260. f_myexit_unflagged=
  2261. frac_nodes_with_descriptors(myexits_unflagged,
  2262. WEIGHT_FOR_EXIT, 0);
  2263. log_debug(LD_NET,
  2264. "f_exit: %.2f, f_myexit: %.2f, f_myexit_unflagged: %.2f",
  2265. f_exit,
  2266. f_myexit,
  2267. f_myexit_unflagged);
  2268. /* If our ExitNodes list has eliminated every possible Exit node, and there
  2269. * were some possible Exit nodes, then instead consider nodes that permit
  2270. * exiting to some ports. */
  2271. if (smartlist_len(myexits) == 0 &&
  2272. smartlist_len(myexits_unflagged)) {
  2273. f_myexit = f_myexit_unflagged;
  2274. }
  2275. smartlist_free(myexits);
  2276. smartlist_free(myexits_unflagged);
  2277. /* This is a tricky point here: we don't want to make it easy for a
  2278. * directory to trickle exits to us until it learns which exits we have
  2279. * configured, so require that we have a threshold both of total exits
  2280. * and usable exits. */
  2281. if (f_myexit < f_exit)
  2282. f_exit = f_myexit;
  2283. }
  2284. /* If the consensus has no exits that pass flag, descriptor, and policy
  2285. * checks, we can only build onion service paths, which are G - M - M. */
  2286. if (router_have_consensus_path() != CONSENSUS_PATH_EXIT) {
  2287. /* If the exit bandwidth weight fraction is not zero, we need to wait for
  2288. * descriptors for those exits. (The bandwidth weight fraction does not
  2289. * check for descriptors.)
  2290. * If the exit bandwidth fraction is zero, there are no exits in the
  2291. * consensus at all. So it is safe to replace f_exit with f_mid.
  2292. *
  2293. * f_exit is non-negative, but some compilers complain about float and ==
  2294. */
  2295. if (f_exit <= 0.0) {
  2296. f_exit = f_mid;
  2297. }
  2298. }
  2299. f_path = f_guard * f_mid * f_exit;
  2300. if (status_out)
  2301. tor_asprintf(status_out,
  2302. "%d%% of guards bw, "
  2303. "%d%% of midpoint bw, and "
  2304. "%d%% of %s = "
  2305. "%d%% of path bw",
  2306. (int)(f_guard*100),
  2307. (int)(f_mid*100),
  2308. (int)(f_exit*100),
  2309. (router_have_consensus_path() == CONSENSUS_PATH_EXIT ?
  2310. "exit bw" :
  2311. "end bw (no exits in consensus, using mid)"),
  2312. (int)(f_path*100));
  2313. return f_path;
  2314. }
  2315. /** We just fetched a new set of descriptors. Compute how far through
  2316. * the "loading descriptors" bootstrapping phase we are, so we can inform
  2317. * the controller of our progress. */
  2318. int
  2319. count_loading_descriptors_progress(void)
  2320. {
  2321. int num_present = 0, num_usable=0;
  2322. time_t now = time(NULL);
  2323. const or_options_t *options = get_options();
  2324. const networkstatus_t *consensus =
  2325. networkstatus_get_reasonably_live_consensus(now,usable_consensus_flavor());
  2326. double paths, fraction;
  2327. if (!consensus)
  2328. return 0; /* can't count descriptors if we have no list of them */
  2329. paths = compute_frac_paths_available(consensus, options, now,
  2330. &num_present, &num_usable,
  2331. NULL);
  2332. fraction = paths / get_frac_paths_needed_for_circs(options,consensus);
  2333. if (fraction > 1.0)
  2334. return 0; /* it's not the number of descriptors holding us back */
  2335. return BOOTSTRAP_STATUS_LOADING_DESCRIPTORS + (int)
  2336. (fraction*(BOOTSTRAP_STATUS_ENOUGH_DIRINFO-1 -
  2337. BOOTSTRAP_STATUS_LOADING_DESCRIPTORS));
  2338. }
  2339. /** Return the fraction of paths needed before we're willing to build
  2340. * circuits, as configured in <b>options</b>, or in the consensus <b>ns</b>. */
  2341. static double
  2342. get_frac_paths_needed_for_circs(const or_options_t *options,
  2343. const networkstatus_t *ns)
  2344. {
  2345. #define DFLT_PCT_USABLE_NEEDED 60
  2346. if (options->PathsNeededToBuildCircuits >= 0.0) {
  2347. return options->PathsNeededToBuildCircuits;
  2348. } else {
  2349. return networkstatus_get_param(ns, "min_paths_for_circs_pct",
  2350. DFLT_PCT_USABLE_NEEDED,
  2351. 25, 95)/100.0;
  2352. }
  2353. }
  2354. /** Change the value of have_min_dir_info, setting it true iff we have enough
  2355. * network and router information to build circuits. Clear the value of
  2356. * need_to_update_have_min_dir_info. */
  2357. static void
  2358. update_router_have_minimum_dir_info(void)
  2359. {
  2360. time_t now = time(NULL);
  2361. int res;
  2362. int num_present=0, num_usable=0;
  2363. const or_options_t *options = get_options();
  2364. const networkstatus_t *consensus =
  2365. networkstatus_get_reasonably_live_consensus(now,usable_consensus_flavor());
  2366. int using_md;
  2367. if (!consensus) {
  2368. if (!networkstatus_get_latest_consensus())
  2369. strlcpy(dir_info_status, "We have no usable consensus.",
  2370. sizeof(dir_info_status));
  2371. else
  2372. strlcpy(dir_info_status, "We have no recent usable consensus.",
  2373. sizeof(dir_info_status));
  2374. res = 0;
  2375. goto done;
  2376. }
  2377. using_md = consensus->flavor == FLAV_MICRODESC;
  2378. /* Check fraction of available paths */
  2379. {
  2380. char *status = NULL;
  2381. double paths = compute_frac_paths_available(consensus, options, now,
  2382. &num_present, &num_usable,
  2383. &status);
  2384. if (paths < get_frac_paths_needed_for_circs(options,consensus)) {
  2385. tor_snprintf(dir_info_status, sizeof(dir_info_status),
  2386. "We need more %sdescriptors: we have %d/%d, and "
  2387. "can only build %d%% of likely paths. (We have %s.)",
  2388. using_md?"micro":"", num_present, num_usable,
  2389. (int)(paths*100), status);
  2390. tor_free(status);
  2391. res = 0;
  2392. control_event_boot_dir(BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS, 0);
  2393. goto done;
  2394. }
  2395. tor_free(status);
  2396. res = 1;
  2397. }
  2398. { /* Check entry guard dirinfo status */
  2399. char *guard_error = entry_guards_get_err_str_if_dir_info_missing(using_md,
  2400. num_present,
  2401. num_usable);
  2402. if (guard_error) {
  2403. strlcpy(dir_info_status, guard_error, sizeof(dir_info_status));
  2404. tor_free(guard_error);
  2405. res = 0;
  2406. goto done;
  2407. }
  2408. }
  2409. done:
  2410. /* If paths have just become available in this update. */
  2411. if (res && !have_min_dir_info) {
  2412. control_event_client_status(LOG_NOTICE, "ENOUGH_DIR_INFO");
  2413. control_event_boot_dir(BOOTSTRAP_STATUS_ENOUGH_DIRINFO, 0);
  2414. log_info(LD_DIR,
  2415. "We now have enough directory information to build circuits.");
  2416. }
  2417. /* If paths have just become unavailable in this update. */
  2418. if (!res && have_min_dir_info) {
  2419. int quiet = directory_too_idle_to_fetch_descriptors(options, now);
  2420. tor_log(quiet ? LOG_INFO : LOG_NOTICE, LD_DIR,
  2421. "Our directory information is no longer up-to-date "
  2422. "enough to build circuits: %s", dir_info_status);
  2423. /* a) make us log when we next complete a circuit, so we know when Tor
  2424. * is back up and usable, and b) disable some activities that Tor
  2425. * should only do while circuits are working, like reachability tests
  2426. * and fetching bridge descriptors only over circuits. */
  2427. note_that_we_maybe_cant_complete_circuits();
  2428. have_consensus_path = CONSENSUS_PATH_UNKNOWN;
  2429. control_event_client_status(LOG_NOTICE, "NOT_ENOUGH_DIR_INFO");
  2430. }
  2431. have_min_dir_info = res;
  2432. need_to_update_have_min_dir_info = 0;
  2433. }