networkstatus.c 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2016, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file networkstatus.c
  8. * \brief Functions and structures for handling network status documents as a
  9. * client or cache.
  10. */
  11. #define NETWORKSTATUS_PRIVATE
  12. #include "or.h"
  13. #include "channel.h"
  14. #include "circuitmux.h"
  15. #include "circuitmux_ewma.h"
  16. #include "circuitstats.h"
  17. #include "config.h"
  18. #include "connection.h"
  19. #include "connection_or.h"
  20. #include "control.h"
  21. #include "directory.h"
  22. #include "dirserv.h"
  23. #include "dirvote.h"
  24. #include "entrynodes.h"
  25. #include "main.h"
  26. #include "microdesc.h"
  27. #include "networkstatus.h"
  28. #include "nodelist.h"
  29. #include "relay.h"
  30. #include "router.h"
  31. #include "routerlist.h"
  32. #include "routerparse.h"
  33. #include "transports.h"
  34. /** Map from lowercase nickname to identity digest of named server, if any. */
  35. static strmap_t *named_server_map = NULL;
  36. /** Map from lowercase nickname to (void*)1 for all names that are listed
  37. * as unnamed for some server in the consensus. */
  38. static strmap_t *unnamed_server_map = NULL;
  39. /** Most recently received and validated v3 consensus network status,
  40. * of whichever type we are using for our own circuits. This will be the same
  41. * as one of current_ns_consensus or current_md_consensus.
  42. */
  43. #define current_consensus \
  44. (we_use_microdescriptors_for_circuits(get_options()) ? \
  45. current_md_consensus : current_ns_consensus)
  46. /** Most recently received and validated v3 "ns"-flavored consensus network
  47. * status. */
  48. static networkstatus_t *current_ns_consensus = NULL;
  49. /** Most recently received and validated v3 "microdec"-flavored consensus
  50. * network status. */
  51. static networkstatus_t *current_md_consensus = NULL;
  52. /** A v3 consensus networkstatus that we've received, but which we don't
  53. * have enough certificates to be happy about. */
  54. typedef struct consensus_waiting_for_certs_t {
  55. /** The consensus itself. */
  56. networkstatus_t *consensus;
  57. /** The encoded version of the consensus, nul-terminated. */
  58. char *body;
  59. /** When did we set the current value of consensus_waiting_for_certs? If
  60. * this is too recent, we shouldn't try to fetch a new consensus for a
  61. * little while, to give ourselves time to get certificates for this one. */
  62. time_t set_at;
  63. /** Set to 1 if we've been holding on to it for so long we should maybe
  64. * treat it as being bad. */
  65. int dl_failed;
  66. } consensus_waiting_for_certs_t;
  67. /** An array, for each flavor of consensus we might want, of consensuses that
  68. * we have downloaded, but which we cannot verify due to having insufficient
  69. * authority certificates. */
  70. static consensus_waiting_for_certs_t
  71. consensus_waiting_for_certs[N_CONSENSUS_FLAVORS];
  72. /** A time before which we shouldn't try to replace the current consensus:
  73. * this will be at some point after the next consensus becomes valid, but
  74. * before the current consensus becomes invalid. */
  75. static time_t time_to_download_next_consensus[N_CONSENSUS_FLAVORS];
  76. /** Download status for the current consensus networkstatus. */
  77. static download_status_t consensus_dl_status[N_CONSENSUS_FLAVORS] =
  78. {
  79. { 0, 0, 0, DL_SCHED_CONSENSUS, DL_WANT_ANY_DIRSERVER,
  80. DL_SCHED_INCREMENT_FAILURE },
  81. { 0, 0, 0, DL_SCHED_CONSENSUS, DL_WANT_ANY_DIRSERVER,
  82. DL_SCHED_INCREMENT_FAILURE },
  83. };
  84. #define N_CONSENSUS_BOOTSTRAP_SCHEDULES 2
  85. #define CONSENSUS_BOOTSTRAP_SOURCE_AUTHORITY 0
  86. #define CONSENSUS_BOOTSTRAP_SOURCE_ANY_DIRSERVER 1
  87. /* Using DL_SCHED_INCREMENT_ATTEMPT on these schedules means that
  88. * download_status_increment_failure won't increment these entries.
  89. * However, any bootstrap connection failures that occur after we have
  90. * a valid consensus will count against the failure counts on the non-bootstrap
  91. * schedules. There should only be one of these, as all the others will have
  92. * been cancelled. (This doesn't seem to be a significant issue.) */
  93. static download_status_t
  94. consensus_bootstrap_dl_status[N_CONSENSUS_BOOTSTRAP_SCHEDULES] =
  95. {
  96. { 0, 0, 0, DL_SCHED_CONSENSUS, DL_WANT_AUTHORITY,
  97. DL_SCHED_INCREMENT_ATTEMPT },
  98. /* During bootstrap, DL_WANT_ANY_DIRSERVER means "use fallbacks". */
  99. { 0, 0, 0, DL_SCHED_CONSENSUS, DL_WANT_ANY_DIRSERVER,
  100. DL_SCHED_INCREMENT_ATTEMPT },
  101. };
  102. /** True iff we have logged a warning about this OR's version being older than
  103. * listed by the authorities. */
  104. static int have_warned_about_old_version = 0;
  105. /** True iff we have logged a warning about this OR's version being newer than
  106. * listed by the authorities. */
  107. static int have_warned_about_new_version = 0;
  108. static void routerstatus_list_update_named_server_map(void);
  109. static void update_consensus_bootstrap_multiple_downloads(
  110. time_t now,
  111. const or_options_t *options,
  112. int we_are_bootstrapping);
  113. /** Forget that we've warned about anything networkstatus-related, so we will
  114. * give fresh warnings if the same behavior happens again. */
  115. void
  116. networkstatus_reset_warnings(void)
  117. {
  118. if (current_consensus) {
  119. SMARTLIST_FOREACH(nodelist_get_list(), node_t *, node,
  120. node->name_lookup_warned = 0);
  121. }
  122. have_warned_about_old_version = 0;
  123. have_warned_about_new_version = 0;
  124. }
  125. /** Reset the descriptor download failure count on all networkstatus docs, so
  126. * that we can retry any long-failed documents immediately.
  127. */
  128. void
  129. networkstatus_reset_download_failures(void)
  130. {
  131. int i;
  132. for (i=0; i < N_CONSENSUS_FLAVORS; ++i)
  133. download_status_reset(&consensus_dl_status[i]);
  134. for (i=0; i < N_CONSENSUS_BOOTSTRAP_SCHEDULES; ++i)
  135. download_status_reset(&consensus_bootstrap_dl_status[i]);
  136. }
  137. /** Read every cached v3 consensus networkstatus from the disk. */
  138. int
  139. router_reload_consensus_networkstatus(void)
  140. {
  141. char *filename;
  142. char *s;
  143. const unsigned int flags = NSSET_FROM_CACHE | NSSET_DONT_DOWNLOAD_CERTS;
  144. int flav;
  145. /* FFFF Suppress warnings if cached consensus is bad? */
  146. for (flav = 0; flav < N_CONSENSUS_FLAVORS; ++flav) {
  147. char buf[128];
  148. const char *flavor = networkstatus_get_flavor_name(flav);
  149. if (flav == FLAV_NS) {
  150. filename = get_datadir_fname("cached-consensus");
  151. } else {
  152. tor_snprintf(buf, sizeof(buf), "cached-%s-consensus", flavor);
  153. filename = get_datadir_fname(buf);
  154. }
  155. s = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
  156. if (s) {
  157. if (networkstatus_set_current_consensus(s, flavor, flags) < -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->ClientBootstrapConsensusMaxDownloadTries;
  730. } else {
  731. return
  732. options->ClientBootstrapConsensusAuthorityOnlyMaxDownloadTries;
  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_bootstrapping(
  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->ClientBootstrapConsensusMaxInProgressTries;
  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 not all connections are "connecting", then some are
  791. * downloading. We want to have at most one downloading at a time. */
  792. if (connect_consens_conn_count < consens_conn_count) {
  793. continue;
  794. }
  795. /* Make multiple connections for a bootstrap consensus download. */
  796. update_consensus_bootstrap_multiple_downloads(now, options,
  797. we_are_bootstrapping);
  798. } else {
  799. /* Check if we failed downloading a consensus too recently */
  800. int max_dl_tries = consensus_max_download_tries(options,
  801. we_are_bootstrapping);
  802. /* Let's make sure we remembered to update consensus_dl_status */
  803. tor_assert(consensus_dl_status[i].schedule == DL_SCHED_CONSENSUS);
  804. if (!download_status_is_ready(&consensus_dl_status[i],
  805. now,
  806. max_dl_tries)) {
  807. continue;
  808. }
  809. /* Check if we're waiting for certificates to download */
  810. if (check_consensus_waiting_for_certs(i, now, &consensus_dl_status[i]))
  811. continue;
  812. /* Try the requested attempt */
  813. log_info(LD_DIR, "Launching %s standard networkstatus consensus "
  814. "download.", networkstatus_get_flavor_name(i));
  815. directory_get_from_dirserver(DIR_PURPOSE_FETCH_CONSENSUS,
  816. ROUTER_PURPOSE_GENERAL, resource,
  817. PDS_RETRY_IF_NO_SERVERS,
  818. consensus_dl_status[i].want_authority);
  819. }
  820. }
  821. }
  822. /** When we're bootstrapping, launch one or more consensus download
  823. * connections, if schedule indicates connection(s) should be made after now.
  824. * If is_authority, connect to an authority, otherwise, use a fallback
  825. * directory mirror.
  826. */
  827. static void
  828. update_consensus_bootstrap_attempt_downloads(
  829. time_t now,
  830. const or_options_t *options,
  831. int we_are_bootstrapping,
  832. download_status_t *dls,
  833. download_want_authority_t want_authority)
  834. {
  835. int max_dl_tries = consensus_max_download_tries(options,
  836. we_are_bootstrapping);
  837. const char *resource = networkstatus_get_flavor_name(
  838. usable_consensus_flavor());
  839. /* Let's make sure we remembered to update schedule */
  840. tor_assert(dls->schedule == DL_SCHED_CONSENSUS);
  841. /* Allow for multiple connections in the same second, if the schedule value
  842. * is 0. */
  843. while (download_status_is_ready(dls, now, max_dl_tries)) {
  844. log_info(LD_DIR, "Launching %s bootstrap %s networkstatus consensus "
  845. "download.", resource, (want_authority == DL_WANT_AUTHORITY
  846. ? "authority"
  847. : "mirror"));
  848. directory_get_from_dirserver(DIR_PURPOSE_FETCH_CONSENSUS,
  849. ROUTER_PURPOSE_GENERAL, resource,
  850. PDS_RETRY_IF_NO_SERVERS, want_authority);
  851. /* schedule the next attempt */
  852. download_status_increment_attempt(dls, resource, now);
  853. }
  854. }
  855. /** If we're bootstrapping, check the connection schedules and see if we want
  856. * to make additional, potentially concurrent, consensus download
  857. * connections.
  858. * Only call when bootstrapping, and when we want to make additional
  859. * connections. Only nodes that satisfy
  860. * networkstatus_consensus_can_use_multiple_directories make additional
  861. * connections.
  862. */
  863. static void
  864. update_consensus_bootstrap_multiple_downloads(time_t now,
  865. const or_options_t *options,
  866. int we_are_bootstrapping)
  867. {
  868. const int usable_flavor = usable_consensus_flavor();
  869. /* make sure we can use multiple connections */
  870. if (!networkstatus_consensus_can_use_multiple_directories(options)) {
  871. return;
  872. }
  873. /* If we've managed to validate a usable consensus, don't make additional
  874. * connections. */
  875. if (!we_are_bootstrapping) {
  876. return;
  877. }
  878. /* Launch concurrent consensus download attempt(s) based on the mirror and
  879. * authority schedules. Try the mirror first - this makes it slightly more
  880. * likely that we'll connect to the fallback first, and then end the
  881. * authority connection attempt. */
  882. /* If a consensus download fails because it's waiting for certificates,
  883. * we'll fail both the authority and fallback schedules. This is better than
  884. * failing only one of the schedules, and having the other continue
  885. * unchecked.
  886. */
  887. /* If we don't have or can't use extra fallbacks, don't try them. */
  888. if (networkstatus_consensus_can_use_extra_fallbacks(options)) {
  889. download_status_t *dls_f =
  890. &consensus_bootstrap_dl_status[CONSENSUS_BOOTSTRAP_SOURCE_ANY_DIRSERVER];
  891. if (!check_consensus_waiting_for_certs(usable_flavor, now, dls_f)) {
  892. /* During bootstrap, DL_WANT_ANY_DIRSERVER means "use fallbacks". */
  893. update_consensus_bootstrap_attempt_downloads(now, options,
  894. we_are_bootstrapping, dls_f,
  895. DL_WANT_ANY_DIRSERVER);
  896. }
  897. }
  898. /* Now try an authority. */
  899. download_status_t *dls_a =
  900. &consensus_bootstrap_dl_status[CONSENSUS_BOOTSTRAP_SOURCE_AUTHORITY];
  901. if (!check_consensus_waiting_for_certs(usable_flavor, now, dls_a)) {
  902. update_consensus_bootstrap_attempt_downloads(now, options,
  903. we_are_bootstrapping, dls_a,
  904. DL_WANT_AUTHORITY);
  905. }
  906. }
  907. /** Called when an attempt to download a consensus fails: note that the
  908. * failure occurred, and possibly retry. */
  909. void
  910. networkstatus_consensus_download_failed(int status_code, const char *flavname)
  911. {
  912. int flav = networkstatus_parse_flavor_name(flavname);
  913. if (flav >= 0) {
  914. tor_assert(flav < N_CONSENSUS_FLAVORS);
  915. /* XXXX handle unrecognized flavors */
  916. download_status_failed(&consensus_dl_status[flav], status_code);
  917. /* Retry immediately, if appropriate. */
  918. update_consensus_networkstatus_downloads(time(NULL));
  919. }
  920. }
  921. /** How long do we (as a cache) wait after a consensus becomes non-fresh
  922. * before trying to fetch another? */
  923. #define CONSENSUS_MIN_SECONDS_BEFORE_CACHING 120
  924. /** Update the time at which we'll consider replacing the current
  925. * consensus of flavor <b>flav</b> */
  926. static void
  927. update_consensus_networkstatus_fetch_time_impl(time_t now, int flav)
  928. {
  929. const or_options_t *options = get_options();
  930. networkstatus_t *c = networkstatus_get_latest_consensus_by_flavor(flav);
  931. const char *flavor = networkstatus_get_flavor_name(flav);
  932. if (! we_want_to_fetch_flavor(get_options(), flav))
  933. return;
  934. if (c && c->valid_after <= now && now <= c->valid_until) {
  935. long dl_interval;
  936. long interval = c->fresh_until - c->valid_after;
  937. long min_sec_before_caching = CONSENSUS_MIN_SECONDS_BEFORE_CACHING;
  938. time_t start;
  939. if (min_sec_before_caching > interval/16) {
  940. /* Usually we allow 2-minutes slop factor in case clocks get
  941. desynchronized a little. If we're on a private network with
  942. a crazy-fast voting interval, though, 2 minutes may be too
  943. much. */
  944. min_sec_before_caching = interval/16;
  945. /* make sure we always delay by at least a second before caching */
  946. if (min_sec_before_caching == 0) {
  947. min_sec_before_caching = 1;
  948. }
  949. }
  950. if (directory_fetches_dir_info_early(options)) {
  951. /* We want to cache the next one at some point after this one
  952. * is no longer fresh... */
  953. start = (time_t)(c->fresh_until + min_sec_before_caching);
  954. /* Some clients may need the consensus sooner than others. */
  955. if (options->FetchDirInfoExtraEarly || authdir_mode_v3(options)) {
  956. dl_interval = 60;
  957. if (min_sec_before_caching + dl_interval > interval)
  958. dl_interval = interval/2;
  959. } else {
  960. /* But only in the first half-interval after that. */
  961. dl_interval = interval/2;
  962. }
  963. } else {
  964. /* We're an ordinary client, a bridge, or a hidden service.
  965. * Give all the caches enough time to download the consensus. */
  966. start = (time_t)(c->fresh_until + (interval*3)/4);
  967. /* But download the next one well before this one is expired. */
  968. dl_interval = ((c->valid_until - start) * 7 )/ 8;
  969. /* If we're a bridge user, make use of the numbers we just computed
  970. * to choose the rest of the interval *after* them. */
  971. if (directory_fetches_dir_info_later(options)) {
  972. /* Give all the *clients* enough time to download the consensus. */
  973. start = (time_t)(start + dl_interval + min_sec_before_caching);
  974. /* But try to get it before ours actually expires. */
  975. dl_interval = (c->valid_until - start) - min_sec_before_caching;
  976. }
  977. }
  978. /* catch low dl_interval in crazy-fast networks */
  979. if (dl_interval < 1)
  980. dl_interval = 1;
  981. /* catch late start in crazy-fast networks */
  982. if (start+dl_interval >= c->valid_until)
  983. start = c->valid_until - dl_interval - 1;
  984. log_debug(LD_DIR,
  985. "fresh_until: %ld start: %ld "
  986. "dl_interval: %ld valid_until: %ld ",
  987. (long)c->fresh_until, (long)start, dl_interval,
  988. (long)c->valid_until);
  989. /* We must not try to replace c while it's still fresh: */
  990. tor_assert(c->fresh_until < start);
  991. /* We must download the next one before c is invalid: */
  992. tor_assert(start+dl_interval < c->valid_until);
  993. time_to_download_next_consensus[flav] =
  994. start + crypto_rand_int((int)dl_interval);
  995. {
  996. char tbuf1[ISO_TIME_LEN+1];
  997. char tbuf2[ISO_TIME_LEN+1];
  998. char tbuf3[ISO_TIME_LEN+1];
  999. format_local_iso_time(tbuf1, c->fresh_until);
  1000. format_local_iso_time(tbuf2, c->valid_until);
  1001. format_local_iso_time(tbuf3, time_to_download_next_consensus[flav]);
  1002. log_info(LD_DIR, "Live %s consensus %s the most recent until %s and "
  1003. "will expire at %s; fetching the next one at %s.",
  1004. flavor, (c->fresh_until > now) ? "will be" : "was",
  1005. tbuf1, tbuf2, tbuf3);
  1006. }
  1007. } else {
  1008. time_to_download_next_consensus[flav] = now;
  1009. log_info(LD_DIR, "No live %s consensus; we should fetch one immediately.",
  1010. flavor);
  1011. }
  1012. }
  1013. /** Update the time at which we'll consider replacing the current
  1014. * consensus of flavor 'flavor' */
  1015. void
  1016. update_consensus_networkstatus_fetch_time(time_t now)
  1017. {
  1018. int i;
  1019. for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
  1020. if (we_want_to_fetch_flavor(get_options(), i))
  1021. update_consensus_networkstatus_fetch_time_impl(now, i);
  1022. }
  1023. }
  1024. /** Return 1 if there's a reason we shouldn't try any directory
  1025. * fetches yet (e.g. we demand bridges and none are yet known).
  1026. * Else return 0.
  1027. * If we return 1 and <b>msg_out</b> is provided, set <b>msg_out</b>
  1028. * to an explanation of why directory fetches are delayed. (If we
  1029. * return 0, we set msg_out to NULL.)
  1030. */
  1031. int
  1032. should_delay_dir_fetches(const or_options_t *options, const char **msg_out)
  1033. {
  1034. if (msg_out) {
  1035. *msg_out = NULL;
  1036. }
  1037. if (options->DisableNetwork) {
  1038. if (msg_out) {
  1039. *msg_out = "DisableNetwork is set.";
  1040. }
  1041. log_info(LD_DIR, "Delaying dir fetches (DisableNetwork is set)");
  1042. return 1;
  1043. }
  1044. if (options->UseBridges) {
  1045. if (!any_bridge_descriptors_known()) {
  1046. if (msg_out) {
  1047. *msg_out = "No running bridges";
  1048. }
  1049. log_info(LD_DIR, "Delaying dir fetches (no running bridges known)");
  1050. return 1;
  1051. }
  1052. if (pt_proxies_configuration_pending()) {
  1053. if (msg_out) {
  1054. *msg_out = "Pluggable transport proxies still configuring";
  1055. }
  1056. log_info(LD_DIR, "Delaying dir fetches (pt proxies still configuring)");
  1057. return 1;
  1058. }
  1059. }
  1060. return 0;
  1061. }
  1062. /** Launch requests for networkstatus documents and authority certificates as
  1063. * appropriate. */
  1064. void
  1065. update_networkstatus_downloads(time_t now)
  1066. {
  1067. const or_options_t *options = get_options();
  1068. if (should_delay_dir_fetches(options, NULL))
  1069. return;
  1070. update_consensus_networkstatus_downloads(now);
  1071. update_certificate_downloads(now);
  1072. }
  1073. /** Launch requests as appropriate for missing directory authority
  1074. * certificates. */
  1075. void
  1076. update_certificate_downloads(time_t now)
  1077. {
  1078. int i;
  1079. for (i = 0; i < N_CONSENSUS_FLAVORS; ++i) {
  1080. if (consensus_waiting_for_certs[i].consensus)
  1081. authority_certs_fetch_missing(consensus_waiting_for_certs[i].consensus,
  1082. now);
  1083. }
  1084. if (current_ns_consensus)
  1085. authority_certs_fetch_missing(current_ns_consensus, now);
  1086. if (current_md_consensus)
  1087. authority_certs_fetch_missing(current_md_consensus, now);
  1088. }
  1089. /** Return 1 if we have a consensus but we don't have enough certificates
  1090. * to start using it yet. */
  1091. int
  1092. consensus_is_waiting_for_certs(void)
  1093. {
  1094. return consensus_waiting_for_certs[usable_consensus_flavor()].consensus
  1095. ? 1 : 0;
  1096. }
  1097. /** Return the most recent consensus that we have downloaded, or NULL if we
  1098. * don't have one. */
  1099. networkstatus_t *
  1100. networkstatus_get_latest_consensus(void)
  1101. {
  1102. return current_consensus;
  1103. }
  1104. /** Return the latest consensus we have whose flavor matches <b>f</b>, or NULL
  1105. * if we don't have one. */
  1106. MOCK_IMPL(networkstatus_t *,
  1107. networkstatus_get_latest_consensus_by_flavor,(consensus_flavor_t f))
  1108. {
  1109. if (f == FLAV_NS)
  1110. return current_ns_consensus;
  1111. else if (f == FLAV_MICRODESC)
  1112. return current_md_consensus;
  1113. else {
  1114. tor_assert(0);
  1115. return NULL;
  1116. }
  1117. }
  1118. /** Return the most recent consensus that we have downloaded, or NULL if it is
  1119. * no longer live. */
  1120. networkstatus_t *
  1121. networkstatus_get_live_consensus(time_t now)
  1122. {
  1123. if (current_consensus &&
  1124. current_consensus->valid_after <= now &&
  1125. now <= current_consensus->valid_until)
  1126. return current_consensus;
  1127. else
  1128. return NULL;
  1129. }
  1130. /* XXXX remove this in favor of get_live_consensus. But actually,
  1131. * leave something like it for bridge users, who need to not totally
  1132. * lose if they spend a while fetching a new consensus. */
  1133. /** As networkstatus_get_live_consensus(), but is way more tolerant of expired
  1134. * consensuses. */
  1135. networkstatus_t *
  1136. networkstatus_get_reasonably_live_consensus(time_t now, int flavor)
  1137. {
  1138. #define REASONABLY_LIVE_TIME (24*60*60)
  1139. networkstatus_t *consensus =
  1140. networkstatus_get_latest_consensus_by_flavor(flavor);
  1141. if (consensus &&
  1142. consensus->valid_after <= now &&
  1143. now <= consensus->valid_until+REASONABLY_LIVE_TIME)
  1144. return consensus;
  1145. else
  1146. return NULL;
  1147. }
  1148. /** Check if we're bootstrapping a consensus download. This means that we are
  1149. * only using the authorities and fallback directory mirrors to download the
  1150. * consensus flavour we'll use. */
  1151. int
  1152. networkstatus_consensus_is_bootstrapping(time_t now)
  1153. {
  1154. /* If we don't have a consensus, we must still be bootstrapping */
  1155. return !networkstatus_get_reasonably_live_consensus(
  1156. now,
  1157. usable_consensus_flavor());
  1158. }
  1159. /** Check if we can use multiple directories for a consensus download.
  1160. * Only clients (including bridge relays, which act like clients) benefit
  1161. * from multiple simultaneous consensus downloads. */
  1162. int
  1163. networkstatus_consensus_can_use_multiple_directories(
  1164. const or_options_t *options)
  1165. {
  1166. /* If we are a client, bridge, bridge client, or hidden service */
  1167. return !public_server_mode(options);
  1168. }
  1169. /** Check if we can use fallback directory mirrors for a consensus download.
  1170. * If we have fallbacks and don't want to fetch from the authorities,
  1171. * we can use them. */
  1172. int
  1173. networkstatus_consensus_can_use_extra_fallbacks(const or_options_t *options)
  1174. {
  1175. /* The list length comparisons are a quick way to check if we have any
  1176. * non-authority fallback directories. If we ever have any authorities that
  1177. * aren't fallback directories, we will need to change this code. */
  1178. tor_assert(smartlist_len(router_get_fallback_dir_servers())
  1179. >= smartlist_len(router_get_trusted_dir_servers()));
  1180. /* If we don't fetch from the authorities, and we have additional mirrors,
  1181. * we can use them. */
  1182. return (!directory_fetches_from_authorities(options)
  1183. && (smartlist_len(router_get_fallback_dir_servers())
  1184. > smartlist_len(router_get_trusted_dir_servers())));
  1185. }
  1186. /* Check if there is more than 1 consensus connection retrieving the usable
  1187. * consensus flavor. If so, return 1, if not, return 0.
  1188. *
  1189. * During normal operation, Tor only makes one consensus download
  1190. * connection. But clients can make multiple simultaneous consensus
  1191. * connections to improve bootstrap speed and reliability.
  1192. *
  1193. * If there is more than one connection, we must have connections left
  1194. * over from bootstrapping. However, some of the connections may have
  1195. * completed and been cleaned up, so it is not sufficient to check the
  1196. * return value of this function to see if a client could make multiple
  1197. * bootstrap connections. Use
  1198. * networkstatus_consensus_can_use_multiple_directories()
  1199. * and networkstatus_consensus_is_bootstrapping(). */
  1200. int
  1201. networkstatus_consensus_has_excess_connections(void)
  1202. {
  1203. const char *usable_resource = networkstatus_get_flavor_name(
  1204. usable_consensus_flavor());
  1205. const int consens_conn_usable_count =
  1206. connection_dir_count_by_purpose_and_resource(
  1207. DIR_PURPOSE_FETCH_CONSENSUS,
  1208. usable_resource);
  1209. /* The maximum number of connections we want downloading a usable consensus
  1210. * Always 1, whether bootstrapping or not. */
  1211. const int max_expected_consens_conn_usable_count = 1;
  1212. if (consens_conn_usable_count > max_expected_consens_conn_usable_count) {
  1213. return 1;
  1214. }
  1215. return 0;
  1216. }
  1217. /* Is tor currently downloading a consensus of the usable flavor? */
  1218. int
  1219. networkstatus_consensus_is_downloading_usable_flavor(void)
  1220. {
  1221. const char *usable_resource = networkstatus_get_flavor_name(
  1222. usable_consensus_flavor());
  1223. const int consens_conn_usable_count =
  1224. connection_dir_count_by_purpose_and_resource(
  1225. DIR_PURPOSE_FETCH_CONSENSUS,
  1226. usable_resource);
  1227. const int connect_consens_conn_usable_count =
  1228. connection_dir_count_by_purpose_resource_and_state(
  1229. DIR_PURPOSE_FETCH_CONSENSUS,
  1230. usable_resource,
  1231. DIR_CONN_STATE_CONNECTING);
  1232. if (connect_consens_conn_usable_count < consens_conn_usable_count) {
  1233. return 1;
  1234. }
  1235. return 0;
  1236. }
  1237. /** Given two router status entries for the same router identity, return 1 if
  1238. * if the contents have changed between them. Otherwise, return 0. */
  1239. static int
  1240. routerstatus_has_changed(const routerstatus_t *a, const routerstatus_t *b)
  1241. {
  1242. tor_assert(tor_memeq(a->identity_digest, b->identity_digest, DIGEST_LEN));
  1243. return strcmp(a->nickname, b->nickname) ||
  1244. fast_memneq(a->descriptor_digest, b->descriptor_digest, DIGEST_LEN) ||
  1245. a->addr != b->addr ||
  1246. a->or_port != b->or_port ||
  1247. a->dir_port != b->dir_port ||
  1248. a->is_authority != b->is_authority ||
  1249. a->is_exit != b->is_exit ||
  1250. a->is_stable != b->is_stable ||
  1251. a->is_fast != b->is_fast ||
  1252. a->is_flagged_running != b->is_flagged_running ||
  1253. a->is_named != b->is_named ||
  1254. a->is_unnamed != b->is_unnamed ||
  1255. a->is_valid != b->is_valid ||
  1256. a->is_possible_guard != b->is_possible_guard ||
  1257. a->is_bad_exit != b->is_bad_exit ||
  1258. a->is_hs_dir != b->is_hs_dir ||
  1259. a->version_known != b->version_known;
  1260. }
  1261. /** Notify controllers of any router status entries that changed between
  1262. * <b>old_c</b> and <b>new_c</b>. */
  1263. static void
  1264. notify_control_networkstatus_changed(const networkstatus_t *old_c,
  1265. const networkstatus_t *new_c)
  1266. {
  1267. smartlist_t *changed;
  1268. if (old_c == new_c)
  1269. return;
  1270. /* tell the controller exactly which relays are still listed, as well
  1271. * as what they're listed as */
  1272. control_event_newconsensus(new_c);
  1273. if (!control_event_is_interesting(EVENT_NS))
  1274. return;
  1275. if (!old_c) {
  1276. control_event_networkstatus_changed(new_c->routerstatus_list);
  1277. return;
  1278. }
  1279. changed = smartlist_new();
  1280. SMARTLIST_FOREACH_JOIN(
  1281. old_c->routerstatus_list, const routerstatus_t *, rs_old,
  1282. new_c->routerstatus_list, const routerstatus_t *, rs_new,
  1283. tor_memcmp(rs_old->identity_digest,
  1284. rs_new->identity_digest, DIGEST_LEN),
  1285. smartlist_add(changed, (void*) rs_new)) {
  1286. if (routerstatus_has_changed(rs_old, rs_new))
  1287. smartlist_add(changed, (void*)rs_new);
  1288. } SMARTLIST_FOREACH_JOIN_END(rs_old, rs_new);
  1289. control_event_networkstatus_changed(changed);
  1290. smartlist_free(changed);
  1291. }
  1292. /** Copy all the ancillary information (like router download status and so on)
  1293. * from <b>old_c</b> to <b>new_c</b>. */
  1294. static void
  1295. networkstatus_copy_old_consensus_info(networkstatus_t *new_c,
  1296. const networkstatus_t *old_c)
  1297. {
  1298. if (old_c == new_c)
  1299. return;
  1300. if (!old_c || !smartlist_len(old_c->routerstatus_list))
  1301. return;
  1302. SMARTLIST_FOREACH_JOIN(old_c->routerstatus_list, routerstatus_t *, rs_old,
  1303. new_c->routerstatus_list, routerstatus_t *, rs_new,
  1304. tor_memcmp(rs_old->identity_digest,
  1305. rs_new->identity_digest, DIGEST_LEN),
  1306. STMT_NIL) {
  1307. /* Okay, so we're looking at the same identity. */
  1308. rs_new->last_dir_503_at = rs_old->last_dir_503_at;
  1309. if (tor_memeq(rs_old->descriptor_digest, rs_new->descriptor_digest,
  1310. DIGEST256_LEN)) {
  1311. /* And the same descriptor too! */
  1312. memcpy(&rs_new->dl_status, &rs_old->dl_status,sizeof(download_status_t));
  1313. }
  1314. } SMARTLIST_FOREACH_JOIN_END(rs_old, rs_new);
  1315. }
  1316. #ifdef TOR_UNIT_TESTS
  1317. /**Accept a <b>flavor</b> consensus <b>c</b> without any additional
  1318. * validation. This is exclusively for unit tests.
  1319. * We copy any ancillary information from a pre-existing consensus
  1320. * and then free the current one and replace it with the newly
  1321. * provided instance. Returns -1 on unrecognized flavor, 0 otherwise.
  1322. */
  1323. int
  1324. networkstatus_set_current_consensus_from_ns(networkstatus_t *c,
  1325. const char *flavor)
  1326. {
  1327. int flav = networkstatus_parse_flavor_name(flavor);
  1328. switch (flav) {
  1329. case FLAV_NS:
  1330. if (current_ns_consensus) {
  1331. networkstatus_copy_old_consensus_info(c, current_ns_consensus);
  1332. networkstatus_vote_free(current_ns_consensus);
  1333. }
  1334. current_ns_consensus = c;
  1335. break;
  1336. case FLAV_MICRODESC:
  1337. if (current_md_consensus) {
  1338. networkstatus_copy_old_consensus_info(c, current_md_consensus);
  1339. networkstatus_vote_free(current_md_consensus);
  1340. }
  1341. current_md_consensus = c;
  1342. break;
  1343. }
  1344. return current_md_consensus ? 0 : -1;
  1345. }
  1346. #endif //TOR_UNIT_TESTS
  1347. /** Try to replace the current cached v3 networkstatus with the one in
  1348. * <b>consensus</b>. If we don't have enough certificates to validate it,
  1349. * store it in consensus_waiting_for_certs and launch a certificate fetch.
  1350. *
  1351. * If flags & NSSET_FROM_CACHE, this networkstatus has come from the disk
  1352. * cache. If flags & NSSET_WAS_WAITING_FOR_CERTS, this networkstatus was
  1353. * already received, but we were waiting for certificates on it. If flags &
  1354. * NSSET_DONT_DOWNLOAD_CERTS, do not launch certificate downloads as needed.
  1355. * If flags & NSSET_ACCEPT_OBSOLETE, then we should be willing to take this
  1356. * consensus, even if it comes from many days in the past.
  1357. *
  1358. * Return 0 on success, <0 on failure. On failure, caller should increment
  1359. * the failure count as appropriate.
  1360. *
  1361. * We return -1 for mild failures that don't need to be reported to the
  1362. * user, and -2 for more serious problems.
  1363. */
  1364. int
  1365. networkstatus_set_current_consensus(const char *consensus,
  1366. const char *flavor,
  1367. unsigned flags)
  1368. {
  1369. networkstatus_t *c=NULL;
  1370. int r, result = -1;
  1371. time_t now = time(NULL);
  1372. const or_options_t *options = get_options();
  1373. char *unverified_fname = NULL, *consensus_fname = NULL;
  1374. int flav = networkstatus_parse_flavor_name(flavor);
  1375. const unsigned from_cache = flags & NSSET_FROM_CACHE;
  1376. const unsigned was_waiting_for_certs = flags & NSSET_WAS_WAITING_FOR_CERTS;
  1377. const unsigned dl_certs = !(flags & NSSET_DONT_DOWNLOAD_CERTS);
  1378. const unsigned accept_obsolete = flags & NSSET_ACCEPT_OBSOLETE;
  1379. const unsigned require_flavor = flags & NSSET_REQUIRE_FLAVOR;
  1380. const common_digests_t *current_digests = NULL;
  1381. consensus_waiting_for_certs_t *waiting = NULL;
  1382. time_t current_valid_after = 0;
  1383. int free_consensus = 1; /* Free 'c' at the end of the function */
  1384. int old_ewma_enabled;
  1385. if (flav < 0) {
  1386. /* XXXX we don't handle unrecognized flavors yet. */
  1387. log_warn(LD_BUG, "Unrecognized consensus flavor %s", flavor);
  1388. return -2;
  1389. }
  1390. /* Make sure it's parseable. */
  1391. c = networkstatus_parse_vote_from_string(consensus, NULL, NS_TYPE_CONSENSUS);
  1392. if (!c) {
  1393. log_warn(LD_DIR, "Unable to parse networkstatus consensus");
  1394. result = -2;
  1395. goto done;
  1396. }
  1397. if ((int)c->flavor != flav) {
  1398. /* This wasn't the flavor we thought we were getting. */
  1399. if (require_flavor) {
  1400. log_warn(LD_DIR, "Got consensus with unexpected flavor %s (wanted %s)",
  1401. networkstatus_get_flavor_name(c->flavor), flavor);
  1402. goto done;
  1403. }
  1404. flav = c->flavor;
  1405. flavor = networkstatus_get_flavor_name(flav);
  1406. }
  1407. if (flav != usable_consensus_flavor() &&
  1408. !directory_caches_dir_info(options)) {
  1409. /* This consensus is totally boring to us: we won't use it, and we won't
  1410. * serve it. Drop it. */
  1411. goto done;
  1412. }
  1413. if (from_cache && !accept_obsolete &&
  1414. c->valid_until < now-OLD_ROUTER_DESC_MAX_AGE) {
  1415. log_info(LD_DIR, "Loaded an expired consensus. Discarding.");
  1416. goto done;
  1417. }
  1418. if (!strcmp(flavor, "ns")) {
  1419. consensus_fname = get_datadir_fname("cached-consensus");
  1420. unverified_fname = get_datadir_fname("unverified-consensus");
  1421. if (current_ns_consensus) {
  1422. current_digests = &current_ns_consensus->digests;
  1423. current_valid_after = current_ns_consensus->valid_after;
  1424. }
  1425. } else if (!strcmp(flavor, "microdesc")) {
  1426. consensus_fname = get_datadir_fname("cached-microdesc-consensus");
  1427. unverified_fname = get_datadir_fname("unverified-microdesc-consensus");
  1428. if (current_md_consensus) {
  1429. current_digests = &current_md_consensus->digests;
  1430. current_valid_after = current_md_consensus->valid_after;
  1431. }
  1432. } else {
  1433. cached_dir_t *cur;
  1434. char buf[128];
  1435. tor_snprintf(buf, sizeof(buf), "cached-%s-consensus", flavor);
  1436. consensus_fname = get_datadir_fname(buf);
  1437. tor_snprintf(buf, sizeof(buf), "unverified-%s-consensus", flavor);
  1438. unverified_fname = get_datadir_fname(buf);
  1439. cur = dirserv_get_consensus(flavor);
  1440. if (cur) {
  1441. current_digests = &cur->digests;
  1442. current_valid_after = cur->published;
  1443. }
  1444. }
  1445. if (current_digests &&
  1446. tor_memeq(&c->digests, current_digests, sizeof(c->digests))) {
  1447. /* We already have this one. That's a failure. */
  1448. log_info(LD_DIR, "Got a %s consensus we already have", flavor);
  1449. goto done;
  1450. }
  1451. if (current_valid_after && c->valid_after <= current_valid_after) {
  1452. /* We have a newer one. There's no point in accepting this one,
  1453. * even if it's great. */
  1454. log_info(LD_DIR, "Got a %s consensus at least as old as the one we have",
  1455. flavor);
  1456. goto done;
  1457. }
  1458. /* Make sure it's signed enough. */
  1459. if ((r=networkstatus_check_consensus_signature(c, 1))<0) {
  1460. if (r == -1) {
  1461. /* Okay, so it _might_ be signed enough if we get more certificates. */
  1462. if (!was_waiting_for_certs) {
  1463. log_info(LD_DIR,
  1464. "Not enough certificates to check networkstatus consensus");
  1465. }
  1466. if (!current_valid_after ||
  1467. c->valid_after > current_valid_after) {
  1468. waiting = &consensus_waiting_for_certs[flav];
  1469. networkstatus_vote_free(waiting->consensus);
  1470. tor_free(waiting->body);
  1471. waiting->consensus = c;
  1472. free_consensus = 0;
  1473. waiting->body = tor_strdup(consensus);
  1474. waiting->set_at = now;
  1475. waiting->dl_failed = 0;
  1476. if (!from_cache) {
  1477. write_str_to_file(unverified_fname, consensus, 0);
  1478. }
  1479. if (dl_certs)
  1480. authority_certs_fetch_missing(c, now);
  1481. /* This case is not a success or a failure until we get the certs
  1482. * or fail to get the certs. */
  1483. result = 0;
  1484. } else {
  1485. /* Even if we had enough signatures, we'd never use this as the
  1486. * latest consensus. */
  1487. if (was_waiting_for_certs && from_cache)
  1488. if (unlink(unverified_fname) != 0) {
  1489. log_warn(LD_FS,
  1490. "Failed to unlink %s: %s",
  1491. unverified_fname, strerror(errno));
  1492. }
  1493. }
  1494. goto done;
  1495. } else {
  1496. /* This can never be signed enough: Kill it. */
  1497. if (!was_waiting_for_certs) {
  1498. log_warn(LD_DIR, "Not enough good signatures on networkstatus "
  1499. "consensus");
  1500. result = -2;
  1501. }
  1502. if (was_waiting_for_certs && (r < -1) && from_cache) {
  1503. if (unlink(unverified_fname) != 0) {
  1504. log_warn(LD_FS,
  1505. "Failed to unlink %s: %s",
  1506. unverified_fname, strerror(errno));
  1507. }
  1508. }
  1509. goto done;
  1510. }
  1511. }
  1512. if (!from_cache && flav == usable_consensus_flavor())
  1513. control_event_client_status(LOG_NOTICE, "CONSENSUS_ARRIVED");
  1514. /* Are we missing any certificates at all? */
  1515. if (r != 1 && dl_certs)
  1516. authority_certs_fetch_missing(c, now);
  1517. if (flav == usable_consensus_flavor()) {
  1518. notify_control_networkstatus_changed(current_consensus, c);
  1519. }
  1520. if (flav == FLAV_NS) {
  1521. if (current_ns_consensus) {
  1522. networkstatus_copy_old_consensus_info(c, current_ns_consensus);
  1523. networkstatus_vote_free(current_ns_consensus);
  1524. /* Defensive programming : we should set current_consensus very soon,
  1525. * but we're about to call some stuff in the meantime, and leaving this
  1526. * dangling pointer around has proven to be trouble. */
  1527. current_ns_consensus = NULL;
  1528. }
  1529. current_ns_consensus = c;
  1530. free_consensus = 0; /* avoid free */
  1531. } else if (flav == FLAV_MICRODESC) {
  1532. if (current_md_consensus) {
  1533. networkstatus_copy_old_consensus_info(c, current_md_consensus);
  1534. networkstatus_vote_free(current_md_consensus);
  1535. /* more defensive programming */
  1536. current_md_consensus = NULL;
  1537. }
  1538. current_md_consensus = c;
  1539. free_consensus = 0; /* avoid free */
  1540. }
  1541. waiting = &consensus_waiting_for_certs[flav];
  1542. if (waiting->consensus &&
  1543. waiting->consensus->valid_after <= c->valid_after) {
  1544. networkstatus_vote_free(waiting->consensus);
  1545. waiting->consensus = NULL;
  1546. if (consensus != waiting->body)
  1547. tor_free(waiting->body);
  1548. else
  1549. waiting->body = NULL;
  1550. waiting->set_at = 0;
  1551. waiting->dl_failed = 0;
  1552. if (unlink(unverified_fname) != 0) {
  1553. log_warn(LD_FS,
  1554. "Failed to unlink %s: %s",
  1555. unverified_fname, strerror(errno));
  1556. }
  1557. }
  1558. /* Reset the failure count only if this consensus is actually valid. */
  1559. if (c->valid_after <= now && now <= c->valid_until) {
  1560. download_status_reset(&consensus_dl_status[flav]);
  1561. } else {
  1562. if (!from_cache)
  1563. download_status_failed(&consensus_dl_status[flav], 0);
  1564. }
  1565. if (flav == usable_consensus_flavor()) {
  1566. /* XXXXNM Microdescs: needs a non-ns variant. ???? NM*/
  1567. update_consensus_networkstatus_fetch_time(now);
  1568. nodelist_set_consensus(current_consensus);
  1569. dirvote_recalculate_timing(options, now);
  1570. routerstatus_list_update_named_server_map();
  1571. /* Update ewma and adjust policy if needed; first cache the old value */
  1572. old_ewma_enabled = cell_ewma_enabled();
  1573. /* Change the cell EWMA settings */
  1574. cell_ewma_set_scale_factor(options, networkstatus_get_latest_consensus());
  1575. /* If we just enabled ewma, set the cmux policy on all active channels */
  1576. if (cell_ewma_enabled() && !old_ewma_enabled) {
  1577. channel_set_cmux_policy_everywhere(&ewma_policy);
  1578. } else if (!cell_ewma_enabled() && old_ewma_enabled) {
  1579. /* Turn it off everywhere */
  1580. channel_set_cmux_policy_everywhere(NULL);
  1581. }
  1582. /* XXXX024 this call might be unnecessary here: can changing the
  1583. * current consensus really alter our view of any OR's rate limits? */
  1584. connection_or_update_token_buckets(get_connection_array(), options);
  1585. circuit_build_times_new_consensus_params(get_circuit_build_times_mutable(),
  1586. current_consensus);
  1587. }
  1588. if (directory_caches_dir_info(options)) {
  1589. dirserv_set_cached_consensus_networkstatus(consensus,
  1590. flavor,
  1591. &c->digests,
  1592. c->valid_after);
  1593. }
  1594. if (!from_cache) {
  1595. write_str_to_file(consensus_fname, consensus, 0);
  1596. }
  1597. /** If a consensus appears more than this many seconds before its declared
  1598. * valid-after time, declare that our clock is skewed. */
  1599. #define EARLY_CONSENSUS_NOTICE_SKEW 60
  1600. if (now < c->valid_after - EARLY_CONSENSUS_NOTICE_SKEW) {
  1601. char tbuf[ISO_TIME_LEN+1];
  1602. char dbuf[64];
  1603. long delta = now - c->valid_after;
  1604. format_iso_time(tbuf, c->valid_after);
  1605. format_time_interval(dbuf, sizeof(dbuf), delta);
  1606. log_warn(LD_GENERAL, "Our clock is %s behind the time published in the "
  1607. "consensus network status document (%s UTC). Tor needs an "
  1608. "accurate clock to work correctly. Please check your time and "
  1609. "date settings!", dbuf, tbuf);
  1610. control_event_general_status(LOG_WARN,
  1611. "CLOCK_SKEW MIN_SKEW=%ld SOURCE=CONSENSUS", delta);
  1612. }
  1613. router_dir_info_changed();
  1614. result = 0;
  1615. done:
  1616. if (free_consensus)
  1617. networkstatus_vote_free(c);
  1618. tor_free(consensus_fname);
  1619. tor_free(unverified_fname);
  1620. return result;
  1621. }
  1622. /** Called when we have gotten more certificates: see whether we can
  1623. * now verify a pending consensus. */
  1624. void
  1625. networkstatus_note_certs_arrived(void)
  1626. {
  1627. int i;
  1628. for (i=0; i<N_CONSENSUS_FLAVORS; ++i) {
  1629. consensus_waiting_for_certs_t *waiting = &consensus_waiting_for_certs[i];
  1630. if (!waiting->consensus)
  1631. continue;
  1632. if (networkstatus_check_consensus_signature(waiting->consensus, 0)>=0) {
  1633. char *waiting_body = waiting->body;
  1634. if (!networkstatus_set_current_consensus(
  1635. waiting_body,
  1636. networkstatus_get_flavor_name(i),
  1637. NSSET_WAS_WAITING_FOR_CERTS)) {
  1638. tor_free(waiting_body);
  1639. }
  1640. }
  1641. }
  1642. }
  1643. /** If the network-status list has changed since the last time we called this
  1644. * function, update the status of every routerinfo from the network-status
  1645. * list. If <b>dir_version</b> is 2, it's a v2 networkstatus that changed.
  1646. * If <b>dir_version</b> is 3, it's a v3 consensus that changed.
  1647. */
  1648. void
  1649. routers_update_all_from_networkstatus(time_t now, int dir_version)
  1650. {
  1651. routerlist_t *rl = router_get_routerlist();
  1652. networkstatus_t *consensus = networkstatus_get_reasonably_live_consensus(now,
  1653. FLAV_NS);
  1654. if (!consensus || dir_version < 3) /* nothing more we should do */
  1655. return;
  1656. /* calls router_dir_info_changed() when it's done -- more routers
  1657. * might be up or down now, which might affect whether there's enough
  1658. * directory info. */
  1659. routers_update_status_from_consensus_networkstatus(rl->routers, 0);
  1660. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri,
  1661. ri->cache_info.routerlist_index = ri_sl_idx);
  1662. if (rl->old_routers)
  1663. signed_descs_update_status_from_consensus_networkstatus(rl->old_routers);
  1664. if (!have_warned_about_old_version) {
  1665. int is_server = server_mode(get_options());
  1666. version_status_t status;
  1667. const char *recommended = is_server ?
  1668. consensus->server_versions : consensus->client_versions;
  1669. status = tor_version_is_obsolete(VERSION, recommended);
  1670. if (status == VS_RECOMMENDED) {
  1671. log_info(LD_GENERAL, "The directory authorities say my version is ok.");
  1672. } else if (status == VS_EMPTY) {
  1673. log_info(LD_GENERAL,
  1674. "The directory authorities don't recommend any versions.");
  1675. } else if (status == VS_NEW || status == VS_NEW_IN_SERIES) {
  1676. if (!have_warned_about_new_version) {
  1677. log_notice(LD_GENERAL, "This version of Tor (%s) is newer than any "
  1678. "recommended version%s, according to the directory "
  1679. "authorities. Recommended versions are: %s",
  1680. VERSION,
  1681. status == VS_NEW_IN_SERIES ? " in its series" : "",
  1682. recommended);
  1683. have_warned_about_new_version = 1;
  1684. control_event_general_status(LOG_WARN, "DANGEROUS_VERSION "
  1685. "CURRENT=%s REASON=%s RECOMMENDED=\"%s\"",
  1686. VERSION, "NEW", recommended);
  1687. }
  1688. } else {
  1689. log_warn(LD_GENERAL, "Please upgrade! "
  1690. "This version of Tor (%s) is %s, according to the directory "
  1691. "authorities. Recommended versions are: %s",
  1692. VERSION,
  1693. status == VS_OLD ? "obsolete" : "not recommended",
  1694. recommended);
  1695. have_warned_about_old_version = 1;
  1696. control_event_general_status(LOG_WARN, "DANGEROUS_VERSION "
  1697. "CURRENT=%s REASON=%s RECOMMENDED=\"%s\"",
  1698. VERSION, status == VS_OLD ? "OBSOLETE" : "UNRECOMMENDED",
  1699. recommended);
  1700. }
  1701. }
  1702. }
  1703. /** Update our view of the list of named servers from the most recently
  1704. * retrieved networkstatus consensus. */
  1705. static void
  1706. routerstatus_list_update_named_server_map(void)
  1707. {
  1708. if (!current_consensus)
  1709. return;
  1710. strmap_free(named_server_map, tor_free_);
  1711. named_server_map = strmap_new();
  1712. strmap_free(unnamed_server_map, NULL);
  1713. unnamed_server_map = strmap_new();
  1714. SMARTLIST_FOREACH_BEGIN(current_consensus->routerstatus_list,
  1715. const routerstatus_t *, rs) {
  1716. if (rs->is_named) {
  1717. strmap_set_lc(named_server_map, rs->nickname,
  1718. tor_memdup(rs->identity_digest, DIGEST_LEN));
  1719. }
  1720. if (rs->is_unnamed) {
  1721. strmap_set_lc(unnamed_server_map, rs->nickname, (void*)1);
  1722. }
  1723. } SMARTLIST_FOREACH_END(rs);
  1724. }
  1725. /** Given a list <b>routers</b> of routerinfo_t *, update each status field
  1726. * according to our current consensus networkstatus. May re-order
  1727. * <b>routers</b>. */
  1728. void
  1729. routers_update_status_from_consensus_networkstatus(smartlist_t *routers,
  1730. int reset_failures)
  1731. {
  1732. const or_options_t *options = get_options();
  1733. int authdir = authdir_mode_v3(options);
  1734. networkstatus_t *ns = current_consensus;
  1735. if (!ns || !smartlist_len(ns->routerstatus_list))
  1736. return;
  1737. routers_sort_by_identity(routers);
  1738. SMARTLIST_FOREACH_JOIN(ns->routerstatus_list, routerstatus_t *, rs,
  1739. routers, routerinfo_t *, router,
  1740. tor_memcmp(rs->identity_digest,
  1741. router->cache_info.identity_digest, DIGEST_LEN),
  1742. {
  1743. }) {
  1744. /* Is it the same descriptor, or only the same identity? */
  1745. if (tor_memeq(router->cache_info.signed_descriptor_digest,
  1746. rs->descriptor_digest, DIGEST_LEN)) {
  1747. if (ns->valid_until > router->cache_info.last_listed_as_valid_until)
  1748. router->cache_info.last_listed_as_valid_until = ns->valid_until;
  1749. }
  1750. if (authdir) {
  1751. /* If we _are_ an authority, we should check whether this router
  1752. * is one that will cause us to need a reachability test. */
  1753. routerinfo_t *old_router =
  1754. router_get_mutable_by_digest(router->cache_info.identity_digest);
  1755. if (old_router != router) {
  1756. router->needs_retest_if_added =
  1757. dirserv_should_launch_reachability_test(router, old_router);
  1758. }
  1759. }
  1760. if (reset_failures) {
  1761. download_status_reset(&rs->dl_status);
  1762. }
  1763. } SMARTLIST_FOREACH_JOIN_END(rs, router);
  1764. router_dir_info_changed();
  1765. }
  1766. /** Given a list of signed_descriptor_t, update their fields (mainly, when
  1767. * they were last listed) from the most recent consensus. */
  1768. void
  1769. signed_descs_update_status_from_consensus_networkstatus(smartlist_t *descs)
  1770. {
  1771. networkstatus_t *ns = current_ns_consensus;
  1772. if (!ns)
  1773. return;
  1774. if (!ns->desc_digest_map) {
  1775. char dummy[DIGEST_LEN];
  1776. /* instantiates the digest map. */
  1777. memset(dummy, 0, sizeof(dummy));
  1778. router_get_consensus_status_by_descriptor_digest(ns, dummy);
  1779. }
  1780. SMARTLIST_FOREACH(descs, signed_descriptor_t *, d,
  1781. {
  1782. const routerstatus_t *rs = digestmap_get(ns->desc_digest_map,
  1783. d->signed_descriptor_digest);
  1784. if (rs) {
  1785. if (ns->valid_until > d->last_listed_as_valid_until)
  1786. d->last_listed_as_valid_until = ns->valid_until;
  1787. }
  1788. });
  1789. }
  1790. /** Generate networkstatus lines for a single routerstatus_t object, and
  1791. * return the result in a newly allocated string. Used only by controller
  1792. * interface (for now.) */
  1793. char *
  1794. networkstatus_getinfo_helper_single(const routerstatus_t *rs)
  1795. {
  1796. return routerstatus_format_entry(rs, NULL, NS_CONTROL_PORT, NULL);
  1797. }
  1798. /** Alloc and return a string describing routerstatuses for the most
  1799. * recent info of each router we know about that is of purpose
  1800. * <b>purpose_string</b>. Return NULL if unrecognized purpose.
  1801. *
  1802. * Right now this function is oriented toward listing bridges (you
  1803. * shouldn't use this for general-purpose routers, since those
  1804. * should be listed from the consensus, not from the routers list). */
  1805. char *
  1806. networkstatus_getinfo_by_purpose(const char *purpose_string, time_t now)
  1807. {
  1808. time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
  1809. char *answer;
  1810. routerlist_t *rl = router_get_routerlist();
  1811. smartlist_t *statuses;
  1812. uint8_t purpose = router_purpose_from_string(purpose_string);
  1813. routerstatus_t rs;
  1814. int bridge_auth = authdir_mode_bridge(get_options());
  1815. if (purpose == ROUTER_PURPOSE_UNKNOWN) {
  1816. log_info(LD_DIR, "Unrecognized purpose '%s' when listing router statuses.",
  1817. purpose_string);
  1818. return NULL;
  1819. }
  1820. statuses = smartlist_new();
  1821. SMARTLIST_FOREACH_BEGIN(rl->routers, routerinfo_t *, ri) {
  1822. node_t *node = node_get_mutable_by_id(ri->cache_info.identity_digest);
  1823. if (!node)
  1824. continue;
  1825. if (ri->cache_info.published_on < cutoff)
  1826. continue;
  1827. if (ri->purpose != purpose)
  1828. continue;
  1829. if (bridge_auth && ri->purpose == ROUTER_PURPOSE_BRIDGE)
  1830. dirserv_set_router_is_running(ri, now);
  1831. /* then generate and write out status lines for each of them */
  1832. set_routerstatus_from_routerinfo(&rs, node, ri, now, 0);
  1833. smartlist_add(statuses, networkstatus_getinfo_helper_single(&rs));
  1834. } SMARTLIST_FOREACH_END(ri);
  1835. answer = smartlist_join_strings(statuses, "", 0, NULL);
  1836. SMARTLIST_FOREACH(statuses, char *, cp, tor_free(cp));
  1837. smartlist_free(statuses);
  1838. return answer;
  1839. }
  1840. /** Write out router status entries for all our bridge descriptors. */
  1841. void
  1842. networkstatus_dump_bridge_status_to_file(time_t now)
  1843. {
  1844. char *status = networkstatus_getinfo_by_purpose("bridge", now);
  1845. const or_options_t *options = get_options();
  1846. char *fname = NULL;
  1847. char *thresholds = NULL;
  1848. char *published_thresholds_and_status = NULL;
  1849. routerlist_t *rl = router_get_routerlist();
  1850. char published[ISO_TIME_LEN+1];
  1851. format_iso_time(published, now);
  1852. dirserv_compute_bridge_flag_thresholds(rl->routers);
  1853. thresholds = dirserv_get_flag_thresholds_line();
  1854. tor_asprintf(&published_thresholds_and_status,
  1855. "published %s\nflag-thresholds %s\n%s",
  1856. published, thresholds, status);
  1857. tor_asprintf(&fname, "%s"PATH_SEPARATOR"networkstatus-bridges",
  1858. options->DataDirectory);
  1859. write_str_to_file(fname,published_thresholds_and_status,0);
  1860. tor_free(thresholds);
  1861. tor_free(published_thresholds_and_status);
  1862. tor_free(fname);
  1863. tor_free(status);
  1864. }
  1865. /* DOCDOC get_net_param_from_list */
  1866. static int32_t
  1867. get_net_param_from_list(smartlist_t *net_params, const char *param_name,
  1868. int32_t default_val, int32_t min_val, int32_t max_val)
  1869. {
  1870. int32_t res = default_val;
  1871. size_t name_len = strlen(param_name);
  1872. tor_assert(max_val > min_val);
  1873. tor_assert(min_val <= default_val);
  1874. tor_assert(max_val >= default_val);
  1875. SMARTLIST_FOREACH_BEGIN(net_params, const char *, p) {
  1876. if (!strcmpstart(p, param_name) && p[name_len] == '=') {
  1877. int ok=0;
  1878. long v = tor_parse_long(p+name_len+1, 10, INT32_MIN,
  1879. INT32_MAX, &ok, NULL);
  1880. if (ok) {
  1881. res = (int32_t) v;
  1882. break;
  1883. }
  1884. }
  1885. } SMARTLIST_FOREACH_END(p);
  1886. if (res < min_val) {
  1887. log_warn(LD_DIR, "Consensus parameter %s is too small. Got %d, raising to "
  1888. "%d.", param_name, res, min_val);
  1889. res = min_val;
  1890. } else if (res > max_val) {
  1891. log_warn(LD_DIR, "Consensus parameter %s is too large. Got %d, capping to "
  1892. "%d.", param_name, res, max_val);
  1893. res = max_val;
  1894. }
  1895. return res;
  1896. }
  1897. /** Return the value of a integer parameter from the networkstatus <b>ns</b>
  1898. * whose name is <b>param_name</b>. If <b>ns</b> is NULL, try loading the
  1899. * latest consensus ourselves. Return <b>default_val</b> if no latest
  1900. * consensus, or if it has no parameter called <b>param_name</b>.
  1901. * Make sure the value parsed from the consensus is at least
  1902. * <b>min_val</b> and at most <b>max_val</b> and raise/cap the parsed value
  1903. * if necessary. */
  1904. int32_t
  1905. networkstatus_get_param(const networkstatus_t *ns, const char *param_name,
  1906. int32_t default_val, int32_t min_val, int32_t max_val)
  1907. {
  1908. if (!ns) /* if they pass in null, go find it ourselves */
  1909. ns = networkstatus_get_latest_consensus();
  1910. if (!ns || !ns->net_params)
  1911. return default_val;
  1912. return get_net_param_from_list(ns->net_params, param_name,
  1913. default_val, min_val, max_val);
  1914. }
  1915. /**
  1916. * Retrieve the consensus parameter that governs the
  1917. * fixed-point precision of our network balancing 'bandwidth-weights'
  1918. * (which are themselves integer consensus values). We divide them
  1919. * by this value and ensure they never exceed this value.
  1920. */
  1921. int
  1922. networkstatus_get_weight_scale_param(networkstatus_t *ns)
  1923. {
  1924. return networkstatus_get_param(ns, "bwweightscale",
  1925. BW_WEIGHT_SCALE,
  1926. BW_MIN_WEIGHT_SCALE,
  1927. BW_MAX_WEIGHT_SCALE);
  1928. }
  1929. /** Return the value of a integer bw weight parameter from the networkstatus
  1930. * <b>ns</b> whose name is <b>weight_name</b>. If <b>ns</b> is NULL, try
  1931. * loading the latest consensus ourselves. Return <b>default_val</b> if no
  1932. * latest consensus, or if it has no parameter called <b>weight_name</b>. */
  1933. int32_t
  1934. networkstatus_get_bw_weight(networkstatus_t *ns, const char *weight_name,
  1935. int32_t default_val)
  1936. {
  1937. int32_t param;
  1938. int max;
  1939. if (!ns) /* if they pass in null, go find it ourselves */
  1940. ns = networkstatus_get_latest_consensus();
  1941. if (!ns || !ns->weight_params)
  1942. return default_val;
  1943. max = networkstatus_get_weight_scale_param(ns);
  1944. param = get_net_param_from_list(ns->weight_params, weight_name,
  1945. default_val, -1,
  1946. BW_MAX_WEIGHT_SCALE);
  1947. if (param > max) {
  1948. log_warn(LD_DIR, "Value of consensus weight %s was too large, capping "
  1949. "to %d", weight_name, max);
  1950. param = max;
  1951. }
  1952. return param;
  1953. }
  1954. /** Return the name of the consensus flavor <b>flav</b> as used to identify
  1955. * the flavor in directory documents. */
  1956. const char *
  1957. networkstatus_get_flavor_name(consensus_flavor_t flav)
  1958. {
  1959. switch (flav) {
  1960. case FLAV_NS:
  1961. return "ns";
  1962. case FLAV_MICRODESC:
  1963. return "microdesc";
  1964. default:
  1965. tor_fragile_assert();
  1966. return "??";
  1967. }
  1968. }
  1969. /** Return the consensus_flavor_t value for the flavor called <b>flavname</b>,
  1970. * or -1 if the flavor is not recognized. */
  1971. int
  1972. networkstatus_parse_flavor_name(const char *flavname)
  1973. {
  1974. if (!strcmp(flavname, "ns"))
  1975. return FLAV_NS;
  1976. else if (!strcmp(flavname, "microdesc"))
  1977. return FLAV_MICRODESC;
  1978. else
  1979. return -1;
  1980. }
  1981. /** Return 0 if this routerstatus is obsolete, too new, isn't
  1982. * running, or otherwise not a descriptor that we would make any
  1983. * use of even if we had it. Else return 1. */
  1984. int
  1985. client_would_use_router(const routerstatus_t *rs, time_t now,
  1986. const or_options_t *options)
  1987. {
  1988. if (!rs->is_flagged_running && !options->FetchUselessDescriptors) {
  1989. /* If we had this router descriptor, we wouldn't even bother using it.
  1990. * But, if we want to have a complete list, fetch it anyway. */
  1991. return 0;
  1992. }
  1993. if (rs->published_on + options->TestingEstimatedDescriptorPropagationTime
  1994. > now) {
  1995. /* Most caches probably don't have this descriptor yet. */
  1996. return 0;
  1997. }
  1998. if (rs->published_on + OLD_ROUTER_DESC_MAX_AGE < now) {
  1999. /* We'd drop it immediately for being too old. */
  2000. return 0;
  2001. }
  2002. return 1;
  2003. }
  2004. /** If <b>question</b> is a string beginning with "ns/" in a format the
  2005. * control interface expects for a GETINFO question, set *<b>answer</b> to a
  2006. * newly-allocated string containing networkstatus lines for the appropriate
  2007. * ORs. Return 0 on success, -1 on unrecognized question format. */
  2008. int
  2009. getinfo_helper_networkstatus(control_connection_t *conn,
  2010. const char *question, char **answer,
  2011. const char **errmsg)
  2012. {
  2013. const routerstatus_t *status;
  2014. (void) conn;
  2015. if (!current_consensus) {
  2016. *answer = tor_strdup("");
  2017. return 0;
  2018. }
  2019. if (!strcmp(question, "ns/all")) {
  2020. smartlist_t *statuses = smartlist_new();
  2021. SMARTLIST_FOREACH(current_consensus->routerstatus_list,
  2022. const routerstatus_t *, rs,
  2023. {
  2024. smartlist_add(statuses, networkstatus_getinfo_helper_single(rs));
  2025. });
  2026. *answer = smartlist_join_strings(statuses, "", 0, NULL);
  2027. SMARTLIST_FOREACH(statuses, char *, cp, tor_free(cp));
  2028. smartlist_free(statuses);
  2029. return 0;
  2030. } else if (!strcmpstart(question, "ns/id/")) {
  2031. char d[DIGEST_LEN];
  2032. const char *q = question + 6;
  2033. if (*q == '$')
  2034. ++q;
  2035. if (base16_decode(d, DIGEST_LEN, q, strlen(q))) {
  2036. *errmsg = "Data not decodeable as hex";
  2037. return -1;
  2038. }
  2039. status = router_get_consensus_status_by_id(d);
  2040. } else if (!strcmpstart(question, "ns/name/")) {
  2041. status = router_get_consensus_status_by_nickname(question+8, 0);
  2042. } else if (!strcmpstart(question, "ns/purpose/")) {
  2043. *answer = networkstatus_getinfo_by_purpose(question+11, time(NULL));
  2044. return *answer ? 0 : -1;
  2045. } else if (!strcmp(question, "consensus/packages")) {
  2046. const networkstatus_t *ns = networkstatus_get_latest_consensus();
  2047. if (ns && ns->package_lines)
  2048. *answer = smartlist_join_strings(ns->package_lines, "\n", 0, NULL);
  2049. else
  2050. *errmsg = "No consensus available";
  2051. return *answer ? 0 : -1;
  2052. } else if (!strcmp(question, "consensus/valid-after") ||
  2053. !strcmp(question, "consensus/fresh-until") ||
  2054. !strcmp(question, "consensus/valid-until")) {
  2055. const networkstatus_t *ns = networkstatus_get_latest_consensus();
  2056. if (ns) {
  2057. time_t t;
  2058. if (!strcmp(question, "consensus/valid-after"))
  2059. t = ns->valid_after;
  2060. else if (!strcmp(question, "consensus/fresh-until"))
  2061. t = ns->fresh_until;
  2062. else
  2063. t = ns->valid_until;
  2064. char tbuf[ISO_TIME_LEN+1];
  2065. format_iso_time(tbuf, t);
  2066. *answer = tor_strdup(tbuf);
  2067. } else {
  2068. *errmsg = "No consensus available";
  2069. }
  2070. return *answer ? 0 : -1;
  2071. } else {
  2072. return 0;
  2073. }
  2074. if (status)
  2075. *answer = networkstatus_getinfo_helper_single(status);
  2076. return 0;
  2077. }
  2078. /** Free all storage held locally in this module. */
  2079. void
  2080. networkstatus_free_all(void)
  2081. {
  2082. int i;
  2083. networkstatus_vote_free(current_ns_consensus);
  2084. networkstatus_vote_free(current_md_consensus);
  2085. current_md_consensus = current_ns_consensus = NULL;
  2086. for (i=0; i < N_CONSENSUS_FLAVORS; ++i) {
  2087. consensus_waiting_for_certs_t *waiting = &consensus_waiting_for_certs[i];
  2088. if (waiting->consensus) {
  2089. networkstatus_vote_free(waiting->consensus);
  2090. waiting->consensus = NULL;
  2091. }
  2092. tor_free(waiting->body);
  2093. }
  2094. strmap_free(named_server_map, tor_free_);
  2095. strmap_free(unnamed_server_map, NULL);
  2096. }