entrynodes.c 86 KB

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