networkstatus.c 87 KB

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