networkstatus.c 84 KB

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