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_bootstrapping(
  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 not all connections are "connecting", then some are
  792. * downloading. We want to have at most one downloading at a time. */
  793. if (connect_consens_conn_count < consens_conn_count) {
  794. continue;
  795. }
  796. /* Make multiple connections for a bootstrap consensus download. */
  797. update_consensus_bootstrap_multiple_downloads(now, options,
  798. we_are_bootstrapping);
  799. } else {
  800. /* Check if we failed downloading a consensus too recently */
  801. int max_dl_tries = consensus_max_download_tries(options,
  802. we_are_bootstrapping);
  803. /* Let's make sure we remembered to update consensus_dl_status */
  804. tor_assert(consensus_dl_status[i].schedule == DL_SCHED_CONSENSUS);
  805. if (!download_status_is_ready(&consensus_dl_status[i],
  806. now,
  807. max_dl_tries)) {
  808. continue;
  809. }
  810. /* Check if we're waiting for certificates to download */
  811. if (check_consensus_waiting_for_certs(i, now, &consensus_dl_status[i]))
  812. continue;
  813. /* Try the requested attempt */
  814. log_info(LD_DIR, "Launching %s standard networkstatus consensus "
  815. "download.", networkstatus_get_flavor_name(i));
  816. directory_get_from_dirserver(DIR_PURPOSE_FETCH_CONSENSUS,
  817. ROUTER_PURPOSE_GENERAL, resource,
  818. PDS_RETRY_IF_NO_SERVERS,
  819. consensus_dl_status[i].want_authority);
  820. }
  821. }
  822. }
  823. /** When we're bootstrapping, launch one or more consensus download
  824. * connections, if schedule indicates connection(s) should be made after now.
  825. * If is_authority, connect to an authority, otherwise, use a fallback
  826. * directory mirror.
  827. */
  828. static void
  829. update_consensus_bootstrap_attempt_downloads(
  830. time_t now,
  831. const or_options_t *options,
  832. int we_are_bootstrapping,
  833. download_status_t *dls,
  834. download_want_authority_t want_authority)
  835. {
  836. int max_dl_tries = consensus_max_download_tries(options,
  837. we_are_bootstrapping);
  838. const char *resource = networkstatus_get_flavor_name(
  839. usable_consensus_flavor());
  840. /* Let's make sure we remembered to update schedule */
  841. tor_assert(dls->schedule == DL_SCHED_CONSENSUS);
  842. /* Allow for multiple connections in the same second, if the schedule value
  843. * is 0. */
  844. while (download_status_is_ready(dls, now, max_dl_tries)) {
  845. log_info(LD_DIR, "Launching %s bootstrap %s networkstatus consensus "
  846. "download.", resource, (want_authority == DL_WANT_AUTHORITY
  847. ? "authority"
  848. : "mirror"));
  849. directory_get_from_dirserver(DIR_PURPOSE_FETCH_CONSENSUS,
  850. ROUTER_PURPOSE_GENERAL, resource,
  851. PDS_RETRY_IF_NO_SERVERS, want_authority);
  852. /* schedule the next attempt */
  853. download_status_increment_attempt(dls, resource, now);
  854. }
  855. }
  856. /** If we're bootstrapping, check the connection schedules and see if we want
  857. * to make additional, potentially concurrent, consensus download
  858. * connections.
  859. * Only call when bootstrapping, and when we want to make additional
  860. * connections. Only nodes that satisfy
  861. * networkstatus_consensus_can_use_multiple_directories make additional
  862. * connections.
  863. */
  864. static void
  865. update_consensus_bootstrap_multiple_downloads(time_t now,
  866. const or_options_t *options,
  867. int we_are_bootstrapping)
  868. {
  869. const int usable_flavor = usable_consensus_flavor();
  870. /* make sure we can use multiple connections */
  871. if (!networkstatus_consensus_can_use_multiple_directories(options)) {
  872. return;
  873. }
  874. /* If we've managed to validate a usable consensus, don't make additional
  875. * connections. */
  876. if (!we_are_bootstrapping) {
  877. return;
  878. }
  879. /* Launch concurrent consensus download attempt(s) based on the mirror and
  880. * authority schedules. Try the mirror first - this makes it slightly more
  881. * likely that we'll connect to the fallback first, and then end the
  882. * authority connection attempt. */
  883. /* If a consensus download fails because it's waiting for certificates,
  884. * we'll fail both the authority and fallback schedules. This is better than
  885. * failing only one of the schedules, and having the other continue
  886. * unchecked.
  887. */
  888. /* If we don't have or can't use extra fallbacks, don't try them. */
  889. if (networkstatus_consensus_can_use_extra_fallbacks(options)) {
  890. download_status_t *dls_f =
  891. &consensus_bootstrap_dl_status[CONSENSUS_BOOTSTRAP_SOURCE_ANY_DIRSERVER];
  892. if (!check_consensus_waiting_for_certs(usable_flavor, now, dls_f)) {
  893. /* During bootstrap, DL_WANT_ANY_DIRSERVER means "use fallbacks". */
  894. update_consensus_bootstrap_attempt_downloads(now, options,
  895. we_are_bootstrapping, dls_f,
  896. DL_WANT_ANY_DIRSERVER);
  897. }
  898. }
  899. /* Now try an authority. */
  900. download_status_t *dls_a =
  901. &consensus_bootstrap_dl_status[CONSENSUS_BOOTSTRAP_SOURCE_AUTHORITY];
  902. if (!check_consensus_waiting_for_certs(usable_flavor, now, dls_a)) {
  903. update_consensus_bootstrap_attempt_downloads(now, options,
  904. we_are_bootstrapping, dls_a,
  905. DL_WANT_AUTHORITY);
  906. }
  907. }
  908. /** Called when an attempt to download a consensus fails: note that the
  909. * failure occurred, and possibly retry. */
  910. void
  911. networkstatus_consensus_download_failed(int status_code, const char *flavname)
  912. {
  913. int flav = networkstatus_parse_flavor_name(flavname);
  914. if (flav >= 0) {
  915. tor_assert(flav < N_CONSENSUS_FLAVORS);
  916. /* XXXX handle unrecognized flavors */
  917. download_status_failed(&consensus_dl_status[flav], status_code);
  918. /* Retry immediately, if appropriate. */
  919. update_consensus_networkstatus_downloads(time(NULL));
  920. }
  921. }
  922. /** How long do we (as a cache) wait after a consensus becomes non-fresh
  923. * before trying to fetch another? */
  924. #define CONSENSUS_MIN_SECONDS_BEFORE_CACHING 120
  925. /** Update the time at which we'll consider replacing the current
  926. * consensus of flavor <b>flav</b> */
  927. static void
  928. update_consensus_networkstatus_fetch_time_impl(time_t now, int flav)
  929. {
  930. const or_options_t *options = get_options();
  931. networkstatus_t *c = networkstatus_get_latest_consensus_by_flavor(flav);
  932. const char *flavor = networkstatus_get_flavor_name(flav);
  933. if (! we_want_to_fetch_flavor(get_options(), flav))
  934. return;
  935. if (c && c->valid_after <= now && now <= c->valid_until) {
  936. long dl_interval;
  937. long interval = c->fresh_until - c->valid_after;
  938. long min_sec_before_caching = CONSENSUS_MIN_SECONDS_BEFORE_CACHING;
  939. time_t start;
  940. if (min_sec_before_caching > interval/16) {
  941. /* Usually we allow 2-minutes slop factor in case clocks get
  942. desynchronized a little. If we're on a private network with
  943. a crazy-fast voting interval, though, 2 minutes may be too
  944. much. */
  945. min_sec_before_caching = interval/16;
  946. /* make sure we always delay by at least a second before caching */
  947. if (min_sec_before_caching == 0) {
  948. min_sec_before_caching = 1;
  949. }
  950. }
  951. if (directory_fetches_dir_info_early(options)) {
  952. /* We want to cache the next one at some point after this one
  953. * is no longer fresh... */
  954. start = (time_t)(c->fresh_until + min_sec_before_caching);
  955. /* Some clients may need the consensus sooner than others. */
  956. if (options->FetchDirInfoExtraEarly || authdir_mode_v3(options)) {
  957. dl_interval = 60;
  958. if (min_sec_before_caching + dl_interval > interval)
  959. dl_interval = interval/2;
  960. } else {
  961. /* But only in the first half-interval after that. */
  962. dl_interval = interval/2;
  963. }
  964. } else {
  965. /* We're an ordinary client, a bridge, or a hidden service.
  966. * Give all the caches enough time to download the consensus. */
  967. start = (time_t)(c->fresh_until + (interval*3)/4);
  968. /* But download the next one well before this one is expired. */
  969. dl_interval = ((c->valid_until - start) * 7 )/ 8;
  970. /* If we're a bridge user, make use of the numbers we just computed
  971. * to choose the rest of the interval *after* them. */
  972. if (directory_fetches_dir_info_later(options)) {
  973. /* Give all the *clients* enough time to download the consensus. */
  974. start = (time_t)(start + dl_interval + min_sec_before_caching);
  975. /* But try to get it before ours actually expires. */
  976. dl_interval = (c->valid_until - start) - min_sec_before_caching;
  977. }
  978. }
  979. /* catch low dl_interval in crazy-fast networks */
  980. if (dl_interval < 1)
  981. dl_interval = 1;
  982. /* catch late start in crazy-fast networks */
  983. if (start+dl_interval >= c->valid_until)
  984. start = c->valid_until - dl_interval - 1;
  985. log_debug(LD_DIR,
  986. "fresh_until: %ld start: %ld "
  987. "dl_interval: %ld valid_until: %ld ",
  988. (long)c->fresh_until, (long)start, dl_interval,
  989. (long)c->valid_until);
  990. /* We must not try to replace c while it's still fresh: */
  991. tor_assert(c->fresh_until < start);
  992. /* We must download the next one before c is invalid: */
  993. tor_assert(start+dl_interval < c->valid_until);
  994. time_to_download_next_consensus[flav] =
  995. start + crypto_rand_int((int)dl_interval);
  996. {
  997. char tbuf1[ISO_TIME_LEN+1];
  998. char tbuf2[ISO_TIME_LEN+1];
  999. char tbuf3[ISO_TIME_LEN+1];
  1000. format_local_iso_time(tbuf1, c->fresh_until);
  1001. format_local_iso_time(tbuf2, c->valid_until);
  1002. format_local_iso_time(tbuf3, time_to_download_next_consensus[flav]);
  1003. log_info(LD_DIR, "Live %s consensus %s the most recent until %s and "
  1004. "will expire at %s; fetching the next one at %s.",
  1005. flavor, (c->fresh_until > now) ? "will be" : "was",
  1006. tbuf1, tbuf2, tbuf3);
  1007. }
  1008. } else {
  1009. time_to_download_next_consensus[flav] = now;
  1010. log_info(LD_DIR, "No live %s consensus; we should fetch one immediately.",
  1011. flavor);
  1012. }
  1013. }
  1014. /** Update the time at which we'll consider replacing the current
  1015. * consensus of flavor 'flavor' */
  1016. void
  1017. update_consensus_networkstatus_fetch_time(time_t now)
  1018. {
  1019. int i;
  1020. for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
  1021. if (we_want_to_fetch_flavor(get_options(), i))
  1022. update_consensus_networkstatus_fetch_time_impl(now, i);
  1023. }
  1024. }
  1025. /** Return 1 if there's a reason we shouldn't try any directory
  1026. * fetches yet (e.g. we demand bridges and none are yet known).
  1027. * Else return 0.
  1028. * If we return 1 and <b>msg_out</b> is provided, set <b>msg_out</b>
  1029. * to an explanation of why directory fetches are delayed. (If we
  1030. * return 0, we set msg_out to NULL.)
  1031. */
  1032. int
  1033. should_delay_dir_fetches(const or_options_t *options, const char **msg_out)
  1034. {
  1035. if (msg_out) {
  1036. *msg_out = NULL;
  1037. }
  1038. if (options->DisableNetwork) {
  1039. if (msg_out) {
  1040. *msg_out = "DisableNetwork is set.";
  1041. }
  1042. log_info(LD_DIR, "Delaying dir fetches (DisableNetwork is set)");
  1043. return 1;
  1044. }
  1045. if (options->UseBridges) {
  1046. if (!any_bridge_descriptors_known()) {
  1047. if (msg_out) {
  1048. *msg_out = "No running bridges";
  1049. }
  1050. log_info(LD_DIR, "Delaying dir fetches (no running bridges known)");
  1051. return 1;
  1052. }
  1053. if (pt_proxies_configuration_pending()) {
  1054. if (msg_out) {
  1055. *msg_out = "Pluggable transport proxies still configuring";
  1056. }
  1057. log_info(LD_DIR, "Delaying dir fetches (pt proxies still configuring)");
  1058. return 1;
  1059. }
  1060. }
  1061. return 0;
  1062. }
  1063. /** Launch requests for networkstatus documents and authority certificates as
  1064. * appropriate. */
  1065. void
  1066. update_networkstatus_downloads(time_t now)
  1067. {
  1068. const or_options_t *options = get_options();
  1069. if (should_delay_dir_fetches(options, NULL))
  1070. return;
  1071. update_consensus_networkstatus_downloads(now);
  1072. update_certificate_downloads(now);
  1073. }
  1074. /** Launch requests as appropriate for missing directory authority
  1075. * certificates. */
  1076. void
  1077. update_certificate_downloads(time_t now)
  1078. {
  1079. int i;
  1080. for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
  1081. if (consensus_waiting_for_certs[i].consensus)
  1082. authority_certs_fetch_missing(consensus_waiting_for_certs[i].consensus,
  1083. now, NULL);
  1084. }
  1085. if (current_ns_consensus)
  1086. authority_certs_fetch_missing(current_ns_consensus, now, NULL);
  1087. if (current_md_consensus)
  1088. authority_certs_fetch_missing(current_md_consensus, now, NULL);
  1089. }
  1090. /** Return 1 if we have a consensus but we don't have enough certificates
  1091. * to start using it yet. */
  1092. int
  1093. consensus_is_waiting_for_certs(void)
  1094. {
  1095. return consensus_waiting_for_certs[usable_consensus_flavor()].consensus
  1096. ? 1 : 0;
  1097. }
  1098. /** Return the most recent consensus that we have downloaded, or NULL if we
  1099. * don't have one. */
  1100. networkstatus_t *
  1101. networkstatus_get_latest_consensus(void)
  1102. {
  1103. return current_consensus;
  1104. }
  1105. /** Return the latest consensus we have whose flavor matches <b>f</b>, or NULL
  1106. * if we don't have one. */
  1107. MOCK_IMPL(networkstatus_t *,
  1108. networkstatus_get_latest_consensus_by_flavor,(consensus_flavor_t f))
  1109. {
  1110. if (f == FLAV_NS)
  1111. return current_ns_consensus;
  1112. else if (f == FLAV_MICRODESC)
  1113. return current_md_consensus;
  1114. else {
  1115. tor_assert(0);
  1116. return NULL;
  1117. }
  1118. }
  1119. /** Return the most recent consensus that we have downloaded, or NULL if it is
  1120. * no longer live. */
  1121. networkstatus_t *
  1122. networkstatus_get_live_consensus(time_t now)
  1123. {
  1124. if (current_consensus &&
  1125. current_consensus->valid_after <= now &&
  1126. now <= current_consensus->valid_until)
  1127. return current_consensus;
  1128. else
  1129. return NULL;
  1130. }
  1131. /* XXXX remove this in favor of get_live_consensus. But actually,
  1132. * leave something like it for bridge users, who need to not totally
  1133. * lose if they spend a while fetching a new consensus. */
  1134. /** As networkstatus_get_live_consensus(), but is way more tolerant of expired
  1135. * consensuses. */
  1136. networkstatus_t *
  1137. networkstatus_get_reasonably_live_consensus(time_t now, int flavor)
  1138. {
  1139. #define REASONABLY_LIVE_TIME (24*60*60)
  1140. networkstatus_t *consensus =
  1141. networkstatus_get_latest_consensus_by_flavor(flavor);
  1142. if (consensus &&
  1143. consensus->valid_after <= now &&
  1144. now <= consensus->valid_until+REASONABLY_LIVE_TIME)
  1145. return consensus;
  1146. else
  1147. return NULL;
  1148. }
  1149. /** Check if we're bootstrapping a consensus download. This means that we are
  1150. * only using the authorities and fallback directory mirrors to download the
  1151. * consensus flavour we'll use. */
  1152. int
  1153. networkstatus_consensus_is_bootstrapping(time_t now)
  1154. {
  1155. /* If we don't have a consensus, we must still be bootstrapping */
  1156. return !networkstatus_get_reasonably_live_consensus(
  1157. now,
  1158. usable_consensus_flavor());
  1159. }
  1160. /** Check if we can use multiple directories for a consensus download.
  1161. * Only clients (including bridge relays, which act like clients) benefit
  1162. * from multiple simultaneous consensus downloads. */
  1163. int
  1164. networkstatus_consensus_can_use_multiple_directories(
  1165. const or_options_t *options)
  1166. {
  1167. /* If we are a client, bridge, bridge client, or hidden service */
  1168. return !public_server_mode(options);
  1169. }
  1170. /** Check if we can use fallback directory mirrors for a consensus download.
  1171. * If we have fallbacks and don't want to fetch from the authorities,
  1172. * we can use them. */
  1173. int
  1174. networkstatus_consensus_can_use_extra_fallbacks(const or_options_t *options)
  1175. {
  1176. /* The list length comparisons are a quick way to check if we have any
  1177. * non-authority fallback directories. If we ever have any authorities that
  1178. * aren't fallback directories, we will need to change this code. */
  1179. tor_assert(smartlist_len(router_get_fallback_dir_servers())
  1180. >= smartlist_len(router_get_trusted_dir_servers()));
  1181. /* If we don't fetch from the authorities, and we have additional mirrors,
  1182. * we can use them. */
  1183. return (!directory_fetches_from_authorities(options)
  1184. && (smartlist_len(router_get_fallback_dir_servers())
  1185. > smartlist_len(router_get_trusted_dir_servers())));
  1186. }
  1187. /* Check if there is more than 1 consensus connection retrieving the usable
  1188. * consensus flavor. If so, return 1, if not, return 0.
  1189. *
  1190. * During normal operation, Tor only makes one consensus download
  1191. * connection. But clients can make multiple simultaneous consensus
  1192. * connections to improve bootstrap speed and reliability.
  1193. *
  1194. * If there is more than one connection, we must have connections left
  1195. * over from bootstrapping. However, some of the connections may have
  1196. * completed and been cleaned up, so it is not sufficient to check the
  1197. * return value of this function to see if a client could make multiple
  1198. * bootstrap connections. Use
  1199. * networkstatus_consensus_can_use_multiple_directories()
  1200. * and networkstatus_consensus_is_bootstrapping(). */
  1201. int
  1202. networkstatus_consensus_has_excess_connections(void)
  1203. {
  1204. const char *usable_resource = networkstatus_get_flavor_name(
  1205. usable_consensus_flavor());
  1206. const int consens_conn_usable_count =
  1207. connection_dir_count_by_purpose_and_resource(
  1208. DIR_PURPOSE_FETCH_CONSENSUS,
  1209. usable_resource);
  1210. /* The maximum number of connections we want downloading a usable consensus
  1211. * Always 1, whether bootstrapping or not. */
  1212. const int max_expected_consens_conn_usable_count = 1;
  1213. if (consens_conn_usable_count > max_expected_consens_conn_usable_count) {
  1214. return 1;
  1215. }
  1216. return 0;
  1217. }
  1218. /* Is tor currently downloading a consensus of the usable flavor? */
  1219. int
  1220. networkstatus_consensus_is_downloading_usable_flavor(void)
  1221. {
  1222. const char *usable_resource = networkstatus_get_flavor_name(
  1223. usable_consensus_flavor());
  1224. const int consens_conn_usable_count =
  1225. connection_dir_count_by_purpose_and_resource(
  1226. DIR_PURPOSE_FETCH_CONSENSUS,
  1227. usable_resource);
  1228. const int connect_consens_conn_usable_count =
  1229. connection_dir_count_by_purpose_resource_and_state(
  1230. DIR_PURPOSE_FETCH_CONSENSUS,
  1231. usable_resource,
  1232. DIR_CONN_STATE_CONNECTING);
  1233. if (connect_consens_conn_usable_count < consens_conn_usable_count) {
  1234. return 1;
  1235. }
  1236. return 0;
  1237. }
  1238. /** Given two router status entries for the same router identity, return 1 if
  1239. * if the contents have changed between them. Otherwise, return 0. */
  1240. static int
  1241. routerstatus_has_changed(const routerstatus_t *a, const routerstatus_t *b)
  1242. {
  1243. tor_assert(tor_memeq(a->identity_digest, b->identity_digest, DIGEST_LEN));
  1244. return strcmp(a->nickname, b->nickname) ||
  1245. fast_memneq(a->descriptor_digest, b->descriptor_digest, DIGEST_LEN) ||
  1246. a->addr != b->addr ||
  1247. a->or_port != b->or_port ||
  1248. a->dir_port != b->dir_port ||
  1249. a->is_authority != b->is_authority ||
  1250. a->is_exit != b->is_exit ||
  1251. a->is_stable != b->is_stable ||
  1252. a->is_fast != b->is_fast ||
  1253. a->is_flagged_running != b->is_flagged_running ||
  1254. a->is_named != b->is_named ||
  1255. a->is_unnamed != b->is_unnamed ||
  1256. a->is_valid != b->is_valid ||
  1257. a->is_possible_guard != b->is_possible_guard ||
  1258. a->is_bad_exit != b->is_bad_exit ||
  1259. a->is_hs_dir != b->is_hs_dir ||
  1260. a->version_known != b->version_known;
  1261. }
  1262. /** Notify controllers of any router status entries that changed between
  1263. * <b>old_c</b> and <b>new_c</b>. */
  1264. static void
  1265. notify_control_networkstatus_changed(const networkstatus_t *old_c,
  1266. const networkstatus_t *new_c)
  1267. {
  1268. smartlist_t *changed;
  1269. if (old_c == new_c)
  1270. return;
  1271. /* tell the controller exactly which relays are still listed, as well
  1272. * as what they're listed as */
  1273. control_event_newconsensus(new_c);
  1274. if (!control_event_is_interesting(EVENT_NS))
  1275. return;
  1276. if (!old_c) {
  1277. control_event_networkstatus_changed(new_c->routerstatus_list);
  1278. return;
  1279. }
  1280. changed = smartlist_new();
  1281. SMARTLIST_FOREACH_JOIN(
  1282. old_c->routerstatus_list, const routerstatus_t *, rs_old,
  1283. new_c->routerstatus_list, const routerstatus_t *, rs_new,
  1284. tor_memcmp(rs_old->identity_digest,
  1285. rs_new->identity_digest, DIGEST_LEN),
  1286. smartlist_add(changed, (void*) rs_new)) {
  1287. if (routerstatus_has_changed(rs_old, rs_new))
  1288. smartlist_add(changed, (void*)rs_new);
  1289. } SMARTLIST_FOREACH_JOIN_END(rs_old, rs_new);
  1290. control_event_networkstatus_changed(changed);
  1291. smartlist_free(changed);
  1292. }
  1293. /** Copy all the ancillary information (like router download status and so on)
  1294. * from <b>old_c</b> to <b>new_c</b>. */
  1295. static void
  1296. networkstatus_copy_old_consensus_info(networkstatus_t *new_c,
  1297. const networkstatus_t *old_c)
  1298. {
  1299. if (old_c == new_c)
  1300. return;
  1301. if (!old_c || !smartlist_len(old_c->routerstatus_list))
  1302. return;
  1303. SMARTLIST_FOREACH_JOIN(old_c->routerstatus_list, routerstatus_t *, rs_old,
  1304. new_c->routerstatus_list, routerstatus_t *, rs_new,
  1305. tor_memcmp(rs_old->identity_digest,
  1306. rs_new->identity_digest, DIGEST_LEN),
  1307. STMT_NIL) {
  1308. /* Okay, so we're looking at the same identity. */
  1309. rs_new->last_dir_503_at = rs_old->last_dir_503_at;
  1310. if (tor_memeq(rs_old->descriptor_digest, rs_new->descriptor_digest,
  1311. DIGEST256_LEN)) {
  1312. /* And the same descriptor too! */
  1313. memcpy(&rs_new->dl_status, &rs_old->dl_status,sizeof(download_status_t));
  1314. }
  1315. } SMARTLIST_FOREACH_JOIN_END(rs_old, rs_new);
  1316. }
  1317. #ifdef TOR_UNIT_TESTS
  1318. /**Accept a <b>flavor</b> consensus <b>c</b> without any additional
  1319. * validation. This is exclusively for unit tests.
  1320. * We copy any ancillary information from a pre-existing consensus
  1321. * and then free the current one and replace it with the newly
  1322. * provided instance. Returns -1 on unrecognized flavor, 0 otherwise.
  1323. */
  1324. int
  1325. networkstatus_set_current_consensus_from_ns(networkstatus_t *c,
  1326. const char *flavor)
  1327. {
  1328. int flav = networkstatus_parse_flavor_name(flavor);
  1329. switch (flav) {
  1330. case FLAV_NS:
  1331. if (current_ns_consensus) {
  1332. networkstatus_copy_old_consensus_info(c, current_ns_consensus);
  1333. networkstatus_vote_free(current_ns_consensus);
  1334. }
  1335. current_ns_consensus = c;
  1336. break;
  1337. case FLAV_MICRODESC:
  1338. if (current_md_consensus) {
  1339. networkstatus_copy_old_consensus_info(c, current_md_consensus);
  1340. networkstatus_vote_free(current_md_consensus);
  1341. }
  1342. current_md_consensus = c;
  1343. break;
  1344. }
  1345. return current_md_consensus ? 0 : -1;
  1346. }
  1347. #endif //TOR_UNIT_TESTS
  1348. /** Try to replace the current cached v3 networkstatus with the one in
  1349. * <b>consensus</b>. If we don't have enough certificates to validate it,
  1350. * store it in consensus_waiting_for_certs and launch a certificate fetch.
  1351. *
  1352. * If flags & NSSET_FROM_CACHE, this networkstatus has come from the disk
  1353. * cache. If flags & NSSET_WAS_WAITING_FOR_CERTS, this networkstatus was
  1354. * already received, but we were waiting for certificates on it. If flags &
  1355. * NSSET_DONT_DOWNLOAD_CERTS, do not launch certificate downloads as needed.
  1356. * If flags & NSSET_ACCEPT_OBSOLETE, then we should be willing to take this
  1357. * consensus, even if it comes from many days in the past.
  1358. *
  1359. * If source_dir is non-NULL, it's the identity digest for a directory that
  1360. * we've just successfully retrieved a consensus or certificates from, so try
  1361. * it first to fetch any missing certificates.
  1362. *
  1363. * Return 0 on success, <0 on failure. On failure, caller should increment
  1364. * the failure count as appropriate.
  1365. *
  1366. * We return -1 for mild failures that don't need to be reported to the
  1367. * user, and -2 for more serious problems.
  1368. */
  1369. int
  1370. networkstatus_set_current_consensus(const char *consensus,
  1371. const char *flavor,
  1372. unsigned flags,
  1373. const char *source_dir)
  1374. {
  1375. networkstatus_t *c=NULL;
  1376. int r, result = -1;
  1377. time_t now = time(NULL);
  1378. const or_options_t *options = get_options();
  1379. char *unverified_fname = NULL, *consensus_fname = NULL;
  1380. int flav = networkstatus_parse_flavor_name(flavor);
  1381. const unsigned from_cache = flags & NSSET_FROM_CACHE;
  1382. const unsigned was_waiting_for_certs = flags & NSSET_WAS_WAITING_FOR_CERTS;
  1383. const unsigned dl_certs = !(flags & NSSET_DONT_DOWNLOAD_CERTS);
  1384. const unsigned accept_obsolete = flags & NSSET_ACCEPT_OBSOLETE;
  1385. const unsigned require_flavor = flags & NSSET_REQUIRE_FLAVOR;
  1386. const common_digests_t *current_digests = NULL;
  1387. consensus_waiting_for_certs_t *waiting = NULL;
  1388. time_t current_valid_after = 0;
  1389. int free_consensus = 1; /* Free 'c' at the end of the function */
  1390. int old_ewma_enabled;
  1391. if (flav < 0) {
  1392. /* XXXX we don't handle unrecognized flavors yet. */
  1393. log_warn(LD_BUG, "Unrecognized consensus flavor %s", flavor);
  1394. return -2;
  1395. }
  1396. /* Make sure it's parseable. */
  1397. c = networkstatus_parse_vote_from_string(consensus, NULL, NS_TYPE_CONSENSUS);
  1398. if (!c) {
  1399. log_warn(LD_DIR, "Unable to parse networkstatus consensus");
  1400. result = -2;
  1401. goto done;
  1402. }
  1403. if ((int)c->flavor != flav) {
  1404. /* This wasn't the flavor we thought we were getting. */
  1405. if (require_flavor) {
  1406. log_warn(LD_DIR, "Got consensus with unexpected flavor %s (wanted %s)",
  1407. networkstatus_get_flavor_name(c->flavor), flavor);
  1408. goto done;
  1409. }
  1410. flav = c->flavor;
  1411. flavor = networkstatus_get_flavor_name(flav);
  1412. }
  1413. if (flav != usable_consensus_flavor() &&
  1414. !directory_caches_dir_info(options)) {
  1415. /* This consensus is totally boring to us: we won't use it, and we won't
  1416. * serve it. Drop it. */
  1417. goto done;
  1418. }
  1419. if (from_cache && !accept_obsolete &&
  1420. c->valid_until < now-OLD_ROUTER_DESC_MAX_AGE) {
  1421. log_info(LD_DIR, "Loaded an expired consensus. Discarding.");
  1422. goto done;
  1423. }
  1424. if (!strcmp(flavor, "ns")) {
  1425. consensus_fname = get_datadir_fname("cached-consensus");
  1426. unverified_fname = get_datadir_fname("unverified-consensus");
  1427. if (current_ns_consensus) {
  1428. current_digests = &current_ns_consensus->digests;
  1429. current_valid_after = current_ns_consensus->valid_after;
  1430. }
  1431. } else if (!strcmp(flavor, "microdesc")) {
  1432. consensus_fname = get_datadir_fname("cached-microdesc-consensus");
  1433. unverified_fname = get_datadir_fname("unverified-microdesc-consensus");
  1434. if (current_md_consensus) {
  1435. current_digests = &current_md_consensus->digests;
  1436. current_valid_after = current_md_consensus->valid_after;
  1437. }
  1438. } else {
  1439. cached_dir_t *cur;
  1440. char buf[128];
  1441. tor_snprintf(buf, sizeof(buf), "cached-%s-consensus", flavor);
  1442. consensus_fname = get_datadir_fname(buf);
  1443. tor_snprintf(buf, sizeof(buf), "unverified-%s-consensus", flavor);
  1444. unverified_fname = get_datadir_fname(buf);
  1445. cur = dirserv_get_consensus(flavor);
  1446. if (cur) {
  1447. current_digests = &cur->digests;
  1448. current_valid_after = cur->published;
  1449. }
  1450. }
  1451. if (current_digests &&
  1452. tor_memeq(&c->digests, current_digests, sizeof(c->digests))) {
  1453. /* We already have this one. That's a failure. */
  1454. log_info(LD_DIR, "Got a %s consensus we already have", flavor);
  1455. goto done;
  1456. }
  1457. if (current_valid_after && c->valid_after <= current_valid_after) {
  1458. /* We have a newer one. There's no point in accepting this one,
  1459. * even if it's great. */
  1460. log_info(LD_DIR, "Got a %s consensus at least as old as the one we have",
  1461. flavor);
  1462. goto done;
  1463. }
  1464. /* Make sure it's signed enough. */
  1465. if ((r=networkstatus_check_consensus_signature(c, 1))<0) {
  1466. if (r == -1) {
  1467. /* Okay, so it _might_ be signed enough if we get more certificates. */
  1468. if (!was_waiting_for_certs) {
  1469. log_info(LD_DIR,
  1470. "Not enough certificates to check networkstatus consensus");
  1471. }
  1472. if (!current_valid_after ||
  1473. c->valid_after > current_valid_after) {
  1474. waiting = &consensus_waiting_for_certs[flav];
  1475. networkstatus_vote_free(waiting->consensus);
  1476. tor_free(waiting->body);
  1477. waiting->consensus = c;
  1478. free_consensus = 0;
  1479. waiting->body = tor_strdup(consensus);
  1480. waiting->set_at = now;
  1481. waiting->dl_failed = 0;
  1482. if (!from_cache) {
  1483. write_str_to_file(unverified_fname, consensus, 0);
  1484. }
  1485. if (dl_certs)
  1486. authority_certs_fetch_missing(c, now, source_dir);
  1487. /* This case is not a success or a failure until we get the certs
  1488. * or fail to get the certs. */
  1489. result = 0;
  1490. } else {
  1491. /* Even if we had enough signatures, we'd never use this as the
  1492. * latest consensus. */
  1493. if (was_waiting_for_certs && from_cache)
  1494. if (unlink(unverified_fname) != 0) {
  1495. log_warn(LD_FS,
  1496. "Failed to unlink %s: %s",
  1497. unverified_fname, strerror(errno));
  1498. }
  1499. }
  1500. goto done;
  1501. } else {
  1502. /* This can never be signed enough: Kill it. */
  1503. if (!was_waiting_for_certs) {
  1504. log_warn(LD_DIR, "Not enough good signatures on networkstatus "
  1505. "consensus");
  1506. result = -2;
  1507. }
  1508. if (was_waiting_for_certs && (r < -1) && from_cache) {
  1509. if (unlink(unverified_fname) != 0) {
  1510. log_warn(LD_FS,
  1511. "Failed to unlink %s: %s",
  1512. unverified_fname, strerror(errno));
  1513. }
  1514. }
  1515. goto done;
  1516. }
  1517. }
  1518. if (!from_cache && flav == usable_consensus_flavor())
  1519. control_event_client_status(LOG_NOTICE, "CONSENSUS_ARRIVED");
  1520. /* Are we missing any certificates at all? */
  1521. if (r != 1 && dl_certs)
  1522. authority_certs_fetch_missing(c, now, source_dir);
  1523. if (flav == usable_consensus_flavor()) {
  1524. notify_control_networkstatus_changed(current_consensus, c);
  1525. }
  1526. if (flav == FLAV_NS) {
  1527. if (current_ns_consensus) {
  1528. networkstatus_copy_old_consensus_info(c, current_ns_consensus);
  1529. networkstatus_vote_free(current_ns_consensus);
  1530. /* Defensive programming : we should set current_consensus very soon,
  1531. * but we're about to call some stuff in the meantime, and leaving this
  1532. * dangling pointer around has proven to be trouble. */
  1533. current_ns_consensus = NULL;
  1534. }
  1535. current_ns_consensus = c;
  1536. free_consensus = 0; /* avoid free */
  1537. } else if (flav == FLAV_MICRODESC) {
  1538. if (current_md_consensus) {
  1539. networkstatus_copy_old_consensus_info(c, current_md_consensus);
  1540. networkstatus_vote_free(current_md_consensus);
  1541. /* more defensive programming */
  1542. current_md_consensus = NULL;
  1543. }
  1544. current_md_consensus = c;
  1545. free_consensus = 0; /* avoid free */
  1546. }
  1547. waiting = &consensus_waiting_for_certs[flav];
  1548. if (waiting->consensus &&
  1549. waiting->consensus->valid_after <= c->valid_after) {
  1550. networkstatus_vote_free(waiting->consensus);
  1551. waiting->consensus = NULL;
  1552. if (consensus != waiting->body)
  1553. tor_free(waiting->body);
  1554. else
  1555. waiting->body = NULL;
  1556. waiting->set_at = 0;
  1557. waiting->dl_failed = 0;
  1558. if (unlink(unverified_fname) != 0) {
  1559. log_warn(LD_FS,
  1560. "Failed to unlink %s: %s",
  1561. unverified_fname, strerror(errno));
  1562. }
  1563. }
  1564. /* Reset the failure count only if this consensus is actually valid. */
  1565. if (c->valid_after <= now && now <= c->valid_until) {
  1566. download_status_reset(&consensus_dl_status[flav]);
  1567. } else {
  1568. if (!from_cache)
  1569. download_status_failed(&consensus_dl_status[flav], 0);
  1570. }
  1571. if (flav == usable_consensus_flavor()) {
  1572. /* XXXXNM Microdescs: needs a non-ns variant. ???? NM*/
  1573. update_consensus_networkstatus_fetch_time(now);
  1574. nodelist_set_consensus(current_consensus);
  1575. dirvote_recalculate_timing(options, now);
  1576. routerstatus_list_update_named_server_map();
  1577. /* Update ewma and adjust policy if needed; first cache the old value */
  1578. old_ewma_enabled = cell_ewma_enabled();
  1579. /* Change the cell EWMA settings */
  1580. cell_ewma_set_scale_factor(options, networkstatus_get_latest_consensus());
  1581. /* If we just enabled ewma, set the cmux policy on all active channels */
  1582. if (cell_ewma_enabled() && !old_ewma_enabled) {
  1583. channel_set_cmux_policy_everywhere(&ewma_policy);
  1584. } else if (!cell_ewma_enabled() && old_ewma_enabled) {
  1585. /* Turn it off everywhere */
  1586. channel_set_cmux_policy_everywhere(NULL);
  1587. }
  1588. /* XXXX024 this call might be unnecessary here: can changing the
  1589. * current consensus really alter our view of any OR's rate limits? */
  1590. connection_or_update_token_buckets(get_connection_array(), options);
  1591. circuit_build_times_new_consensus_params(get_circuit_build_times_mutable(),
  1592. current_consensus);
  1593. }
  1594. if (directory_caches_dir_info(options)) {
  1595. dirserv_set_cached_consensus_networkstatus(consensus,
  1596. flavor,
  1597. &c->digests,
  1598. c->valid_after);
  1599. }
  1600. if (!from_cache) {
  1601. write_str_to_file(consensus_fname, consensus, 0);
  1602. }
  1603. /** If a consensus appears more than this many seconds before its declared
  1604. * valid-after time, declare that our clock is skewed. */
  1605. #define EARLY_CONSENSUS_NOTICE_SKEW 60
  1606. if (now < c->valid_after - EARLY_CONSENSUS_NOTICE_SKEW) {
  1607. char tbuf[ISO_TIME_LEN+1];
  1608. char dbuf[64];
  1609. long delta = now - c->valid_after;
  1610. format_iso_time(tbuf, c->valid_after);
  1611. format_time_interval(dbuf, sizeof(dbuf), delta);
  1612. log_warn(LD_GENERAL, "Our clock is %s behind the time published in the "
  1613. "consensus network status document (%s UTC). Tor needs an "
  1614. "accurate clock to work correctly. Please check your time and "
  1615. "date settings!", dbuf, tbuf);
  1616. control_event_general_status(LOG_WARN,
  1617. "CLOCK_SKEW MIN_SKEW=%ld SOURCE=CONSENSUS", delta);
  1618. }
  1619. router_dir_info_changed();
  1620. result = 0;
  1621. done:
  1622. if (free_consensus)
  1623. networkstatus_vote_free(c);
  1624. tor_free(consensus_fname);
  1625. tor_free(unverified_fname);
  1626. return result;
  1627. }
  1628. /** Called when we have gotten more certificates: see whether we can
  1629. * now verify a pending consensus.
  1630. *
  1631. * If source_dir is non-NULL, it's the identity digest for a directory that
  1632. * we've just successfully retrieved certificates from, so try it first to
  1633. * fetch any missing certificates.
  1634. */
  1635. void
  1636. networkstatus_note_certs_arrived(const char *source_dir)
  1637. {
  1638. int i;
  1639. for (i=0; i<N_CONSENSUS_FLAVORS; ++i) {
  1640. consensus_waiting_for_certs_t *waiting = &consensus_waiting_for_certs[i];
  1641. if (!waiting->consensus)
  1642. continue;
  1643. if (networkstatus_check_consensus_signature(waiting->consensus, 0)>=0) {
  1644. char *waiting_body = waiting->body;
  1645. if (!networkstatus_set_current_consensus(
  1646. waiting_body,
  1647. networkstatus_get_flavor_name(i),
  1648. NSSET_WAS_WAITING_FOR_CERTS,
  1649. source_dir)) {
  1650. tor_free(waiting_body);
  1651. }
  1652. }
  1653. }
  1654. }
  1655. /** If the network-status list has changed since the last time we called this
  1656. * function, update the status of every routerinfo from the network-status
  1657. * list. If <b>dir_version</b> is 2, it's a v2 networkstatus that changed.
  1658. * If <b>dir_version</b> is 3, it's a v3 consensus that changed.
  1659. */
  1660. void
  1661. routers_update_all_from_networkstatus(time_t now, int dir_version)
  1662. {
  1663. routerlist_t *rl = router_get_routerlist();
  1664. networkstatus_t *consensus = networkstatus_get_reasonably_live_consensus(now,
  1665. FLAV_NS);
  1666. if (!consensus || dir_version < 3) /* nothing more we should do */
  1667. return;
  1668. /* calls router_dir_info_changed() when it's done -- more routers
  1669. * might be up or down now, which might affect whether there's enough
  1670. * directory info. */
  1671. routers_update_status_from_consensus_networkstatus(rl->routers, 0);
  1672. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri,
  1673. ri->cache_info.routerlist_index = ri_sl_idx);
  1674. if (rl->old_routers)
  1675. signed_descs_update_status_from_consensus_networkstatus(rl->old_routers);
  1676. if (!have_warned_about_old_version) {
  1677. int is_server = server_mode(get_options());
  1678. version_status_t status;
  1679. const char *recommended = is_server ?
  1680. consensus->server_versions : consensus->client_versions;
  1681. status = tor_version_is_obsolete(VERSION, recommended);
  1682. if (status == VS_RECOMMENDED) {
  1683. log_info(LD_GENERAL, "The directory authorities say my version is ok.");
  1684. } else if (status == VS_EMPTY) {
  1685. log_info(LD_GENERAL,
  1686. "The directory authorities don't recommend any versions.");
  1687. } else if (status == VS_NEW || status == VS_NEW_IN_SERIES) {
  1688. if (!have_warned_about_new_version) {
  1689. log_notice(LD_GENERAL, "This version of Tor (%s) is newer than any "
  1690. "recommended version%s, according to the directory "
  1691. "authorities. Recommended versions are: %s",
  1692. VERSION,
  1693. status == VS_NEW_IN_SERIES ? " in its series" : "",
  1694. recommended);
  1695. have_warned_about_new_version = 1;
  1696. control_event_general_status(LOG_WARN, "DANGEROUS_VERSION "
  1697. "CURRENT=%s REASON=%s RECOMMENDED=\"%s\"",
  1698. VERSION, "NEW", recommended);
  1699. }
  1700. } else {
  1701. log_warn(LD_GENERAL, "Please upgrade! "
  1702. "This version of Tor (%s) is %s, according to the directory "
  1703. "authorities. Recommended versions are: %s",
  1704. VERSION,
  1705. status == VS_OLD ? "obsolete" : "not recommended",
  1706. recommended);
  1707. have_warned_about_old_version = 1;
  1708. control_event_general_status(LOG_WARN, "DANGEROUS_VERSION "
  1709. "CURRENT=%s REASON=%s RECOMMENDED=\"%s\"",
  1710. VERSION, status == VS_OLD ? "OBSOLETE" : "UNRECOMMENDED",
  1711. recommended);
  1712. }
  1713. }
  1714. }
  1715. /** Update our view of the list of named servers from the most recently
  1716. * retrieved networkstatus consensus. */
  1717. static void
  1718. routerstatus_list_update_named_server_map(void)
  1719. {
  1720. if (!current_consensus)
  1721. return;
  1722. strmap_free(named_server_map, tor_free_);
  1723. named_server_map = strmap_new();
  1724. strmap_free(unnamed_server_map, NULL);
  1725. unnamed_server_map = strmap_new();
  1726. SMARTLIST_FOREACH_BEGIN(current_consensus->routerstatus_list,
  1727. const routerstatus_t *, rs) {
  1728. if (rs->is_named) {
  1729. strmap_set_lc(named_server_map, rs->nickname,
  1730. tor_memdup(rs->identity_digest, DIGEST_LEN));
  1731. }
  1732. if (rs->is_unnamed) {
  1733. strmap_set_lc(unnamed_server_map, rs->nickname, (void*)1);
  1734. }
  1735. } SMARTLIST_FOREACH_END(rs);
  1736. }
  1737. /** Given a list <b>routers</b> of routerinfo_t *, update each status field
  1738. * according to our current consensus networkstatus. May re-order
  1739. * <b>routers</b>. */
  1740. void
  1741. routers_update_status_from_consensus_networkstatus(smartlist_t *routers,
  1742. int reset_failures)
  1743. {
  1744. const or_options_t *options = get_options();
  1745. int authdir = authdir_mode_v3(options);
  1746. networkstatus_t *ns = current_consensus;
  1747. if (!ns || !smartlist_len(ns->routerstatus_list))
  1748. return;
  1749. routers_sort_by_identity(routers);
  1750. SMARTLIST_FOREACH_JOIN(ns->routerstatus_list, routerstatus_t *, rs,
  1751. routers, routerinfo_t *, router,
  1752. tor_memcmp(rs->identity_digest,
  1753. router->cache_info.identity_digest, DIGEST_LEN),
  1754. {
  1755. }) {
  1756. /* Is it the same descriptor, or only the same identity? */
  1757. if (tor_memeq(router->cache_info.signed_descriptor_digest,
  1758. rs->descriptor_digest, DIGEST_LEN)) {
  1759. if (ns->valid_until > router->cache_info.last_listed_as_valid_until)
  1760. router->cache_info.last_listed_as_valid_until = ns->valid_until;
  1761. }
  1762. if (authdir) {
  1763. /* If we _are_ an authority, we should check whether this router
  1764. * is one that will cause us to need a reachability test. */
  1765. routerinfo_t *old_router =
  1766. router_get_mutable_by_digest(router->cache_info.identity_digest);
  1767. if (old_router != router) {
  1768. router->needs_retest_if_added =
  1769. dirserv_should_launch_reachability_test(router, old_router);
  1770. }
  1771. }
  1772. if (reset_failures) {
  1773. download_status_reset(&rs->dl_status);
  1774. }
  1775. } SMARTLIST_FOREACH_JOIN_END(rs, router);
  1776. router_dir_info_changed();
  1777. }
  1778. /** Given a list of signed_descriptor_t, update their fields (mainly, when
  1779. * they were last listed) from the most recent consensus. */
  1780. void
  1781. signed_descs_update_status_from_consensus_networkstatus(smartlist_t *descs)
  1782. {
  1783. networkstatus_t *ns = current_ns_consensus;
  1784. if (!ns)
  1785. return;
  1786. if (!ns->desc_digest_map) {
  1787. char dummy[DIGEST_LEN];
  1788. /* instantiates the digest map. */
  1789. memset(dummy, 0, sizeof(dummy));
  1790. router_get_consensus_status_by_descriptor_digest(ns, dummy);
  1791. }
  1792. SMARTLIST_FOREACH(descs, signed_descriptor_t *, d,
  1793. {
  1794. const routerstatus_t *rs = digestmap_get(ns->desc_digest_map,
  1795. d->signed_descriptor_digest);
  1796. if (rs) {
  1797. if (ns->valid_until > d->last_listed_as_valid_until)
  1798. d->last_listed_as_valid_until = ns->valid_until;
  1799. }
  1800. });
  1801. }
  1802. /** Generate networkstatus lines for a single routerstatus_t object, and
  1803. * return the result in a newly allocated string. Used only by controller
  1804. * interface (for now.) */
  1805. char *
  1806. networkstatus_getinfo_helper_single(const routerstatus_t *rs)
  1807. {
  1808. return routerstatus_format_entry(rs, NULL, NS_CONTROL_PORT, NULL);
  1809. }
  1810. /** Alloc and return a string describing routerstatuses for the most
  1811. * recent info of each router we know about that is of purpose
  1812. * <b>purpose_string</b>. Return NULL if unrecognized purpose.
  1813. *
  1814. * Right now this function is oriented toward listing bridges (you
  1815. * shouldn't use this for general-purpose routers, since those
  1816. * should be listed from the consensus, not from the routers list). */
  1817. char *
  1818. networkstatus_getinfo_by_purpose(const char *purpose_string, time_t now)
  1819. {
  1820. time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
  1821. char *answer;
  1822. routerlist_t *rl = router_get_routerlist();
  1823. smartlist_t *statuses;
  1824. uint8_t purpose = router_purpose_from_string(purpose_string);
  1825. routerstatus_t rs;
  1826. int bridge_auth = authdir_mode_bridge(get_options());
  1827. if (purpose == ROUTER_PURPOSE_UNKNOWN) {
  1828. log_info(LD_DIR, "Unrecognized purpose '%s' when listing router statuses.",
  1829. purpose_string);
  1830. return NULL;
  1831. }
  1832. statuses = smartlist_new();
  1833. SMARTLIST_FOREACH_BEGIN(rl->routers, routerinfo_t *, ri) {
  1834. node_t *node = node_get_mutable_by_id(ri->cache_info.identity_digest);
  1835. if (!node)
  1836. continue;
  1837. if (ri->cache_info.published_on < cutoff)
  1838. continue;
  1839. if (ri->purpose != purpose)
  1840. continue;
  1841. if (bridge_auth && ri->purpose == ROUTER_PURPOSE_BRIDGE)
  1842. dirserv_set_router_is_running(ri, now);
  1843. /* then generate and write out status lines for each of them */
  1844. set_routerstatus_from_routerinfo(&rs, node, ri, now, 0);
  1845. smartlist_add(statuses, networkstatus_getinfo_helper_single(&rs));
  1846. } SMARTLIST_FOREACH_END(ri);
  1847. answer = smartlist_join_strings(statuses, "", 0, NULL);
  1848. SMARTLIST_FOREACH(statuses, char *, cp, tor_free(cp));
  1849. smartlist_free(statuses);
  1850. return answer;
  1851. }
  1852. /** Write out router status entries for all our bridge descriptors. */
  1853. void
  1854. networkstatus_dump_bridge_status_to_file(time_t now)
  1855. {
  1856. char *status = networkstatus_getinfo_by_purpose("bridge", now);
  1857. const or_options_t *options = get_options();
  1858. char *fname = NULL;
  1859. char *thresholds = NULL;
  1860. char *published_thresholds_and_status = NULL;
  1861. char published[ISO_TIME_LEN+1];
  1862. format_iso_time(published, now);
  1863. dirserv_compute_bridge_flag_thresholds();
  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. }