entrynodes.c 108 KB

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