networkstatus.c 81 KB

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