entrynodes.c 88 KB

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