networkstatus.c 80 KB

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