networkstatus.c 83 KB

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