entrynodes.c 76 KB

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