entrynodes.c 81 KB

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