entrynodes.c 98 KB

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