entrynodes.c 98 KB

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