entrynodes.c 98 KB

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