networkstatus.c 84 KB

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