entrynodes.c 85 KB

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