entrynodes.c 83 KB

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