networkstatus.c 89 KB

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