entrynodes.c 88 KB

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