networkstatus.c 82 KB

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