networkstatus.c 81 KB

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