entrynodes.c 81 KB

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