networkstatus.c 76 KB

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