entrynodes.c 98 KB

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