entrynodes.c 81 KB

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