entrynodes.c 80 KB

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