networkstatus.c 83 KB

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