networkstatus.c 83 KB

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