networkstatus.c 83 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331
  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 networkstatus.c
  8. * \brief Functions and structures for handling network status documents as a
  9. * client or cache.
  10. */
  11. #define NETWORKSTATUS_PRIVATE
  12. #include "or.h"
  13. #include "channel.h"
  14. #include "circuitmux.h"
  15. #include "circuitmux_ewma.h"
  16. #include "circuitstats.h"
  17. #include "config.h"
  18. #include "connection.h"
  19. #include "connection_or.h"
  20. #include "control.h"
  21. #include "directory.h"
  22. #include "dirserv.h"
  23. #include "dirvote.h"
  24. #include "entrynodes.h"
  25. #include "main.h"
  26. #include "microdesc.h"
  27. #include "networkstatus.h"
  28. #include "nodelist.h"
  29. #include "relay.h"
  30. #include "router.h"
  31. #include "routerlist.h"
  32. #include "routerparse.h"
  33. #include "transports.h"
  34. /** Map from lowercase nickname to identity digest of named server, if any. */
  35. static strmap_t *named_server_map = NULL;
  36. /** Map from lowercase nickname to (void*)1 for all names that are listed
  37. * as unnamed for some server in the consensus. */
  38. static strmap_t *unnamed_server_map = NULL;
  39. /** Most recently received and validated v3 consensus network status,
  40. * of whichever type we are using for our own circuits. This will be the same
  41. * as one of current_ns_consensus or current_md_consensus.
  42. */
  43. #define current_consensus \
  44. (we_use_microdescriptors_for_circuits(get_options()) ? \
  45. current_md_consensus : current_ns_consensus)
  46. /** Most recently received and validated v3 "ns"-flavored consensus network
  47. * status. */
  48. static networkstatus_t *current_ns_consensus = NULL;
  49. /** Most recently received and validated v3 "microdec"-flavored consensus
  50. * network status. */
  51. static networkstatus_t *current_md_consensus = NULL;
  52. /** A v3 consensus networkstatus that we've received, but which we don't
  53. * have enough certificates to be happy about. */
  54. typedef struct consensus_waiting_for_certs_t {
  55. /** The consensus itself. */
  56. networkstatus_t *consensus;
  57. /** The encoded version of the consensus, nul-terminated. */
  58. char *body;
  59. /** When did we set the current value of consensus_waiting_for_certs? If
  60. * this is too recent, we shouldn't try to fetch a new consensus for a
  61. * little while, to give ourselves time to get certificates for this one. */
  62. time_t set_at;
  63. /** Set to 1 if we've been holding on to it for so long we should maybe
  64. * treat it as being bad. */
  65. int dl_failed;
  66. } consensus_waiting_for_certs_t;
  67. /** An array, for each flavor of consensus we might want, of consensuses that
  68. * we have downloaded, but which we cannot verify due to having insufficient
  69. * authority certificates. */
  70. static consensus_waiting_for_certs_t
  71. consensus_waiting_for_certs[N_CONSENSUS_FLAVORS];
  72. /** A time before which we shouldn't try to replace the current consensus:
  73. * this will be at some point after the next consensus becomes valid, but
  74. * before the current consensus becomes invalid. */
  75. static time_t time_to_download_next_consensus[N_CONSENSUS_FLAVORS];
  76. /** Download status for the current consensus networkstatus. */
  77. static download_status_t consensus_dl_status[N_CONSENSUS_FLAVORS] =
  78. {
  79. { 0, 0, 0, DL_SCHED_CONSENSUS, DL_WANT_ANY_DIRSERVER,
  80. DL_SCHED_INCREMENT_FAILURE },
  81. { 0, 0, 0, DL_SCHED_CONSENSUS, DL_WANT_ANY_DIRSERVER,
  82. DL_SCHED_INCREMENT_FAILURE },
  83. };
  84. #define N_CONSENSUS_BOOTSTRAP_SCHEDULES 2
  85. #define CONSENSUS_BOOTSTRAP_SOURCE_AUTHORITY 0
  86. #define CONSENSUS_BOOTSTRAP_SOURCE_ANY_DIRSERVER 1
  87. /* Using DL_SCHED_INCREMENT_ATTEMPT on these schedules means that
  88. * download_status_increment_failure won't increment these entries.
  89. * However, any bootstrap connection failures that occur after we have
  90. * a valid consensus will count against the failure counts on the non-bootstrap
  91. * schedules. There should only be one of these, as all the others will have
  92. * been cancelled. (This doesn't seem to be a significant issue.) */
  93. static download_status_t
  94. consensus_bootstrap_dl_status[N_CONSENSUS_BOOTSTRAP_SCHEDULES] =
  95. {
  96. { 0, 0, 0, DL_SCHED_CONSENSUS, DL_WANT_AUTHORITY,
  97. DL_SCHED_INCREMENT_ATTEMPT },
  98. /* During bootstrap, DL_WANT_ANY_DIRSERVER means "use fallbacks". */
  99. { 0, 0, 0, DL_SCHED_CONSENSUS, DL_WANT_ANY_DIRSERVER,
  100. DL_SCHED_INCREMENT_ATTEMPT },
  101. };
  102. /** True iff we have logged a warning about this OR's version being older than
  103. * listed by the authorities. */
  104. static int have_warned_about_old_version = 0;
  105. /** True iff we have logged a warning about this OR's version being newer than
  106. * listed by the authorities. */
  107. static int have_warned_about_new_version = 0;
  108. static void routerstatus_list_update_named_server_map(void);
  109. static void update_consensus_bootstrap_multiple_downloads(
  110. time_t now,
  111. const or_options_t *options,
  112. int we_are_bootstrapping);
  113. /** Forget that we've warned about anything networkstatus-related, so we will
  114. * give fresh warnings if the same behavior happens again. */
  115. void
  116. networkstatus_reset_warnings(void)
  117. {
  118. if (current_consensus) {
  119. SMARTLIST_FOREACH(nodelist_get_list(), node_t *, node,
  120. node->name_lookup_warned = 0);
  121. }
  122. have_warned_about_old_version = 0;
  123. have_warned_about_new_version = 0;
  124. }
  125. /** Reset the descriptor download failure count on all networkstatus docs, so
  126. * that we can retry any long-failed documents immediately.
  127. */
  128. void
  129. networkstatus_reset_download_failures(void)
  130. {
  131. int i;
  132. for (i=0; i < N_CONSENSUS_FLAVORS; ++i)
  133. download_status_reset(&consensus_dl_status[i]);
  134. for (i=0; i < N_CONSENSUS_BOOTSTRAP_SCHEDULES; ++i)
  135. download_status_reset(&consensus_bootstrap_dl_status[i]);
  136. }
  137. /** Read every cached v3 consensus networkstatus from the disk. */
  138. int
  139. router_reload_consensus_networkstatus(void)
  140. {
  141. char *filename;
  142. char *s;
  143. const unsigned int flags = NSSET_FROM_CACHE | NSSET_DONT_DOWNLOAD_CERTS;
  144. int flav;
  145. /* FFFF Suppress warnings if cached consensus is bad? */
  146. for (flav = 0; flav < N_CONSENSUS_FLAVORS; ++flav) {
  147. char buf[128];
  148. const char *flavor = networkstatus_get_flavor_name(flav);
  149. if (flav == FLAV_NS) {
  150. filename = get_datadir_fname("cached-consensus");
  151. } else {
  152. tor_snprintf(buf, sizeof(buf), "cached-%s-consensus", flavor);
  153. filename = get_datadir_fname(buf);
  154. }
  155. s = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
  156. if (s) {
  157. if (networkstatus_set_current_consensus(s, flavor, flags, NULL) < -1) {
  158. log_warn(LD_FS, "Couldn't load consensus %s networkstatus from \"%s\"",
  159. flavor, filename);
  160. }
  161. tor_free(s);
  162. }
  163. tor_free(filename);
  164. if (flav == FLAV_NS) {
  165. filename = get_datadir_fname("unverified-consensus");
  166. } else {
  167. tor_snprintf(buf, sizeof(buf), "unverified-%s-consensus", flavor);
  168. filename = get_datadir_fname(buf);
  169. }
  170. s = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
  171. if (s) {
  172. if (networkstatus_set_current_consensus(s, flavor,
  173. flags|NSSET_WAS_WAITING_FOR_CERTS,
  174. NULL)) {
  175. log_info(LD_FS, "Couldn't load consensus %s networkstatus from \"%s\"",
  176. flavor, filename);
  177. }
  178. tor_free(s);
  179. }
  180. tor_free(filename);
  181. }
  182. if (!current_consensus) {
  183. if (!named_server_map)
  184. named_server_map = strmap_new();
  185. if (!unnamed_server_map)
  186. unnamed_server_map = strmap_new();
  187. }
  188. update_certificate_downloads(time(NULL));
  189. routers_update_all_from_networkstatus(time(NULL), 3);
  190. update_microdescs_from_networkstatus(time(NULL));
  191. return 0;
  192. }
  193. /** Free all storage held by the vote_routerstatus object <b>rs</b>. */
  194. STATIC void
  195. vote_routerstatus_free(vote_routerstatus_t *rs)
  196. {
  197. vote_microdesc_hash_t *h, *next;
  198. if (!rs)
  199. return;
  200. tor_free(rs->version);
  201. tor_free(rs->status.exitsummary);
  202. for (h = rs->microdesc; h; h = next) {
  203. tor_free(h->microdesc_hash_line);
  204. next = h->next;
  205. tor_free(h);
  206. }
  207. tor_free(rs);
  208. }
  209. /** Free all storage held by the routerstatus object <b>rs</b>. */
  210. void
  211. routerstatus_free(routerstatus_t *rs)
  212. {
  213. if (!rs)
  214. return;
  215. tor_free(rs->exitsummary);
  216. tor_free(rs);
  217. }
  218. /** Free all storage held in <b>sig</b> */
  219. void
  220. document_signature_free(document_signature_t *sig)
  221. {
  222. tor_free(sig->signature);
  223. tor_free(sig);
  224. }
  225. /** Return a newly allocated copy of <b>sig</b> */
  226. document_signature_t *
  227. document_signature_dup(const document_signature_t *sig)
  228. {
  229. document_signature_t *r = tor_memdup(sig, sizeof(document_signature_t));
  230. if (r->signature)
  231. r->signature = tor_memdup(sig->signature, sig->signature_len);
  232. return r;
  233. }
  234. /** Free all storage held in <b>ns</b>. */
  235. void
  236. networkstatus_vote_free(networkstatus_t *ns)
  237. {
  238. if (!ns)
  239. return;
  240. tor_free(ns->client_versions);
  241. tor_free(ns->server_versions);
  242. if (ns->known_flags) {
  243. SMARTLIST_FOREACH(ns->known_flags, char *, c, tor_free(c));
  244. smartlist_free(ns->known_flags);
  245. }
  246. if (ns->weight_params) {
  247. SMARTLIST_FOREACH(ns->weight_params, char *, c, tor_free(c));
  248. smartlist_free(ns->weight_params);
  249. }
  250. if (ns->net_params) {
  251. SMARTLIST_FOREACH(ns->net_params, char *, c, tor_free(c));
  252. smartlist_free(ns->net_params);
  253. }
  254. if (ns->supported_methods) {
  255. SMARTLIST_FOREACH(ns->supported_methods, char *, c, tor_free(c));
  256. smartlist_free(ns->supported_methods);
  257. }
  258. if (ns->package_lines) {
  259. SMARTLIST_FOREACH(ns->package_lines, char *, c, tor_free(c));
  260. smartlist_free(ns->package_lines);
  261. }
  262. if (ns->voters) {
  263. SMARTLIST_FOREACH_BEGIN(ns->voters, networkstatus_voter_info_t *, voter) {
  264. tor_free(voter->nickname);
  265. tor_free(voter->address);
  266. tor_free(voter->contact);
  267. if (voter->sigs) {
  268. SMARTLIST_FOREACH(voter->sigs, document_signature_t *, sig,
  269. document_signature_free(sig));
  270. smartlist_free(voter->sigs);
  271. }
  272. tor_free(voter);
  273. } SMARTLIST_FOREACH_END(voter);
  274. smartlist_free(ns->voters);
  275. }
  276. authority_cert_free(ns->cert);
  277. if (ns->routerstatus_list) {
  278. if (ns->type == NS_TYPE_VOTE || ns->type == NS_TYPE_OPINION) {
  279. SMARTLIST_FOREACH(ns->routerstatus_list, vote_routerstatus_t *, rs,
  280. vote_routerstatus_free(rs));
  281. } else {
  282. SMARTLIST_FOREACH(ns->routerstatus_list, routerstatus_t *, rs,
  283. routerstatus_free(rs));
  284. }
  285. smartlist_free(ns->routerstatus_list);
  286. }
  287. digestmap_free(ns->desc_digest_map, NULL);
  288. memwipe(ns, 11, sizeof(*ns));
  289. tor_free(ns);
  290. }
  291. /** Return the voter info from <b>vote</b> for the voter whose identity digest
  292. * is <b>identity</b>, or NULL if no such voter is associated with
  293. * <b>vote</b>. */
  294. networkstatus_voter_info_t *
  295. networkstatus_get_voter_by_id(networkstatus_t *vote,
  296. const char *identity)
  297. {
  298. if (!vote || !vote->voters)
  299. return NULL;
  300. SMARTLIST_FOREACH(vote->voters, networkstatus_voter_info_t *, voter,
  301. if (fast_memeq(voter->identity_digest, identity, DIGEST_LEN))
  302. return voter);
  303. return NULL;
  304. }
  305. /** Check whether the signature <b>sig</b> is correctly signed with the
  306. * signing key in <b>cert</b>. Return -1 if <b>cert</b> doesn't match the
  307. * signing key; otherwise set the good_signature or bad_signature flag on
  308. * <b>voter</b>, and return 0. */
  309. int
  310. networkstatus_check_document_signature(const networkstatus_t *consensus,
  311. document_signature_t *sig,
  312. const authority_cert_t *cert)
  313. {
  314. char key_digest[DIGEST_LEN];
  315. const int dlen = sig->alg == DIGEST_SHA1 ? DIGEST_LEN : DIGEST256_LEN;
  316. char *signed_digest;
  317. size_t signed_digest_len;
  318. if (crypto_pk_get_digest(cert->signing_key, key_digest)<0)
  319. return -1;
  320. if (tor_memneq(sig->signing_key_digest, key_digest, DIGEST_LEN) ||
  321. tor_memneq(sig->identity_digest, cert->cache_info.identity_digest,
  322. DIGEST_LEN))
  323. return -1;
  324. if (authority_cert_is_blacklisted(cert)) {
  325. /* We implement blacklisting for authority signing keys by treating
  326. * all their signatures as always bad. That way we don't get into
  327. * crazy loops of dropping and re-fetching signatures. */
  328. log_warn(LD_DIR, "Ignoring a consensus signature made with deprecated"
  329. " signing key %s",
  330. hex_str(cert->signing_key_digest, DIGEST_LEN));
  331. sig->bad_signature = 1;
  332. return 0;
  333. }
  334. signed_digest_len = crypto_pk_keysize(cert->signing_key);
  335. signed_digest = tor_malloc(signed_digest_len);
  336. if (crypto_pk_public_checksig(cert->signing_key,
  337. signed_digest,
  338. signed_digest_len,
  339. sig->signature,
  340. sig->signature_len) < dlen ||
  341. tor_memneq(signed_digest, consensus->digests.d[sig->alg], dlen)) {
  342. log_warn(LD_DIR, "Got a bad signature on a networkstatus vote");
  343. sig->bad_signature = 1;
  344. } else {
  345. sig->good_signature = 1;
  346. }
  347. tor_free(signed_digest);
  348. return 0;
  349. }
  350. /** Given a v3 networkstatus consensus in <b>consensus</b>, check every
  351. * as-yet-unchecked signature on <b>consensus</b>. Return 1 if there is a
  352. * signature from every recognized authority on it, 0 if there are
  353. * enough good signatures from recognized authorities on it, -1 if we might
  354. * get enough good signatures by fetching missing certificates, and -2
  355. * otherwise. Log messages at INFO or WARN: if <b>warn</b> is over 1, warn
  356. * about every problem; if warn is at least 1, warn only if we can't get
  357. * enough signatures; if warn is negative, log nothing at all. */
  358. int
  359. networkstatus_check_consensus_signature(networkstatus_t *consensus,
  360. int warn)
  361. {
  362. int n_good = 0;
  363. int n_missing_key = 0, n_dl_failed_key = 0;
  364. int n_bad = 0;
  365. int n_unknown = 0;
  366. int n_no_signature = 0;
  367. int n_v3_authorities = get_n_authorities(V3_DIRINFO);
  368. int n_required = n_v3_authorities/2 + 1;
  369. smartlist_t *list_good = smartlist_new();
  370. smartlist_t *list_no_signature = smartlist_new();
  371. smartlist_t *need_certs_from = smartlist_new();
  372. smartlist_t *unrecognized = smartlist_new();
  373. smartlist_t *missing_authorities = smartlist_new();
  374. int severity;
  375. time_t now = time(NULL);
  376. tor_assert(consensus->type == NS_TYPE_CONSENSUS);
  377. SMARTLIST_FOREACH_BEGIN(consensus->voters, networkstatus_voter_info_t *,
  378. voter) {
  379. int good_here = 0;
  380. int bad_here = 0;
  381. int unknown_here = 0;
  382. int missing_key_here = 0, dl_failed_key_here = 0;
  383. SMARTLIST_FOREACH_BEGIN(voter->sigs, document_signature_t *, sig) {
  384. if (!sig->good_signature && !sig->bad_signature &&
  385. sig->signature) {
  386. /* we can try to check the signature. */
  387. int is_v3_auth = trusteddirserver_get_by_v3_auth_digest(
  388. sig->identity_digest) != NULL;
  389. authority_cert_t *cert =
  390. authority_cert_get_by_digests(sig->identity_digest,
  391. sig->signing_key_digest);
  392. tor_assert(tor_memeq(sig->identity_digest, voter->identity_digest,
  393. DIGEST_LEN));
  394. if (!is_v3_auth) {
  395. smartlist_add(unrecognized, voter);
  396. ++unknown_here;
  397. continue;
  398. } else if (!cert || cert->expires < now) {
  399. smartlist_add(need_certs_from, voter);
  400. ++missing_key_here;
  401. if (authority_cert_dl_looks_uncertain(sig->identity_digest))
  402. ++dl_failed_key_here;
  403. continue;
  404. }
  405. if (networkstatus_check_document_signature(consensus, sig, cert) < 0) {
  406. smartlist_add(need_certs_from, voter);
  407. ++missing_key_here;
  408. if (authority_cert_dl_looks_uncertain(sig->identity_digest))
  409. ++dl_failed_key_here;
  410. continue;
  411. }
  412. }
  413. if (sig->good_signature)
  414. ++good_here;
  415. else if (sig->bad_signature)
  416. ++bad_here;
  417. } SMARTLIST_FOREACH_END(sig);
  418. if (good_here) {
  419. ++n_good;
  420. smartlist_add(list_good, voter->nickname);
  421. } else if (bad_here) {
  422. ++n_bad;
  423. } else if (missing_key_here) {
  424. ++n_missing_key;
  425. if (dl_failed_key_here)
  426. ++n_dl_failed_key;
  427. } else if (unknown_here) {
  428. ++n_unknown;
  429. } else {
  430. ++n_no_signature;
  431. smartlist_add(list_no_signature, voter->nickname);
  432. }
  433. } SMARTLIST_FOREACH_END(voter);
  434. /* Now see whether we're missing any voters entirely. */
  435. SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
  436. dir_server_t *, ds,
  437. {
  438. if ((ds->type & V3_DIRINFO) &&
  439. !networkstatus_get_voter_by_id(consensus, ds->v3_identity_digest))
  440. smartlist_add(missing_authorities, ds);
  441. });
  442. if (warn > 1 || (warn >= 0 &&
  443. (n_good + n_missing_key - n_dl_failed_key < n_required))) {
  444. severity = LOG_WARN;
  445. } else {
  446. severity = LOG_INFO;
  447. }
  448. if (warn >= 0) {
  449. SMARTLIST_FOREACH(unrecognized, networkstatus_voter_info_t *, voter,
  450. {
  451. tor_log(severity, LD_DIR, "Consensus includes unrecognized authority "
  452. "'%s' at %s:%d (contact %s; identity %s)",
  453. voter->nickname, voter->address, (int)voter->dir_port,
  454. voter->contact?voter->contact:"n/a",
  455. hex_str(voter->identity_digest, DIGEST_LEN));
  456. });
  457. SMARTLIST_FOREACH(need_certs_from, networkstatus_voter_info_t *, voter,
  458. {
  459. tor_log(severity, LD_DIR, "Looks like we need to download a new "
  460. "certificate from authority '%s' at %s:%d (contact %s; "
  461. "identity %s)",
  462. voter->nickname, voter->address, (int)voter->dir_port,
  463. voter->contact?voter->contact:"n/a",
  464. hex_str(voter->identity_digest, DIGEST_LEN));
  465. });
  466. SMARTLIST_FOREACH(missing_authorities, dir_server_t *, ds,
  467. {
  468. tor_log(severity, LD_DIR, "Consensus does not include configured "
  469. "authority '%s' at %s:%d (identity %s)",
  470. ds->nickname, ds->address, (int)ds->dir_port,
  471. hex_str(ds->v3_identity_digest, DIGEST_LEN));
  472. });
  473. {
  474. char *joined;
  475. smartlist_t *sl = smartlist_new();
  476. char *tmp = smartlist_join_strings(list_good, " ", 0, NULL);
  477. smartlist_add_asprintf(sl,
  478. "A consensus needs %d good signatures from recognized "
  479. "authorities for us to accept it. This one has %d (%s).",
  480. n_required, n_good, tmp);
  481. tor_free(tmp);
  482. if (n_no_signature) {
  483. tmp = smartlist_join_strings(list_no_signature, " ", 0, NULL);
  484. smartlist_add_asprintf(sl,
  485. "%d (%s) of the authorities we know didn't sign it.",
  486. n_no_signature, tmp);
  487. tor_free(tmp);
  488. }
  489. if (n_unknown) {
  490. smartlist_add_asprintf(sl,
  491. "It has %d signatures from authorities we don't "
  492. "recognize.", n_unknown);
  493. }
  494. if (n_bad) {
  495. smartlist_add_asprintf(sl, "%d of the signatures on it didn't verify "
  496. "correctly.", n_bad);
  497. }
  498. if (n_missing_key) {
  499. smartlist_add_asprintf(sl,
  500. "We were unable to check %d of the signatures, "
  501. "because we were missing the keys.", n_missing_key);
  502. }
  503. joined = smartlist_join_strings(sl, " ", 0, NULL);
  504. tor_log(severity, LD_DIR, "%s", joined);
  505. tor_free(joined);
  506. SMARTLIST_FOREACH(sl, char *, c, tor_free(c));
  507. smartlist_free(sl);
  508. }
  509. }
  510. smartlist_free(list_good);
  511. smartlist_free(list_no_signature);
  512. smartlist_free(unrecognized);
  513. smartlist_free(need_certs_from);
  514. smartlist_free(missing_authorities);
  515. if (n_good == n_v3_authorities)
  516. return 1;
  517. else if (n_good >= n_required)
  518. return 0;
  519. else if (n_good + n_missing_key >= n_required)
  520. return -1;
  521. else
  522. return -2;
  523. }
  524. /** How far in the future do we allow a network-status to get before removing
  525. * it? (seconds) */
  526. #define NETWORKSTATUS_ALLOW_SKEW (24*60*60)
  527. /** Helper for bsearching a list of routerstatus_t pointers: compare a
  528. * digest in the key to the identity digest of a routerstatus_t. */
  529. int
  530. compare_digest_to_routerstatus_entry(const void *_key, const void **_member)
  531. {
  532. const char *key = _key;
  533. const routerstatus_t *rs = *_member;
  534. return tor_memcmp(key, rs->identity_digest, DIGEST_LEN);
  535. }
  536. /** Helper for bsearching a list of routerstatus_t pointers: compare a
  537. * digest in the key to the identity digest of a routerstatus_t. */
  538. int
  539. compare_digest_to_vote_routerstatus_entry(const void *_key,
  540. const void **_member)
  541. {
  542. const char *key = _key;
  543. const vote_routerstatus_t *vrs = *_member;
  544. return tor_memcmp(key, vrs->status.identity_digest, DIGEST_LEN);
  545. }
  546. /** As networkstatus_find_entry, but do not return a const pointer */
  547. routerstatus_t *
  548. networkstatus_vote_find_mutable_entry(networkstatus_t *ns, const char *digest)
  549. {
  550. return smartlist_bsearch(ns->routerstatus_list, digest,
  551. compare_digest_to_routerstatus_entry);
  552. }
  553. /** Return the entry in <b>ns</b> for the identity digest <b>digest</b>, or
  554. * NULL if none was found. */
  555. const routerstatus_t *
  556. networkstatus_vote_find_entry(networkstatus_t *ns, const char *digest)
  557. {
  558. return networkstatus_vote_find_mutable_entry(ns, digest);
  559. }
  560. /*XXXX MOVE make this static once functions are moved into this file. */
  561. /** Search the routerstatuses in <b>ns</b> for one whose identity digest is
  562. * <b>digest</b>. Return value and set *<b>found_out</b> as for
  563. * smartlist_bsearch_idx(). */
  564. int
  565. networkstatus_vote_find_entry_idx(networkstatus_t *ns,
  566. const char *digest, int *found_out)
  567. {
  568. return smartlist_bsearch_idx(ns->routerstatus_list, digest,
  569. compare_digest_to_routerstatus_entry,
  570. found_out);
  571. }
  572. /** As router_get_consensus_status_by_descriptor_digest, but does not return
  573. * a const pointer. */
  574. MOCK_IMPL(routerstatus_t *,
  575. router_get_mutable_consensus_status_by_descriptor_digest,(
  576. networkstatus_t *consensus,
  577. const char *digest))
  578. {
  579. if (!consensus)
  580. consensus = current_consensus;
  581. if (!consensus)
  582. return NULL;
  583. if (!consensus->desc_digest_map) {
  584. digestmap_t *m = consensus->desc_digest_map = digestmap_new();
  585. SMARTLIST_FOREACH(consensus->routerstatus_list,
  586. routerstatus_t *, rs,
  587. {
  588. digestmap_set(m, rs->descriptor_digest, rs);
  589. });
  590. }
  591. return digestmap_get(consensus->desc_digest_map, digest);
  592. }
  593. /** Return the consensus view of the status of the router whose current
  594. * <i>descriptor</i> digest in <b>consensus</b> is <b>digest</b>, or NULL if
  595. * no such router is known. */
  596. const routerstatus_t *
  597. router_get_consensus_status_by_descriptor_digest(networkstatus_t *consensus,
  598. const char *digest)
  599. {
  600. return router_get_mutable_consensus_status_by_descriptor_digest(
  601. consensus, digest);
  602. }
  603. /** Given the digest of a router descriptor, return its current download
  604. * status, or NULL if the digest is unrecognized. */
  605. MOCK_IMPL(download_status_t *,
  606. router_get_dl_status_by_descriptor_digest,(const char *d))
  607. {
  608. routerstatus_t *rs;
  609. if (!current_ns_consensus)
  610. return NULL;
  611. if ((rs = router_get_mutable_consensus_status_by_descriptor_digest(
  612. current_ns_consensus, d)))
  613. return &rs->dl_status;
  614. return NULL;
  615. }
  616. /** As router_get_consensus_status_by_id, but do not return a const pointer */
  617. routerstatus_t *
  618. router_get_mutable_consensus_status_by_id(const char *digest)
  619. {
  620. if (!current_consensus)
  621. return NULL;
  622. return smartlist_bsearch(current_consensus->routerstatus_list, digest,
  623. compare_digest_to_routerstatus_entry);
  624. }
  625. /** Return the consensus view of the status of the router whose identity
  626. * digest is <b>digest</b>, or NULL if we don't know about any such router. */
  627. const routerstatus_t *
  628. router_get_consensus_status_by_id(const char *digest)
  629. {
  630. return router_get_mutable_consensus_status_by_id(digest);
  631. }
  632. /** Given a nickname (possibly verbose, possibly a hexadecimal digest), return
  633. * the corresponding routerstatus_t, or NULL if none exists. Warn the
  634. * user if <b>warn_if_unnamed</b> is set, and they have specified a router by
  635. * nickname, but the Named flag isn't set for that router. */
  636. const routerstatus_t *
  637. router_get_consensus_status_by_nickname(const char *nickname,
  638. int warn_if_unnamed)
  639. {
  640. const node_t *node = node_get_by_nickname(nickname, warn_if_unnamed);
  641. if (node)
  642. return node->rs;
  643. else
  644. return NULL;
  645. }
  646. /** Return the identity digest that's mapped to officially by
  647. * <b>nickname</b>. */
  648. const char *
  649. networkstatus_get_router_digest_by_nickname(const char *nickname)
  650. {
  651. if (!named_server_map)
  652. return NULL;
  653. return strmap_get_lc(named_server_map, nickname);
  654. }
  655. /** Return true iff <b>nickname</b> is disallowed from being the nickname
  656. * of any server. */
  657. int
  658. networkstatus_nickname_is_unnamed(const char *nickname)
  659. {
  660. if (!unnamed_server_map)
  661. return 0;
  662. return strmap_get_lc(unnamed_server_map, nickname) != NULL;
  663. }
  664. /** How frequently do directory authorities re-download fresh networkstatus
  665. * documents? */
  666. #define AUTHORITY_NS_CACHE_INTERVAL (10*60)
  667. /** How frequently do non-authority directory caches re-download fresh
  668. * networkstatus documents? */
  669. #define NONAUTHORITY_NS_CACHE_INTERVAL (60*60)
  670. /** Return true iff, given the options listed in <b>options</b>, <b>flavor</b>
  671. * is the flavor of a consensus networkstatus that we would like to fetch. */
  672. static int
  673. we_want_to_fetch_flavor(const or_options_t *options, int flavor)
  674. {
  675. if (flavor < 0 || flavor > N_CONSENSUS_FLAVORS) {
  676. /* This flavor is crazy; we don't want it */
  677. /*XXXX handle unrecognized flavors later */
  678. return 0;
  679. }
  680. if (authdir_mode_v3(options) || directory_caches_dir_info(options)) {
  681. /* We want to serve all flavors to others, regardless if we would use
  682. * it ourselves. */
  683. return 1;
  684. }
  685. if (options->FetchUselessDescriptors) {
  686. /* In order to get all descriptors, we need to fetch all consensuses. */
  687. return 1;
  688. }
  689. /* Otherwise, we want the flavor only if we want to use it to build
  690. * circuits. */
  691. return flavor == usable_consensus_flavor();
  692. }
  693. /** How long will we hang onto a possibly live consensus for which we're
  694. * fetching certs before we check whether there is a better one? */
  695. #define DELAY_WHILE_FETCHING_CERTS (20*60)
  696. /* Check if a downloaded consensus flavor should still wait for certificates
  697. * to download now.
  698. * If so, return 1. If not, fail dls and return 0. */
  699. static int
  700. check_consensus_waiting_for_certs(int flavor, time_t now,
  701. download_status_t *dls)
  702. {
  703. consensus_waiting_for_certs_t *waiting;
  704. /* We should always have a known flavor, because we_want_to_fetch_flavor()
  705. * filters out unknown flavors. */
  706. tor_assert(flavor >= 0 && flavor < N_CONSENSUS_FLAVORS);
  707. waiting = &consensus_waiting_for_certs[flavor];
  708. if (waiting->consensus) {
  709. /* XXXX make sure this doesn't delay sane downloads. */
  710. if (waiting->set_at + DELAY_WHILE_FETCHING_CERTS > now) {
  711. return 1;
  712. } else {
  713. if (!waiting->dl_failed) {
  714. download_status_failed(dls, 0);
  715. waiting->dl_failed=1;
  716. }
  717. }
  718. }
  719. return 0;
  720. }
  721. /* Return the maximum download tries for a consensus, based on options and
  722. * whether we_are_bootstrapping. */
  723. static int
  724. consensus_max_download_tries(const or_options_t *options,
  725. int we_are_bootstrapping)
  726. {
  727. int use_fallbacks = networkstatus_consensus_can_use_extra_fallbacks(options);
  728. if (we_are_bootstrapping) {
  729. if (use_fallbacks) {
  730. return options->ClientBootstrapConsensusMaxDownloadTries;
  731. } else {
  732. return
  733. options->ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries;
  734. }
  735. }
  736. return options->TestingConsensusMaxDownloadTries;
  737. }
  738. /** If we want to download a fresh consensus, launch a new download as
  739. * appropriate. */
  740. static void
  741. update_consensus_networkstatus_downloads(time_t now)
  742. {
  743. int i;
  744. const or_options_t *options = get_options();
  745. const int we_are_bootstrapping = networkstatus_consensus_is_boostrapping(
  746. now);
  747. const int use_multi_conn =
  748. networkstatus_consensus_can_use_multiple_directories(options);
  749. if (should_delay_dir_fetches(options, NULL))
  750. return;
  751. for (i=0; i < N_CONSENSUS_FLAVORS; ++i) {
  752. /* XXXX need some way to download unknown flavors if we are caching. */
  753. const char *resource;
  754. networkstatus_t *c;
  755. int max_in_progress_conns = 1;
  756. if (! we_want_to_fetch_flavor(options, i))
  757. continue;
  758. c = networkstatus_get_latest_consensus_by_flavor(i);
  759. if (! (c && c->valid_after <= now && now <= c->valid_until)) {
  760. /* No live consensus? Get one now!*/
  761. time_to_download_next_consensus[i] = now;
  762. }
  763. if (time_to_download_next_consensus[i] > now)
  764. continue; /* Wait until the current consensus is older. */
  765. resource = networkstatus_get_flavor_name(i);
  766. /* Check if we already have enough connections in progress */
  767. if (we_are_bootstrapping) {
  768. max_in_progress_conns =
  769. options->ClientBootstrapConsensusMaxInProgressTries;
  770. }
  771. if (connection_dir_count_by_purpose_and_resource(
  772. DIR_PURPOSE_FETCH_CONSENSUS,
  773. resource)
  774. >= max_in_progress_conns) {
  775. continue;
  776. }
  777. /* Check if we want to launch another download for a usable consensus.
  778. * Only used during bootstrap. */
  779. if (we_are_bootstrapping && use_multi_conn
  780. && i == usable_consensus_flavor()) {
  781. /* Check if we're already downloading a usable consensus */
  782. int consens_conn_count =
  783. connection_dir_count_by_purpose_and_resource(
  784. DIR_PURPOSE_FETCH_CONSENSUS,
  785. resource);
  786. int connect_consens_conn_count =
  787. connection_dir_count_by_purpose_resource_and_state(
  788. DIR_PURPOSE_FETCH_CONSENSUS,
  789. resource,
  790. DIR_CONN_STATE_CONNECTING);
  791. if (i == usable_consensus_flavor()
  792. && connect_consens_conn_count < consens_conn_count) {
  793. continue;
  794. }
  795. /* Make multiple connections for a bootstrap consensus download */
  796. update_consensus_bootstrap_multiple_downloads(now, options,
  797. we_are_bootstrapping);
  798. } else {
  799. /* Check if we failed downloading a consensus too recently */
  800. int max_dl_tries = consensus_max_download_tries(options,
  801. we_are_bootstrapping);
  802. /* Let's make sure we remembered to update consensus_dl_status */
  803. tor_assert(consensus_dl_status[i].schedule == DL_SCHED_CONSENSUS);
  804. if (!download_status_is_ready(&consensus_dl_status[i],
  805. now,
  806. max_dl_tries)) {
  807. continue;
  808. }
  809. /* Check if we're waiting for certificates to download */
  810. if (check_consensus_waiting_for_certs(i, now, &consensus_dl_status[i]))
  811. continue;
  812. /* Try the requested attempt */
  813. log_info(LD_DIR, "Launching %s standard networkstatus consensus "
  814. "download.", networkstatus_get_flavor_name(i));
  815. directory_get_from_dirserver(DIR_PURPOSE_FETCH_CONSENSUS,
  816. ROUTER_PURPOSE_GENERAL, resource,
  817. PDS_RETRY_IF_NO_SERVERS,
  818. consensus_dl_status[i].want_authority);
  819. }
  820. }
  821. }
  822. /** When we're bootstrapping, launch one or more consensus download
  823. * connections, if schedule indicates connection(s) should be made after now.
  824. * If is_authority, connect to an authority, otherwise, use a fallback
  825. * directory mirror.
  826. */
  827. static void
  828. update_consensus_bootstrap_attempt_downloads(
  829. time_t now,
  830. const or_options_t *options,
  831. int we_are_bootstrapping,
  832. download_status_t *dls,
  833. download_want_authority_t want_authority)
  834. {
  835. int max_dl_tries = consensus_max_download_tries(options,
  836. we_are_bootstrapping);
  837. const char *resource = networkstatus_get_flavor_name(
  838. usable_consensus_flavor());
  839. /* Let's make sure we remembered to update schedule */
  840. tor_assert(dls->schedule == DL_SCHED_CONSENSUS);
  841. /* Allow for multiple connections in the same second, if the schedule value
  842. * is 0. */
  843. while (download_status_is_ready(dls, now, max_dl_tries)) {
  844. log_info(LD_DIR, "Launching %s bootstrap %s networkstatus consensus "
  845. "download.", resource, (want_authority == DL_WANT_AUTHORITY
  846. ? "authority"
  847. : "mirror"));
  848. directory_get_from_dirserver(DIR_PURPOSE_FETCH_CONSENSUS,
  849. ROUTER_PURPOSE_GENERAL, resource,
  850. PDS_RETRY_IF_NO_SERVERS, want_authority);
  851. /* schedule the next attempt */
  852. download_status_increment_attempt(dls, resource, now);
  853. }
  854. }
  855. /** If we're bootstrapping, check the connection schedules and see if we want
  856. * to make additional, potentially concurrent, consensus download
  857. * connections.
  858. * Only call when bootstrapping, and when we want to make additional
  859. * connections. Only nodes that satisfy
  860. * networkstatus_consensus_can_use_multiple_directories make additonal
  861. * connections.
  862. */
  863. static void
  864. update_consensus_bootstrap_multiple_downloads(time_t now,
  865. const or_options_t *options,
  866. int we_are_bootstrapping)
  867. {
  868. const int usable_flavor = usable_consensus_flavor();
  869. /* make sure we can use multiple connections */
  870. if (!networkstatus_consensus_can_use_multiple_directories(options)) {
  871. return;
  872. }
  873. /* If we've managed to validate a usable consensus, don't make additonal
  874. * connections. */
  875. if (!we_are_bootstrapping) {
  876. return;
  877. }
  878. /* Launch concurrent consensus download attempt(s) based on the mirror and
  879. * authority schedules. Try the mirror first - this makes it slightly more
  880. * likely that we'll connect to the fallback first, and then end the
  881. * authority connection attempt. */
  882. /* If a consensus download fails because it's waiting for certificates,
  883. * we'll fail both the authority and fallback schedules. This is better than
  884. * failing only one of the schedules, and having the other continue
  885. * unchecked.
  886. */
  887. /* If we don't have or can't use extra fallbacks, don't try them. */
  888. if (networkstatus_consensus_can_use_extra_fallbacks(options)) {
  889. download_status_t *dls_f =
  890. &consensus_bootstrap_dl_status[CONSENSUS_BOOTSTRAP_SOURCE_ANY_DIRSERVER];
  891. if (!check_consensus_waiting_for_certs(usable_flavor, now, dls_f)) {
  892. /* During bootstrap, DL_WANT_ANY_DIRSERVER means "use fallbacks". */
  893. update_consensus_bootstrap_attempt_downloads(now, options,
  894. we_are_bootstrapping, dls_f,
  895. DL_WANT_ANY_DIRSERVER);
  896. }
  897. }
  898. /* Now try an authority. */
  899. download_status_t *dls_a =
  900. &consensus_bootstrap_dl_status[CONSENSUS_BOOTSTRAP_SOURCE_AUTHORITY];
  901. if (!check_consensus_waiting_for_certs(usable_flavor, now, dls_a)) {
  902. update_consensus_bootstrap_attempt_downloads(now, options,
  903. we_are_bootstrapping, dls_a,
  904. DL_WANT_AUTHORITY);
  905. }
  906. }
  907. /** Called when an attempt to download a consensus fails: note that the
  908. * failure occurred, and possibly retry. */
  909. void
  910. networkstatus_consensus_download_failed(int status_code, const char *flavname)
  911. {
  912. int flav = networkstatus_parse_flavor_name(flavname);
  913. if (flav >= 0) {
  914. tor_assert(flav < N_CONSENSUS_FLAVORS);
  915. /* XXXX handle unrecognized flavors */
  916. download_status_failed(&consensus_dl_status[flav], status_code);
  917. /* Retry immediately, if appropriate. */
  918. update_consensus_networkstatus_downloads(time(NULL));
  919. }
  920. }
  921. /** How long do we (as a cache) wait after a consensus becomes non-fresh
  922. * before trying to fetch another? */
  923. #define CONSENSUS_MIN_SECONDS_BEFORE_CACHING 120
  924. /** Update the time at which we'll consider replacing the current
  925. * consensus of flavor <b>flav</b> */
  926. static void
  927. update_consensus_networkstatus_fetch_time_impl(time_t now, int flav)
  928. {
  929. const or_options_t *options = get_options();
  930. networkstatus_t *c = networkstatus_get_latest_consensus_by_flavor(flav);
  931. const char *flavor = networkstatus_get_flavor_name(flav);
  932. if (! we_want_to_fetch_flavor(get_options(), flav))
  933. return;
  934. if (c && c->valid_after <= now && now <= c->valid_until) {
  935. long dl_interval;
  936. long interval = c->fresh_until - c->valid_after;
  937. long min_sec_before_caching = CONSENSUS_MIN_SECONDS_BEFORE_CACHING;
  938. time_t start;
  939. if (min_sec_before_caching > interval/16) {
  940. /* Usually we allow 2-minutes slop factor in case clocks get
  941. desynchronized a little. If we're on a private network with
  942. a crazy-fast voting interval, though, 2 minutes may be too
  943. much. */
  944. min_sec_before_caching = interval/16;
  945. /* make sure we always delay by at least a second before caching */
  946. if (min_sec_before_caching == 0) {
  947. min_sec_before_caching = 1;
  948. }
  949. }
  950. if (directory_fetches_dir_info_early(options)) {
  951. /* We want to cache the next one at some point after this one
  952. * is no longer fresh... */
  953. start = (time_t)(c->fresh_until + min_sec_before_caching);
  954. /* Some clients may need the consensus sooner than others. */
  955. if (options->FetchDirInfoExtraEarly || authdir_mode_v3(options)) {
  956. dl_interval = 60;
  957. if (min_sec_before_caching + dl_interval > interval)
  958. dl_interval = interval/2;
  959. } else {
  960. /* But only in the first half-interval after that. */
  961. dl_interval = interval/2;
  962. }
  963. } else {
  964. /* We're an ordinary client, a bridge, or a hidden service.
  965. * Give all the caches enough time to download the consensus. */
  966. start = (time_t)(c->fresh_until + (interval*3)/4);
  967. /* But download the next one well before this one is expired. */
  968. dl_interval = ((c->valid_until - start) * 7 )/ 8;
  969. /* If we're a bridge user, make use of the numbers we just computed
  970. * to choose the rest of the interval *after* them. */
  971. if (directory_fetches_dir_info_later(options)) {
  972. /* Give all the *clients* enough time to download the consensus. */
  973. start = (time_t)(start + dl_interval + min_sec_before_caching);
  974. /* But try to get it before ours actually expires. */
  975. dl_interval = (c->valid_until - start) - min_sec_before_caching;
  976. }
  977. }
  978. /* catch low dl_interval in crazy-fast networks */
  979. if (dl_interval < 1)
  980. dl_interval = 1;
  981. /* catch late start in crazy-fast networks */
  982. if (start+dl_interval >= c->valid_until)
  983. start = c->valid_until - dl_interval - 1;
  984. log_debug(LD_DIR,
  985. "fresh_until: %ld start: %ld "
  986. "dl_interval: %ld valid_until: %ld ",
  987. (long)c->fresh_until, (long)start, dl_interval,
  988. (long)c->valid_until);
  989. /* We must not try to replace c while it's still fresh: */
  990. tor_assert(c->fresh_until < start);
  991. /* We must download the next one before c is invalid: */
  992. tor_assert(start+dl_interval < c->valid_until);
  993. time_to_download_next_consensus[flav] =
  994. start + crypto_rand_int((int)dl_interval);
  995. {
  996. char tbuf1[ISO_TIME_LEN+1];
  997. char tbuf2[ISO_TIME_LEN+1];
  998. char tbuf3[ISO_TIME_LEN+1];
  999. format_local_iso_time(tbuf1, c->fresh_until);
  1000. format_local_iso_time(tbuf2, c->valid_until);
  1001. format_local_iso_time(tbuf3, time_to_download_next_consensus[flav]);
  1002. log_info(LD_DIR, "Live %s consensus %s the most recent until %s and "
  1003. "will expire at %s; fetching the next one at %s.",
  1004. flavor, (c->fresh_until > now) ? "will be" : "was",
  1005. tbuf1, tbuf2, tbuf3);
  1006. }
  1007. } else {
  1008. time_to_download_next_consensus[flav] = now;
  1009. log_info(LD_DIR, "No live %s consensus; we should fetch one immediately.",
  1010. flavor);
  1011. }
  1012. }
  1013. /** Update the time at which we'll consider replacing the current
  1014. * consensus of flavor 'flavor' */
  1015. void
  1016. update_consensus_networkstatus_fetch_time(time_t now)
  1017. {
  1018. int i;
  1019. for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
  1020. if (we_want_to_fetch_flavor(get_options(), i))
  1021. update_consensus_networkstatus_fetch_time_impl(now, i);
  1022. }
  1023. }
  1024. /** Return 1 if there's a reason we shouldn't try any directory
  1025. * fetches yet (e.g. we demand bridges and none are yet known).
  1026. * Else return 0.
  1027. * If we return 1 and <b>msg_out</b> is provided, set <b>msg_out</b>
  1028. * to an explanation of why directory fetches are delayed. (If we
  1029. * return 0, we set msg_out to NULL.)
  1030. */
  1031. int
  1032. should_delay_dir_fetches(const or_options_t *options, const char **msg_out)
  1033. {
  1034. if (msg_out) {
  1035. *msg_out = NULL;
  1036. }
  1037. if (options->DisableNetwork) {
  1038. if (msg_out) {
  1039. *msg_out = "DisableNetwork is set.";
  1040. }
  1041. log_info(LD_DIR, "Delaying dir fetches (DisableNetwork is set)");
  1042. return 1;
  1043. }
  1044. if (options->UseBridges) {
  1045. if (!any_bridge_descriptors_known()) {
  1046. if (msg_out) {
  1047. *msg_out = "No running bridges";
  1048. }
  1049. log_info(LD_DIR, "Delaying dir fetches (no running bridges known)");
  1050. return 1;
  1051. }
  1052. if (pt_proxies_configuration_pending()) {
  1053. if (msg_out) {
  1054. *msg_out = "Pluggable transport proxies still configuring";
  1055. }
  1056. log_info(LD_DIR, "Delaying dir fetches (pt proxies still configuring)");
  1057. return 1;
  1058. }
  1059. }
  1060. return 0;
  1061. }
  1062. /** Launch requests for networkstatus documents and authority certificates as
  1063. * appropriate. */
  1064. void
  1065. update_networkstatus_downloads(time_t now)
  1066. {
  1067. const or_options_t *options = get_options();
  1068. if (should_delay_dir_fetches(options, NULL))
  1069. return;
  1070. update_consensus_networkstatus_downloads(now);
  1071. update_certificate_downloads(now);
  1072. }
  1073. /** Launch requests as appropriate for missing directory authority
  1074. * certificates. */
  1075. void
  1076. update_certificate_downloads(time_t now)
  1077. {
  1078. int i;
  1079. for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
  1080. if (consensus_waiting_for_certs[i].consensus)
  1081. authority_certs_fetch_missing(consensus_waiting_for_certs[i].consensus,
  1082. now, NULL);
  1083. }
  1084. if (current_ns_consensus)
  1085. authority_certs_fetch_missing(current_ns_consensus, now, NULL);
  1086. if (current_md_consensus)
  1087. authority_certs_fetch_missing(current_md_consensus, now, NULL);
  1088. }
  1089. /** Return 1 if we have a consensus but we don't have enough certificates
  1090. * to start using it yet. */
  1091. int
  1092. consensus_is_waiting_for_certs(void)
  1093. {
  1094. return consensus_waiting_for_certs[usable_consensus_flavor()].consensus
  1095. ? 1 : 0;
  1096. }
  1097. /** Return the most recent consensus that we have downloaded, or NULL if we
  1098. * don't have one. */
  1099. networkstatus_t *
  1100. networkstatus_get_latest_consensus(void)
  1101. {
  1102. return current_consensus;
  1103. }
  1104. /** Return the latest consensus we have whose flavor matches <b>f</b>, or NULL
  1105. * if we don't have one. */
  1106. MOCK_IMPL(networkstatus_t *,
  1107. networkstatus_get_latest_consensus_by_flavor,(consensus_flavor_t f))
  1108. {
  1109. if (f == FLAV_NS)
  1110. return current_ns_consensus;
  1111. else if (f == FLAV_MICRODESC)
  1112. return current_md_consensus;
  1113. else {
  1114. tor_assert(0);
  1115. return NULL;
  1116. }
  1117. }
  1118. /** Return the most recent consensus that we have downloaded, or NULL if it is
  1119. * no longer live. */
  1120. networkstatus_t *
  1121. networkstatus_get_live_consensus(time_t now)
  1122. {
  1123. if (current_consensus &&
  1124. current_consensus->valid_after <= now &&
  1125. now <= current_consensus->valid_until)
  1126. return current_consensus;
  1127. else
  1128. return NULL;
  1129. }
  1130. /* XXXX remove this in favor of get_live_consensus. But actually,
  1131. * leave something like it for bridge users, who need to not totally
  1132. * lose if they spend a while fetching a new consensus. */
  1133. /** As networkstatus_get_live_consensus(), but is way more tolerant of expired
  1134. * consensuses. */
  1135. networkstatus_t *
  1136. networkstatus_get_reasonably_live_consensus(time_t now, int flavor)
  1137. {
  1138. #define REASONABLY_LIVE_TIME (24*60*60)
  1139. networkstatus_t *consensus =
  1140. networkstatus_get_latest_consensus_by_flavor(flavor);
  1141. if (consensus &&
  1142. consensus->valid_after <= now &&
  1143. now <= consensus->valid_until+REASONABLY_LIVE_TIME)
  1144. return consensus;
  1145. else
  1146. return NULL;
  1147. }
  1148. /** Check if we're bootstrapping a consensus download. This means that we are
  1149. * only using the authorities and fallback directory mirrors to download the
  1150. * consensus flavour we'll use. */
  1151. int
  1152. networkstatus_consensus_is_boostrapping(time_t now)
  1153. {
  1154. /* If we don't have a consensus, we must still be bootstrapping */
  1155. return !networkstatus_get_reasonably_live_consensus(
  1156. now,
  1157. usable_consensus_flavor());
  1158. }
  1159. /** Check if we can use multiple directories for a consensus download.
  1160. * Only clients (including bridge relays, which act like clients) benefit
  1161. * from multiple simultaneous consensus downloads. */
  1162. int
  1163. networkstatus_consensus_can_use_multiple_directories(
  1164. const or_options_t *options)
  1165. {
  1166. /* If we are a client, bridge, bridge client, or hidden service */
  1167. return !public_server_mode(options);
  1168. }
  1169. /** Check if we can use fallback directory mirrors for a consensus download.
  1170. * If we have fallbacks and don't want to fetch from the authorities,
  1171. * we can use them. */
  1172. int
  1173. networkstatus_consensus_can_use_extra_fallbacks(const or_options_t *options)
  1174. {
  1175. /* The list length comparisons are a quick way to check if we have any
  1176. * non-authority fallback directories. If we ever have any authorities that
  1177. * aren't fallback directories, we will need to change this code. */
  1178. tor_assert(smartlist_len(router_get_fallback_dir_servers())
  1179. >= smartlist_len(router_get_trusted_dir_servers()));
  1180. /* If we don't fetch from the authorities, and we have additional mirrors,
  1181. * we can use them. */
  1182. return (!directory_fetches_from_authorities(options)
  1183. && (smartlist_len(router_get_fallback_dir_servers())
  1184. > smartlist_len(router_get_trusted_dir_servers())));
  1185. }
  1186. /* Check if there is more than 1 consensus connection retrieving the usable
  1187. * consensus flavor. If so, return 1, if not, return 0.
  1188. *
  1189. * During normal operation, Tor only makes one consensus download
  1190. * connection. But clients can make multiple simultaneous consensus
  1191. * connections to improve bootstrap speed and reliability.
  1192. *
  1193. * If there is more than one connection, we must have connections left
  1194. * over from bootstrapping. However, some of the connections may have
  1195. * completed and been cleaned up, so it is not sufficient to check the
  1196. * return value of this function to see if a client could make multiple
  1197. * bootstrap connections. Use
  1198. * networkstatus_consensus_can_use_multiple_directories()
  1199. * and networkstatus_consensus_is_boostrapping(). */
  1200. int
  1201. networkstatus_consensus_has_excess_connections(void)
  1202. {
  1203. const char *usable_resource = networkstatus_get_flavor_name(
  1204. usable_consensus_flavor());
  1205. const int consens_conn_usable_count =
  1206. connection_dir_count_by_purpose_and_resource(
  1207. DIR_PURPOSE_FETCH_CONSENSUS,
  1208. usable_resource);
  1209. /* The maximum number of connections we want downloading a usable consensus
  1210. * Always 1, whether bootstrapping or not. */
  1211. const int max_expected_consens_conn_usable_count = 1;
  1212. if (consens_conn_usable_count > max_expected_consens_conn_usable_count) {
  1213. return 1;
  1214. }
  1215. return 0;
  1216. }
  1217. /* Is tor currently downloading a consensus of the usable flavor? */
  1218. int
  1219. networkstatus_consensus_is_downloading_usable_flavor(void)
  1220. {
  1221. const char *usable_resource = networkstatus_get_flavor_name(
  1222. usable_consensus_flavor());
  1223. const int consens_conn_usable_count =
  1224. connection_dir_count_by_purpose_and_resource(
  1225. DIR_PURPOSE_FETCH_CONSENSUS,
  1226. usable_resource);
  1227. const int connect_consens_conn_usable_count =
  1228. connection_dir_count_by_purpose_resource_and_state(
  1229. DIR_PURPOSE_FETCH_CONSENSUS,
  1230. usable_resource,
  1231. DIR_CONN_STATE_CONNECTING);
  1232. if (connect_consens_conn_usable_count < consens_conn_usable_count) {
  1233. return 1;
  1234. }
  1235. return 0;
  1236. }
  1237. /** Given two router status entries for the same router identity, return 1 if
  1238. * if the contents have changed between them. Otherwise, return 0. */
  1239. static int
  1240. routerstatus_has_changed(const routerstatus_t *a, const routerstatus_t *b)
  1241. {
  1242. tor_assert(tor_memeq(a->identity_digest, b->identity_digest, DIGEST_LEN));
  1243. return strcmp(a->nickname, b->nickname) ||
  1244. fast_memneq(a->descriptor_digest, b->descriptor_digest, DIGEST_LEN) ||
  1245. a->addr != b->addr ||
  1246. a->or_port != b->or_port ||
  1247. a->dir_port != b->dir_port ||
  1248. a->is_authority != b->is_authority ||
  1249. a->is_exit != b->is_exit ||
  1250. a->is_stable != b->is_stable ||
  1251. a->is_fast != b->is_fast ||
  1252. a->is_flagged_running != b->is_flagged_running ||
  1253. a->is_named != b->is_named ||
  1254. a->is_unnamed != b->is_unnamed ||
  1255. a->is_valid != b->is_valid ||
  1256. a->is_possible_guard != b->is_possible_guard ||
  1257. a->is_bad_exit != b->is_bad_exit ||
  1258. a->is_hs_dir != b->is_hs_dir ||
  1259. a->version_known != b->version_known;
  1260. }
  1261. /** Notify controllers of any router status entries that changed between
  1262. * <b>old_c</b> and <b>new_c</b>. */
  1263. static void
  1264. notify_control_networkstatus_changed(const networkstatus_t *old_c,
  1265. const networkstatus_t *new_c)
  1266. {
  1267. smartlist_t *changed;
  1268. if (old_c == new_c)
  1269. return;
  1270. /* tell the controller exactly which relays are still listed, as well
  1271. * as what they're listed as */
  1272. control_event_newconsensus(new_c);
  1273. if (!control_event_is_interesting(EVENT_NS))
  1274. return;
  1275. if (!old_c) {
  1276. control_event_networkstatus_changed(new_c->routerstatus_list);
  1277. return;
  1278. }
  1279. changed = smartlist_new();
  1280. SMARTLIST_FOREACH_JOIN(
  1281. old_c->routerstatus_list, const routerstatus_t *, rs_old,
  1282. new_c->routerstatus_list, const routerstatus_t *, rs_new,
  1283. tor_memcmp(rs_old->identity_digest,
  1284. rs_new->identity_digest, DIGEST_LEN),
  1285. smartlist_add(changed, (void*) rs_new)) {
  1286. if (routerstatus_has_changed(rs_old, rs_new))
  1287. smartlist_add(changed, (void*)rs_new);
  1288. } SMARTLIST_FOREACH_JOIN_END(rs_old, rs_new);
  1289. control_event_networkstatus_changed(changed);
  1290. smartlist_free(changed);
  1291. }
  1292. /** Copy all the ancillary information (like router download status and so on)
  1293. * from <b>old_c</b> to <b>new_c</b>. */
  1294. static void
  1295. networkstatus_copy_old_consensus_info(networkstatus_t *new_c,
  1296. const networkstatus_t *old_c)
  1297. {
  1298. if (old_c == new_c)
  1299. return;
  1300. if (!old_c || !smartlist_len(old_c->routerstatus_list))
  1301. return;
  1302. SMARTLIST_FOREACH_JOIN(old_c->routerstatus_list, routerstatus_t *, rs_old,
  1303. new_c->routerstatus_list, routerstatus_t *, rs_new,
  1304. tor_memcmp(rs_old->identity_digest,
  1305. rs_new->identity_digest, DIGEST_LEN),
  1306. STMT_NIL) {
  1307. /* Okay, so we're looking at the same identity. */
  1308. rs_new->last_dir_503_at = rs_old->last_dir_503_at;
  1309. if (tor_memeq(rs_old->descriptor_digest, rs_new->descriptor_digest,
  1310. DIGEST256_LEN)) {
  1311. /* And the same descriptor too! */
  1312. memcpy(&rs_new->dl_status, &rs_old->dl_status,sizeof(download_status_t));
  1313. }
  1314. } SMARTLIST_FOREACH_JOIN_END(rs_old, rs_new);
  1315. }
  1316. #ifdef TOR_UNIT_TESTS
  1317. /**Accept a <b>flavor</b> consensus <b>c</b> without any additional
  1318. * validation. This is exclusively for unit tests.
  1319. * We copy any ancillary information from a pre-existing consensus
  1320. * and then free the current one and replace it with the newly
  1321. * provided instance. Returns -1 on unrecognized flavor, 0 otherwise.
  1322. */
  1323. int
  1324. networkstatus_set_current_consensus_from_ns(networkstatus_t *c,
  1325. const char *flavor)
  1326. {
  1327. int flav = networkstatus_parse_flavor_name(flavor);
  1328. switch (flav) {
  1329. case FLAV_NS:
  1330. if (current_ns_consensus) {
  1331. networkstatus_copy_old_consensus_info(c, current_ns_consensus);
  1332. networkstatus_vote_free(current_ns_consensus);
  1333. }
  1334. current_ns_consensus = c;
  1335. break;
  1336. case FLAV_MICRODESC:
  1337. if (current_md_consensus) {
  1338. networkstatus_copy_old_consensus_info(c, current_md_consensus);
  1339. networkstatus_vote_free(current_md_consensus);
  1340. }
  1341. current_md_consensus = c;
  1342. break;
  1343. }
  1344. return current_md_consensus ? 0 : -1;
  1345. }
  1346. #endif //TOR_UNIT_TESTS
  1347. /** Try to replace the current cached v3 networkstatus with the one in
  1348. * <b>consensus</b>. If we don't have enough certificates to validate it,
  1349. * store it in consensus_waiting_for_certs and launch a certificate fetch.
  1350. *
  1351. * If flags & NSSET_FROM_CACHE, this networkstatus has come from the disk
  1352. * cache. If flags & NSSET_WAS_WAITING_FOR_CERTS, this networkstatus was
  1353. * already received, but we were waiting for certificates on it. If flags &
  1354. * NSSET_DONT_DOWNLOAD_CERTS, do not launch certificate downloads as needed.
  1355. * If flags & NSSET_ACCEPT_OBSOLETE, then we should be willing to take this
  1356. * consensus, even if it comes from many days in the past.
  1357. *
  1358. * If source_dir is non-NULL, it's the identity digest for a directory that
  1359. * we've just successfully retrieved a consensus or certificates from, so try
  1360. * it first to fetch any missing certificates.
  1361. *
  1362. * Return 0 on success, <0 on failure. On failure, caller should increment
  1363. * the failure count as appropriate.
  1364. *
  1365. * We return -1 for mild failures that don't need to be reported to the
  1366. * user, and -2 for more serious problems.
  1367. */
  1368. int
  1369. networkstatus_set_current_consensus(const char *consensus,
  1370. const char *flavor,
  1371. unsigned flags,
  1372. const char *source_dir)
  1373. {
  1374. networkstatus_t *c=NULL;
  1375. int r, result = -1;
  1376. time_t now = time(NULL);
  1377. const or_options_t *options = get_options();
  1378. char *unverified_fname = NULL, *consensus_fname = NULL;
  1379. int flav = networkstatus_parse_flavor_name(flavor);
  1380. const unsigned from_cache = flags & NSSET_FROM_CACHE;
  1381. const unsigned was_waiting_for_certs = flags & NSSET_WAS_WAITING_FOR_CERTS;
  1382. const unsigned dl_certs = !(flags & NSSET_DONT_DOWNLOAD_CERTS);
  1383. const unsigned accept_obsolete = flags & NSSET_ACCEPT_OBSOLETE;
  1384. const unsigned require_flavor = flags & NSSET_REQUIRE_FLAVOR;
  1385. const common_digests_t *current_digests = NULL;
  1386. consensus_waiting_for_certs_t *waiting = NULL;
  1387. time_t current_valid_after = 0;
  1388. int free_consensus = 1; /* Free 'c' at the end of the function */
  1389. int old_ewma_enabled;
  1390. if (flav < 0) {
  1391. /* XXXX we don't handle unrecognized flavors yet. */
  1392. log_warn(LD_BUG, "Unrecognized consensus flavor %s", flavor);
  1393. return -2;
  1394. }
  1395. /* Make sure it's parseable. */
  1396. c = networkstatus_parse_vote_from_string(consensus, NULL, NS_TYPE_CONSENSUS);
  1397. if (!c) {
  1398. log_warn(LD_DIR, "Unable to parse networkstatus consensus");
  1399. result = -2;
  1400. goto done;
  1401. }
  1402. if ((int)c->flavor != flav) {
  1403. /* This wasn't the flavor we thought we were getting. */
  1404. if (require_flavor) {
  1405. log_warn(LD_DIR, "Got consensus with unexpected flavor %s (wanted %s)",
  1406. networkstatus_get_flavor_name(c->flavor), flavor);
  1407. goto done;
  1408. }
  1409. flav = c->flavor;
  1410. flavor = networkstatus_get_flavor_name(flav);
  1411. }
  1412. if (flav != usable_consensus_flavor() &&
  1413. !directory_caches_dir_info(options)) {
  1414. /* This consensus is totally boring to us: we won't use it, and we won't
  1415. * serve it. Drop it. */
  1416. goto done;
  1417. }
  1418. if (from_cache && !accept_obsolete &&
  1419. c->valid_until < now-OLD_ROUTER_DESC_MAX_AGE) {
  1420. log_info(LD_DIR, "Loaded an expired consensus. Discarding.");
  1421. goto done;
  1422. }
  1423. if (!strcmp(flavor, "ns")) {
  1424. consensus_fname = get_datadir_fname("cached-consensus");
  1425. unverified_fname = get_datadir_fname("unverified-consensus");
  1426. if (current_ns_consensus) {
  1427. current_digests = &current_ns_consensus->digests;
  1428. current_valid_after = current_ns_consensus->valid_after;
  1429. }
  1430. } else if (!strcmp(flavor, "microdesc")) {
  1431. consensus_fname = get_datadir_fname("cached-microdesc-consensus");
  1432. unverified_fname = get_datadir_fname("unverified-microdesc-consensus");
  1433. if (current_md_consensus) {
  1434. current_digests = &current_md_consensus->digests;
  1435. current_valid_after = current_md_consensus->valid_after;
  1436. }
  1437. } else {
  1438. cached_dir_t *cur;
  1439. char buf[128];
  1440. tor_snprintf(buf, sizeof(buf), "cached-%s-consensus", flavor);
  1441. consensus_fname = get_datadir_fname(buf);
  1442. tor_snprintf(buf, sizeof(buf), "unverified-%s-consensus", flavor);
  1443. unverified_fname = get_datadir_fname(buf);
  1444. cur = dirserv_get_consensus(flavor);
  1445. if (cur) {
  1446. current_digests = &cur->digests;
  1447. current_valid_after = cur->published;
  1448. }
  1449. }
  1450. if (current_digests &&
  1451. tor_memeq(&c->digests, current_digests, sizeof(c->digests))) {
  1452. /* We already have this one. That's a failure. */
  1453. log_info(LD_DIR, "Got a %s consensus we already have", flavor);
  1454. goto done;
  1455. }
  1456. if (current_valid_after && c->valid_after <= current_valid_after) {
  1457. /* We have a newer one. There's no point in accepting this one,
  1458. * even if it's great. */
  1459. log_info(LD_DIR, "Got a %s consensus at least as old as the one we have",
  1460. flavor);
  1461. goto done;
  1462. }
  1463. /* Make sure it's signed enough. */
  1464. if ((r=networkstatus_check_consensus_signature(c, 1))<0) {
  1465. if (r == -1) {
  1466. /* Okay, so it _might_ be signed enough if we get more certificates. */
  1467. if (!was_waiting_for_certs) {
  1468. log_info(LD_DIR,
  1469. "Not enough certificates to check networkstatus consensus");
  1470. }
  1471. if (!current_valid_after ||
  1472. c->valid_after > current_valid_after) {
  1473. waiting = &consensus_waiting_for_certs[flav];
  1474. networkstatus_vote_free(waiting->consensus);
  1475. tor_free(waiting->body);
  1476. waiting->consensus = c;
  1477. free_consensus = 0;
  1478. waiting->body = tor_strdup(consensus);
  1479. waiting->set_at = now;
  1480. waiting->dl_failed = 0;
  1481. if (!from_cache) {
  1482. write_str_to_file(unverified_fname, consensus, 0);
  1483. }
  1484. if (dl_certs)
  1485. authority_certs_fetch_missing(c, now, source_dir);
  1486. /* This case is not a success or a failure until we get the certs
  1487. * or fail to get the certs. */
  1488. result = 0;
  1489. } else {
  1490. /* Even if we had enough signatures, we'd never use this as the
  1491. * latest consensus. */
  1492. if (was_waiting_for_certs && from_cache)
  1493. if (unlink(unverified_fname) != 0) {
  1494. log_warn(LD_FS,
  1495. "Failed to unlink %s: %s",
  1496. unverified_fname, strerror(errno));
  1497. }
  1498. }
  1499. goto done;
  1500. } else {
  1501. /* This can never be signed enough: Kill it. */
  1502. if (!was_waiting_for_certs) {
  1503. log_warn(LD_DIR, "Not enough good signatures on networkstatus "
  1504. "consensus");
  1505. result = -2;
  1506. }
  1507. if (was_waiting_for_certs && (r < -1) && from_cache) {
  1508. if (unlink(unverified_fname) != 0) {
  1509. log_warn(LD_FS,
  1510. "Failed to unlink %s: %s",
  1511. unverified_fname, strerror(errno));
  1512. }
  1513. }
  1514. goto done;
  1515. }
  1516. }
  1517. if (!from_cache && flav == usable_consensus_flavor())
  1518. control_event_client_status(LOG_NOTICE, "CONSENSUS_ARRIVED");
  1519. /* Are we missing any certificates at all? */
  1520. if (r != 1 && dl_certs)
  1521. authority_certs_fetch_missing(c, now, source_dir);
  1522. if (flav == usable_consensus_flavor()) {
  1523. notify_control_networkstatus_changed(current_consensus, c);
  1524. }
  1525. if (flav == FLAV_NS) {
  1526. if (current_ns_consensus) {
  1527. networkstatus_copy_old_consensus_info(c, current_ns_consensus);
  1528. networkstatus_vote_free(current_ns_consensus);
  1529. /* Defensive programming : we should set current_consensus very soon,
  1530. * but we're about to call some stuff in the meantime, and leaving this
  1531. * dangling pointer around has proven to be trouble. */
  1532. current_ns_consensus = NULL;
  1533. }
  1534. current_ns_consensus = c;
  1535. free_consensus = 0; /* avoid free */
  1536. } else if (flav == FLAV_MICRODESC) {
  1537. if (current_md_consensus) {
  1538. networkstatus_copy_old_consensus_info(c, current_md_consensus);
  1539. networkstatus_vote_free(current_md_consensus);
  1540. /* more defensive programming */
  1541. current_md_consensus = NULL;
  1542. }
  1543. current_md_consensus = c;
  1544. free_consensus = 0; /* avoid free */
  1545. }
  1546. waiting = &consensus_waiting_for_certs[flav];
  1547. if (waiting->consensus &&
  1548. waiting->consensus->valid_after <= c->valid_after) {
  1549. networkstatus_vote_free(waiting->consensus);
  1550. waiting->consensus = NULL;
  1551. if (consensus != waiting->body)
  1552. tor_free(waiting->body);
  1553. else
  1554. waiting->body = NULL;
  1555. waiting->set_at = 0;
  1556. waiting->dl_failed = 0;
  1557. if (unlink(unverified_fname) != 0) {
  1558. log_warn(LD_FS,
  1559. "Failed to unlink %s: %s",
  1560. unverified_fname, strerror(errno));
  1561. }
  1562. }
  1563. /* Reset the failure count only if this consensus is actually valid. */
  1564. if (c->valid_after <= now && now <= c->valid_until) {
  1565. download_status_reset(&consensus_dl_status[flav]);
  1566. } else {
  1567. if (!from_cache)
  1568. download_status_failed(&consensus_dl_status[flav], 0);
  1569. }
  1570. if (flav == usable_consensus_flavor()) {
  1571. /* XXXXNM Microdescs: needs a non-ns variant. ???? NM*/
  1572. update_consensus_networkstatus_fetch_time(now);
  1573. nodelist_set_consensus(current_consensus);
  1574. dirvote_recalculate_timing(options, now);
  1575. routerstatus_list_update_named_server_map();
  1576. /* Update ewma and adjust policy if needed; first cache the old value */
  1577. old_ewma_enabled = cell_ewma_enabled();
  1578. /* Change the cell EWMA settings */
  1579. cell_ewma_set_scale_factor(options, networkstatus_get_latest_consensus());
  1580. /* If we just enabled ewma, set the cmux policy on all active channels */
  1581. if (cell_ewma_enabled() && !old_ewma_enabled) {
  1582. channel_set_cmux_policy_everywhere(&ewma_policy);
  1583. } else if (!cell_ewma_enabled() && old_ewma_enabled) {
  1584. /* Turn it off everywhere */
  1585. channel_set_cmux_policy_everywhere(NULL);
  1586. }
  1587. /* XXXX024 this call might be unnecessary here: can changing the
  1588. * current consensus really alter our view of any OR's rate limits? */
  1589. connection_or_update_token_buckets(get_connection_array(), options);
  1590. circuit_build_times_new_consensus_params(get_circuit_build_times_mutable(),
  1591. current_consensus);
  1592. }
  1593. if (directory_caches_dir_info(options)) {
  1594. dirserv_set_cached_consensus_networkstatus(consensus,
  1595. flavor,
  1596. &c->digests,
  1597. c->valid_after);
  1598. }
  1599. if (!from_cache) {
  1600. write_str_to_file(consensus_fname, consensus, 0);
  1601. }
  1602. /** If a consensus appears more than this many seconds before its declared
  1603. * valid-after time, declare that our clock is skewed. */
  1604. #define EARLY_CONSENSUS_NOTICE_SKEW 60
  1605. if (now < c->valid_after - EARLY_CONSENSUS_NOTICE_SKEW) {
  1606. char tbuf[ISO_TIME_LEN+1];
  1607. char dbuf[64];
  1608. long delta = now - c->valid_after;
  1609. format_iso_time(tbuf, c->valid_after);
  1610. format_time_interval(dbuf, sizeof(dbuf), delta);
  1611. log_warn(LD_GENERAL, "Our clock is %s behind the time published in the "
  1612. "consensus network status document (%s UTC). Tor needs an "
  1613. "accurate clock to work correctly. Please check your time and "
  1614. "date settings!", dbuf, tbuf);
  1615. control_event_general_status(LOG_WARN,
  1616. "CLOCK_SKEW MIN_SKEW=%ld SOURCE=CONSENSUS", delta);
  1617. }
  1618. router_dir_info_changed();
  1619. result = 0;
  1620. done:
  1621. if (free_consensus)
  1622. networkstatus_vote_free(c);
  1623. tor_free(consensus_fname);
  1624. tor_free(unverified_fname);
  1625. return result;
  1626. }
  1627. /** Called when we have gotten more certificates: see whether we can
  1628. * now verify a pending consensus.
  1629. *
  1630. * If source_dir is non-NULL, it's the identity digest for a directory that
  1631. * we've just successfully retrieved certificates from, so try it first to
  1632. * fetch any missing certificates.
  1633. */
  1634. void
  1635. networkstatus_note_certs_arrived(const char *source_dir)
  1636. {
  1637. int i;
  1638. for (i=0; i<N_CONSENSUS_FLAVORS; ++i) {
  1639. consensus_waiting_for_certs_t *waiting = &consensus_waiting_for_certs[i];
  1640. if (!waiting->consensus)
  1641. continue;
  1642. if (networkstatus_check_consensus_signature(waiting->consensus, 0)>=0) {
  1643. char *waiting_body = waiting->body;
  1644. if (!networkstatus_set_current_consensus(
  1645. waiting_body,
  1646. networkstatus_get_flavor_name(i),
  1647. NSSET_WAS_WAITING_FOR_CERTS,
  1648. source_dir)) {
  1649. tor_free(waiting_body);
  1650. }
  1651. }
  1652. }
  1653. }
  1654. /** If the network-status list has changed since the last time we called this
  1655. * function, update the status of every routerinfo from the network-status
  1656. * list. If <b>dir_version</b> is 2, it's a v2 networkstatus that changed.
  1657. * If <b>dir_version</b> is 3, it's a v3 consensus that changed.
  1658. */
  1659. void
  1660. routers_update_all_from_networkstatus(time_t now, int dir_version)
  1661. {
  1662. routerlist_t *rl = router_get_routerlist();
  1663. networkstatus_t *consensus = networkstatus_get_reasonably_live_consensus(now,
  1664. FLAV_NS);
  1665. if (!consensus || dir_version < 3) /* nothing more we should do */
  1666. return;
  1667. /* calls router_dir_info_changed() when it's done -- more routers
  1668. * might be up or down now, which might affect whether there's enough
  1669. * directory info. */
  1670. routers_update_status_from_consensus_networkstatus(rl->routers, 0);
  1671. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri,
  1672. ri->cache_info.routerlist_index = ri_sl_idx);
  1673. if (rl->old_routers)
  1674. signed_descs_update_status_from_consensus_networkstatus(rl->old_routers);
  1675. if (!have_warned_about_old_version) {
  1676. int is_server = server_mode(get_options());
  1677. version_status_t status;
  1678. const char *recommended = is_server ?
  1679. consensus->server_versions : consensus->client_versions;
  1680. status = tor_version_is_obsolete(VERSION, recommended);
  1681. if (status == VS_RECOMMENDED) {
  1682. log_info(LD_GENERAL, "The directory authorities say my version is ok.");
  1683. } else if (status == VS_EMPTY) {
  1684. log_info(LD_GENERAL,
  1685. "The directory authorities don't recommend any versions.");
  1686. } else if (status == VS_NEW || status == VS_NEW_IN_SERIES) {
  1687. if (!have_warned_about_new_version) {
  1688. log_notice(LD_GENERAL, "This version of Tor (%s) is newer than any "
  1689. "recommended version%s, according to the directory "
  1690. "authorities. Recommended versions are: %s",
  1691. VERSION,
  1692. status == VS_NEW_IN_SERIES ? " in its series" : "",
  1693. recommended);
  1694. have_warned_about_new_version = 1;
  1695. control_event_general_status(LOG_WARN, "DANGEROUS_VERSION "
  1696. "CURRENT=%s REASON=%s RECOMMENDED=\"%s\"",
  1697. VERSION, "NEW", recommended);
  1698. }
  1699. } else {
  1700. log_warn(LD_GENERAL, "Please upgrade! "
  1701. "This version of Tor (%s) is %s, according to the directory "
  1702. "authorities. Recommended versions are: %s",
  1703. VERSION,
  1704. status == VS_OLD ? "obsolete" : "not recommended",
  1705. recommended);
  1706. have_warned_about_old_version = 1;
  1707. control_event_general_status(LOG_WARN, "DANGEROUS_VERSION "
  1708. "CURRENT=%s REASON=%s RECOMMENDED=\"%s\"",
  1709. VERSION, status == VS_OLD ? "OBSOLETE" : "UNRECOMMENDED",
  1710. recommended);
  1711. }
  1712. }
  1713. }
  1714. /** Update our view of the list of named servers from the most recently
  1715. * retrieved networkstatus consensus. */
  1716. static void
  1717. routerstatus_list_update_named_server_map(void)
  1718. {
  1719. if (!current_consensus)
  1720. return;
  1721. strmap_free(named_server_map, tor_free_);
  1722. named_server_map = strmap_new();
  1723. strmap_free(unnamed_server_map, NULL);
  1724. unnamed_server_map = strmap_new();
  1725. SMARTLIST_FOREACH_BEGIN(current_consensus->routerstatus_list,
  1726. const routerstatus_t *, rs) {
  1727. if (rs->is_named) {
  1728. strmap_set_lc(named_server_map, rs->nickname,
  1729. tor_memdup(rs->identity_digest, DIGEST_LEN));
  1730. }
  1731. if (rs->is_unnamed) {
  1732. strmap_set_lc(unnamed_server_map, rs->nickname, (void*)1);
  1733. }
  1734. } SMARTLIST_FOREACH_END(rs);
  1735. }
  1736. /** Given a list <b>routers</b> of routerinfo_t *, update each status field
  1737. * according to our current consensus networkstatus. May re-order
  1738. * <b>routers</b>. */
  1739. void
  1740. routers_update_status_from_consensus_networkstatus(smartlist_t *routers,
  1741. int reset_failures)
  1742. {
  1743. const or_options_t *options = get_options();
  1744. int authdir = authdir_mode_v3(options);
  1745. networkstatus_t *ns = current_consensus;
  1746. if (!ns || !smartlist_len(ns->routerstatus_list))
  1747. return;
  1748. routers_sort_by_identity(routers);
  1749. SMARTLIST_FOREACH_JOIN(ns->routerstatus_list, routerstatus_t *, rs,
  1750. routers, routerinfo_t *, router,
  1751. tor_memcmp(rs->identity_digest,
  1752. router->cache_info.identity_digest, DIGEST_LEN),
  1753. {
  1754. }) {
  1755. /* Is it the same descriptor, or only the same identity? */
  1756. if (tor_memeq(router->cache_info.signed_descriptor_digest,
  1757. rs->descriptor_digest, DIGEST_LEN)) {
  1758. if (ns->valid_until > router->cache_info.last_listed_as_valid_until)
  1759. router->cache_info.last_listed_as_valid_until = ns->valid_until;
  1760. }
  1761. if (authdir) {
  1762. /* If we _are_ an authority, we should check whether this router
  1763. * is one that will cause us to need a reachability test. */
  1764. routerinfo_t *old_router =
  1765. router_get_mutable_by_digest(router->cache_info.identity_digest);
  1766. if (old_router != router) {
  1767. router->needs_retest_if_added =
  1768. dirserv_should_launch_reachability_test(router, old_router);
  1769. }
  1770. }
  1771. if (reset_failures) {
  1772. download_status_reset(&rs->dl_status);
  1773. }
  1774. } SMARTLIST_FOREACH_JOIN_END(rs, router);
  1775. router_dir_info_changed();
  1776. }
  1777. /** Given a list of signed_descriptor_t, update their fields (mainly, when
  1778. * they were last listed) from the most recent consensus. */
  1779. void
  1780. signed_descs_update_status_from_consensus_networkstatus(smartlist_t *descs)
  1781. {
  1782. networkstatus_t *ns = current_ns_consensus;
  1783. if (!ns)
  1784. return;
  1785. if (!ns->desc_digest_map) {
  1786. char dummy[DIGEST_LEN];
  1787. /* instantiates the digest map. */
  1788. memset(dummy, 0, sizeof(dummy));
  1789. router_get_consensus_status_by_descriptor_digest(ns, dummy);
  1790. }
  1791. SMARTLIST_FOREACH(descs, signed_descriptor_t *, d,
  1792. {
  1793. const routerstatus_t *rs = digestmap_get(ns->desc_digest_map,
  1794. d->signed_descriptor_digest);
  1795. if (rs) {
  1796. if (ns->valid_until > d->last_listed_as_valid_until)
  1797. d->last_listed_as_valid_until = ns->valid_until;
  1798. }
  1799. });
  1800. }
  1801. /** Generate networkstatus lines for a single routerstatus_t object, and
  1802. * return the result in a newly allocated string. Used only by controller
  1803. * interface (for now.) */
  1804. char *
  1805. networkstatus_getinfo_helper_single(const routerstatus_t *rs)
  1806. {
  1807. return routerstatus_format_entry(rs, NULL, NS_CONTROL_PORT, NULL);
  1808. }
  1809. /** Alloc and return a string describing routerstatuses for the most
  1810. * recent info of each router we know about that is of purpose
  1811. * <b>purpose_string</b>. Return NULL if unrecognized purpose.
  1812. *
  1813. * Right now this function is oriented toward listing bridges (you
  1814. * shouldn't use this for general-purpose routers, since those
  1815. * should be listed from the consensus, not from the routers list). */
  1816. char *
  1817. networkstatus_getinfo_by_purpose(const char *purpose_string, time_t now)
  1818. {
  1819. time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
  1820. char *answer;
  1821. routerlist_t *rl = router_get_routerlist();
  1822. smartlist_t *statuses;
  1823. uint8_t purpose = router_purpose_from_string(purpose_string);
  1824. routerstatus_t rs;
  1825. int bridge_auth = authdir_mode_bridge(get_options());
  1826. if (purpose == ROUTER_PURPOSE_UNKNOWN) {
  1827. log_info(LD_DIR, "Unrecognized purpose '%s' when listing router statuses.",
  1828. purpose_string);
  1829. return NULL;
  1830. }
  1831. statuses = smartlist_new();
  1832. SMARTLIST_FOREACH_BEGIN(rl->routers, routerinfo_t *, ri) {
  1833. node_t *node = node_get_mutable_by_id(ri->cache_info.identity_digest);
  1834. if (!node)
  1835. continue;
  1836. if (ri->cache_info.published_on < cutoff)
  1837. continue;
  1838. if (ri->purpose != purpose)
  1839. continue;
  1840. if (bridge_auth && ri->purpose == ROUTER_PURPOSE_BRIDGE)
  1841. dirserv_set_router_is_running(ri, now);
  1842. /* then generate and write out status lines for each of them */
  1843. set_routerstatus_from_routerinfo(&rs, node, ri, now, 0);
  1844. smartlist_add(statuses, networkstatus_getinfo_helper_single(&rs));
  1845. } SMARTLIST_FOREACH_END(ri);
  1846. answer = smartlist_join_strings(statuses, "", 0, NULL);
  1847. SMARTLIST_FOREACH(statuses, char *, cp, tor_free(cp));
  1848. smartlist_free(statuses);
  1849. return answer;
  1850. }
  1851. /** Write out router status entries for all our bridge descriptors. */
  1852. void
  1853. networkstatus_dump_bridge_status_to_file(time_t now)
  1854. {
  1855. char *status = networkstatus_getinfo_by_purpose("bridge", now);
  1856. const or_options_t *options = get_options();
  1857. char *fname = NULL;
  1858. char *thresholds = NULL;
  1859. char *published_thresholds_and_status = NULL;
  1860. routerlist_t *rl = router_get_routerlist();
  1861. char published[ISO_TIME_LEN+1];
  1862. format_iso_time(published, now);
  1863. dirserv_compute_bridge_flag_thresholds(rl->routers);
  1864. thresholds = dirserv_get_flag_thresholds_line();
  1865. tor_asprintf(&published_thresholds_and_status,
  1866. "published %s\nflag-thresholds %s\n%s",
  1867. published, thresholds, status);
  1868. tor_asprintf(&fname, "%s"PATH_SEPARATOR"networkstatus-bridges",
  1869. options->DataDirectory);
  1870. write_str_to_file(fname,published_thresholds_and_status,0);
  1871. tor_free(thresholds);
  1872. tor_free(published_thresholds_and_status);
  1873. tor_free(fname);
  1874. tor_free(status);
  1875. }
  1876. /* DOCDOC get_net_param_from_list */
  1877. static int32_t
  1878. get_net_param_from_list(smartlist_t *net_params, const char *param_name,
  1879. int32_t default_val, int32_t min_val, int32_t max_val)
  1880. {
  1881. int32_t res = default_val;
  1882. size_t name_len = strlen(param_name);
  1883. tor_assert(max_val > min_val);
  1884. tor_assert(min_val <= default_val);
  1885. tor_assert(max_val >= default_val);
  1886. SMARTLIST_FOREACH_BEGIN(net_params, const char *, p) {
  1887. if (!strcmpstart(p, param_name) && p[name_len] == '=') {
  1888. int ok=0;
  1889. long v = tor_parse_long(p+name_len+1, 10, INT32_MIN,
  1890. INT32_MAX, &ok, NULL);
  1891. if (ok) {
  1892. res = (int32_t) v;
  1893. break;
  1894. }
  1895. }
  1896. } SMARTLIST_FOREACH_END(p);
  1897. if (res < min_val) {
  1898. log_warn(LD_DIR, "Consensus parameter %s is too small. Got %d, raising to "
  1899. "%d.", param_name, res, min_val);
  1900. res = min_val;
  1901. } else if (res > max_val) {
  1902. log_warn(LD_DIR, "Consensus parameter %s is too large. Got %d, capping to "
  1903. "%d.", param_name, res, max_val);
  1904. res = max_val;
  1905. }
  1906. return res;
  1907. }
  1908. /** Return the value of a integer parameter from the networkstatus <b>ns</b>
  1909. * whose name is <b>param_name</b>. If <b>ns</b> is NULL, try loading the
  1910. * latest consensus ourselves. Return <b>default_val</b> if no latest
  1911. * consensus, or if it has no parameter called <b>param_name</b>.
  1912. * Make sure the value parsed from the consensus is at least
  1913. * <b>min_val</b> and at most <b>max_val</b> and raise/cap the parsed value
  1914. * if necessary. */
  1915. int32_t
  1916. networkstatus_get_param(const networkstatus_t *ns, const char *param_name,
  1917. int32_t default_val, int32_t min_val, int32_t max_val)
  1918. {
  1919. if (!ns) /* if they pass in null, go find it ourselves */
  1920. ns = networkstatus_get_latest_consensus();
  1921. if (!ns || !ns->net_params)
  1922. return default_val;
  1923. return get_net_param_from_list(ns->net_params, param_name,
  1924. default_val, min_val, max_val);
  1925. }
  1926. /**
  1927. * Retrieve the consensus parameter that governs the
  1928. * fixed-point precision of our network balancing 'bandwidth-weights'
  1929. * (which are themselves integer consensus values). We divide them
  1930. * by this value and ensure they never exceed this value.
  1931. */
  1932. int
  1933. networkstatus_get_weight_scale_param(networkstatus_t *ns)
  1934. {
  1935. return networkstatus_get_param(ns, "bwweightscale",
  1936. BW_WEIGHT_SCALE,
  1937. BW_MIN_WEIGHT_SCALE,
  1938. BW_MAX_WEIGHT_SCALE);
  1939. }
  1940. /** Return the value of a integer bw weight parameter from the networkstatus
  1941. * <b>ns</b> whose name is <b>weight_name</b>. If <b>ns</b> is NULL, try
  1942. * loading the latest consensus ourselves. Return <b>default_val</b> if no
  1943. * latest consensus, or if it has no parameter called <b>weight_name</b>. */
  1944. int32_t
  1945. networkstatus_get_bw_weight(networkstatus_t *ns, const char *weight_name,
  1946. int32_t default_val)
  1947. {
  1948. int32_t param;
  1949. int max;
  1950. if (!ns) /* if they pass in null, go find it ourselves */
  1951. ns = networkstatus_get_latest_consensus();
  1952. if (!ns || !ns->weight_params)
  1953. return default_val;
  1954. max = networkstatus_get_weight_scale_param(ns);
  1955. param = get_net_param_from_list(ns->weight_params, weight_name,
  1956. default_val, -1,
  1957. BW_MAX_WEIGHT_SCALE);
  1958. if (param > max) {
  1959. log_warn(LD_DIR, "Value of consensus weight %s was too large, capping "
  1960. "to %d", weight_name, max);
  1961. param = max;
  1962. }
  1963. return param;
  1964. }
  1965. /** Return the name of the consensus flavor <b>flav</b> as used to identify
  1966. * the flavor in directory documents. */
  1967. const char *
  1968. networkstatus_get_flavor_name(consensus_flavor_t flav)
  1969. {
  1970. switch (flav) {
  1971. case FLAV_NS:
  1972. return "ns";
  1973. case FLAV_MICRODESC:
  1974. return "microdesc";
  1975. default:
  1976. tor_fragile_assert();
  1977. return "??";
  1978. }
  1979. }
  1980. /** Return the consensus_flavor_t value for the flavor called <b>flavname</b>,
  1981. * or -1 if the flavor is not recognized. */
  1982. int
  1983. networkstatus_parse_flavor_name(const char *flavname)
  1984. {
  1985. if (!strcmp(flavname, "ns"))
  1986. return FLAV_NS;
  1987. else if (!strcmp(flavname, "microdesc"))
  1988. return FLAV_MICRODESC;
  1989. else
  1990. return -1;
  1991. }
  1992. /** Return 0 if this routerstatus is obsolete, too new, isn't
  1993. * running, or otherwise not a descriptor that we would make any
  1994. * use of even if we had it. Else return 1. */
  1995. int
  1996. client_would_use_router(const routerstatus_t *rs, time_t now,
  1997. const or_options_t *options)
  1998. {
  1999. if (!rs->is_flagged_running && !options->FetchUselessDescriptors) {
  2000. /* If we had this router descriptor, we wouldn't even bother using it.
  2001. * But, if we want to have a complete list, fetch it anyway. */
  2002. return 0;
  2003. }
  2004. if (rs->published_on + options->TestingEstimatedDescriptorPropagationTime
  2005. > now) {
  2006. /* Most caches probably don't have this descriptor yet. */
  2007. return 0;
  2008. }
  2009. if (rs->published_on + OLD_ROUTER_DESC_MAX_AGE < now) {
  2010. /* We'd drop it immediately for being too old. */
  2011. return 0;
  2012. }
  2013. return 1;
  2014. }
  2015. /** If <b>question</b> is a string beginning with "ns/" in a format the
  2016. * control interface expects for a GETINFO question, set *<b>answer</b> to a
  2017. * newly-allocated string containing networkstatus lines for the appropriate
  2018. * ORs. Return 0 on success, -1 on unrecognized question format. */
  2019. int
  2020. getinfo_helper_networkstatus(control_connection_t *conn,
  2021. const char *question, char **answer,
  2022. const char **errmsg)
  2023. {
  2024. const routerstatus_t *status;
  2025. (void) conn;
  2026. if (!current_consensus) {
  2027. *answer = tor_strdup("");
  2028. return 0;
  2029. }
  2030. if (!strcmp(question, "ns/all")) {
  2031. smartlist_t *statuses = smartlist_new();
  2032. SMARTLIST_FOREACH(current_consensus->routerstatus_list,
  2033. const routerstatus_t *, rs,
  2034. {
  2035. smartlist_add(statuses, networkstatus_getinfo_helper_single(rs));
  2036. });
  2037. *answer = smartlist_join_strings(statuses, "", 0, NULL);
  2038. SMARTLIST_FOREACH(statuses, char *, cp, tor_free(cp));
  2039. smartlist_free(statuses);
  2040. return 0;
  2041. } else if (!strcmpstart(question, "ns/id/")) {
  2042. char d[DIGEST_LEN];
  2043. const char *q = question + 6;
  2044. if (*q == '$')
  2045. ++q;
  2046. if (base16_decode(d, DIGEST_LEN, q, strlen(q))) {
  2047. *errmsg = "Data not decodeable as hex";
  2048. return -1;
  2049. }
  2050. status = router_get_consensus_status_by_id(d);
  2051. } else if (!strcmpstart(question, "ns/name/")) {
  2052. status = router_get_consensus_status_by_nickname(question+8, 0);
  2053. } else if (!strcmpstart(question, "ns/purpose/")) {
  2054. *answer = networkstatus_getinfo_by_purpose(question+11, time(NULL));
  2055. return *answer ? 0 : -1;
  2056. } else if (!strcmp(question, "consensus/packages")) {
  2057. const networkstatus_t *ns = networkstatus_get_latest_consensus();
  2058. if (ns && ns->package_lines)
  2059. *answer = smartlist_join_strings(ns->package_lines, "\n", 0, NULL);
  2060. else
  2061. *errmsg = "No consensus available";
  2062. return *answer ? 0 : -1;
  2063. } else if (!strcmp(question, "consensus/valid-after") ||
  2064. !strcmp(question, "consensus/fresh-until") ||
  2065. !strcmp(question, "consensus/valid-until")) {
  2066. const networkstatus_t *ns = networkstatus_get_latest_consensus();
  2067. if (ns) {
  2068. time_t t;
  2069. if (!strcmp(question, "consensus/valid-after"))
  2070. t = ns->valid_after;
  2071. else if (!strcmp(question, "consensus/fresh-until"))
  2072. t = ns->fresh_until;
  2073. else
  2074. t = ns->valid_until;
  2075. char tbuf[ISO_TIME_LEN+1];
  2076. format_iso_time(tbuf, t);
  2077. *answer = tor_strdup(tbuf);
  2078. } else {
  2079. *errmsg = "No consensus available";
  2080. }
  2081. return *answer ? 0 : -1;
  2082. } else {
  2083. return 0;
  2084. }
  2085. if (status)
  2086. *answer = networkstatus_getinfo_helper_single(status);
  2087. return 0;
  2088. }
  2089. /** Free all storage held locally in this module. */
  2090. void
  2091. networkstatus_free_all(void)
  2092. {
  2093. int i;
  2094. networkstatus_vote_free(current_ns_consensus);
  2095. networkstatus_vote_free(current_md_consensus);
  2096. current_md_consensus = current_ns_consensus = NULL;
  2097. for (i=0; i < N_CONSENSUS_FLAVORS; ++i) {
  2098. consensus_waiting_for_certs_t *waiting = &consensus_waiting_for_certs[i];
  2099. if (waiting->consensus) {
  2100. networkstatus_vote_free(waiting->consensus);
  2101. waiting->consensus = NULL;
  2102. }
  2103. tor_free(waiting->body);
  2104. }
  2105. strmap_free(named_server_map, tor_free_);
  2106. strmap_free(unnamed_server_map, NULL);
  2107. }