networkstatus.c 83 KB

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