entrynodes.c 82 KB

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