networkstatus.c 66 KB

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