entrynodes.c 88 KB

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