entrynodes.c 72 KB

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