entrynodes.c 81 KB

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