entrynodes.c 98 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863
  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-2016, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file entrynodes.c
  8. * \brief Code to manage our fixed first nodes for various functions.
  9. *
  10. * Entry nodes can be guards (for general use) or bridges (for censorship
  11. * circumvention).
  12. **/
  13. #define ENTRYNODES_PRIVATE
  14. #include "or.h"
  15. #include "circpathbias.h"
  16. #include "circuitbuild.h"
  17. #include "circuitstats.h"
  18. #include "config.h"
  19. #include "confparse.h"
  20. #include "connection.h"
  21. #include "connection_or.h"
  22. #include "control.h"
  23. #include "directory.h"
  24. #include "entrynodes.h"
  25. #include "main.h"
  26. #include "microdesc.h"
  27. #include "networkstatus.h"
  28. #include "nodelist.h"
  29. #include "policies.h"
  30. #include "router.h"
  31. #include "routerlist.h"
  32. #include "routerparse.h"
  33. #include "routerset.h"
  34. #include "transports.h"
  35. #include "statefile.h"
  36. /** Information about a configured bridge. Currently this just matches the
  37. * ones in the torrc file, but one day we may be able to learn about new
  38. * bridges on our own, and remember them in the state file. */
  39. typedef struct {
  40. /** Address of the bridge. */
  41. tor_addr_t addr;
  42. /** TLS port for the bridge. */
  43. uint16_t port;
  44. /** Boolean: We are re-parsing our bridge list, and we are going to remove
  45. * this one if we don't find it in the list of configured bridges. */
  46. unsigned marked_for_removal : 1;
  47. /** Expected identity digest, or all zero bytes if we don't know what the
  48. * digest should be. */
  49. char identity[DIGEST_LEN];
  50. /** Name of pluggable transport protocol taken from its config line. */
  51. char *transport_name;
  52. /** When should we next try to fetch a descriptor for this bridge? */
  53. download_status_t fetch_status;
  54. /** A smartlist of k=v values to be passed to the SOCKS proxy, if
  55. transports are used for this bridge. */
  56. smartlist_t *socks_args;
  57. } bridge_info_t;
  58. /** All the context for guard selection on a particular client */
  59. struct guard_selection_s {
  60. /**
  61. * A value of 1 means that guard_selection_t structures have changed
  62. * and those changes need to be flushed to disk.
  63. *
  64. * XXX we don't know how to flush multiple guard contexts to disk yet;
  65. * fix that as soon as any way to change the default exists, or at least
  66. * make sure this gets set on change.
  67. */
  68. int dirty;
  69. /**
  70. * A list of our chosen entry guards, as entry_guard_t structures; this
  71. * preserves the pre-Prop271 behavior.
  72. */
  73. smartlist_t *chosen_entry_guards;
  74. /**
  75. * When we try to choose an entry guard, should we parse and add
  76. * config's EntryNodes first? This was formerly a global.
  77. */
  78. int should_add_entry_nodes;
  79. };
  80. static smartlist_t *guard_contexts = NULL;
  81. static guard_selection_t *curr_guard_context = NULL;
  82. static void bridge_free(bridge_info_t *bridge);
  83. static const node_t *choose_random_entry_impl(guard_selection_t *gs,
  84. cpath_build_state_t *state,
  85. int for_directory,
  86. dirinfo_type_t dirtype,
  87. int *n_options_out);
  88. static guard_selection_t * guard_selection_new(void);
  89. static int num_bridges_usable(void);
  90. /* Default number of entry guards in the case where the NumEntryGuards
  91. * consensus parameter is not set */
  92. #define DEFAULT_N_GUARDS 1
  93. /* Minimum and maximum number of entry guards (in case the NumEntryGuards
  94. * consensus parameter is set). */
  95. #define MIN_N_GUARDS 1
  96. #define MAX_N_GUARDS 10
  97. /** Allocate a new guard_selection_t */
  98. static guard_selection_t *
  99. guard_selection_new(void)
  100. {
  101. guard_selection_t *gs;
  102. gs = tor_malloc_zero(sizeof(*gs));
  103. gs->chosen_entry_guards = smartlist_new();
  104. return gs;
  105. }
  106. /** Get current default guard_selection_t, creating it if necessary */
  107. guard_selection_t *
  108. get_guard_selection_info(void)
  109. {
  110. if (!guard_contexts) {
  111. guard_contexts = smartlist_new();
  112. }
  113. if (!curr_guard_context) {
  114. curr_guard_context = guard_selection_new();
  115. smartlist_add(guard_contexts, curr_guard_context);
  116. }
  117. return curr_guard_context;
  118. }
  119. /** Return the list of entry guards for a guard_selection_t, creating it
  120. * if necessary. */
  121. const smartlist_t *
  122. get_entry_guards_for_guard_selection(guard_selection_t *gs)
  123. {
  124. tor_assert(gs != NULL);
  125. tor_assert(gs->chosen_entry_guards != NULL);
  126. return gs->chosen_entry_guards;
  127. }
  128. /** Return the list of entry guards for the default guard_selection_t,
  129. * creating it if necessary. */
  130. const smartlist_t *
  131. get_entry_guards(void)
  132. {
  133. return get_entry_guards_for_guard_selection(get_guard_selection_info());
  134. }
  135. /** Helper: mark an entry guard as not usable. */
  136. void
  137. entry_guard_mark_bad(entry_guard_t *guard)
  138. {
  139. guard->bad_since = approx_time();
  140. entry_guards_changed();
  141. }
  142. /** Return a statically allocated human-readable description of <b>guard</b>
  143. */
  144. const char *
  145. entry_guard_describe(const entry_guard_t *guard)
  146. {
  147. static char buf[256];
  148. tor_snprintf(buf, sizeof(buf),
  149. "%s ($%s)",
  150. guard->nickname, hex_str(guard->identity, DIGEST_LEN));
  151. return buf;
  152. }
  153. /** Return <b>guard</b>'s 20-byte RSA identity digest */
  154. const char *
  155. entry_guard_get_rsa_id_digest(const entry_guard_t *guard)
  156. {
  157. return guard->identity;
  158. }
  159. /** Return the pathbias state associated with <b>guard</b>. */
  160. guard_pathbias_t *
  161. entry_guard_get_pathbias_state(entry_guard_t *guard)
  162. {
  163. return &guard->pb;
  164. }
  165. /** Check whether the entry guard <b>e</b> is usable, given the directory
  166. * authorities' opinion about the router (stored in <b>ri</b>) and the user's
  167. * configuration (in <b>options</b>). Set <b>e</b>->bad_since
  168. * accordingly. Return true iff the entry guard's status changes.
  169. *
  170. * If it's not usable, set *<b>reason</b> to a static string explaining why.
  171. */
  172. static int
  173. entry_guard_set_status(entry_guard_t *e, const node_t *node,
  174. time_t now, const or_options_t *options,
  175. const char **reason)
  176. {
  177. char buf[HEX_DIGEST_LEN+1];
  178. int changed = 0;
  179. *reason = NULL;
  180. /* Do we want to mark this guard as bad? */
  181. if (!node)
  182. *reason = "unlisted";
  183. else if (!node->is_running)
  184. *reason = "down";
  185. else if (options->UseBridges && (!node->ri ||
  186. node->ri->purpose != ROUTER_PURPOSE_BRIDGE))
  187. *reason = "not a bridge";
  188. else if (options->UseBridges && !node_is_a_configured_bridge(node))
  189. *reason = "not a configured bridge";
  190. else if (!options->UseBridges && !node->is_possible_guard &&
  191. !routerset_contains_node(options->EntryNodes,node))
  192. *reason = "not recommended as a guard";
  193. else if (routerset_contains_node(options->ExcludeNodes, node))
  194. *reason = "excluded";
  195. /* We only care about OR connection connectivity for entry guards. */
  196. else if (!fascist_firewall_allows_node(node, FIREWALL_OR_CONNECTION, 0))
  197. *reason = "unreachable by config";
  198. else if (e->pb.path_bias_disabled)
  199. *reason = "path-biased";
  200. if (*reason && ! e->bad_since) {
  201. /* Router is newly bad. */
  202. base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
  203. log_info(LD_CIRC, "Entry guard %s (%s) is %s: marking as unusable.",
  204. e->nickname, buf, *reason);
  205. e->bad_since = now;
  206. control_event_guard(e->nickname, e->identity, "BAD");
  207. changed = 1;
  208. } else if (!*reason && e->bad_since) {
  209. /* There's nothing wrong with the router any more. */
  210. base16_encode(buf, sizeof(buf), e->identity, DIGEST_LEN);
  211. log_info(LD_CIRC, "Entry guard %s (%s) is no longer unusable: "
  212. "marking as ok.", e->nickname, buf);
  213. e->bad_since = 0;
  214. control_event_guard(e->nickname, e->identity, "GOOD");
  215. changed = 1;
  216. }
  217. if (node) {
  218. int is_dir = node_is_dir(node);
  219. if (options->UseBridges && node_is_a_configured_bridge(node))
  220. is_dir = 1;
  221. if (e->is_dir_cache != is_dir) {
  222. e->is_dir_cache = is_dir;
  223. changed = 1;
  224. }
  225. }
  226. return changed;
  227. }
  228. /** Return true iff enough time has passed since we last tried to connect
  229. * to the unreachable guard <b>e</b> that we're willing to try again. */
  230. STATIC int
  231. entry_is_time_to_retry(const entry_guard_t *e, time_t now)
  232. {
  233. struct guard_retry_period_s {
  234. time_t period_duration;
  235. time_t interval_during_period;
  236. };
  237. struct guard_retry_period_s periods[] = {
  238. { 6*60*60, 60*60 }, /* For first 6 hrs., retry hourly; */
  239. { 3*24*60*60, 4*60*60 }, /* Then retry every 4 hrs. until the
  240. 3-day mark; */
  241. { 7*24*60*60, 18*60*60 }, /* After 3 days, retry every 18 hours until
  242. 1 week mark. */
  243. { TIME_MAX, 36*60*60 } /* After 1 week, retry every 36 hours. */
  244. };
  245. time_t ith_deadline_for_retry;
  246. time_t unreachable_for;
  247. unsigned i;
  248. if (e->last_attempted < e->unreachable_since)
  249. return 1;
  250. unreachable_for = now - e->unreachable_since;
  251. for (i = 0; i < ARRAY_LENGTH(periods); i++) {
  252. if (unreachable_for <= periods[i].period_duration) {
  253. ith_deadline_for_retry = e->last_attempted +
  254. periods[i].interval_during_period;
  255. return (now > ith_deadline_for_retry);
  256. }
  257. }
  258. return 0;
  259. }
  260. /** Return the node corresponding to <b>e</b>, if <b>e</b> is
  261. * working well enough that we are willing to use it as an entry
  262. * right now. (Else return NULL.) In particular, it must be
  263. * - Listed as either up or never yet contacted;
  264. * - Present in the routerlist;
  265. * - Listed as 'stable' or 'fast' by the current dirserver consensus,
  266. * if demanded by <b>need_uptime</b> or <b>need_capacity</b>
  267. * (unless it's a configured EntryNode);
  268. * - Allowed by our current ReachableORAddresses config option; and
  269. * - Currently thought to be reachable by us (unless <b>assume_reachable</b>
  270. * is true).
  271. *
  272. * If the answer is no, set *<b>msg</b> to an explanation of why.
  273. *
  274. * If need_descriptor is true, only return the node if we currently have
  275. * a descriptor (routerinfo or microdesc) for it.
  276. */
  277. STATIC const node_t *
  278. entry_is_live(const entry_guard_t *e, entry_is_live_flags_t flags,
  279. const char **msg)
  280. {
  281. const node_t *node;
  282. const or_options_t *options = get_options();
  283. int need_uptime = (flags & ENTRY_NEED_UPTIME) != 0;
  284. int need_capacity = (flags & ENTRY_NEED_CAPACITY) != 0;
  285. const int assume_reachable = (flags & ENTRY_ASSUME_REACHABLE) != 0;
  286. const int need_descriptor = (flags & ENTRY_NEED_DESCRIPTOR) != 0;
  287. tor_assert(msg);
  288. if (e->pb.path_bias_disabled) {
  289. *msg = "path-biased";
  290. return NULL;
  291. }
  292. if (e->bad_since) {
  293. *msg = "bad";
  294. return NULL;
  295. }
  296. /* no good if it's unreachable, unless assume_unreachable or can_retry. */
  297. if (!assume_reachable && !e->can_retry &&
  298. e->unreachable_since && !entry_is_time_to_retry(e, time(NULL))) {
  299. *msg = "unreachable";
  300. return NULL;
  301. }
  302. node = node_get_by_id(e->identity);
  303. if (!node) {
  304. *msg = "no node info";
  305. return NULL;
  306. }
  307. if (need_descriptor && !node_has_descriptor(node)) {
  308. *msg = "no descriptor";
  309. return NULL;
  310. }
  311. if (get_options()->UseBridges) {
  312. if (node_get_purpose(node) != ROUTER_PURPOSE_BRIDGE) {
  313. *msg = "not a bridge";
  314. return NULL;
  315. }
  316. if (!node_is_a_configured_bridge(node)) {
  317. *msg = "not a configured bridge";
  318. return NULL;
  319. }
  320. } else { /* !get_options()->UseBridges */
  321. if (node_get_purpose(node) != ROUTER_PURPOSE_GENERAL) {
  322. *msg = "not general-purpose";
  323. return NULL;
  324. }
  325. }
  326. if (routerset_contains_node(options->EntryNodes, node)) {
  327. /* they asked for it, they get it */
  328. need_uptime = need_capacity = 0;
  329. }
  330. if (node_is_unreliable(node, need_uptime, need_capacity, 0)) {
  331. *msg = "not fast/stable";
  332. return NULL;
  333. }
  334. if (!fascist_firewall_allows_node(node, FIREWALL_OR_CONNECTION, 0)) {
  335. *msg = "unreachable by config";
  336. return NULL;
  337. }
  338. return node;
  339. }
  340. /** Return the number of entry guards that we think are usable, in the
  341. * context of the given guard_selection_t */
  342. int
  343. num_live_entry_guards_for_guard_selection(guard_selection_t *gs,
  344. int for_directory)
  345. {
  346. int n = 0;
  347. const char *msg;
  348. tor_assert(gs != NULL);
  349. /* Set the entry node attributes we are interested in. */
  350. entry_is_live_flags_t entry_flags = ENTRY_NEED_CAPACITY;
  351. if (!for_directory) {
  352. entry_flags |= ENTRY_NEED_DESCRIPTOR;
  353. }
  354. if (!(gs->chosen_entry_guards)) {
  355. return 0;
  356. }
  357. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, entry) {
  358. if (for_directory && !entry->is_dir_cache)
  359. continue;
  360. if (entry_is_live(entry, entry_flags, &msg))
  361. ++n;
  362. } SMARTLIST_FOREACH_END(entry);
  363. return n;
  364. }
  365. /** Return the number of entry guards that we think are usable, for the
  366. * default guard selection */
  367. int
  368. num_live_entry_guards(int for_directory)
  369. {
  370. return num_live_entry_guards_for_guard_selection(
  371. get_guard_selection_info(), for_directory);
  372. }
  373. /** If <b>digest</b> matches the identity of any node in the
  374. * entry_guards list for the provided guard selection state,
  375. return that node. Else return NULL. */
  376. entry_guard_t *
  377. entry_guard_get_by_id_digest_for_guard_selection(guard_selection_t *gs,
  378. const char *digest)
  379. {
  380. tor_assert(gs != NULL);
  381. SMARTLIST_FOREACH(gs->chosen_entry_guards, entry_guard_t *, entry,
  382. if (tor_memeq(digest, entry->identity, DIGEST_LEN))
  383. return entry;
  384. );
  385. return NULL;
  386. }
  387. /** Return the node_t associated with a single entry_guard_t. May
  388. * return NULL if the guard is not currently in the consensus. */
  389. const node_t *
  390. entry_guard_find_node(const entry_guard_t *guard)
  391. {
  392. tor_assert(guard);
  393. return node_get_by_id(guard->identity);
  394. }
  395. /** If <b>digest</b> matches the identity of any node in the
  396. * entry_guards list for the default guard selection state,
  397. return that node. Else return NULL. */
  398. entry_guard_t *
  399. entry_guard_get_by_id_digest(const char *digest)
  400. {
  401. return entry_guard_get_by_id_digest_for_guard_selection(
  402. get_guard_selection_info(), digest);
  403. }
  404. /** Dump a description of our list of entry guards in the given guard
  405. * selection context to the log at level <b>severity</b>. */
  406. static void
  407. log_entry_guards_for_guard_selection(guard_selection_t *gs, int severity)
  408. {
  409. smartlist_t *elements = smartlist_new();
  410. char *s;
  411. /*
  412. * TODO this should probably log more info about prop-271 state too
  413. * when it's implemented.
  414. */
  415. tor_assert(gs != NULL);
  416. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, e)
  417. {
  418. const char *msg = NULL;
  419. if (entry_is_live(e, ENTRY_NEED_CAPACITY, &msg))
  420. smartlist_add_asprintf(elements, "%s [%s] (up %s)",
  421. e->nickname,
  422. hex_str(e->identity, DIGEST_LEN),
  423. e->made_contact ? "made-contact" : "never-contacted");
  424. else
  425. smartlist_add_asprintf(elements, "%s [%s] (%s, %s)",
  426. e->nickname,
  427. hex_str(e->identity, DIGEST_LEN),
  428. msg,
  429. e->made_contact ? "made-contact" : "never-contacted");
  430. }
  431. SMARTLIST_FOREACH_END(e);
  432. s = smartlist_join_strings(elements, ",", 0, NULL);
  433. SMARTLIST_FOREACH(elements, char*, cp, tor_free(cp));
  434. smartlist_free(elements);
  435. log_fn(severity,LD_CIRC,"%s",s);
  436. tor_free(s);
  437. }
  438. /** Called when one or more guards that we would previously have used for some
  439. * purpose are no longer in use because a higher-priority guard has become
  440. * usable again. */
  441. static void
  442. control_event_guard_deferred(void)
  443. {
  444. /* XXXX We don't actually have a good way to figure out _how many_ entries
  445. * are live for some purpose. We need an entry_is_even_slightly_live()
  446. * function for this to work right. NumEntryGuards isn't reliable: if we
  447. * need guards with weird properties, we can have more than that number
  448. * live.
  449. **/
  450. #if 0
  451. int n = 0;
  452. const char *msg;
  453. const or_options_t *options = get_options();
  454. if (!entry_guards)
  455. return;
  456. SMARTLIST_FOREACH(entry_guards, entry_guard_t *, entry,
  457. {
  458. if (entry_is_live(entry, 0, 1, 0, &msg)) {
  459. if (n++ == options->NumEntryGuards) {
  460. control_event_guard(entry->nickname, entry->identity, "DEFERRED");
  461. return;
  462. }
  463. }
  464. });
  465. #endif
  466. }
  467. /** Largest amount that we'll backdate chosen_on_date */
  468. #define CHOSEN_ON_DATE_SLOP (30*86400)
  469. /** Add a new (preferably stable and fast) router to our chosen_entry_guards
  470. * list for the supplied guard selection. Return a pointer to the router if
  471. * we succeed, or NULL if we can't find any more suitable entries.
  472. *
  473. * If <b>chosen</b> is defined, use that one, and if it's not
  474. * already in our entry_guards list, put it at the *beginning*.
  475. * Else, put the one we pick at the end of the list. */
  476. STATIC const node_t *
  477. add_an_entry_guard(guard_selection_t *gs,
  478. const node_t *chosen, int reset_status, int prepend,
  479. int for_discovery, int for_directory)
  480. {
  481. const node_t *node;
  482. entry_guard_t *entry;
  483. tor_assert(gs != NULL);
  484. tor_assert(gs->chosen_entry_guards != NULL);
  485. if (chosen) {
  486. node = chosen;
  487. entry = entry_guard_get_by_id_digest_for_guard_selection(gs,
  488. node->identity);
  489. if (entry) {
  490. if (reset_status) {
  491. entry->bad_since = 0;
  492. entry->can_retry = 1;
  493. }
  494. entry->is_dir_cache = node_is_dir(node);
  495. if (get_options()->UseBridges && node_is_a_configured_bridge(node))
  496. entry->is_dir_cache = 1;
  497. return NULL;
  498. }
  499. } else if (!for_directory) {
  500. node = choose_good_entry_server(CIRCUIT_PURPOSE_C_GENERAL, NULL);
  501. if (!node)
  502. return NULL;
  503. } else {
  504. const routerstatus_t *rs;
  505. rs = router_pick_directory_server(MICRODESC_DIRINFO|V3_DIRINFO,
  506. PDS_FOR_GUARD);
  507. if (!rs)
  508. return NULL;
  509. node = node_get_by_id(rs->identity_digest);
  510. if (!node)
  511. return NULL;
  512. }
  513. if (entry_guard_get_by_id_digest_for_guard_selection(gs, node->identity)
  514. != NULL) {
  515. log_info(LD_CIRC, "I was about to add a duplicate entry guard.");
  516. /* This can happen if we choose a guard, then the node goes away, then
  517. * comes back. */
  518. return NULL;
  519. }
  520. entry = tor_malloc_zero(sizeof(entry_guard_t));
  521. log_info(LD_CIRC, "Chose %s as new entry guard.",
  522. node_describe(node));
  523. strlcpy(entry->nickname, node_get_nickname(node), sizeof(entry->nickname));
  524. memcpy(entry->identity, node->identity, DIGEST_LEN);
  525. entry->is_dir_cache = node_is_dir(node);
  526. if (get_options()->UseBridges && node_is_a_configured_bridge(node))
  527. entry->is_dir_cache = 1;
  528. /* Choose expiry time smudged over the past month. The goal here
  529. * is to a) spread out when Tor clients rotate their guards, so they
  530. * don't all select them on the same day, and b) avoid leaving a
  531. * precise timestamp in the state file about when we first picked
  532. * this guard. For details, see the Jan 2010 or-dev thread. */
  533. time_t now = time(NULL);
  534. entry->chosen_on_date = crypto_rand_time_range(now - 3600*24*30, now);
  535. entry->chosen_by_version = tor_strdup(VERSION);
  536. /* Are we picking this guard because all of our current guards are
  537. * down so we need another one (for_discovery is 1), or because we
  538. * decided we need more variety in our guard list (for_discovery is 0)?
  539. *
  540. * Currently we hack this behavior into place by setting "made_contact"
  541. * for guards of the latter variety, so we'll be willing to use any of
  542. * them right off the bat.
  543. */
  544. if (!for_discovery)
  545. entry->made_contact = 1;
  546. if (prepend)
  547. smartlist_insert(gs->chosen_entry_guards, 0, entry);
  548. else
  549. smartlist_add(gs->chosen_entry_guards, entry);
  550. control_event_guard(entry->nickname, entry->identity, "NEW");
  551. control_event_guard_deferred();
  552. log_entry_guards_for_guard_selection(gs, LOG_INFO);
  553. return node;
  554. }
  555. /** Choose how many entry guards or directory guards we'll use. If
  556. * <b>for_directory</b> is true, we return how many directory guards to
  557. * use; else we return how many entry guards to use. */
  558. STATIC int
  559. decide_num_guards(const or_options_t *options, int for_directory)
  560. {
  561. if (for_directory) {
  562. int answer;
  563. if (options->NumDirectoryGuards != 0)
  564. return options->NumDirectoryGuards;
  565. answer = networkstatus_get_param(NULL, "NumDirectoryGuards", 0, 0, 10);
  566. if (answer) /* non-zero means use the consensus value */
  567. return answer;
  568. }
  569. if (options->NumEntryGuards)
  570. return options->NumEntryGuards;
  571. /* Use the value from the consensus, or 3 if no guidance. */
  572. return networkstatus_get_param(NULL, "NumEntryGuards", DEFAULT_N_GUARDS,
  573. MIN_N_GUARDS, MAX_N_GUARDS);
  574. }
  575. /** If the use of entry guards is configured, choose more entry guards
  576. * until we have enough in the list. */
  577. static void
  578. pick_entry_guards(guard_selection_t *gs,
  579. const or_options_t *options,
  580. int for_directory)
  581. {
  582. int changed = 0;
  583. const int num_needed = decide_num_guards(options, for_directory);
  584. tor_assert(gs != NULL);
  585. tor_assert(gs->chosen_entry_guards != NULL);
  586. while (num_live_entry_guards_for_guard_selection(gs, for_directory)
  587. < num_needed) {
  588. if (!add_an_entry_guard(gs, NULL, 0, 0, 0, for_directory))
  589. break;
  590. changed = 1;
  591. }
  592. if (changed)
  593. entry_guards_changed_for_guard_selection(gs);
  594. }
  595. /** How long (in seconds) do we allow an entry guard to be nonfunctional,
  596. * unlisted, excluded, or otherwise nonusable before we give up on it? */
  597. #define ENTRY_GUARD_REMOVE_AFTER (30*24*60*60)
  598. /** Release all storage held by <b>e</b>. */
  599. static void
  600. entry_guard_free(entry_guard_t *e)
  601. {
  602. if (!e)
  603. return;
  604. tor_free(e->chosen_by_version);
  605. tor_free(e->sampled_by_version);
  606. tor_free(e);
  607. }
  608. /**
  609. * Return the minimum lifetime of working entry guard, in seconds,
  610. * as given in the consensus networkstatus. (Plus CHOSEN_ON_DATE_SLOP,
  611. * so that we can do the chosen_on_date randomization while achieving the
  612. * desired minimum lifetime.)
  613. */
  614. static int32_t
  615. guards_get_lifetime(void)
  616. {
  617. const or_options_t *options = get_options();
  618. #define DFLT_GUARD_LIFETIME (86400 * 60) /* Two months. */
  619. #define MIN_GUARD_LIFETIME (86400 * 30) /* One months. */
  620. #define MAX_GUARD_LIFETIME (86400 * 1826) /* Five years. */
  621. if (options->GuardLifetime >= 1) {
  622. return CLAMP(MIN_GUARD_LIFETIME,
  623. options->GuardLifetime,
  624. MAX_GUARD_LIFETIME) + CHOSEN_ON_DATE_SLOP;
  625. }
  626. return networkstatus_get_param(NULL, "GuardLifetime",
  627. DFLT_GUARD_LIFETIME,
  628. MIN_GUARD_LIFETIME,
  629. MAX_GUARD_LIFETIME) + CHOSEN_ON_DATE_SLOP;
  630. }
  631. /** Remove from a guard selection context any entry guard which was selected
  632. * by an unknown version of Tor, or which was selected by a version of Tor
  633. * that's known to select entry guards badly, or which was selected more 2
  634. * months ago. */
  635. /* XXXX The "obsolete guards" and "chosen long ago guards" things should
  636. * probably be different functions. */
  637. static int
  638. remove_obsolete_entry_guards(guard_selection_t *gs, time_t now)
  639. {
  640. int changed = 0, i;
  641. int32_t guard_lifetime = guards_get_lifetime();
  642. tor_assert(gs != NULL);
  643. if (!(gs->chosen_entry_guards)) goto done;
  644. for (i = 0; i < smartlist_len(gs->chosen_entry_guards); ++i) {
  645. entry_guard_t *entry = smartlist_get(gs->chosen_entry_guards, i);
  646. const char *ver = entry->chosen_by_version;
  647. const char *msg = NULL;
  648. tor_version_t v;
  649. int version_is_bad = 0, date_is_bad = 0;
  650. if (!ver) {
  651. msg = "does not say what version of Tor it was selected by";
  652. version_is_bad = 1;
  653. } else if (tor_version_parse(ver, &v)) {
  654. msg = "does not seem to be from any recognized version of Tor";
  655. version_is_bad = 1;
  656. }
  657. if (!version_is_bad && entry->chosen_on_date + guard_lifetime < now) {
  658. /* It's been too long since the date listed in our state file. */
  659. msg = "was selected several months ago";
  660. date_is_bad = 1;
  661. }
  662. if (version_is_bad || date_is_bad) { /* we need to drop it */
  663. char dbuf[HEX_DIGEST_LEN+1];
  664. tor_assert(msg);
  665. base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
  666. log_fn(version_is_bad ? LOG_NOTICE : LOG_INFO, LD_CIRC,
  667. "Entry guard '%s' (%s) %s. (Version=%s.) Replacing it.",
  668. entry->nickname, dbuf, msg, ver?escaped(ver):"none");
  669. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  670. entry_guard_free(entry);
  671. smartlist_del_keeporder(gs->chosen_entry_guards, i--);
  672. log_entry_guards_for_guard_selection(gs, LOG_INFO);
  673. changed = 1;
  674. }
  675. }
  676. done:
  677. return changed ? 1 : 0;
  678. }
  679. /** Remove all entry guards from this guard selection context that have
  680. * been down or unlisted for so long that we don't think they'll come up
  681. * again. Return 1 if we removed any, or 0 if we did nothing. */
  682. static int
  683. remove_dead_entry_guards(guard_selection_t *gs, time_t now)
  684. {
  685. char dbuf[HEX_DIGEST_LEN+1];
  686. char tbuf[ISO_TIME_LEN+1];
  687. int i;
  688. int changed = 0;
  689. tor_assert(gs != NULL);
  690. if (!(gs->chosen_entry_guards)) goto done;
  691. for (i = 0; i < smartlist_len(gs->chosen_entry_guards); ) {
  692. entry_guard_t *entry = smartlist_get(gs->chosen_entry_guards, i);
  693. if (entry->bad_since &&
  694. ! entry->pb.path_bias_disabled &&
  695. entry->bad_since + ENTRY_GUARD_REMOVE_AFTER < now) {
  696. base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
  697. format_local_iso_time(tbuf, entry->bad_since);
  698. log_info(LD_CIRC, "Entry guard '%s' (%s) has been down or unlisted "
  699. "since %s local time; removing.",
  700. entry->nickname, dbuf, tbuf);
  701. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  702. entry_guard_free(entry);
  703. smartlist_del_keeporder(gs->chosen_entry_guards, i);
  704. log_entry_guards_for_guard_selection(gs, LOG_INFO);
  705. changed = 1;
  706. } else
  707. ++i;
  708. }
  709. done:
  710. return changed ? 1 : 0;
  711. }
  712. /** Remove all currently listed entry guards for a given guard selection
  713. * context */
  714. void
  715. remove_all_entry_guards_for_guard_selection(guard_selection_t *gs)
  716. {
  717. char dbuf[HEX_DIGEST_LEN+1];
  718. tor_assert(gs != NULL);
  719. if (gs->chosen_entry_guards) {
  720. while (smartlist_len(gs->chosen_entry_guards)) {
  721. entry_guard_t *entry = smartlist_get(gs->chosen_entry_guards, 0);
  722. base16_encode(dbuf, sizeof(dbuf), entry->identity, DIGEST_LEN);
  723. log_info(LD_CIRC, "Entry guard '%s' (%s) has been dropped.",
  724. entry->nickname, dbuf);
  725. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  726. entry_guard_free(entry);
  727. smartlist_del(gs->chosen_entry_guards, 0);
  728. }
  729. }
  730. log_entry_guards_for_guard_selection(gs, LOG_INFO);
  731. entry_guards_changed_for_guard_selection(gs);
  732. }
  733. /** Remove all currently listed entry guards. So new ones will be chosen. */
  734. void
  735. remove_all_entry_guards(void)
  736. {
  737. remove_all_entry_guards_for_guard_selection(get_guard_selection_info());
  738. }
  739. /** A new directory or router-status has arrived; update the down/listed
  740. * status of the entry guards.
  741. *
  742. * An entry is 'down' if the directory lists it as nonrunning.
  743. * An entry is 'unlisted' if the directory doesn't include it.
  744. *
  745. * Don't call this on startup; only on a fresh download. Otherwise we'll
  746. * think that things are unlisted.
  747. */
  748. void
  749. entry_guards_compute_status_for_guard_selection(guard_selection_t *gs,
  750. const or_options_t *options,
  751. time_t now)
  752. {
  753. int changed = 0;
  754. digestmap_t *reasons;
  755. if ((!gs) || !(gs->chosen_entry_guards))
  756. return;
  757. if (options->EntryNodes) /* reshuffle the entry guard list if needed */
  758. entry_nodes_should_be_added();
  759. reasons = digestmap_new();
  760. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, entry)
  761. {
  762. const node_t *r = node_get_by_id(entry->identity);
  763. const char *reason = NULL;
  764. if (entry_guard_set_status(entry, r, now, options, &reason))
  765. changed = 1;
  766. if (entry->bad_since)
  767. tor_assert(reason);
  768. if (reason)
  769. digestmap_set(reasons, entry->identity, (char*)reason);
  770. }
  771. SMARTLIST_FOREACH_END(entry);
  772. if (remove_dead_entry_guards(gs, now))
  773. changed = 1;
  774. if (remove_obsolete_entry_guards(gs, now))
  775. changed = 1;
  776. if (changed) {
  777. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *,
  778. entry) {
  779. const char *reason = digestmap_get(reasons, entry->identity);
  780. const char *live_msg = "";
  781. const node_t *r = entry_is_live(entry, ENTRY_NEED_CAPACITY, &live_msg);
  782. log_info(LD_CIRC, "Summary: Entry %s [%s] is %s, %s%s%s, and %s%s.",
  783. entry->nickname,
  784. hex_str(entry->identity, DIGEST_LEN),
  785. entry->unreachable_since ? "unreachable" : "reachable",
  786. entry->bad_since ? "unusable" : "usable",
  787. reason ? ", ": "",
  788. reason ? reason : "",
  789. r ? "live" : "not live / ",
  790. r ? "" : live_msg);
  791. } SMARTLIST_FOREACH_END(entry);
  792. log_info(LD_CIRC, " (%d/%d entry guards are usable/new)",
  793. num_live_entry_guards_for_guard_selection(gs, 0),
  794. smartlist_len(gs->chosen_entry_guards));
  795. log_entry_guards_for_guard_selection(gs, LOG_INFO);
  796. entry_guards_changed_for_guard_selection(gs);
  797. }
  798. digestmap_free(reasons, NULL);
  799. }
  800. /** A new directory or router-status has arrived; update the down/listed
  801. * status of the entry guards.
  802. *
  803. * An entry is 'down' if the directory lists it as nonrunning.
  804. * An entry is 'unlisted' if the directory doesn't include it.
  805. *
  806. * Don't call this on startup; only on a fresh download. Otherwise we'll
  807. * think that things are unlisted.
  808. */
  809. void
  810. entry_guards_compute_status(const or_options_t *options, time_t now)
  811. {
  812. entry_guards_compute_status_for_guard_selection(get_guard_selection_info(),
  813. options, now);
  814. }
  815. /** Called when a connection to an OR with the identity digest <b>digest</b>
  816. * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
  817. * If the OR is an entry, change that entry's up/down status.
  818. * Return 0 normally, or -1 if we want to tear down the new connection.
  819. *
  820. * If <b>mark_relay_status</b>, also call router_set_status() on this
  821. * relay.
  822. */
  823. /* XXX We could change succeeded and mark_relay_status into 'int flags'.
  824. * Too many boolean arguments is a recipe for confusion.
  825. */
  826. int
  827. entry_guard_register_connect_status_for_guard_selection(
  828. guard_selection_t *gs, const char *digest, int succeeded,
  829. int mark_relay_status, time_t now)
  830. {
  831. int changed = 0;
  832. int refuse_conn = 0;
  833. int first_contact = 0;
  834. entry_guard_t *entry = NULL;
  835. int idx = -1;
  836. char buf[HEX_DIGEST_LEN+1];
  837. if (!(gs) || !(gs->chosen_entry_guards)) {
  838. return 0;
  839. }
  840. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, e) {
  841. tor_assert(e);
  842. if (tor_memeq(e->identity, digest, DIGEST_LEN)) {
  843. entry = e;
  844. idx = e_sl_idx;
  845. break;
  846. }
  847. } SMARTLIST_FOREACH_END(e);
  848. if (!entry)
  849. return 0;
  850. base16_encode(buf, sizeof(buf), entry->identity, DIGEST_LEN);
  851. if (succeeded) {
  852. if (entry->unreachable_since) {
  853. log_info(LD_CIRC, "Entry guard '%s' (%s) is now reachable again. Good.",
  854. entry->nickname, buf);
  855. entry->can_retry = 0;
  856. entry->unreachable_since = 0;
  857. entry->last_attempted = now;
  858. control_event_guard(entry->nickname, entry->identity, "UP");
  859. changed = 1;
  860. }
  861. if (!entry->made_contact) {
  862. entry->made_contact = 1;
  863. first_contact = changed = 1;
  864. }
  865. } else { /* ! succeeded */
  866. if (!entry->made_contact) {
  867. /* We've never connected to this one. */
  868. log_info(LD_CIRC,
  869. "Connection to never-contacted entry guard '%s' (%s) failed. "
  870. "Removing from the list. %d/%d entry guards usable/new.",
  871. entry->nickname, buf,
  872. num_live_entry_guards_for_guard_selection(gs, 0) - 1,
  873. smartlist_len(gs->chosen_entry_guards)-1);
  874. control_event_guard(entry->nickname, entry->identity, "DROPPED");
  875. entry_guard_free(entry);
  876. smartlist_del_keeporder(gs->chosen_entry_guards, idx);
  877. log_entry_guards_for_guard_selection(gs, LOG_INFO);
  878. changed = 1;
  879. } else if (!entry->unreachable_since) {
  880. log_info(LD_CIRC, "Unable to connect to entry guard '%s' (%s). "
  881. "Marking as unreachable.", entry->nickname, buf);
  882. entry->unreachable_since = entry->last_attempted = now;
  883. control_event_guard(entry->nickname, entry->identity, "DOWN");
  884. changed = 1;
  885. entry->can_retry = 0; /* We gave it an early chance; no good. */
  886. } else {
  887. char tbuf[ISO_TIME_LEN+1];
  888. format_iso_time(tbuf, entry->unreachable_since);
  889. log_debug(LD_CIRC, "Failed to connect to unreachable entry guard "
  890. "'%s' (%s). It has been unreachable since %s.",
  891. entry->nickname, buf, tbuf);
  892. entry->last_attempted = now;
  893. entry->can_retry = 0; /* We gave it an early chance; no good. */
  894. }
  895. }
  896. /* if the caller asked us to, also update the is_running flags for this
  897. * relay */
  898. if (mark_relay_status)
  899. router_set_status(digest, succeeded);
  900. if (first_contact) {
  901. /* We've just added a new long-term entry guard. Perhaps the network just
  902. * came back? We should give our earlier entries another try too,
  903. * and close this connection so we don't use it before we've given
  904. * the others a shot. */
  905. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, e) {
  906. if (e == entry)
  907. break;
  908. if (e->made_contact) {
  909. const char *msg;
  910. const node_t *r = entry_is_live(e,
  911. ENTRY_NEED_CAPACITY | ENTRY_ASSUME_REACHABLE,
  912. &msg);
  913. if (r && e->unreachable_since) {
  914. refuse_conn = 1;
  915. e->can_retry = 1;
  916. }
  917. }
  918. } SMARTLIST_FOREACH_END(e);
  919. if (refuse_conn) {
  920. log_info(LD_CIRC,
  921. "Connected to new entry guard '%s' (%s). Marking earlier "
  922. "entry guards up. %d/%d entry guards usable/new.",
  923. entry->nickname, buf,
  924. num_live_entry_guards_for_guard_selection(gs, 0),
  925. smartlist_len(gs->chosen_entry_guards));
  926. log_entry_guards_for_guard_selection(gs, LOG_INFO);
  927. changed = 1;
  928. }
  929. }
  930. if (changed)
  931. entry_guards_changed_for_guard_selection(gs);
  932. return refuse_conn ? -1 : 0;
  933. }
  934. /** Called when a connection to an OR with the identity digest <b>digest</b>
  935. * is established (<b>succeeded</b>==1) or has failed (<b>succeeded</b>==0).
  936. * If the OR is an entry, change that entry's up/down status in the default
  937. * guard selection context.
  938. * Return 0 normally, or -1 if we want to tear down the new connection.
  939. *
  940. * If <b>mark_relay_status</b>, also call router_set_status() on this
  941. * relay.
  942. */
  943. int
  944. entry_guard_register_connect_status(const char *digest, int succeeded,
  945. int mark_relay_status, time_t now)
  946. {
  947. return entry_guard_register_connect_status_for_guard_selection(
  948. get_guard_selection_info(), digest, succeeded, mark_relay_status, now);
  949. }
  950. /** Called when the value of EntryNodes changes in our configuration. */
  951. void
  952. entry_nodes_should_be_added_for_guard_selection(guard_selection_t *gs)
  953. {
  954. tor_assert(gs != NULL);
  955. log_info(LD_CIRC, "EntryNodes config option set. Putting configured "
  956. "relays at the front of the entry guard list.");
  957. gs->should_add_entry_nodes = 1;
  958. }
  959. /** Called when the value of EntryNodes changes in our configuration. */
  960. void
  961. entry_nodes_should_be_added(void)
  962. {
  963. entry_nodes_should_be_added_for_guard_selection(
  964. get_guard_selection_info());
  965. }
  966. /** Adjust the entry guards list so that it only contains entries from
  967. * EntryNodes, adding new entries from EntryNodes to the list as needed. */
  968. STATIC void
  969. entry_guards_set_from_config(guard_selection_t *gs,
  970. const or_options_t *options)
  971. {
  972. smartlist_t *entry_nodes, *worse_entry_nodes, *entry_fps;
  973. smartlist_t *old_entry_guards_on_list, *old_entry_guards_not_on_list;
  974. const int numentryguards = decide_num_guards(options, 0);
  975. tor_assert(gs != NULL);
  976. tor_assert(gs->chosen_entry_guards != NULL);
  977. gs->should_add_entry_nodes = 0;
  978. if (!options->EntryNodes) {
  979. /* It's possible that a controller set EntryNodes, thus making
  980. * should_add_entry_nodes set, then cleared it again, all before the
  981. * call to choose_random_entry() that triggered us. If so, just return.
  982. */
  983. return;
  984. }
  985. {
  986. char *string = routerset_to_string(options->EntryNodes);
  987. log_info(LD_CIRC,"Adding configured EntryNodes '%s'.", string);
  988. tor_free(string);
  989. }
  990. entry_nodes = smartlist_new();
  991. worse_entry_nodes = smartlist_new();
  992. entry_fps = smartlist_new();
  993. old_entry_guards_on_list = smartlist_new();
  994. old_entry_guards_not_on_list = smartlist_new();
  995. /* Split entry guards into those on the list and those not. */
  996. routerset_get_all_nodes(entry_nodes, options->EntryNodes,
  997. options->ExcludeNodes, 0);
  998. SMARTLIST_FOREACH(entry_nodes, const node_t *,node,
  999. smartlist_add(entry_fps, (void*)node->identity));
  1000. SMARTLIST_FOREACH(gs->chosen_entry_guards, entry_guard_t *, e, {
  1001. if (smartlist_contains_digest(entry_fps, e->identity))
  1002. smartlist_add(old_entry_guards_on_list, e);
  1003. else
  1004. smartlist_add(old_entry_guards_not_on_list, e);
  1005. });
  1006. /* Remove all currently configured guard nodes, excluded nodes, unreachable
  1007. * nodes, or non-Guard nodes from entry_nodes. */
  1008. SMARTLIST_FOREACH_BEGIN(entry_nodes, const node_t *, node) {
  1009. if (entry_guard_get_by_id_digest_for_guard_selection(gs,
  1010. node->identity)) {
  1011. SMARTLIST_DEL_CURRENT(entry_nodes, node);
  1012. continue;
  1013. } else if (routerset_contains_node(options->ExcludeNodes, node)) {
  1014. SMARTLIST_DEL_CURRENT(entry_nodes, node);
  1015. continue;
  1016. } else if (!fascist_firewall_allows_node(node, FIREWALL_OR_CONNECTION,
  1017. 0)) {
  1018. SMARTLIST_DEL_CURRENT(entry_nodes, node);
  1019. continue;
  1020. } else if (! node->is_possible_guard) {
  1021. smartlist_add(worse_entry_nodes, (node_t*)node);
  1022. SMARTLIST_DEL_CURRENT(entry_nodes, node);
  1023. }
  1024. } SMARTLIST_FOREACH_END(node);
  1025. /* Now build the new entry_guards list. */
  1026. smartlist_clear(gs->chosen_entry_guards);
  1027. /* First, the previously configured guards that are in EntryNodes. */
  1028. smartlist_add_all(gs->chosen_entry_guards, old_entry_guards_on_list);
  1029. /* Next, scramble the rest of EntryNodes, putting the guards first. */
  1030. smartlist_shuffle(entry_nodes);
  1031. smartlist_shuffle(worse_entry_nodes);
  1032. smartlist_add_all(entry_nodes, worse_entry_nodes);
  1033. /* Next, the rest of EntryNodes */
  1034. SMARTLIST_FOREACH_BEGIN(entry_nodes, const node_t *, node) {
  1035. add_an_entry_guard(gs, node, 0, 0, 1, 0);
  1036. if (smartlist_len(gs->chosen_entry_guards) > numentryguards * 10)
  1037. break;
  1038. } SMARTLIST_FOREACH_END(node);
  1039. log_notice(LD_GENERAL, "%d entries in guards",
  1040. smartlist_len(gs->chosen_entry_guards));
  1041. /* Finally, free the remaining previously configured guards that are not in
  1042. * EntryNodes. */
  1043. SMARTLIST_FOREACH(old_entry_guards_not_on_list, entry_guard_t *, e,
  1044. entry_guard_free(e));
  1045. smartlist_free(entry_nodes);
  1046. smartlist_free(worse_entry_nodes);
  1047. smartlist_free(entry_fps);
  1048. smartlist_free(old_entry_guards_on_list);
  1049. smartlist_free(old_entry_guards_not_on_list);
  1050. entry_guards_changed_for_guard_selection(gs);
  1051. }
  1052. /** Return 0 if we're fine adding arbitrary routers out of the
  1053. * directory to our entry guard list, or return 1 if we have a
  1054. * list already and we must stick to it.
  1055. */
  1056. int
  1057. entry_list_is_constrained(const or_options_t *options)
  1058. {
  1059. if (options->EntryNodes)
  1060. return 1;
  1061. if (options->UseBridges)
  1062. return 1;
  1063. return 0;
  1064. }
  1065. /** Pick a live (up and listed) entry guard from entry_guards. If
  1066. * <b>state</b> is non-NULL, this is for a specific circuit --
  1067. * make sure not to pick this circuit's exit or any node in the
  1068. * exit's family. If <b>state</b> is NULL, we're looking for a random
  1069. * guard (likely a bridge). If <b>dirinfo</b> is not NO_DIRINFO (zero),
  1070. * then only select from nodes that know how to answer directory questions
  1071. * of that type. */
  1072. const node_t *
  1073. choose_random_entry(cpath_build_state_t *state)
  1074. {
  1075. return choose_random_entry_impl(get_guard_selection_info(),
  1076. state, 0, NO_DIRINFO, NULL);
  1077. }
  1078. /** Pick a live (up and listed) directory guard from entry_guards for
  1079. * downloading information of type <b>type</b>. */
  1080. const node_t *
  1081. choose_random_dirguard(dirinfo_type_t type)
  1082. {
  1083. return choose_random_entry_impl(get_guard_selection_info(),
  1084. NULL, 1, type, NULL);
  1085. }
  1086. /** Filter <b>all_entry_guards</b> for usable entry guards and put them
  1087. * in <b>live_entry_guards</b>. We filter based on whether the node is
  1088. * currently alive, and on whether it satisfies the restrictions
  1089. * imposed by the other arguments of this function.
  1090. *
  1091. * We don't place more guards than NumEntryGuards in <b>live_entry_guards</b>.
  1092. *
  1093. * If <b>chosen_exit</b> is set, it contains the exit node of this
  1094. * circuit. Make sure to not use it or its family as an entry guard.
  1095. *
  1096. * If <b>need_uptime</b> is set, we are looking for a stable entry guard.
  1097. * if <b>need_capacity</b> is set, we are looking for a fast entry guard.
  1098. *
  1099. * The rest of the arguments are the same as in choose_random_entry_impl().
  1100. *
  1101. * Return 1 if we should choose a guard right away. Return 0 if we
  1102. * should try to add more nodes to our list before deciding on a
  1103. * guard.
  1104. */
  1105. STATIC int
  1106. populate_live_entry_guards(smartlist_t *live_entry_guards,
  1107. const smartlist_t *all_entry_guards,
  1108. const node_t *chosen_exit,
  1109. dirinfo_type_t dirinfo_type,
  1110. int for_directory,
  1111. int need_uptime, int need_capacity)
  1112. {
  1113. const or_options_t *options = get_options();
  1114. const node_t *node = NULL;
  1115. const int num_needed = decide_num_guards(options, for_directory);
  1116. smartlist_t *exit_family = smartlist_new();
  1117. int retval = 0;
  1118. entry_is_live_flags_t entry_flags = 0;
  1119. (void) dirinfo_type;
  1120. { /* Set the flags we want our entry node to have */
  1121. if (need_uptime) {
  1122. entry_flags |= ENTRY_NEED_UPTIME;
  1123. }
  1124. if (need_capacity) {
  1125. entry_flags |= ENTRY_NEED_CAPACITY;
  1126. }
  1127. if (!for_directory) {
  1128. entry_flags |= ENTRY_NEED_DESCRIPTOR;
  1129. }
  1130. }
  1131. tor_assert(all_entry_guards);
  1132. if (chosen_exit) {
  1133. nodelist_add_node_and_family(exit_family, chosen_exit);
  1134. }
  1135. SMARTLIST_FOREACH_BEGIN(all_entry_guards, const entry_guard_t *, entry) {
  1136. const char *msg;
  1137. node = entry_is_live(entry, entry_flags, &msg);
  1138. if (!node)
  1139. continue; /* down, no point */
  1140. if (for_directory) {
  1141. if (!entry->is_dir_cache)
  1142. continue; /* We need a directory and didn't get one. */
  1143. }
  1144. if (node == chosen_exit)
  1145. continue; /* don't pick the same node for entry and exit */
  1146. if (smartlist_contains(exit_family, node))
  1147. continue; /* avoid relays that are family members of our exit */
  1148. smartlist_add(live_entry_guards, (void*)node);
  1149. if (!entry->made_contact) {
  1150. /* Always start with the first not-yet-contacted entry
  1151. * guard. Otherwise we might add several new ones, pick
  1152. * the second new one, and now we've expanded our entry
  1153. * guard list without needing to. */
  1154. retval = 1;
  1155. goto done;
  1156. }
  1157. if (smartlist_len(live_entry_guards) >= num_needed) {
  1158. retval = 1;
  1159. goto done; /* We picked enough entry guards. Done! */
  1160. }
  1161. } SMARTLIST_FOREACH_END(entry);
  1162. done:
  1163. smartlist_free(exit_family);
  1164. return retval;
  1165. }
  1166. /** Pick a node to be used as the entry guard of a circuit, relative to
  1167. * a supplied guard selection context.
  1168. *
  1169. * If <b>state</b> is set, it contains the information we know about
  1170. * the upcoming circuit.
  1171. *
  1172. * If <b>for_directory</b> is set, we are looking for a directory guard.
  1173. *
  1174. * <b>dirinfo_type</b> contains the kind of directory information we
  1175. * are looking for in our node, or NO_DIRINFO (zero) if we are not
  1176. * looking for any particular directory information (when set to
  1177. * NO_DIRINFO, the <b>dirinfo_type</b> filter is ignored).
  1178. *
  1179. * If <b>n_options_out</b> is set, we set it to the number of
  1180. * candidate guard nodes we had before picking a specific guard node.
  1181. *
  1182. * On success, return the node that should be used as the entry guard
  1183. * of the circuit. Return NULL if no such node could be found.
  1184. *
  1185. * Helper for choose_random{entry,dirguard}.
  1186. */
  1187. static const node_t *
  1188. choose_random_entry_impl(guard_selection_t *gs,
  1189. cpath_build_state_t *state, int for_directory,
  1190. dirinfo_type_t dirinfo_type, int *n_options_out)
  1191. {
  1192. const or_options_t *options = get_options();
  1193. smartlist_t *live_entry_guards = smartlist_new();
  1194. const node_t *chosen_exit =
  1195. state?build_state_get_exit_node(state) : NULL;
  1196. const node_t *node = NULL;
  1197. int need_uptime = state ? state->need_uptime : 0;
  1198. int need_capacity = state ? state->need_capacity : 0;
  1199. int preferred_min = 0;
  1200. const int num_needed = decide_num_guards(options, for_directory);
  1201. int retval = 0;
  1202. tor_assert(gs != NULL);
  1203. tor_assert(gs->chosen_entry_guards != NULL);
  1204. if (n_options_out)
  1205. *n_options_out = 0;
  1206. if (gs->should_add_entry_nodes)
  1207. entry_guards_set_from_config(gs, options);
  1208. if (!entry_list_is_constrained(options) &&
  1209. smartlist_len(gs->chosen_entry_guards) < num_needed)
  1210. pick_entry_guards(gs, options, for_directory);
  1211. retry:
  1212. smartlist_clear(live_entry_guards);
  1213. /* Populate the list of live entry guards so that we pick one of
  1214. them. */
  1215. retval = populate_live_entry_guards(live_entry_guards,
  1216. gs->chosen_entry_guards,
  1217. chosen_exit,
  1218. dirinfo_type,
  1219. for_directory,
  1220. need_uptime, need_capacity);
  1221. if (retval == 1) { /* We should choose a guard right now. */
  1222. goto choose_and_finish;
  1223. }
  1224. if (entry_list_is_constrained(options)) {
  1225. /* If we prefer the entry nodes we've got, and we have at least
  1226. * one choice, that's great. Use it. */
  1227. preferred_min = 1;
  1228. } else {
  1229. /* Try to have at least 2 choices available. This way we don't
  1230. * get stuck with a single live-but-crummy entry and just keep
  1231. * using it.
  1232. * (We might get 2 live-but-crummy entry guards, but so be it.) */
  1233. preferred_min = 2;
  1234. }
  1235. if (smartlist_len(live_entry_guards) < preferred_min) {
  1236. if (!entry_list_is_constrained(options)) {
  1237. /* still no? try adding a new entry then */
  1238. /* XXX if guard doesn't imply fast and stable, then we need
  1239. * to tell add_an_entry_guard below what we want, or it might
  1240. * be a long time til we get it. -RD */
  1241. node = add_an_entry_guard(gs, NULL, 0, 0, 1, for_directory);
  1242. if (node) {
  1243. entry_guards_changed_for_guard_selection(gs);
  1244. /* XXX we start over here in case the new node we added shares
  1245. * a family with our exit node. There's a chance that we'll just
  1246. * load up on entry guards here, if the network we're using is
  1247. * one big family. Perhaps we should teach add_an_entry_guard()
  1248. * to understand nodes-to-avoid-if-possible? -RD */
  1249. goto retry;
  1250. }
  1251. }
  1252. if (!node && need_uptime) {
  1253. need_uptime = 0; /* try without that requirement */
  1254. goto retry;
  1255. }
  1256. if (!node && need_capacity) {
  1257. /* still no? last attempt, try without requiring capacity */
  1258. need_capacity = 0;
  1259. goto retry;
  1260. }
  1261. /* live_entry_guards may be empty below. Oh well, we tried. */
  1262. }
  1263. choose_and_finish:
  1264. if (entry_list_is_constrained(options)) {
  1265. /* We need to weight by bandwidth, because our bridges or entryguards
  1266. * were not already selected proportional to their bandwidth. */
  1267. node = node_sl_choose_by_bandwidth(live_entry_guards, WEIGHT_FOR_GUARD);
  1268. } else {
  1269. /* We choose uniformly at random here, because choose_good_entry_server()
  1270. * already weights its choices by bandwidth, so we don't want to
  1271. * *double*-weight our guard selection. */
  1272. node = smartlist_choose(live_entry_guards);
  1273. }
  1274. if (n_options_out)
  1275. *n_options_out = smartlist_len(live_entry_guards);
  1276. smartlist_free(live_entry_guards);
  1277. return node;
  1278. }
  1279. /** Parse <b>state</b> and learn about the entry guards it describes.
  1280. * If <b>set</b> is true, and there are no errors, replace the guard
  1281. * list in the provided guard selection context with what we find.
  1282. * On success, return 0. On failure, alloc into *<b>msg</b> a string
  1283. * describing the error, and return -1.
  1284. */
  1285. int
  1286. entry_guards_parse_state_for_guard_selection(
  1287. guard_selection_t *gs,
  1288. or_state_t *state, int set, char **msg)
  1289. {
  1290. entry_guard_t *node = NULL;
  1291. smartlist_t *new_entry_guards = smartlist_new();
  1292. config_line_t *line;
  1293. time_t now = time(NULL);
  1294. const char *state_version = state->TorVersion;
  1295. digestmap_t *added_by = digestmap_new();
  1296. tor_assert(gs != NULL);
  1297. *msg = NULL;
  1298. for (line = state->EntryGuards; line; line = line->next) {
  1299. if (!strcasecmp(line->key, "EntryGuard")) {
  1300. smartlist_t *args = smartlist_new();
  1301. node = tor_malloc_zero(sizeof(entry_guard_t));
  1302. /* all entry guards on disk have been contacted */
  1303. node->made_contact = 1;
  1304. smartlist_add(new_entry_guards, node);
  1305. smartlist_split_string(args, line->value, " ",
  1306. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1307. if (smartlist_len(args)<2) {
  1308. *msg = tor_strdup("Unable to parse entry nodes: "
  1309. "Too few arguments to EntryGuard");
  1310. } else if (!is_legal_nickname(smartlist_get(args,0))) {
  1311. *msg = tor_strdup("Unable to parse entry nodes: "
  1312. "Bad nickname for EntryGuard");
  1313. } else {
  1314. strlcpy(node->nickname, smartlist_get(args,0), MAX_NICKNAME_LEN+1);
  1315. if (base16_decode(node->identity, DIGEST_LEN, smartlist_get(args,1),
  1316. strlen(smartlist_get(args,1))) != DIGEST_LEN) {
  1317. *msg = tor_strdup("Unable to parse entry nodes: "
  1318. "Bad hex digest for EntryGuard");
  1319. }
  1320. }
  1321. if (smartlist_len(args) >= 3) {
  1322. const char *is_cache = smartlist_get(args, 2);
  1323. if (!strcasecmp(is_cache, "DirCache")) {
  1324. node->is_dir_cache = 1;
  1325. } else if (!strcasecmp(is_cache, "NoDirCache")) {
  1326. node->is_dir_cache = 0;
  1327. } else {
  1328. log_warn(LD_CONFIG, "Bogus third argument to EntryGuard line: %s",
  1329. escaped(is_cache));
  1330. }
  1331. }
  1332. SMARTLIST_FOREACH(args, char*, cp, tor_free(cp));
  1333. smartlist_free(args);
  1334. if (*msg)
  1335. break;
  1336. } else if (!strcasecmp(line->key, "EntryGuardDownSince") ||
  1337. !strcasecmp(line->key, "EntryGuardUnlistedSince")) {
  1338. time_t when;
  1339. time_t last_try = 0;
  1340. if (!node) {
  1341. *msg = tor_strdup("Unable to parse entry nodes: "
  1342. "EntryGuardDownSince/UnlistedSince without EntryGuard");
  1343. break;
  1344. }
  1345. if (parse_iso_time_(line->value, &when, 0, 0)<0) {
  1346. *msg = tor_strdup("Unable to parse entry nodes: "
  1347. "Bad time in EntryGuardDownSince/UnlistedSince");
  1348. break;
  1349. }
  1350. if (when > now) {
  1351. /* It's a bad idea to believe info in the future: you can wind
  1352. * up with timeouts that aren't allowed to happen for years. */
  1353. continue;
  1354. }
  1355. if (strlen(line->value) >= ISO_TIME_LEN+ISO_TIME_LEN+1) {
  1356. /* ignore failure */
  1357. (void) parse_iso_time(line->value+ISO_TIME_LEN+1, &last_try);
  1358. }
  1359. if (!strcasecmp(line->key, "EntryGuardDownSince")) {
  1360. node->unreachable_since = when;
  1361. node->last_attempted = last_try;
  1362. } else {
  1363. node->bad_since = when;
  1364. }
  1365. } else if (!strcasecmp(line->key, "EntryGuardAddedBy")) {
  1366. char d[DIGEST_LEN];
  1367. /* format is digest version date */
  1368. if (strlen(line->value) < HEX_DIGEST_LEN+1+1+1+ISO_TIME_LEN) {
  1369. log_warn(LD_BUG, "EntryGuardAddedBy line is not long enough.");
  1370. continue;
  1371. }
  1372. if (base16_decode(d, sizeof(d),
  1373. line->value, HEX_DIGEST_LEN) != sizeof(d) ||
  1374. line->value[HEX_DIGEST_LEN] != ' ') {
  1375. log_warn(LD_BUG, "EntryGuardAddedBy line %s does not begin with "
  1376. "hex digest", escaped(line->value));
  1377. continue;
  1378. }
  1379. digestmap_set(added_by, d, tor_strdup(line->value+HEX_DIGEST_LEN+1));
  1380. } else if (!strcasecmp(line->key, "EntryGuardPathUseBias")) {
  1381. const or_options_t *options = get_options();
  1382. double use_cnt, success_cnt;
  1383. if (!node) {
  1384. *msg = tor_strdup("Unable to parse entry nodes: "
  1385. "EntryGuardPathUseBias without EntryGuard");
  1386. break;
  1387. }
  1388. if (tor_sscanf(line->value, "%lf %lf",
  1389. &use_cnt, &success_cnt) != 2) {
  1390. log_info(LD_GENERAL, "Malformed path use bias line for node %s",
  1391. node->nickname);
  1392. continue;
  1393. }
  1394. if (use_cnt < success_cnt) {
  1395. int severity = LOG_INFO;
  1396. /* If this state file was written by a Tor that would have
  1397. * already fixed it, then the overcounting bug is still there.. */
  1398. if (tor_version_as_new_as(state_version, "0.2.4.13-alpha")) {
  1399. severity = LOG_NOTICE;
  1400. }
  1401. log_fn(severity, LD_BUG,
  1402. "State file contains unexpectedly high usage success "
  1403. "counts %lf/%lf for Guard %s ($%s)",
  1404. success_cnt, use_cnt,
  1405. node->nickname, hex_str(node->identity, DIGEST_LEN));
  1406. success_cnt = use_cnt;
  1407. }
  1408. node->pb.use_attempts = use_cnt;
  1409. node->pb.use_successes = success_cnt;
  1410. log_info(LD_GENERAL, "Read %f/%f path use bias for node %s",
  1411. node->pb.use_successes, node->pb.use_attempts, node->nickname);
  1412. /* Note: We rely on the < comparison here to allow us to set a 0
  1413. * rate and disable the feature entirely. If refactoring, don't
  1414. * change to <= */
  1415. if (pathbias_get_use_success_count(node)/node->pb.use_attempts
  1416. < pathbias_get_extreme_use_rate(options) &&
  1417. pathbias_get_dropguards(options)) {
  1418. node->pb.path_bias_disabled = 1;
  1419. log_info(LD_GENERAL,
  1420. "Path use bias is too high (%f/%f); disabling node %s",
  1421. node->pb.circ_successes, node->pb.circ_attempts,
  1422. node->nickname);
  1423. }
  1424. } else if (!strcasecmp(line->key, "EntryGuardPathBias")) {
  1425. const or_options_t *options = get_options();
  1426. double hop_cnt, success_cnt, timeouts, collapsed, successful_closed,
  1427. unusable;
  1428. if (!node) {
  1429. *msg = tor_strdup("Unable to parse entry nodes: "
  1430. "EntryGuardPathBias without EntryGuard");
  1431. break;
  1432. }
  1433. /* First try 3 params, then 2. */
  1434. /* In the long run: circuit_success ~= successful_circuit_close +
  1435. * collapsed_circuits +
  1436. * unusable_circuits */
  1437. if (tor_sscanf(line->value, "%lf %lf %lf %lf %lf %lf",
  1438. &hop_cnt, &success_cnt, &successful_closed,
  1439. &collapsed, &unusable, &timeouts) != 6) {
  1440. int old_success, old_hops;
  1441. if (tor_sscanf(line->value, "%u %u", &old_success, &old_hops) != 2) {
  1442. continue;
  1443. }
  1444. log_info(LD_GENERAL, "Reading old-style EntryGuardPathBias %s",
  1445. escaped(line->value));
  1446. success_cnt = old_success;
  1447. successful_closed = old_success;
  1448. hop_cnt = old_hops;
  1449. timeouts = 0;
  1450. collapsed = 0;
  1451. unusable = 0;
  1452. }
  1453. if (hop_cnt < success_cnt) {
  1454. int severity = LOG_INFO;
  1455. /* If this state file was written by a Tor that would have
  1456. * already fixed it, then the overcounting bug is still there.. */
  1457. if (tor_version_as_new_as(state_version, "0.2.4.13-alpha")) {
  1458. severity = LOG_NOTICE;
  1459. }
  1460. log_fn(severity, LD_BUG,
  1461. "State file contains unexpectedly high success counts "
  1462. "%lf/%lf for Guard %s ($%s)",
  1463. success_cnt, hop_cnt,
  1464. node->nickname, hex_str(node->identity, DIGEST_LEN));
  1465. success_cnt = hop_cnt;
  1466. }
  1467. node->pb.circ_attempts = hop_cnt;
  1468. node->pb.circ_successes = success_cnt;
  1469. node->pb.successful_circuits_closed = successful_closed;
  1470. node->pb.timeouts = timeouts;
  1471. node->pb.collapsed_circuits = collapsed;
  1472. node->pb.unusable_circuits = unusable;
  1473. log_info(LD_GENERAL, "Read %f/%f path bias for node %s",
  1474. node->pb.circ_successes, node->pb.circ_attempts,
  1475. node->nickname);
  1476. /* Note: We rely on the < comparison here to allow us to set a 0
  1477. * rate and disable the feature entirely. If refactoring, don't
  1478. * change to <= */
  1479. if (pathbias_get_close_success_count(node)/node->pb.circ_attempts
  1480. < pathbias_get_extreme_rate(options) &&
  1481. pathbias_get_dropguards(options)) {
  1482. node->pb.path_bias_disabled = 1;
  1483. log_info(LD_GENERAL,
  1484. "Path bias is too high (%f/%f); disabling node %s",
  1485. node->pb.circ_successes, node->pb.circ_attempts,
  1486. node->nickname);
  1487. }
  1488. } else {
  1489. log_warn(LD_BUG, "Unexpected key %s", line->key);
  1490. }
  1491. }
  1492. SMARTLIST_FOREACH_BEGIN(new_entry_guards, entry_guard_t *, e) {
  1493. char *sp;
  1494. char *val = digestmap_get(added_by, e->identity);
  1495. if (val && (sp = strchr(val, ' '))) {
  1496. time_t when;
  1497. *sp++ = '\0';
  1498. if (parse_iso_time(sp, &when)<0) {
  1499. log_warn(LD_BUG, "Can't read time %s in EntryGuardAddedBy", sp);
  1500. } else {
  1501. e->chosen_by_version = tor_strdup(val);
  1502. e->chosen_on_date = when;
  1503. }
  1504. } else {
  1505. if (state_version) {
  1506. e->chosen_on_date = crypto_rand_time_range(now - 3600*24*30, now);
  1507. e->chosen_by_version = tor_strdup(state_version);
  1508. }
  1509. }
  1510. if (e->pb.path_bias_disabled && !e->bad_since)
  1511. e->bad_since = time(NULL);
  1512. }
  1513. SMARTLIST_FOREACH_END(e);
  1514. if (*msg || !set) {
  1515. SMARTLIST_FOREACH(new_entry_guards, entry_guard_t *, e,
  1516. entry_guard_free(e));
  1517. smartlist_free(new_entry_guards);
  1518. } else { /* !err && set */
  1519. if (gs->chosen_entry_guards) {
  1520. SMARTLIST_FOREACH(gs->chosen_entry_guards, entry_guard_t *, e,
  1521. entry_guard_free(e));
  1522. smartlist_free(gs->chosen_entry_guards);
  1523. }
  1524. gs->chosen_entry_guards = new_entry_guards;
  1525. gs->dirty = 0;
  1526. /* XXX hand new_entry_guards to this func, and move it up a
  1527. * few lines, so we don't have to re-dirty it */
  1528. if (remove_obsolete_entry_guards(gs, now))
  1529. gs->dirty = 1;
  1530. }
  1531. digestmap_free(added_by, tor_free_);
  1532. return *msg ? -1 : 0;
  1533. }
  1534. /** Parse <b>state</b> and learn about the entry guards it describes.
  1535. * If <b>set</b> is true, and there are no errors, replace the guard
  1536. * list in the default guard selection context with what we find.
  1537. * On success, return 0. On failure, alloc into *<b>msg</b> a string
  1538. * describing the error, and return -1.
  1539. */
  1540. int
  1541. entry_guards_parse_state(or_state_t *state, int set, char **msg)
  1542. {
  1543. return entry_guards_parse_state_for_guard_selection(
  1544. get_guard_selection_info(),
  1545. state, set, msg);
  1546. }
  1547. /** How long will we let a change in our guard nodes stay un-saved
  1548. * when we are trying to avoid disk writes? */
  1549. #define SLOW_GUARD_STATE_FLUSH_TIME 600
  1550. /** How long will we let a change in our guard nodes stay un-saved
  1551. * when we are not trying to avoid disk writes? */
  1552. #define FAST_GUARD_STATE_FLUSH_TIME 30
  1553. /** Our list of entry guards has changed for a particular guard selection
  1554. * context, or some element of one of our entry guards has changed for one.
  1555. * Write the changes to disk within the next few minutes.
  1556. */
  1557. void
  1558. entry_guards_changed_for_guard_selection(guard_selection_t *gs)
  1559. {
  1560. time_t when;
  1561. tor_assert(gs != NULL);
  1562. gs->dirty = 1;
  1563. if (get_options()->AvoidDiskWrites)
  1564. when = time(NULL) + SLOW_GUARD_STATE_FLUSH_TIME;
  1565. else
  1566. when = time(NULL) + FAST_GUARD_STATE_FLUSH_TIME;
  1567. /* or_state_save() will call entry_guards_update_state(). */
  1568. or_state_mark_dirty(get_or_state(), when);
  1569. }
  1570. /** Our list of entry guards has changed for the default guard selection
  1571. * context, or some element of one of our entry guards has changed. Write
  1572. * the changes to disk within the next few minutes.
  1573. */
  1574. void
  1575. entry_guards_changed(void)
  1576. {
  1577. entry_guards_changed_for_guard_selection(get_guard_selection_info());
  1578. }
  1579. /** If the entry guard info has not changed, do nothing and return.
  1580. * Otherwise, free the EntryGuards piece of <b>state</b> and create
  1581. * a new one out of the global entry_guards list, and then mark
  1582. * <b>state</b> dirty so it will get saved to disk.
  1583. *
  1584. * XXX this should get totally redesigned around storing multiple
  1585. * entry guard contexts. For the initial refactor we'll just
  1586. * always use the current default. Fix it as soon as we actually
  1587. * have any way that default can change.
  1588. */
  1589. void
  1590. entry_guards_update_state(or_state_t *state)
  1591. {
  1592. config_line_t **next, *line;
  1593. guard_selection_t *gs = get_guard_selection_info();
  1594. tor_assert(gs != NULL);
  1595. tor_assert(gs->chosen_entry_guards != NULL);
  1596. if (!gs->dirty)
  1597. return;
  1598. config_free_lines(state->EntryGuards);
  1599. next = &state->EntryGuards;
  1600. *next = NULL;
  1601. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, e) {
  1602. char dbuf[HEX_DIGEST_LEN+1];
  1603. if (!e->made_contact)
  1604. continue; /* don't write this one to disk */
  1605. *next = line = tor_malloc_zero(sizeof(config_line_t));
  1606. line->key = tor_strdup("EntryGuard");
  1607. base16_encode(dbuf, sizeof(dbuf), e->identity, DIGEST_LEN);
  1608. tor_asprintf(&line->value, "%s %s %sDirCache", e->nickname, dbuf,
  1609. e->is_dir_cache ? "" : "No");
  1610. next = &(line->next);
  1611. if (e->unreachable_since) {
  1612. *next = line = tor_malloc_zero(sizeof(config_line_t));
  1613. line->key = tor_strdup("EntryGuardDownSince");
  1614. line->value = tor_malloc(ISO_TIME_LEN+1+ISO_TIME_LEN+1);
  1615. format_iso_time(line->value, e->unreachable_since);
  1616. if (e->last_attempted) {
  1617. line->value[ISO_TIME_LEN] = ' ';
  1618. format_iso_time(line->value+ISO_TIME_LEN+1, e->last_attempted);
  1619. }
  1620. next = &(line->next);
  1621. }
  1622. if (e->bad_since) {
  1623. *next = line = tor_malloc_zero(sizeof(config_line_t));
  1624. line->key = tor_strdup("EntryGuardUnlistedSince");
  1625. line->value = tor_malloc(ISO_TIME_LEN+1);
  1626. format_iso_time(line->value, e->bad_since);
  1627. next = &(line->next);
  1628. }
  1629. if (e->chosen_on_date && e->chosen_by_version &&
  1630. !strchr(e->chosen_by_version, ' ')) {
  1631. char d[HEX_DIGEST_LEN+1];
  1632. char t[ISO_TIME_LEN+1];
  1633. *next = line = tor_malloc_zero(sizeof(config_line_t));
  1634. line->key = tor_strdup("EntryGuardAddedBy");
  1635. base16_encode(d, sizeof(d), e->identity, DIGEST_LEN);
  1636. format_iso_time(t, e->chosen_on_date);
  1637. tor_asprintf(&line->value, "%s %s %s",
  1638. d, e->chosen_by_version, t);
  1639. next = &(line->next);
  1640. }
  1641. if (e->pb.circ_attempts > 0) {
  1642. *next = line = tor_malloc_zero(sizeof(config_line_t));
  1643. line->key = tor_strdup("EntryGuardPathBias");
  1644. /* In the long run: circuit_success ~= successful_circuit_close +
  1645. * collapsed_circuits +
  1646. * unusable_circuits */
  1647. tor_asprintf(&line->value, "%f %f %f %f %f %f",
  1648. e->pb.circ_attempts, e->pb.circ_successes,
  1649. pathbias_get_close_success_count(e),
  1650. e->pb.collapsed_circuits,
  1651. e->pb.unusable_circuits, e->pb.timeouts);
  1652. next = &(line->next);
  1653. }
  1654. if (e->pb.use_attempts > 0) {
  1655. *next = line = tor_malloc_zero(sizeof(config_line_t));
  1656. line->key = tor_strdup("EntryGuardPathUseBias");
  1657. tor_asprintf(&line->value, "%f %f",
  1658. e->pb.use_attempts,
  1659. pathbias_get_use_success_count(e));
  1660. next = &(line->next);
  1661. }
  1662. } SMARTLIST_FOREACH_END(e);
  1663. if (!get_options()->AvoidDiskWrites)
  1664. or_state_mark_dirty(get_or_state(), 0);
  1665. gs->dirty = 0;
  1666. }
  1667. /** If <b>question</b> is the string "entry-guards", then dump
  1668. * to *<b>answer</b> a newly allocated string describing all of
  1669. * the nodes in the global entry_guards list. See control-spec.txt
  1670. * for details.
  1671. * For backward compatibility, we also handle the string "helper-nodes".
  1672. *
  1673. * XXX this should be totally redesigned after prop 271 too, and that's
  1674. * going to take some control spec work.
  1675. * */
  1676. int
  1677. getinfo_helper_entry_guards(control_connection_t *conn,
  1678. const char *question, char **answer,
  1679. const char **errmsg)
  1680. {
  1681. guard_selection_t *gs = get_guard_selection_info();
  1682. tor_assert(gs != NULL);
  1683. tor_assert(gs->chosen_entry_guards != NULL);
  1684. (void) conn;
  1685. (void) errmsg;
  1686. if (!strcmp(question,"entry-guards") ||
  1687. !strcmp(question,"helper-nodes")) {
  1688. smartlist_t *sl = smartlist_new();
  1689. char tbuf[ISO_TIME_LEN+1];
  1690. char nbuf[MAX_VERBOSE_NICKNAME_LEN+1];
  1691. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, e) {
  1692. const char *status = NULL;
  1693. time_t when = 0;
  1694. const node_t *node;
  1695. if (!e->made_contact) {
  1696. status = "never-connected";
  1697. } else if (e->bad_since) {
  1698. when = e->bad_since;
  1699. status = "unusable";
  1700. } else if (e->unreachable_since) {
  1701. when = e->unreachable_since;
  1702. status = "down";
  1703. } else {
  1704. status = "up";
  1705. }
  1706. node = node_get_by_id(e->identity);
  1707. if (node) {
  1708. node_get_verbose_nickname(node, nbuf);
  1709. } else {
  1710. nbuf[0] = '$';
  1711. base16_encode(nbuf+1, sizeof(nbuf)-1, e->identity, DIGEST_LEN);
  1712. /* e->nickname field is not very reliable if we don't know about
  1713. * this router any longer; don't include it. */
  1714. }
  1715. if (when) {
  1716. format_iso_time(tbuf, when);
  1717. smartlist_add_asprintf(sl, "%s %s %s\n", nbuf, status, tbuf);
  1718. } else {
  1719. smartlist_add_asprintf(sl, "%s %s\n", nbuf, status);
  1720. }
  1721. } SMARTLIST_FOREACH_END(e);
  1722. *answer = smartlist_join_strings(sl, "", 0, NULL);
  1723. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  1724. smartlist_free(sl);
  1725. }
  1726. return 0;
  1727. }
  1728. /** Return 0 if we should apply guardfraction information found in the
  1729. * consensus. A specific consensus can be specified with the
  1730. * <b>ns</b> argument, if NULL the most recent one will be picked.*/
  1731. int
  1732. should_apply_guardfraction(const networkstatus_t *ns)
  1733. {
  1734. /* We need to check the corresponding torrc option and the consensus
  1735. * parameter if we need to. */
  1736. const or_options_t *options = get_options();
  1737. /* If UseGuardFraction is 'auto' then check the same-named consensus
  1738. * parameter. If the consensus parameter is not present, default to
  1739. * "off". */
  1740. if (options->UseGuardFraction == -1) {
  1741. return networkstatus_get_param(ns, "UseGuardFraction",
  1742. 0, /* default to "off" */
  1743. 0, 1);
  1744. }
  1745. return options->UseGuardFraction;
  1746. }
  1747. /* Given the original bandwidth of a guard and its guardfraction,
  1748. * calculate how much bandwidth the guard should have as a guard and
  1749. * as a non-guard.
  1750. *
  1751. * Quoting from proposal236:
  1752. *
  1753. * Let Wpf denote the weight from the 'bandwidth-weights' line a
  1754. * client would apply to N for position p if it had the guard
  1755. * flag, Wpn the weight if it did not have the guard flag, and B the
  1756. * measured bandwidth of N in the consensus. Then instead of choosing
  1757. * N for position p proportionally to Wpf*B or Wpn*B, clients should
  1758. * choose N proportionally to F*Wpf*B + (1-F)*Wpn*B.
  1759. *
  1760. * This function fills the <b>guardfraction_bw</b> structure. It sets
  1761. * <b>guard_bw</b> to F*B and <b>non_guard_bw</b> to (1-F)*B.
  1762. */
  1763. void
  1764. guard_get_guardfraction_bandwidth(guardfraction_bandwidth_t *guardfraction_bw,
  1765. int orig_bandwidth,
  1766. uint32_t guardfraction_percentage)
  1767. {
  1768. double guardfraction_fraction;
  1769. /* Turn the percentage into a fraction. */
  1770. tor_assert(guardfraction_percentage <= 100);
  1771. guardfraction_fraction = guardfraction_percentage / 100.0;
  1772. long guard_bw = tor_lround(guardfraction_fraction * orig_bandwidth);
  1773. tor_assert(guard_bw <= INT_MAX);
  1774. guardfraction_bw->guard_bw = (int) guard_bw;
  1775. guardfraction_bw->non_guard_bw = orig_bandwidth - (int) guard_bw;
  1776. }
  1777. /** A list of configured bridges. Whenever we actually get a descriptor
  1778. * for one, we add it as an entry guard. Note that the order of bridges
  1779. * in this list does not necessarily correspond to the order of bridges
  1780. * in the torrc. */
  1781. static smartlist_t *bridge_list = NULL;
  1782. /** Mark every entry of the bridge list to be removed on our next call to
  1783. * sweep_bridge_list unless it has first been un-marked. */
  1784. void
  1785. mark_bridge_list(void)
  1786. {
  1787. if (!bridge_list)
  1788. bridge_list = smartlist_new();
  1789. SMARTLIST_FOREACH(bridge_list, bridge_info_t *, b,
  1790. b->marked_for_removal = 1);
  1791. }
  1792. /** Remove every entry of the bridge list that was marked with
  1793. * mark_bridge_list if it has not subsequently been un-marked. */
  1794. void
  1795. sweep_bridge_list(void)
  1796. {
  1797. if (!bridge_list)
  1798. bridge_list = smartlist_new();
  1799. SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, b) {
  1800. if (b->marked_for_removal) {
  1801. SMARTLIST_DEL_CURRENT(bridge_list, b);
  1802. bridge_free(b);
  1803. }
  1804. } SMARTLIST_FOREACH_END(b);
  1805. }
  1806. /** Initialize the bridge list to empty, creating it if needed. */
  1807. static void
  1808. clear_bridge_list(void)
  1809. {
  1810. if (!bridge_list)
  1811. bridge_list = smartlist_new();
  1812. SMARTLIST_FOREACH(bridge_list, bridge_info_t *, b, bridge_free(b));
  1813. smartlist_clear(bridge_list);
  1814. }
  1815. /** Free the bridge <b>bridge</b>. */
  1816. static void
  1817. bridge_free(bridge_info_t *bridge)
  1818. {
  1819. if (!bridge)
  1820. return;
  1821. tor_free(bridge->transport_name);
  1822. if (bridge->socks_args) {
  1823. SMARTLIST_FOREACH(bridge->socks_args, char*, s, tor_free(s));
  1824. smartlist_free(bridge->socks_args);
  1825. }
  1826. tor_free(bridge);
  1827. }
  1828. /** If we have a bridge configured whose digest matches <b>digest</b>, or a
  1829. * bridge with no known digest whose address matches any of the
  1830. * tor_addr_port_t's in <b>orports</b>, return that bridge. Else return
  1831. * NULL. */
  1832. static bridge_info_t *
  1833. get_configured_bridge_by_orports_digest(const char *digest,
  1834. const smartlist_t *orports)
  1835. {
  1836. if (!bridge_list)
  1837. return NULL;
  1838. SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge)
  1839. {
  1840. if (tor_digest_is_zero(bridge->identity)) {
  1841. SMARTLIST_FOREACH_BEGIN(orports, tor_addr_port_t *, ap)
  1842. {
  1843. if (tor_addr_compare(&bridge->addr, &ap->addr, CMP_EXACT) == 0 &&
  1844. bridge->port == ap->port)
  1845. return bridge;
  1846. }
  1847. SMARTLIST_FOREACH_END(ap);
  1848. }
  1849. if (digest && tor_memeq(bridge->identity, digest, DIGEST_LEN))
  1850. return bridge;
  1851. }
  1852. SMARTLIST_FOREACH_END(bridge);
  1853. return NULL;
  1854. }
  1855. /** If we have a bridge configured whose digest matches <b>digest</b>, or a
  1856. * bridge with no known digest whose address matches <b>addr</b>:<b>port</b>,
  1857. * return that bridge. Else return NULL. If <b>digest</b> is NULL, check for
  1858. * address/port matches only. */
  1859. static bridge_info_t *
  1860. get_configured_bridge_by_addr_port_digest(const tor_addr_t *addr,
  1861. uint16_t port,
  1862. const char *digest)
  1863. {
  1864. if (!bridge_list)
  1865. return NULL;
  1866. SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge)
  1867. {
  1868. if ((tor_digest_is_zero(bridge->identity) || digest == NULL) &&
  1869. !tor_addr_compare(&bridge->addr, addr, CMP_EXACT) &&
  1870. bridge->port == port)
  1871. return bridge;
  1872. if (digest && tor_memeq(bridge->identity, digest, DIGEST_LEN))
  1873. return bridge;
  1874. }
  1875. SMARTLIST_FOREACH_END(bridge);
  1876. return NULL;
  1877. }
  1878. /** If we have a bridge configured whose digest matches <b>digest</b>, or a
  1879. * bridge with no known digest whose address matches <b>addr</b>:<b>port</b>,
  1880. * return 1. Else return 0. If <b>digest</b> is NULL, check for
  1881. * address/port matches only. */
  1882. int
  1883. addr_is_a_configured_bridge(const tor_addr_t *addr,
  1884. uint16_t port,
  1885. const char *digest)
  1886. {
  1887. tor_assert(addr);
  1888. return get_configured_bridge_by_addr_port_digest(addr, port, digest) ? 1 : 0;
  1889. }
  1890. /** If we have a bridge configured whose digest matches
  1891. * <b>ei->identity_digest</b>, or a bridge with no known digest whose address
  1892. * matches <b>ei->addr</b>:<b>ei->port</b>, return 1. Else return 0.
  1893. * If <b>ei->onion_key</b> is NULL, check for address/port matches only. */
  1894. int
  1895. extend_info_is_a_configured_bridge(const extend_info_t *ei)
  1896. {
  1897. const char *digest = ei->onion_key ? ei->identity_digest : NULL;
  1898. return addr_is_a_configured_bridge(&ei->addr, ei->port, digest);
  1899. }
  1900. /** Wrapper around get_configured_bridge_by_addr_port_digest() to look
  1901. * it up via router descriptor <b>ri</b>. */
  1902. static bridge_info_t *
  1903. get_configured_bridge_by_routerinfo(const routerinfo_t *ri)
  1904. {
  1905. bridge_info_t *bi = NULL;
  1906. smartlist_t *orports = router_get_all_orports(ri);
  1907. bi = get_configured_bridge_by_orports_digest(ri->cache_info.identity_digest,
  1908. orports);
  1909. SMARTLIST_FOREACH(orports, tor_addr_port_t *, p, tor_free(p));
  1910. smartlist_free(orports);
  1911. return bi;
  1912. }
  1913. /** Return 1 if <b>ri</b> is one of our known bridges, else 0. */
  1914. int
  1915. routerinfo_is_a_configured_bridge(const routerinfo_t *ri)
  1916. {
  1917. return get_configured_bridge_by_routerinfo(ri) ? 1 : 0;
  1918. }
  1919. /** Return 1 if <b>node</b> is one of our configured bridges, else 0. */
  1920. int
  1921. node_is_a_configured_bridge(const node_t *node)
  1922. {
  1923. int retval = 0;
  1924. smartlist_t *orports = node_get_all_orports(node);
  1925. retval = get_configured_bridge_by_orports_digest(node->identity,
  1926. orports) != NULL;
  1927. SMARTLIST_FOREACH(orports, tor_addr_port_t *, p, tor_free(p));
  1928. smartlist_free(orports);
  1929. return retval;
  1930. }
  1931. /** We made a connection to a router at <b>addr</b>:<b>port</b>
  1932. * without knowing its digest. Its digest turned out to be <b>digest</b>.
  1933. * If it was a bridge, and we still don't know its digest, record it.
  1934. */
  1935. void
  1936. learned_router_identity(const tor_addr_t *addr, uint16_t port,
  1937. const char *digest)
  1938. {
  1939. bridge_info_t *bridge =
  1940. get_configured_bridge_by_addr_port_digest(addr, port, digest);
  1941. if (bridge && tor_digest_is_zero(bridge->identity)) {
  1942. char *transport_info = NULL;
  1943. const char *transport_name =
  1944. find_transport_name_by_bridge_addrport(addr, port);
  1945. if (transport_name)
  1946. tor_asprintf(&transport_info, " (with transport '%s')", transport_name);
  1947. memcpy(bridge->identity, digest, DIGEST_LEN);
  1948. log_notice(LD_DIR, "Learned fingerprint %s for bridge %s%s.",
  1949. hex_str(digest, DIGEST_LEN), fmt_addrport(addr, port),
  1950. transport_info ? transport_info : "");
  1951. tor_free(transport_info);
  1952. }
  1953. }
  1954. /** Return true if <b>bridge</b> has the same identity digest as
  1955. * <b>digest</b>. If <b>digest</b> is NULL, it matches
  1956. * bridges with unspecified identity digests. */
  1957. static int
  1958. bridge_has_digest(const bridge_info_t *bridge, const char *digest)
  1959. {
  1960. if (digest)
  1961. return tor_memeq(digest, bridge->identity, DIGEST_LEN);
  1962. else
  1963. return tor_digest_is_zero(bridge->identity);
  1964. }
  1965. /** We are about to add a new bridge at <b>addr</b>:<b>port</b>, with optional
  1966. * <b>digest</b> and <b>transport_name</b>. Mark for removal any previously
  1967. * existing bridge with the same address and port, and warn the user as
  1968. * appropriate.
  1969. */
  1970. static void
  1971. bridge_resolve_conflicts(const tor_addr_t *addr, uint16_t port,
  1972. const char *digest, const char *transport_name)
  1973. {
  1974. /* Iterate the already-registered bridge list:
  1975. If you find a bridge with the same adress and port, mark it for
  1976. removal. It doesn't make sense to have two active bridges with
  1977. the same IP:PORT. If the bridge in question has a different
  1978. digest or transport than <b>digest</b>/<b>transport_name</b>,
  1979. it's probably a misconfiguration and we should warn the user.
  1980. */
  1981. SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge) {
  1982. if (bridge->marked_for_removal)
  1983. continue;
  1984. if (tor_addr_eq(&bridge->addr, addr) && (bridge->port == port)) {
  1985. bridge->marked_for_removal = 1;
  1986. if (!bridge_has_digest(bridge, digest) ||
  1987. strcmp_opt(bridge->transport_name, transport_name)) {
  1988. /* warn the user */
  1989. char *bridge_description_new, *bridge_description_old;
  1990. tor_asprintf(&bridge_description_new, "%s:%s:%s",
  1991. fmt_addrport(addr, port),
  1992. digest ? hex_str(digest, DIGEST_LEN) : "",
  1993. transport_name ? transport_name : "");
  1994. tor_asprintf(&bridge_description_old, "%s:%s:%s",
  1995. fmt_addrport(&bridge->addr, bridge->port),
  1996. tor_digest_is_zero(bridge->identity) ?
  1997. "" : hex_str(bridge->identity,DIGEST_LEN),
  1998. bridge->transport_name ? bridge->transport_name : "");
  1999. log_warn(LD_GENERAL,"Tried to add bridge '%s', but we found a conflict"
  2000. " with the already registered bridge '%s'. We will discard"
  2001. " the old bridge and keep '%s'. If this is not what you"
  2002. " wanted, please change your configuration file accordingly.",
  2003. bridge_description_new, bridge_description_old,
  2004. bridge_description_new);
  2005. tor_free(bridge_description_new);
  2006. tor_free(bridge_description_old);
  2007. }
  2008. }
  2009. } SMARTLIST_FOREACH_END(bridge);
  2010. }
  2011. /** Return True if we have a bridge that uses a transport with name
  2012. * <b>transport_name</b>. */
  2013. MOCK_IMPL(int,
  2014. transport_is_needed, (const char *transport_name))
  2015. {
  2016. if (!bridge_list)
  2017. return 0;
  2018. SMARTLIST_FOREACH_BEGIN(bridge_list, const bridge_info_t *, bridge) {
  2019. if (bridge->transport_name &&
  2020. !strcmp(bridge->transport_name, transport_name))
  2021. return 1;
  2022. } SMARTLIST_FOREACH_END(bridge);
  2023. return 0;
  2024. }
  2025. /** Register the bridge information in <b>bridge_line</b> to the
  2026. * bridge subsystem. Steals reference of <b>bridge_line</b>. */
  2027. void
  2028. bridge_add_from_config(bridge_line_t *bridge_line)
  2029. {
  2030. bridge_info_t *b;
  2031. { /* Log the bridge we are about to register: */
  2032. log_debug(LD_GENERAL, "Registering bridge at %s (transport: %s) (%s)",
  2033. fmt_addrport(&bridge_line->addr, bridge_line->port),
  2034. bridge_line->transport_name ?
  2035. bridge_line->transport_name : "no transport",
  2036. tor_digest_is_zero(bridge_line->digest) ?
  2037. "no key listed" : hex_str(bridge_line->digest, DIGEST_LEN));
  2038. if (bridge_line->socks_args) { /* print socks arguments */
  2039. int i = 0;
  2040. tor_assert(smartlist_len(bridge_line->socks_args) > 0);
  2041. log_debug(LD_GENERAL, "Bridge uses %d SOCKS arguments:",
  2042. smartlist_len(bridge_line->socks_args));
  2043. SMARTLIST_FOREACH(bridge_line->socks_args, const char *, arg,
  2044. log_debug(LD_CONFIG, "%d: %s", ++i, arg));
  2045. }
  2046. }
  2047. bridge_resolve_conflicts(&bridge_line->addr,
  2048. bridge_line->port,
  2049. bridge_line->digest,
  2050. bridge_line->transport_name);
  2051. b = tor_malloc_zero(sizeof(bridge_info_t));
  2052. tor_addr_copy(&b->addr, &bridge_line->addr);
  2053. b->port = bridge_line->port;
  2054. memcpy(b->identity, bridge_line->digest, DIGEST_LEN);
  2055. if (bridge_line->transport_name)
  2056. b->transport_name = bridge_line->transport_name;
  2057. b->fetch_status.schedule = DL_SCHED_BRIDGE;
  2058. b->fetch_status.backoff = DL_SCHED_RANDOM_EXPONENTIAL;
  2059. b->socks_args = bridge_line->socks_args;
  2060. if (!bridge_list)
  2061. bridge_list = smartlist_new();
  2062. tor_free(bridge_line); /* Deallocate bridge_line now. */
  2063. smartlist_add(bridge_list, b);
  2064. }
  2065. /** Returns true iff the node is used as a guard in the specified guard
  2066. * context */
  2067. int
  2068. is_node_used_as_guard_for_guard_selection(guard_selection_t *gs,
  2069. const node_t *node)
  2070. {
  2071. int res = 0;
  2072. /*
  2073. * We used to have a using_as_guard flag in node_t, but it had to go away
  2074. * to allow for multiple guard selection contexts. Instead, search the
  2075. * guard list for a matching digest.
  2076. */
  2077. tor_assert(gs != NULL);
  2078. tor_assert(node != NULL);
  2079. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, e) {
  2080. if (tor_memeq(e->identity, node->identity, DIGEST_LEN)) {
  2081. res = 1;
  2082. break;
  2083. }
  2084. } SMARTLIST_FOREACH_END(e);
  2085. return res;
  2086. }
  2087. /** Returns true iff the node is used as a guard in the default guard
  2088. * context */
  2089. MOCK_IMPL(int,
  2090. is_node_used_as_guard, (const node_t *node))
  2091. {
  2092. return is_node_used_as_guard_for_guard_selection(
  2093. get_guard_selection_info(), node);
  2094. }
  2095. /** Return true iff <b>routerset</b> contains the bridge <b>bridge</b>. */
  2096. static int
  2097. routerset_contains_bridge(const routerset_t *routerset,
  2098. const bridge_info_t *bridge)
  2099. {
  2100. int result;
  2101. extend_info_t *extinfo;
  2102. tor_assert(bridge);
  2103. if (!routerset)
  2104. return 0;
  2105. extinfo = extend_info_new(
  2106. NULL, bridge->identity, NULL, NULL, &bridge->addr, bridge->port);
  2107. result = routerset_contains_extendinfo(routerset, extinfo);
  2108. extend_info_free(extinfo);
  2109. return result;
  2110. }
  2111. /** If <b>digest</b> is one of our known bridges, return it. */
  2112. static bridge_info_t *
  2113. find_bridge_by_digest(const char *digest)
  2114. {
  2115. SMARTLIST_FOREACH(bridge_list, bridge_info_t *, bridge,
  2116. {
  2117. if (tor_memeq(bridge->identity, digest, DIGEST_LEN))
  2118. return bridge;
  2119. });
  2120. return NULL;
  2121. }
  2122. /** Given the <b>addr</b> and <b>port</b> of a bridge, if that bridge
  2123. * supports a pluggable transport, return its name. Otherwise, return
  2124. * NULL. */
  2125. const char *
  2126. find_transport_name_by_bridge_addrport(const tor_addr_t *addr, uint16_t port)
  2127. {
  2128. if (!bridge_list)
  2129. return NULL;
  2130. SMARTLIST_FOREACH_BEGIN(bridge_list, const bridge_info_t *, bridge) {
  2131. if (tor_addr_eq(&bridge->addr, addr) &&
  2132. (bridge->port == port))
  2133. return bridge->transport_name;
  2134. } SMARTLIST_FOREACH_END(bridge);
  2135. return NULL;
  2136. }
  2137. /** If <b>addr</b> and <b>port</b> match the address and port of a
  2138. * bridge of ours that uses pluggable transports, place its transport
  2139. * in <b>transport</b>.
  2140. *
  2141. * Return 0 on success (found a transport, or found a bridge with no
  2142. * transport, or found no bridge); return -1 if we should be using a
  2143. * transport, but the transport could not be found.
  2144. */
  2145. int
  2146. get_transport_by_bridge_addrport(const tor_addr_t *addr, uint16_t port,
  2147. const transport_t **transport)
  2148. {
  2149. *transport = NULL;
  2150. if (!bridge_list)
  2151. return 0;
  2152. SMARTLIST_FOREACH_BEGIN(bridge_list, const bridge_info_t *, bridge) {
  2153. if (tor_addr_eq(&bridge->addr, addr) &&
  2154. (bridge->port == port)) { /* bridge matched */
  2155. if (bridge->transport_name) { /* it also uses pluggable transports */
  2156. *transport = transport_get_by_name(bridge->transport_name);
  2157. if (*transport == NULL) { /* it uses pluggable transports, but
  2158. the transport could not be found! */
  2159. return -1;
  2160. }
  2161. return 0;
  2162. } else { /* bridge matched, but it doesn't use transports. */
  2163. break;
  2164. }
  2165. }
  2166. } SMARTLIST_FOREACH_END(bridge);
  2167. *transport = NULL;
  2168. return 0;
  2169. }
  2170. /** Return a smartlist containing all the SOCKS arguments that we
  2171. * should pass to the SOCKS proxy. */
  2172. const smartlist_t *
  2173. get_socks_args_by_bridge_addrport(const tor_addr_t *addr, uint16_t port)
  2174. {
  2175. bridge_info_t *bridge = get_configured_bridge_by_addr_port_digest(addr,
  2176. port,
  2177. NULL);
  2178. return bridge ? bridge->socks_args : NULL;
  2179. }
  2180. /** We need to ask <b>bridge</b> for its server descriptor. */
  2181. static void
  2182. launch_direct_bridge_descriptor_fetch(bridge_info_t *bridge)
  2183. {
  2184. const or_options_t *options = get_options();
  2185. if (connection_get_by_type_addr_port_purpose(
  2186. CONN_TYPE_DIR, &bridge->addr, bridge->port,
  2187. DIR_PURPOSE_FETCH_SERVERDESC))
  2188. return; /* it's already on the way */
  2189. if (routerset_contains_bridge(options->ExcludeNodes, bridge)) {
  2190. download_status_mark_impossible(&bridge->fetch_status);
  2191. log_warn(LD_APP, "Not using bridge at %s: it is in ExcludeNodes.",
  2192. safe_str_client(fmt_and_decorate_addr(&bridge->addr)));
  2193. return;
  2194. }
  2195. /* Until we get a descriptor for the bridge, we only know one address for
  2196. * it. */
  2197. if (!fascist_firewall_allows_address_addr(&bridge->addr, bridge->port,
  2198. FIREWALL_OR_CONNECTION, 0, 0)) {
  2199. log_notice(LD_CONFIG, "Tried to fetch a descriptor directly from a "
  2200. "bridge, but that bridge is not reachable through our "
  2201. "firewall.");
  2202. return;
  2203. }
  2204. directory_initiate_command(&bridge->addr, bridge->port,
  2205. NULL, 0, /*no dirport*/
  2206. bridge->identity,
  2207. DIR_PURPOSE_FETCH_SERVERDESC,
  2208. ROUTER_PURPOSE_BRIDGE,
  2209. DIRIND_ONEHOP, "authority.z", NULL, 0, 0);
  2210. }
  2211. /** Fetching the bridge descriptor from the bridge authority returned a
  2212. * "not found". Fall back to trying a direct fetch. */
  2213. void
  2214. retry_bridge_descriptor_fetch_directly(const char *digest)
  2215. {
  2216. bridge_info_t *bridge = find_bridge_by_digest(digest);
  2217. if (!bridge)
  2218. return; /* not found? oh well. */
  2219. launch_direct_bridge_descriptor_fetch(bridge);
  2220. }
  2221. /** For each bridge in our list for which we don't currently have a
  2222. * descriptor, fetch a new copy of its descriptor -- either directly
  2223. * from the bridge or via a bridge authority. */
  2224. void
  2225. fetch_bridge_descriptors(const or_options_t *options, time_t now)
  2226. {
  2227. int num_bridge_auths = get_n_authorities(BRIDGE_DIRINFO);
  2228. int ask_bridge_directly;
  2229. int can_use_bridge_authority;
  2230. if (!bridge_list)
  2231. return;
  2232. /* If we still have unconfigured managed proxies, don't go and
  2233. connect to a bridge. */
  2234. if (pt_proxies_configuration_pending())
  2235. return;
  2236. SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, bridge)
  2237. {
  2238. if (!download_status_is_ready(&bridge->fetch_status, now,
  2239. IMPOSSIBLE_TO_DOWNLOAD))
  2240. continue; /* don't bother, no need to retry yet */
  2241. if (routerset_contains_bridge(options->ExcludeNodes, bridge)) {
  2242. download_status_mark_impossible(&bridge->fetch_status);
  2243. log_warn(LD_APP, "Not using bridge at %s: it is in ExcludeNodes.",
  2244. safe_str_client(fmt_and_decorate_addr(&bridge->addr)));
  2245. continue;
  2246. }
  2247. /* schedule another fetch as if this one will fail, in case it does */
  2248. download_status_failed(&bridge->fetch_status, 0);
  2249. can_use_bridge_authority = !tor_digest_is_zero(bridge->identity) &&
  2250. num_bridge_auths;
  2251. ask_bridge_directly = !can_use_bridge_authority ||
  2252. !options->UpdateBridgesFromAuthority;
  2253. log_debug(LD_DIR, "ask_bridge_directly=%d (%d, %d, %d)",
  2254. ask_bridge_directly, tor_digest_is_zero(bridge->identity),
  2255. !options->UpdateBridgesFromAuthority, !num_bridge_auths);
  2256. if (ask_bridge_directly &&
  2257. !fascist_firewall_allows_address_addr(&bridge->addr, bridge->port,
  2258. FIREWALL_OR_CONNECTION, 0,
  2259. 0)) {
  2260. log_notice(LD_DIR, "Bridge at '%s' isn't reachable by our "
  2261. "firewall policy. %s.",
  2262. fmt_addrport(&bridge->addr, bridge->port),
  2263. can_use_bridge_authority ?
  2264. "Asking bridge authority instead" : "Skipping");
  2265. if (can_use_bridge_authority)
  2266. ask_bridge_directly = 0;
  2267. else
  2268. continue;
  2269. }
  2270. if (ask_bridge_directly) {
  2271. /* we need to ask the bridge itself for its descriptor. */
  2272. launch_direct_bridge_descriptor_fetch(bridge);
  2273. } else {
  2274. /* We have a digest and we want to ask an authority. We could
  2275. * combine all the requests into one, but that may give more
  2276. * hints to the bridge authority than we want to give. */
  2277. char resource[10 + HEX_DIGEST_LEN];
  2278. memcpy(resource, "fp/", 3);
  2279. base16_encode(resource+3, HEX_DIGEST_LEN+1,
  2280. bridge->identity, DIGEST_LEN);
  2281. memcpy(resource+3+HEX_DIGEST_LEN, ".z", 3);
  2282. log_info(LD_DIR, "Fetching bridge info '%s' from bridge authority.",
  2283. resource);
  2284. directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
  2285. ROUTER_PURPOSE_BRIDGE, resource, 0, DL_WANT_AUTHORITY);
  2286. }
  2287. }
  2288. SMARTLIST_FOREACH_END(bridge);
  2289. }
  2290. /** If our <b>bridge</b> is configured to be a different address than
  2291. * the bridge gives in <b>node</b>, rewrite the routerinfo
  2292. * we received to use the address we meant to use. Now we handle
  2293. * multihomed bridges better.
  2294. */
  2295. static void
  2296. rewrite_node_address_for_bridge(const bridge_info_t *bridge, node_t *node)
  2297. {
  2298. /* XXXX move this function. */
  2299. /* XXXX overridden addresses should really live in the node_t, so that the
  2300. * routerinfo_t and the microdesc_t can be immutable. But we can only
  2301. * do that safely if we know that no function that connects to an OR
  2302. * does so through an address from any source other than node_get_addr().
  2303. */
  2304. tor_addr_t addr;
  2305. const or_options_t *options = get_options();
  2306. if (node->ri) {
  2307. routerinfo_t *ri = node->ri;
  2308. tor_addr_from_ipv4h(&addr, ri->addr);
  2309. if ((!tor_addr_compare(&bridge->addr, &addr, CMP_EXACT) &&
  2310. bridge->port == ri->or_port) ||
  2311. (!tor_addr_compare(&bridge->addr, &ri->ipv6_addr, CMP_EXACT) &&
  2312. bridge->port == ri->ipv6_orport)) {
  2313. /* they match, so no need to do anything */
  2314. } else {
  2315. if (tor_addr_family(&bridge->addr) == AF_INET) {
  2316. ri->addr = tor_addr_to_ipv4h(&bridge->addr);
  2317. ri->or_port = bridge->port;
  2318. log_info(LD_DIR,
  2319. "Adjusted bridge routerinfo for '%s' to match configured "
  2320. "address %s:%d.",
  2321. ri->nickname, fmt_addr32(ri->addr), ri->or_port);
  2322. } else if (tor_addr_family(&bridge->addr) == AF_INET6) {
  2323. tor_addr_copy(&ri->ipv6_addr, &bridge->addr);
  2324. ri->ipv6_orport = bridge->port;
  2325. log_info(LD_DIR,
  2326. "Adjusted bridge routerinfo for '%s' to match configured "
  2327. "address %s.",
  2328. ri->nickname, fmt_addrport(&ri->ipv6_addr, ri->ipv6_orport));
  2329. } else {
  2330. log_err(LD_BUG, "Address family not supported: %d.",
  2331. tor_addr_family(&bridge->addr));
  2332. return;
  2333. }
  2334. }
  2335. if (options->ClientPreferIPv6ORPort == -1) {
  2336. /* Mark which address to use based on which bridge_t we got. */
  2337. node->ipv6_preferred = (tor_addr_family(&bridge->addr) == AF_INET6 &&
  2338. !tor_addr_is_null(&node->ri->ipv6_addr));
  2339. } else {
  2340. /* Mark which address to use based on user preference */
  2341. node->ipv6_preferred = (fascist_firewall_prefer_ipv6_orport(options) &&
  2342. !tor_addr_is_null(&node->ri->ipv6_addr));
  2343. }
  2344. /* XXXipv6 we lack support for falling back to another address for
  2345. the same relay, warn the user */
  2346. if (!tor_addr_is_null(&ri->ipv6_addr)) {
  2347. tor_addr_port_t ap;
  2348. node_get_pref_orport(node, &ap);
  2349. log_notice(LD_CONFIG,
  2350. "Bridge '%s' has both an IPv4 and an IPv6 address. "
  2351. "Will prefer using its %s address (%s) based on %s.",
  2352. ri->nickname,
  2353. node->ipv6_preferred ? "IPv6" : "IPv4",
  2354. fmt_addrport(&ap.addr, ap.port),
  2355. options->ClientPreferIPv6ORPort == -1 ?
  2356. "the configured Bridge address" :
  2357. "ClientPreferIPv6ORPort");
  2358. }
  2359. }
  2360. if (node->rs) {
  2361. routerstatus_t *rs = node->rs;
  2362. tor_addr_from_ipv4h(&addr, rs->addr);
  2363. if (!tor_addr_compare(&bridge->addr, &addr, CMP_EXACT) &&
  2364. bridge->port == rs->or_port) {
  2365. /* they match, so no need to do anything */
  2366. } else {
  2367. rs->addr = tor_addr_to_ipv4h(&bridge->addr);
  2368. rs->or_port = bridge->port;
  2369. log_info(LD_DIR,
  2370. "Adjusted bridge routerstatus for '%s' to match "
  2371. "configured address %s.",
  2372. rs->nickname, fmt_addrport(&bridge->addr, rs->or_port));
  2373. }
  2374. }
  2375. }
  2376. /** We just learned a descriptor for a bridge. See if that
  2377. * digest is in our entry guard list, and add it if not. */
  2378. void
  2379. learned_bridge_descriptor(routerinfo_t *ri, int from_cache)
  2380. {
  2381. tor_assert(ri);
  2382. tor_assert(ri->purpose == ROUTER_PURPOSE_BRIDGE);
  2383. if (get_options()->UseBridges) {
  2384. int first = num_bridges_usable() <= 1;
  2385. bridge_info_t *bridge = get_configured_bridge_by_routerinfo(ri);
  2386. time_t now = time(NULL);
  2387. router_set_status(ri->cache_info.identity_digest, 1);
  2388. if (bridge) { /* if we actually want to use this one */
  2389. node_t *node;
  2390. /* it's here; schedule its re-fetch for a long time from now. */
  2391. if (!from_cache)
  2392. download_status_reset(&bridge->fetch_status);
  2393. node = node_get_mutable_by_id(ri->cache_info.identity_digest);
  2394. tor_assert(node);
  2395. rewrite_node_address_for_bridge(bridge, node);
  2396. if (tor_digest_is_zero(bridge->identity)) {
  2397. memcpy(bridge->identity,ri->cache_info.identity_digest, DIGEST_LEN);
  2398. log_notice(LD_DIR, "Learned identity %s for bridge at %s:%d",
  2399. hex_str(bridge->identity, DIGEST_LEN),
  2400. fmt_and_decorate_addr(&bridge->addr),
  2401. (int) bridge->port);
  2402. }
  2403. add_an_entry_guard(get_guard_selection_info(), node, 1, 1, 0, 0);
  2404. log_notice(LD_DIR, "new bridge descriptor '%s' (%s): %s", ri->nickname,
  2405. from_cache ? "cached" : "fresh", router_describe(ri));
  2406. /* set entry->made_contact so if it goes down we don't drop it from
  2407. * our entry node list */
  2408. entry_guard_register_connect_status(ri->cache_info.identity_digest,
  2409. 1, 0, now);
  2410. if (first) {
  2411. routerlist_retry_directory_downloads(now);
  2412. }
  2413. }
  2414. }
  2415. }
  2416. /** Return the number of bridges that have descriptors that
  2417. * are marked with purpose 'bridge' and are running.
  2418. *
  2419. * We use this function to decide if we're ready to start building
  2420. * circuits through our bridges, or if we need to wait until the
  2421. * directory "server/authority" requests finish. */
  2422. int
  2423. any_bridge_descriptors_known(void)
  2424. {
  2425. tor_assert(get_options()->UseBridges);
  2426. return choose_random_entry(NULL) != NULL;
  2427. }
  2428. /** Return the number of bridges that have descriptors that are marked with
  2429. * purpose 'bridge' and are running.
  2430. */
  2431. static int
  2432. num_bridges_usable(void)
  2433. {
  2434. int n_options = 0;
  2435. tor_assert(get_options()->UseBridges);
  2436. (void) choose_random_entry_impl(get_guard_selection_info(),
  2437. NULL, 0, 0, &n_options);
  2438. return n_options;
  2439. }
  2440. /** Return a smartlist containing all bridge identity digests */
  2441. MOCK_IMPL(smartlist_t *,
  2442. list_bridge_identities, (void))
  2443. {
  2444. smartlist_t *result = NULL;
  2445. char *digest_tmp;
  2446. if (get_options()->UseBridges && bridge_list) {
  2447. result = smartlist_new();
  2448. SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, b) {
  2449. digest_tmp = tor_malloc(DIGEST_LEN);
  2450. memcpy(digest_tmp, b->identity, DIGEST_LEN);
  2451. smartlist_add(result, digest_tmp);
  2452. } SMARTLIST_FOREACH_END(b);
  2453. }
  2454. return result;
  2455. }
  2456. /** Get the download status for a bridge descriptor given its identity */
  2457. MOCK_IMPL(download_status_t *,
  2458. get_bridge_dl_status_by_id, (const char *digest))
  2459. {
  2460. download_status_t *dl = NULL;
  2461. if (digest && get_options()->UseBridges && bridge_list) {
  2462. SMARTLIST_FOREACH_BEGIN(bridge_list, bridge_info_t *, b) {
  2463. if (tor_memeq(digest, b->identity, DIGEST_LEN)) {
  2464. dl = &(b->fetch_status);
  2465. break;
  2466. }
  2467. } SMARTLIST_FOREACH_END(b);
  2468. }
  2469. return dl;
  2470. }
  2471. /** Return 1 if we have at least one descriptor for an entry guard
  2472. * (bridge or member of EntryNodes) and all descriptors we know are
  2473. * down. Else return 0. If <b>act</b> is 1, then mark the down guards
  2474. * up; else just observe and report. */
  2475. static int
  2476. entries_retry_helper(const or_options_t *options, int act)
  2477. {
  2478. const node_t *node;
  2479. int any_known = 0;
  2480. int any_running = 0;
  2481. int need_bridges = options->UseBridges != 0;
  2482. guard_selection_t *gs = get_guard_selection_info();
  2483. tor_assert(gs != NULL);
  2484. tor_assert(gs->chosen_entry_guards != NULL);
  2485. SMARTLIST_FOREACH_BEGIN(gs->chosen_entry_guards, entry_guard_t *, e) {
  2486. node = node_get_by_id(e->identity);
  2487. if (node && node_has_descriptor(node) &&
  2488. node_is_bridge(node) == need_bridges &&
  2489. (!need_bridges || (!e->bad_since &&
  2490. node_is_a_configured_bridge(node)))) {
  2491. any_known = 1;
  2492. if (node->is_running)
  2493. any_running = 1; /* some entry is both known and running */
  2494. else if (act) {
  2495. /* Mark all current connections to this OR as unhealthy, since
  2496. * otherwise there could be one that started 30 seconds
  2497. * ago, and in 30 seconds it will time out, causing us to mark
  2498. * the node down and undermine the retry attempt. We mark even
  2499. * the established conns, since if the network just came back
  2500. * we'll want to attach circuits to fresh conns. */
  2501. connection_or_set_bad_connections(node->identity, 1);
  2502. /* mark this entry node for retry */
  2503. router_set_status(node->identity, 1);
  2504. e->can_retry = 1;
  2505. e->bad_since = 0;
  2506. }
  2507. }
  2508. } SMARTLIST_FOREACH_END(e);
  2509. log_debug(LD_DIR, "%d: any_known %d, any_running %d",
  2510. act, any_known, any_running);
  2511. return any_known && !any_running;
  2512. }
  2513. /** Do we know any descriptors for our bridges / entrynodes, and are
  2514. * all the ones we have descriptors for down? */
  2515. int
  2516. entries_known_but_down(const or_options_t *options)
  2517. {
  2518. tor_assert(entry_list_is_constrained(options));
  2519. return entries_retry_helper(options, 0);
  2520. }
  2521. /** Mark all down known bridges / entrynodes up. */
  2522. void
  2523. entries_retry_all(const or_options_t *options)
  2524. {
  2525. tor_assert(entry_list_is_constrained(options));
  2526. entries_retry_helper(options, 1);
  2527. }
  2528. /** Free one guard selection context */
  2529. static void
  2530. guard_selection_free(guard_selection_t *gs)
  2531. {
  2532. if (!gs) return;
  2533. if (gs->chosen_entry_guards) {
  2534. SMARTLIST_FOREACH(gs->chosen_entry_guards, entry_guard_t *, e,
  2535. entry_guard_free(e));
  2536. smartlist_free(gs->chosen_entry_guards);
  2537. gs->chosen_entry_guards = NULL;
  2538. }
  2539. tor_free(gs);
  2540. }
  2541. /** Release all storage held by the list of entry guards and related
  2542. * memory structs. */
  2543. void
  2544. entry_guards_free_all(void)
  2545. {
  2546. /* Null out the default */
  2547. curr_guard_context = NULL;
  2548. /* Free all the guard contexts */
  2549. if (guard_contexts != NULL) {
  2550. SMARTLIST_FOREACH_BEGIN(guard_contexts, guard_selection_t *, gs) {
  2551. guard_selection_free(gs);
  2552. } SMARTLIST_FOREACH_END(gs);
  2553. smartlist_free(guard_contexts);
  2554. guard_contexts = NULL;
  2555. }
  2556. clear_bridge_list();
  2557. smartlist_free(bridge_list);
  2558. bridge_list = NULL;
  2559. circuit_build_times_free_timeouts(get_circuit_build_times_mutable());
  2560. }