routerlist.c 92 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779
  1. /* Copyright 2001 Matej Pfajfar.
  2. * Copyright 2001-2004 Roger Dingledine.
  3. * Copyright 2004-2005 Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char routerlist_c_id[] = "$Id$";
  7. /**
  8. * \file routerlist.c
  9. * \brief Code to
  10. * maintain and access the global list of routerinfos for known
  11. * servers.
  12. **/
  13. #include "or.h"
  14. /****************************************************************************/
  15. /** Global list of a trusted_dir_server_t object for each trusted directory
  16. * server. */
  17. static smartlist_t *trusted_dir_servers = NULL;
  18. /* static function prototypes */
  19. static routerinfo_t *router_pick_directory_server_impl(int requireother,
  20. int fascistfirewall,
  21. int for_v2_directory);
  22. static trusted_dir_server_t *router_pick_trusteddirserver_impl(
  23. int need_v1_support, int requireother, int fascistfirewall);
  24. static void mark_all_trusteddirservers_up(void);
  25. static int router_nickname_is_in_list(routerinfo_t *router, const char *list);
  26. static int router_nickname_matches(routerinfo_t *router, const char *nickname);
  27. static void routerstatus_list_update_from_networkstatus(time_t now);
  28. static void local_routerstatus_free(local_routerstatus_t *rs);
  29. static void trusted_dir_server_free(trusted_dir_server_t *ds);
  30. static void update_networkstatus_cache_downloads(time_t now);
  31. static void update_networkstatus_client_downloads(time_t now);
  32. /****************************************************************************/
  33. /****
  34. * Functions to manage and access our list of known routers. (Note:
  35. * dirservers maintain a separate, independent list of known router
  36. * descriptors.)
  37. ****/
  38. /** Global list of all of the routers that we know about. */
  39. static routerlist_t *routerlist = NULL;
  40. extern int has_fetched_directory; /**< from main.c */
  41. /** Global list of all of the current network_status documents that we know
  42. * about. This list is kept sorted by published_on. */
  43. static smartlist_t *networkstatus_list = NULL;
  44. /** Global list of local_routerstatus_t for each router, known or unknown. */
  45. static smartlist_t *routerstatus_list = NULL;
  46. /** True iff any member of networkstatus_list has changed since the last time
  47. * we called routerstatus_list_update_from_networkstatus(). */
  48. static int networkstatus_list_has_changed = 0;
  49. /** True iff any element of routerstatus_list has changed since the last
  50. * time we called routers_update_all_from_networkstatus().*/
  51. static int routerstatus_list_has_changed = 0;
  52. /** List of strings for nicknames we've already warned about and that are
  53. * still unknown / unavailable. */
  54. static smartlist_t *warned_nicknames = NULL;
  55. /** List of strings for nicknames or fingerprints we've already warned about
  56. * and that are still conflicted. */
  57. static smartlist_t *warned_conflicts = NULL;
  58. /* DOCDOC */
  59. static time_t last_routerdesc_download_attempted = 0;
  60. /* DOCDOC */
  61. static time_t last_networkstatus_download_attempted = 0;
  62. /*DOCDOC*/
  63. static int have_warned_about_unverified_status = 0;
  64. static int have_warned_about_old_version = 0;
  65. static int have_warned_about_new_version = 0;
  66. /** Repopulate our list of network_status_t objects from the list cached on
  67. * disk. Return 0 on success, -1 on failure. */
  68. int
  69. router_reload_networkstatus(void)
  70. {
  71. char filename[512];
  72. struct stat st;
  73. smartlist_t *entries;
  74. char *s;
  75. tor_assert(get_options()->DataDirectory);
  76. if (!networkstatus_list)
  77. networkstatus_list = smartlist_create();
  78. tor_snprintf(filename,sizeof(filename),"%s/cached-status",
  79. get_options()->DataDirectory);
  80. entries = tor_listdir(filename);
  81. SMARTLIST_FOREACH(entries, const char *, fn, {
  82. char buf[DIGEST_LEN];
  83. if (strlen(fn) != HEX_DIGEST_LEN ||
  84. base16_decode(buf, sizeof(buf), fn, strlen(fn))) {
  85. log_fn(LOG_INFO,
  86. "Skipping cached-status file with unexpected name \"%s\"",fn);
  87. continue;
  88. }
  89. tor_snprintf(filename,sizeof(filename),"%s/cached-status/%s",
  90. get_options()->DataDirectory, fn);
  91. s = read_file_to_str(filename, 0);
  92. if (s) {
  93. stat(filename, &st);
  94. if (router_set_networkstatus(s, st.st_mtime, NS_FROM_CACHE, NULL)<0) {
  95. log_fn(LOG_WARN, "Couldn't load networkstatus from \"%s\"",filename);
  96. }
  97. tor_free(s);
  98. }
  99. });
  100. SMARTLIST_FOREACH(entries, char *, fn, tor_free(fn));
  101. smartlist_free(entries);
  102. networkstatus_list_clean(time(NULL));
  103. routers_update_all_from_networkstatus();
  104. return 0;
  105. }
  106. /* Router descriptor storage.
  107. *
  108. * Routerdescs are stored in a big file, named "cached-routers". As new
  109. * routerdescs arrive, we append them to a journal file named
  110. * "cached-routers.new".
  111. *
  112. * From time to time, we replace "cached-routers" with a new file containing
  113. * only the live, non-superseded descriptors, and clear cached-routers.new.
  114. *
  115. * On startup, we read both files.
  116. */
  117. /** The size of the router log, in bytes. */
  118. static size_t router_journal_len = 0;
  119. /** The size of the router store, in bytes. */
  120. static size_t router_store_len = 0;
  121. /** Helper: return 1 iff the router log is so big we want to rebuild the
  122. * store. */
  123. static int
  124. router_should_rebuild_store(void)
  125. {
  126. if (router_store_len > (1<<16))
  127. return router_journal_len > router_store_len / 2;
  128. else
  129. return router_journal_len > (1<<15);
  130. }
  131. /** Add the <b>len</b>-type router descriptor in <b>s</b> to the router
  132. * journal. */
  133. static int
  134. router_append_to_journal(const char *s, size_t len)
  135. {
  136. or_options_t *options = get_options();
  137. size_t fname_len = strlen(options->DataDirectory)+32;
  138. char *fname = tor_malloc(len);
  139. tor_snprintf(fname, fname_len, "%s/cached-routers.new",
  140. options->DataDirectory);
  141. if (!len)
  142. len = strlen(s);
  143. if (append_bytes_to_file(fname, s, len, 0)) {
  144. log_fn(LOG_WARN, "Unable to store router descriptor");
  145. tor_free(fname);
  146. return -1;
  147. }
  148. tor_free(fname);
  149. router_journal_len += len;
  150. return 0;
  151. }
  152. /** If the journal is too long, or if <b>force</b> is true, then atomically
  153. * replace the router store with the routers currently in our routerlist, and
  154. * clear the journal. Return 0 on success, -1 on failure.
  155. */
  156. static int
  157. router_rebuild_store(int force)
  158. {
  159. size_t len = 0;
  160. or_options_t *options;
  161. size_t fname_len;
  162. smartlist_t *chunk_list = NULL;
  163. char *fname = NULL;
  164. int r = -1;
  165. if (!force && !router_should_rebuild_store())
  166. return 0;
  167. if (!routerlist)
  168. return 0;
  169. /* Don't save deadweight. */
  170. routerlist_remove_old_routers(ROUTER_MAX_AGE);
  171. options = get_options();
  172. fname_len = strlen(options->DataDirectory)+32;
  173. fname = tor_malloc(fname_len);
  174. tor_snprintf(fname, fname_len, "%s/cached-routers", options->DataDirectory);
  175. chunk_list = smartlist_create();
  176. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
  177. {
  178. sized_chunk_t *c;
  179. if (!ri->signed_descriptor) {
  180. log_fn(LOG_WARN, "Bug! No descriptor stored for router '%s'.",
  181. ri->nickname);
  182. goto done;
  183. }
  184. c = tor_malloc(sizeof(sized_chunk_t));
  185. c->bytes = ri->signed_descriptor;
  186. c->len = ri->signed_descriptor_len;
  187. smartlist_add(chunk_list, c);
  188. });
  189. if (write_chunks_to_file(fname, chunk_list, 0)<0) {
  190. log_fn(LOG_WARN, "Error writing router store to disk.");
  191. goto done;
  192. }
  193. tor_snprintf(fname, fname_len, "%s/cached-routers.new",
  194. options->DataDirectory);
  195. write_str_to_file(fname, "", 0);
  196. r = 0;
  197. router_store_len = len;
  198. router_journal_len = 0;
  199. done:
  200. tor_free(fname);
  201. if (chunk_list) {
  202. SMARTLIST_FOREACH(chunk_list, sized_chunk_t *, c, tor_free(c));
  203. smartlist_free(chunk_list);
  204. }
  205. return r;
  206. }
  207. /* Load all cached router descriptors from the store. Return 0 on success and
  208. * -1 on failure.
  209. */
  210. int
  211. router_reload_router_list(void)
  212. {
  213. or_options_t *options = get_options();
  214. size_t fname_len = strlen(options->DataDirectory)+32;
  215. char *fname = tor_malloc(fname_len);
  216. struct stat st;
  217. int j;
  218. if (!routerlist) {
  219. routerlist = tor_malloc_zero(sizeof(routerlist_t));
  220. routerlist->routers = smartlist_create();
  221. }
  222. router_journal_len = router_store_len = 0;
  223. for (j = 0; j < 2; ++j) {
  224. char *contents;
  225. tor_snprintf(fname, fname_len,
  226. (j==0)?"%s/cached-routers":"%s/cached-routers.new",
  227. options->DataDirectory);
  228. contents = read_file_to_str(fname, 0);
  229. if (contents) {
  230. stat(fname, &st);
  231. if (j==0)
  232. router_store_len = st.st_size;
  233. else
  234. router_journal_len = st.st_size;
  235. router_load_routers_from_string(contents, 1, NULL);
  236. tor_free(contents);
  237. }
  238. }
  239. tor_free(fname);
  240. /* Don't cache expired routers. */
  241. routerlist_remove_old_routers(ROUTER_MAX_AGE);
  242. if (router_journal_len) {
  243. /* Always clear the journal on startup.*/
  244. router_rebuild_store(1);
  245. }
  246. return 0;
  247. }
  248. /** Set *<b>outp</b> to a smartlist containing a list of
  249. * trusted_dir_server_t * for all known trusted dirservers. Callers
  250. * must not modify the list or its contents.
  251. */
  252. void
  253. router_get_trusted_dir_servers(smartlist_t **outp)
  254. {
  255. if (!trusted_dir_servers)
  256. trusted_dir_servers = smartlist_create();
  257. *outp = trusted_dir_servers;
  258. }
  259. /** Try to find a running dirserver. If there are no running dirservers
  260. * in our routerlist and <b>retry_if_no_servers</b> is non-zero,
  261. * set all the authoritative ones as running again, and pick one;
  262. * if there are then no dirservers at all in our routerlist,
  263. * reload the routerlist and try one last time. If for_runningrouters is
  264. * true, then only pick a dirserver that can answer runningrouters queries
  265. * (that is, a trusted dirserver, or one running 0.0.9rc5-cvs or later).
  266. * Other args are as in router_pick_directory_server_impl().
  267. */
  268. routerinfo_t *
  269. router_pick_directory_server(int requireother,
  270. int fascistfirewall,
  271. int for_v2_directory,
  272. int retry_if_no_servers)
  273. {
  274. routerinfo_t *choice;
  275. if (!routerlist)
  276. return NULL;
  277. choice = router_pick_directory_server_impl(requireother, fascistfirewall,
  278. for_v2_directory);
  279. if (choice || !retry_if_no_servers)
  280. return choice;
  281. log_fn(LOG_INFO,"No reachable router entries for dirservers. Trying them all again.");
  282. /* mark all authdirservers as up again */
  283. mark_all_trusteddirservers_up();
  284. /* try again */
  285. choice = router_pick_directory_server_impl(requireother, fascistfirewall,
  286. for_v2_directory);
  287. if (choice)
  288. return choice;
  289. log_fn(LOG_INFO,"Still no %s router entries. Reloading and trying again.",
  290. firewall_is_fascist() ? "reachable" : "known");
  291. has_fetched_directory=0; /* reset it */
  292. if (router_reload_router_list()) {
  293. return NULL;
  294. }
  295. /* give it one last try */
  296. choice = router_pick_directory_server_impl(requireother, 0,
  297. for_v2_directory);
  298. return choice;
  299. }
  300. trusted_dir_server_t *
  301. router_get_trusteddirserver_by_digest(const char *digest)
  302. {
  303. if (!trusted_dir_servers)
  304. return NULL;
  305. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  306. {
  307. if (!memcmp(ds->digest, digest, DIGEST_LEN))
  308. return ds;
  309. });
  310. return NULL;
  311. }
  312. /** Try to find a running trusted dirserver. If there are no running
  313. * trusted dirservers and <b>retry_if_no_servers</b> is non-zero,
  314. * set them all as running again, and try again.
  315. * Other args are as in router_pick_trusteddirserver_impl().
  316. */
  317. trusted_dir_server_t *
  318. router_pick_trusteddirserver(int need_v1_support,
  319. int requireother,
  320. int fascistfirewall,
  321. int retry_if_no_servers)
  322. {
  323. trusted_dir_server_t *choice;
  324. choice = router_pick_trusteddirserver_impl(need_v1_support,
  325. requireother, fascistfirewall);
  326. if (choice || !retry_if_no_servers)
  327. return choice;
  328. log_fn(LOG_INFO,"No trusted dirservers are reachable. Trying them all again.");
  329. mark_all_trusteddirservers_up();
  330. return router_pick_trusteddirserver_impl(need_v1_support,
  331. requireother, fascistfirewall);
  332. }
  333. /** Pick a random running verified directory server/mirror from our
  334. * routerlist.
  335. * If <b>fascistfirewall</b> and we're not using a proxy,
  336. * make sure the port we pick is allowed by options-\>firewallports.
  337. * If <b>requireother</b>, it cannot be us. If <b>for_v2_directory</b>,
  338. * choose a directory server new enough to support the v2 directory
  339. * functionality.
  340. */
  341. static routerinfo_t *
  342. router_pick_directory_server_impl(int requireother, int fascistfirewall,
  343. int for_v2_directory)
  344. {
  345. routerinfo_t *result;
  346. smartlist_t *sl;
  347. if (!routerlist)
  348. return NULL;
  349. if (get_options()->HttpProxy)
  350. fascistfirewall = 0;
  351. /* Find all the running dirservers we know about. */
  352. sl = smartlist_create();
  353. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  354. {
  355. if (!router->is_running || !router->dir_port || !router->is_verified)
  356. continue;
  357. if (requireother && router_is_me(router))
  358. continue;
  359. if (fascistfirewall) {
  360. if (!fascist_firewall_allows_address(router->addr, router->dir_port))
  361. continue;
  362. }
  363. /* Before 0.1.1.6-alpha, only trusted dirservers served status info.
  364. * Before 0.1.1.7-alpha, retrieving nonexistent server IDs could bork
  365. * the directory server.
  366. */
  367. if (for_v2_directory &&
  368. !(tor_version_as_new_as(router->platform,"0.1.1.7-alpha") ||
  369. router_digest_is_trusted_dir(router->identity_digest)))
  370. continue;
  371. smartlist_add(sl, router);
  372. });
  373. result = smartlist_choose(sl);
  374. smartlist_free(sl);
  375. return result;
  376. }
  377. /** Choose randomly from among the trusted dirservers that are up.
  378. * If <b>fascistfirewall</b> and we're not using a proxy,
  379. * make sure the port we pick is allowed by options-\>firewallports.
  380. * If <b>requireother</b>, it cannot be us. If <b>need_v1_support</b>, choose
  381. * a trusted authority for the v1 directory system.
  382. */
  383. static trusted_dir_server_t *
  384. router_pick_trusteddirserver_impl(int need_v1_support,
  385. int requireother, int fascistfirewall)
  386. {
  387. smartlist_t *sl;
  388. routerinfo_t *me;
  389. trusted_dir_server_t *ds;
  390. sl = smartlist_create();
  391. me = router_get_my_routerinfo();
  392. if (!trusted_dir_servers)
  393. return NULL;
  394. if (get_options()->HttpProxy)
  395. fascistfirewall = 0;
  396. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
  397. {
  398. if (!d->is_running) continue;
  399. if (need_v1_support && !d->supports_v1_protocol)
  400. continue;
  401. if (requireother && me &&
  402. !memcmp(me->identity_digest, d->digest, DIGEST_LEN))
  403. continue;
  404. if (fascistfirewall) {
  405. if (!fascist_firewall_allows_address(d->addr, d->dir_port))
  406. continue;
  407. }
  408. smartlist_add(sl, d);
  409. });
  410. ds = smartlist_choose(sl);
  411. smartlist_free(sl);
  412. return ds;
  413. }
  414. /** Go through and mark the authoritative dirservers as up. */
  415. static void
  416. mark_all_trusteddirservers_up(void)
  417. {
  418. if (routerlist) {
  419. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  420. if (router_digest_is_trusted_dir(router->identity_digest) &&
  421. router->dir_port > 0) {
  422. router->is_running = 1;
  423. });
  424. }
  425. if (trusted_dir_servers) {
  426. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
  427. {
  428. dir->is_running = 1;
  429. dir->n_networkstatus_failures = 0;
  430. });
  431. }
  432. last_networkstatus_download_attempted = 0;
  433. }
  434. /** Reset all internal variables used to count failed downloads of network
  435. * status objects. */
  436. void
  437. router_reset_status_download_failures(void)
  438. {
  439. mark_all_trusteddirservers_up();
  440. }
  441. /** Return 0 if \\exists an authoritative dirserver that's currently
  442. * thought to be running, else return 1.
  443. */
  444. int
  445. all_trusted_directory_servers_down(void)
  446. {
  447. if (!trusted_dir_servers)
  448. return 1;
  449. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, dir,
  450. if (dir->is_running) return 0);
  451. return 1;
  452. }
  453. /** Add all the family of <b>router</b> to the smartlist <b>sl</b>.
  454. * This is used to make sure we don't pick siblings in a single path.
  455. */
  456. void
  457. routerlist_add_family(smartlist_t *sl, routerinfo_t *router)
  458. {
  459. routerinfo_t *r;
  460. config_line_t *cl;
  461. if (!router->declared_family)
  462. return;
  463. /* Add every r such that router declares familyness with r, and r
  464. * declares familyhood with router. */
  465. SMARTLIST_FOREACH(router->declared_family, const char *, n,
  466. {
  467. if (!(r = router_get_by_nickname(n, 0)))
  468. continue;
  469. if (!r->declared_family)
  470. continue;
  471. SMARTLIST_FOREACH(r->declared_family, const char *, n2,
  472. {
  473. if (router_nickname_matches(router, n2))
  474. smartlist_add(sl, r);
  475. });
  476. });
  477. /* If the user declared any families locally, honor those too. */
  478. for (cl = get_options()->NodeFamilies; cl; cl = cl->next) {
  479. if (router_nickname_is_in_list(router, cl->value)) {
  480. add_nickname_list_to_smartlist(sl, cl->value, 1, 1);
  481. }
  482. }
  483. }
  484. /** Given a comma-and-whitespace separated list of nicknames, see which
  485. * nicknames in <b>list</b> name routers in our routerlist that are
  486. * currently running. Add the routerinfos for those routers to <b>sl</b>.
  487. */
  488. void
  489. add_nickname_list_to_smartlist(smartlist_t *sl, const char *list, int warn_if_down, int warn_if_unnamed)
  490. {
  491. routerinfo_t *router;
  492. smartlist_t *nickname_list;
  493. if (!list)
  494. return; /* nothing to do */
  495. tor_assert(sl);
  496. nickname_list = smartlist_create();
  497. if (!warned_nicknames)
  498. warned_nicknames = smartlist_create();
  499. smartlist_split_string(nickname_list, list, ",",
  500. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  501. SMARTLIST_FOREACH(nickname_list, const char *, nick, {
  502. int warned;
  503. if (!is_legal_nickname_or_hexdigest(nick)) {
  504. log_fn(LOG_WARN,"Nickname %s is misformed; skipping", nick);
  505. continue;
  506. }
  507. router = router_get_by_nickname(nick, warn_if_unnamed);
  508. warned = smartlist_string_isin(warned_nicknames, nick);
  509. if (router) {
  510. if (router->is_running) {
  511. smartlist_add(sl,router);
  512. if (warned)
  513. smartlist_string_remove(warned_nicknames, nick);
  514. } else {
  515. if (!warned) {
  516. log_fn(warn_if_down ? LOG_WARN : LOG_DEBUG,
  517. "Nickname list includes '%s' which is known but down.",nick);
  518. smartlist_add(warned_nicknames, tor_strdup(nick));
  519. }
  520. }
  521. } else {
  522. if (!warned) {
  523. log_fn(has_fetched_directory ? LOG_WARN : LOG_INFO,
  524. "Nickname list includes '%s' which isn't a known router.",nick);
  525. smartlist_add(warned_nicknames, tor_strdup(nick));
  526. }
  527. }
  528. });
  529. SMARTLIST_FOREACH(nickname_list, char *, nick, tor_free(nick));
  530. smartlist_free(nickname_list);
  531. }
  532. /** Return 1 iff any member of the comma-separated list <b>list</b> is an
  533. * acceptable nickname or hexdigest for <b>router</b>. Else return 0.
  534. */
  535. static int
  536. router_nickname_is_in_list(routerinfo_t *router, const char *list)
  537. {
  538. smartlist_t *nickname_list;
  539. int v = 0;
  540. if (!list)
  541. return 0; /* definitely not */
  542. tor_assert(router);
  543. nickname_list = smartlist_create();
  544. smartlist_split_string(nickname_list, list, ",",
  545. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  546. SMARTLIST_FOREACH(nickname_list, const char *, cp,
  547. if (router_nickname_matches(router, cp)) {v=1;break;});
  548. SMARTLIST_FOREACH(nickname_list, char *, cp, tor_free(cp));
  549. smartlist_free(nickname_list);
  550. return v;
  551. }
  552. /** Add every router from our routerlist that is currently running to
  553. * <b>sl</b>.
  554. */
  555. static void
  556. router_add_running_routers_to_smartlist(smartlist_t *sl, int allow_unverified,
  557. int need_uptime, int need_capacity)
  558. {
  559. if (!routerlist)
  560. return;
  561. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  562. {
  563. if (router->is_running &&
  564. (router->is_verified ||
  565. (allow_unverified &&
  566. !router_is_unreliable(router, need_uptime, need_capacity)))) {
  567. /* If it's running, and either it's verified or we're ok picking
  568. * unverified routers and this one is suitable.
  569. */
  570. smartlist_add(sl, router);
  571. }
  572. });
  573. }
  574. /** Look through the routerlist until we find a router that has my key.
  575. Return it. */
  576. routerinfo_t *
  577. routerlist_find_my_routerinfo(void)
  578. {
  579. if (!routerlist)
  580. return NULL;
  581. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  582. {
  583. if (router_is_me(router))
  584. return router;
  585. });
  586. return NULL;
  587. }
  588. /** Find a router that's up, that has this IP address, and
  589. * that allows exit to this address:port, or return NULL if there
  590. * isn't a good one.
  591. */
  592. routerinfo_t *
  593. router_find_exact_exit_enclave(const char *address, uint16_t port)
  594. {
  595. uint32_t addr;
  596. struct in_addr in;
  597. if (!tor_inet_aton(address, &in))
  598. return NULL; /* it's not an IP already */
  599. addr = ntohl(in.s_addr);
  600. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  601. {
  602. if (router->is_running &&
  603. router->addr == addr &&
  604. router_compare_addr_to_addr_policy(addr, port, router->exit_policy) ==
  605. ADDR_POLICY_ACCEPTED)
  606. return router;
  607. });
  608. return NULL;
  609. }
  610. /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
  611. * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
  612. * If <b>need_capacity</b> is non-zero, we require a minimum advertised
  613. * bandwidth.
  614. */
  615. int
  616. router_is_unreliable(routerinfo_t *router, int need_uptime, int need_capacity)
  617. {
  618. if (need_uptime && router->uptime < ROUTER_REQUIRED_MIN_UPTIME)
  619. return 1;
  620. if (need_capacity && router->bandwidthcapacity < ROUTER_REQUIRED_MIN_BANDWIDTH)
  621. return 1;
  622. return 0;
  623. }
  624. /** Remove from routerlist <b>sl</b> all routers who have a low uptime. */
  625. static void
  626. routerlist_sl_remove_unreliable_routers(smartlist_t *sl)
  627. {
  628. int i;
  629. routerinfo_t *router;
  630. for (i = 0; i < smartlist_len(sl); ++i) {
  631. router = smartlist_get(sl, i);
  632. if (router_is_unreliable(router, 1, 0)) {
  633. // log(LOG_DEBUG, "Router '%s' has insufficient uptime; deleting.",
  634. // router->nickname);
  635. smartlist_del(sl, i--);
  636. }
  637. }
  638. }
  639. #define MAX_BELIEVABLE_BANDWIDTH 2000000 /* 2 MB/sec */
  640. /** Choose a random element of router list <b>sl</b>, weighted by
  641. * the advertised bandwidth of each router.
  642. */
  643. routerinfo_t *
  644. routerlist_sl_choose_by_bandwidth(smartlist_t *sl)
  645. {
  646. int i;
  647. routerinfo_t *router;
  648. smartlist_t *bandwidths;
  649. uint32_t this_bw, tmp, total_bw=0, rand_bw;
  650. uint32_t *p;
  651. /* First count the total bandwidth weight, and make a smartlist
  652. * of each value. */
  653. bandwidths = smartlist_create();
  654. for (i = 0; i < smartlist_len(sl); ++i) {
  655. router = smartlist_get(sl, i);
  656. this_bw = (router->bandwidthcapacity < router->bandwidthrate) ?
  657. router->bandwidthcapacity : router->bandwidthrate;
  658. /* if they claim something huge, don't believe it */
  659. if (this_bw > MAX_BELIEVABLE_BANDWIDTH)
  660. this_bw = MAX_BELIEVABLE_BANDWIDTH;
  661. p = tor_malloc(sizeof(uint32_t));
  662. *p = this_bw;
  663. smartlist_add(bandwidths, p);
  664. total_bw += this_bw;
  665. }
  666. if (!total_bw) {
  667. SMARTLIST_FOREACH(bandwidths, uint32_t*, p, tor_free(p));
  668. smartlist_free(bandwidths);
  669. return smartlist_choose(sl);
  670. }
  671. /* Second, choose a random value from the bandwidth weights. */
  672. rand_bw = crypto_pseudo_rand_int(total_bw);
  673. /* Last, count through sl until we get to the element we picked */
  674. tmp = 0;
  675. for (i=0; ; i++) {
  676. tor_assert(i < smartlist_len(sl));
  677. p = smartlist_get(bandwidths, i);
  678. tmp += *p;
  679. if (tmp >= rand_bw)
  680. break;
  681. }
  682. SMARTLIST_FOREACH(bandwidths, uint32_t*, p, tor_free(p));
  683. smartlist_free(bandwidths);
  684. return (routerinfo_t *)smartlist_get(sl, i);
  685. }
  686. /** Return a random running router from the routerlist. If any node
  687. * named in <b>preferred</b> is available, pick one of those. Never
  688. * pick a node named in <b>excluded</b>, or whose routerinfo is in
  689. * <b>excludedsmartlist</b>, even if they are the only nodes
  690. * available. If <b>strict</b> is true, never pick any node besides
  691. * those in <b>preferred</b>.
  692. * If <b>need_uptime</b> is non-zero, don't return a router with less
  693. * than a minimum uptime.
  694. * If <b>need_capacity</b> is non-zero, weight your choice by the
  695. * advertised capacity of each router.
  696. */
  697. routerinfo_t *
  698. router_choose_random_node(const char *preferred,
  699. const char *excluded,
  700. smartlist_t *excludedsmartlist,
  701. int need_uptime, int need_capacity,
  702. int allow_unverified, int strict)
  703. {
  704. smartlist_t *sl, *excludednodes;
  705. routerinfo_t *choice;
  706. excludednodes = smartlist_create();
  707. add_nickname_list_to_smartlist(excludednodes,excluded,0,1);
  708. /* Try the preferred nodes first. Ignore need_uptime and need_capacity,
  709. * since the user explicitly asked for these nodes. */
  710. sl = smartlist_create();
  711. add_nickname_list_to_smartlist(sl,preferred,1,1);
  712. smartlist_subtract(sl,excludednodes);
  713. if (excludedsmartlist)
  714. smartlist_subtract(sl,excludedsmartlist);
  715. choice = smartlist_choose(sl);
  716. smartlist_free(sl);
  717. if (!choice && !strict) {
  718. /* Then give up on our preferred choices: any node
  719. * will do that has the required attributes. */
  720. sl = smartlist_create();
  721. router_add_running_routers_to_smartlist(sl, allow_unverified,
  722. need_uptime, need_capacity);
  723. smartlist_subtract(sl,excludednodes);
  724. if (excludedsmartlist)
  725. smartlist_subtract(sl,excludedsmartlist);
  726. if (need_uptime)
  727. routerlist_sl_remove_unreliable_routers(sl);
  728. if (need_capacity)
  729. choice = routerlist_sl_choose_by_bandwidth(sl);
  730. else
  731. choice = smartlist_choose(sl);
  732. smartlist_free(sl);
  733. }
  734. smartlist_free(excludednodes);
  735. if (!choice)
  736. log_fn(LOG_WARN,"No available nodes when trying to choose node. Failing.");
  737. return choice;
  738. }
  739. /** Return true iff the digest of <b>router</b>'s identity key,
  740. * encoded in hexadecimal, matches <b>hexdigest</b> (which is
  741. * optionally prefixed with a single dollar sign). Return false if
  742. * <b>hexdigest</b> is malformed, or it doesn't match. */
  743. static INLINE int
  744. router_hex_digest_matches(routerinfo_t *router, const char *hexdigest)
  745. {
  746. char digest[DIGEST_LEN];
  747. tor_assert(hexdigest);
  748. if (hexdigest[0] == '$')
  749. ++hexdigest;
  750. if (strlen(hexdigest) != HEX_DIGEST_LEN ||
  751. base16_decode(digest, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0)
  752. return 0;
  753. return (!memcmp(digest, router->identity_digest, DIGEST_LEN));
  754. }
  755. /** Return true if <b>router</b>'s nickname matches <b>nickname</b>
  756. * (case-insensitive), or if <b>router's</b> identity key digest
  757. * matches a hexadecimal value stored in <b>nickname</b>. Return
  758. * false otherwise. */
  759. static int
  760. router_nickname_matches(routerinfo_t *router, const char *nickname)
  761. {
  762. if (nickname[0]!='$' && !strcasecmp(router->nickname, nickname))
  763. return 1;
  764. return router_hex_digest_matches(router, nickname);
  765. }
  766. /** Return the router in our routerlist whose (case-insensitive)
  767. * nickname or (case-sensitive) hexadecimal key digest is
  768. * <b>nickname</b>. Return NULL if no such router is known.
  769. */
  770. routerinfo_t *
  771. router_get_by_nickname(const char *nickname, int warn_if_unnamed)
  772. {
  773. int maybedigest;
  774. char digest[DIGEST_LEN];
  775. routerinfo_t *best_match=NULL;
  776. int n_matches = 0;
  777. tor_assert(nickname);
  778. if (!routerlist)
  779. return NULL;
  780. if (nickname[0] == '$')
  781. return router_get_by_hexdigest(nickname);
  782. if (server_mode(get_options()) &&
  783. !strcasecmp(nickname, get_options()->Nickname))
  784. return router_get_my_routerinfo();
  785. maybedigest = (strlen(nickname) == HEX_DIGEST_LEN) &&
  786. (base16_decode(digest,DIGEST_LEN,nickname,HEX_DIGEST_LEN) == 0);
  787. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  788. {
  789. if (!strcasecmp(router->nickname, nickname)) {
  790. if (router->is_named)
  791. return router;
  792. else {
  793. ++n_matches;
  794. best_match = router;
  795. }
  796. } else if (maybedigest &&
  797. !memcmp(digest, router->identity_digest, DIGEST_LEN)) {
  798. return router;
  799. }
  800. });
  801. if (best_match) {
  802. if (n_matches>1) {
  803. smartlist_t *fps = smartlist_create();
  804. int any_unwarned = 0;
  805. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  806. {
  807. local_routerstatus_t *rs;
  808. char *desc;
  809. size_t dlen;
  810. char fp[HEX_DIGEST_LEN+1];
  811. if (strcasecmp(router->nickname, nickname))
  812. continue;
  813. rs=router_get_combined_status_by_digest(router->identity_digest);
  814. if (!rs->name_lookup_warned) {
  815. rs->name_lookup_warned = 1;
  816. any_unwarned = 1;
  817. }
  818. base16_encode(fp, sizeof(fp), router->identity_digest, DIGEST_LEN);
  819. dlen = 32 + HEX_DIGEST_LEN + strlen(router->address);
  820. desc = tor_malloc(dlen);
  821. tor_snprintf(desc, dlen, "\"$%s\" for the one at %s:%d",
  822. fp, router->address, router->or_port);
  823. smartlist_add(fps, desc);
  824. });
  825. if (any_unwarned) {
  826. char *alternatives = smartlist_join_strings(fps, "; ",0,NULL);
  827. log_fn(LOG_WARN, "There are multiple matches for the nickname \"%s\","
  828. " but none is listed as named by the directory authories. "
  829. "Choosing one arbitrarily. If you meant one in particular, "
  830. "you should say %s.", nickname, alternatives);
  831. tor_free(alternatives);
  832. }
  833. SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
  834. smartlist_free(fps);
  835. } else if (warn_if_unnamed) {
  836. local_routerstatus_t *rs =
  837. router_get_combined_status_by_digest(best_match->identity_digest);
  838. if (rs && !rs->name_lookup_warned) {
  839. char fp[HEX_DIGEST_LEN+1];
  840. base16_encode(fp, sizeof(fp), best_match->identity_digest, DIGEST_LEN);
  841. log_fn(LOG_WARN, "You specified a server \"%s\" by name, but the "
  842. "directory authorities do not have a listing for this name. "
  843. "To make sure you get the same server in the future, refer to "
  844. "it by key, as \"$%s\".", nickname, fp);
  845. rs->name_lookup_warned = 1;
  846. }
  847. }
  848. return best_match;
  849. }
  850. return NULL;
  851. }
  852. /** Return true iff <b>digest</b> is the digest of the identity key of
  853. * a trusted directory. */
  854. int
  855. router_digest_is_trusted_dir(const char *digest)
  856. {
  857. if (!trusted_dir_servers)
  858. return 0;
  859. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  860. if (!memcmp(digest, ent->digest, DIGEST_LEN)) return 1);
  861. return 0;
  862. }
  863. /** Return the router in our routerlist whose hexadecimal key digest
  864. * is <b>hexdigest</b>. Return NULL if no such router is known. */
  865. routerinfo_t *
  866. router_get_by_hexdigest(const char *hexdigest)
  867. {
  868. char digest[DIGEST_LEN];
  869. tor_assert(hexdigest);
  870. if (!routerlist)
  871. return NULL;
  872. if (hexdigest[0]=='$')
  873. ++hexdigest;
  874. if (strlen(hexdigest) != HEX_DIGEST_LEN ||
  875. base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
  876. return NULL;
  877. return router_get_by_digest(digest);
  878. }
  879. /** Return the router in our routerlist whose 20-byte key digest
  880. * is <b>digest</b>. Return NULL if no such router is known. */
  881. routerinfo_t *
  882. router_get_by_digest(const char *digest)
  883. {
  884. tor_assert(digest);
  885. if (!routerlist) return NULL;
  886. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t*, router,
  887. {
  888. if (0 == memcmp(router->identity_digest, digest, DIGEST_LEN))
  889. return router;
  890. });
  891. return NULL;
  892. }
  893. /** Set *<b>prouterlist</b> to the current list of all known routers. */
  894. void
  895. router_get_routerlist(routerlist_t **prouterlist)
  896. {
  897. *prouterlist = routerlist;
  898. }
  899. /** Free all storage held by <b>router</b>. */
  900. void
  901. routerinfo_free(routerinfo_t *router)
  902. {
  903. if (!router)
  904. return;
  905. tor_free(router->signed_descriptor);
  906. tor_free(router->address);
  907. tor_free(router->nickname);
  908. tor_free(router->platform);
  909. tor_free(router->contact_info);
  910. if (router->onion_pkey)
  911. crypto_free_pk_env(router->onion_pkey);
  912. if (router->identity_pkey)
  913. crypto_free_pk_env(router->identity_pkey);
  914. if (router->declared_family) {
  915. SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
  916. smartlist_free(router->declared_family);
  917. }
  918. addr_policy_free(router->exit_policy);
  919. tor_free(router);
  920. }
  921. /** Allocate a fresh copy of <b>router</b> */
  922. routerinfo_t *
  923. routerinfo_copy(const routerinfo_t *router)
  924. {
  925. routerinfo_t *r;
  926. addr_policy_t **e, *tmp;
  927. r = tor_malloc(sizeof(routerinfo_t));
  928. memcpy(r, router, sizeof(routerinfo_t));
  929. r->address = tor_strdup(r->address);
  930. r->nickname = tor_strdup(r->nickname);
  931. r->platform = tor_strdup(r->platform);
  932. if (r->signed_descriptor)
  933. r->signed_descriptor = tor_strdup(r->signed_descriptor);
  934. if (r->onion_pkey)
  935. r->onion_pkey = crypto_pk_dup_key(r->onion_pkey);
  936. if (r->identity_pkey)
  937. r->identity_pkey = crypto_pk_dup_key(r->identity_pkey);
  938. e = &r->exit_policy;
  939. while (*e) {
  940. tmp = tor_malloc(sizeof(addr_policy_t));
  941. memcpy(tmp,*e,sizeof(addr_policy_t));
  942. *e = tmp;
  943. (*e)->string = tor_strdup((*e)->string);
  944. e = & ((*e)->next);
  945. }
  946. if (r->declared_family) {
  947. r->declared_family = smartlist_create();
  948. SMARTLIST_FOREACH(router->declared_family, const char *, s,
  949. smartlist_add(r->declared_family, tor_strdup(s)));
  950. }
  951. return r;
  952. }
  953. /** Free all storage held by a routerlist <b>rl</b> */
  954. void
  955. routerlist_free(routerlist_t *rl)
  956. {
  957. tor_assert(rl);
  958. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  959. routerinfo_free(r));
  960. smartlist_free(rl->routers);
  961. tor_free(rl);
  962. }
  963. /** Free all memory held by the rouerlist module */
  964. void
  965. routerlist_free_all(void)
  966. {
  967. if (routerlist)
  968. routerlist_free(routerlist);
  969. routerlist = NULL;
  970. if (warned_nicknames) {
  971. SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
  972. smartlist_free(warned_nicknames);
  973. warned_nicknames = NULL;
  974. }
  975. if (warned_conflicts) {
  976. SMARTLIST_FOREACH(warned_conflicts, char *, cp, tor_free(cp));
  977. smartlist_free(warned_conflicts);
  978. warned_conflicts = NULL;
  979. }
  980. if (trusted_dir_servers) {
  981. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  982. trusted_dir_server_free(ds));
  983. smartlist_free(trusted_dir_servers);
  984. trusted_dir_servers = NULL;
  985. }
  986. if (networkstatus_list) {
  987. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  988. networkstatus_free(ns));
  989. smartlist_free(networkstatus_list);
  990. networkstatus_list = NULL;
  991. }
  992. if (routerstatus_list) {
  993. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  994. local_routerstatus_free(rs));
  995. smartlist_free(routerstatus_list);
  996. routerstatus_list = NULL;
  997. }
  998. }
  999. /** Free all storage held by the routerstatus object <b>rs</b>. */
  1000. void
  1001. routerstatus_free(routerstatus_t *rs)
  1002. {
  1003. tor_free(rs);
  1004. }
  1005. /** Free all storage held by the local_routerstatus object <b>rs</b>. */
  1006. static void
  1007. local_routerstatus_free(local_routerstatus_t *rs)
  1008. {
  1009. tor_free(rs);
  1010. }
  1011. /** Free all storage held by the networkstatus object <b>ns</b>. */
  1012. void
  1013. networkstatus_free(networkstatus_t *ns)
  1014. {
  1015. tor_free(ns->source_address);
  1016. tor_free(ns->contact);
  1017. if (ns->signing_key)
  1018. crypto_free_pk_env(ns->signing_key);
  1019. tor_free(ns->client_versions);
  1020. tor_free(ns->server_versions);
  1021. if (ns->entries) {
  1022. SMARTLIST_FOREACH(ns->entries, routerstatus_t *, rs, routerstatus_free(rs));
  1023. smartlist_free(ns->entries);
  1024. }
  1025. tor_free(ns);
  1026. }
  1027. /** Forget that we have issued any router-related warnings, so that we'll
  1028. * warn again if we see the same errors. */
  1029. void
  1030. routerlist_reset_warnings(void)
  1031. {
  1032. if (!warned_nicknames)
  1033. warned_nicknames = smartlist_create();
  1034. SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
  1035. smartlist_clear(warned_nicknames); /* now the list is empty. */
  1036. if (!warned_conflicts)
  1037. warned_conflicts = smartlist_create();
  1038. SMARTLIST_FOREACH(warned_conflicts, char *, cp, tor_free(cp));
  1039. smartlist_clear(warned_conflicts); /* now the list is empty. */
  1040. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  1041. rs->name_lookup_warned = 0);
  1042. have_warned_about_unverified_status = 0;
  1043. have_warned_about_old_version = 0;
  1044. have_warned_about_new_version = 0;
  1045. }
  1046. /** Mark the router with ID <b>digest</b> as non-running in our routerlist. */
  1047. void
  1048. router_mark_as_down(const char *digest)
  1049. {
  1050. routerinfo_t *router;
  1051. tor_assert(digest);
  1052. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, d,
  1053. if (!memcmp(d->digest, digest, DIGEST_LEN))
  1054. d->is_running = 0);
  1055. router = router_get_by_digest(digest);
  1056. if (!router) /* we don't seem to know about him in the first place */
  1057. return;
  1058. log_fn(LOG_DEBUG,"Marking router '%s' as down.",router->nickname);
  1059. if (router_is_me(router) && !we_are_hibernating())
  1060. log_fn(LOG_WARN, "We just marked ourself as down. Are your external addresses reachable?");
  1061. router->is_running = 0;
  1062. }
  1063. /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
  1064. * older entries (if any) with the same key. Note: Callers should not hold
  1065. * their pointers to <b>router</b> if this function fails; <b>router</b>
  1066. * will either be inserted into the routerlist or freed.
  1067. *
  1068. * Returns >= 0 if the router was added; less than 0 if it was not.
  1069. *
  1070. * If we're returning non-zero, then assign to *<b>msg</b> a static string
  1071. * describing the reason for not liking the routerinfo.
  1072. *
  1073. * If the return value is less than -1, there was a problem with the
  1074. * routerinfo. If the return value is equal to -1, then the routerinfo was
  1075. * fine, but out-of-date. If the return value is equal to 1, the
  1076. * routerinfo was accepted, but we should notify the generator of the
  1077. * descriptor using the message *<b>msg</b>.
  1078. *
  1079. * This function should be called *after*
  1080. * routers_update_status_from_networkstatus; subsequenctly, you should call
  1081. * router_rebuild_store and control_event_descriptors_changed.
  1082. *
  1083. * XXXX never replace your own descriptor.
  1084. */
  1085. int
  1086. router_add_to_routerlist(routerinfo_t *router, const char **msg,
  1087. int from_cache)
  1088. {
  1089. int i;
  1090. char id_digest[DIGEST_LEN];
  1091. int authdir = get_options()->AuthoritativeDir;
  1092. int authdir_verified = 0;
  1093. tor_assert(msg);
  1094. if (!routerlist) {
  1095. routerlist = tor_malloc_zero(sizeof(routerlist_t));
  1096. routerlist->routers = smartlist_create();
  1097. }
  1098. crypto_pk_get_digest(router->identity_pkey, id_digest);
  1099. if (authdir) {
  1100. if (authdir_wants_to_reject_router(router, msg))
  1101. return -2;
  1102. authdir_verified = router->is_verified;
  1103. }
  1104. /* If we have a router with this name, and the identity key is the same,
  1105. * choose the newer one. If the identity key has changed, drop the router.
  1106. */
  1107. for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
  1108. routerinfo_t *old_router = smartlist_get(routerlist->routers, i);
  1109. if (!crypto_pk_cmp_keys(router->identity_pkey,old_router->identity_pkey)) {
  1110. if (router->published_on <= old_router->published_on) {
  1111. /* Same key, but old */
  1112. log_fn(LOG_DEBUG, "Skipping not-new descriptor for router '%s'",
  1113. router->nickname);
  1114. routerinfo_free(router);
  1115. *msg = "Router descriptor was not new.";
  1116. return -1;
  1117. } else {
  1118. /* Same key, new. */
  1119. int unreachable = 0;
  1120. log_fn(LOG_DEBUG, "Replacing entry for router '%s/%s' [%s]",
  1121. router->nickname, old_router->nickname,
  1122. hex_str(id_digest,DIGEST_LEN));
  1123. if (router->addr == old_router->addr &&
  1124. router->or_port == old_router->or_port) {
  1125. /* these carry over when the address and orport are unchanged.*/
  1126. router->last_reachable = old_router->last_reachable;
  1127. router->testing_since = old_router->testing_since;
  1128. router->num_unreachable_notifications =
  1129. old_router->num_unreachable_notifications;
  1130. }
  1131. if (authdir &&
  1132. dirserv_thinks_router_is_blatantly_unreachable(router, time(NULL))) {
  1133. if (router->num_unreachable_notifications >= 3) {
  1134. unreachable = 1;
  1135. log_fn(LOG_NOTICE, "Notifying server '%s' that it's unreachable. (ContactInfo '%s', platform '%s').",
  1136. router->nickname, router->contact_info ? router->contact_info : "",
  1137. router->platform ? router->platform : "");
  1138. } else {
  1139. log_fn(LOG_INFO,"'%s' may be unreachable -- the %d previous descriptors were thought to be unreachable.", router->nickname, router->num_unreachable_notifications);
  1140. router->num_unreachable_notifications++;
  1141. }
  1142. }
  1143. routerinfo_free(old_router);
  1144. smartlist_set(routerlist->routers, i, router);
  1145. if (!from_cache)
  1146. router_append_to_journal(router->signed_descriptor,
  1147. router->signed_descriptor_len);
  1148. directory_set_dirty();
  1149. *msg = unreachable ? "Dirserver believes your ORPort is unreachable" :
  1150. authdir_verified ? "Verified server updated" :
  1151. "Unverified server updated. (Have you sent us your key fingerprint?)";
  1152. return unreachable ? 1 : 0;
  1153. }
  1154. } else if (!strcasecmp(router->nickname, old_router->nickname)) {
  1155. /* nicknames match, keys don't. */
  1156. if (router->is_named) {
  1157. /* The new verified router replaces the old one; remove the
  1158. * old one. And carry on to the end of the list, in case
  1159. * there are more old unverified routers with this nickname
  1160. */
  1161. /* mark-for-close connections using the old key, so we can
  1162. * make new ones with the new key.
  1163. */
  1164. connection_t *conn;
  1165. while ((conn = connection_get_by_identity_digest(
  1166. old_router->identity_digest, CONN_TYPE_OR))) {
  1167. log_fn(LOG_INFO,"Closing conn to obsolete router '%s'",
  1168. old_router->nickname);
  1169. connection_mark_for_close(conn);
  1170. }
  1171. routerinfo_free(old_router);
  1172. smartlist_del_keeporder(routerlist->routers, i--);
  1173. } else if (old_router->is_named) {
  1174. /* Can't replace a verified router with an unverified one. */
  1175. log_fn(LOG_DEBUG, "Skipping unverified entry for verified router '%s'",
  1176. router->nickname);
  1177. routerinfo_free(router);
  1178. *msg = "Already have named router with same nickname and different key.";
  1179. return -2;
  1180. }
  1181. }
  1182. }
  1183. /* We haven't seen a router with this name before. Add it to the end of
  1184. * the list. */
  1185. smartlist_add(routerlist->routers, router);
  1186. if (!from_cache)
  1187. router_append_to_journal(router->signed_descriptor,
  1188. router->signed_descriptor_len);
  1189. directory_set_dirty();
  1190. return 0;
  1191. }
  1192. /** Remove any routers from the routerlist that are more than <b>age</b>
  1193. * seconds old.
  1194. */
  1195. void
  1196. routerlist_remove_old_routers(int age)
  1197. {
  1198. int i;
  1199. time_t cutoff;
  1200. routerinfo_t *router;
  1201. if (!routerlist)
  1202. return;
  1203. cutoff = time(NULL) - age;
  1204. for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
  1205. router = smartlist_get(routerlist->routers, i);
  1206. if (router->published_on <= cutoff) {
  1207. /* Too old. Remove it. */
  1208. log_fn(LOG_INFO,"Forgetting obsolete routerinfo for router '%s'", router->nickname);
  1209. routerinfo_free(router);
  1210. smartlist_del(routerlist->routers, i--);
  1211. }
  1212. }
  1213. }
  1214. /**
  1215. * Code to parse a single router descriptor and insert it into the
  1216. * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
  1217. * descriptor was well-formed but could not be added; and 1 if the
  1218. * descriptor was added.
  1219. *
  1220. * If we don't add it and <b>msg</b> is not NULL, then assign to
  1221. * *<b>msg</b> a static string describing the reason for refusing the
  1222. * descriptor.
  1223. *
  1224. * This is used only by the controller.
  1225. */
  1226. int
  1227. router_load_single_router(const char *s, const char **msg)
  1228. {
  1229. routerinfo_t *ri;
  1230. smartlist_t *lst;
  1231. tor_assert(msg);
  1232. *msg = NULL;
  1233. if (!(ri = router_parse_entry_from_string(s, NULL))) {
  1234. log_fn(LOG_WARN, "Error parsing router descriptor; dropping.");
  1235. *msg = "Couldn't parse router descriptor.";
  1236. return -1;
  1237. }
  1238. if (router_is_me(ri)) {
  1239. log_fn(LOG_WARN, "Router's identity key matches mine; dropping.");
  1240. *msg = "Router's identity key matches mine.";
  1241. routerinfo_free(ri);
  1242. return 0;
  1243. }
  1244. lst = smartlist_create();
  1245. smartlist_add(lst, ri);
  1246. routers_update_status_from_networkstatus(lst, 0);
  1247. if (router_add_to_routerlist(ri, msg, 0)<0) {
  1248. log_fn(LOG_WARN, "Couldn't add router to list: %s Dropping.",
  1249. *msg?*msg:"(No message).");
  1250. /* we've already assigned to *msg now, and ri is already freed */
  1251. smartlist_free(lst);
  1252. return 0;
  1253. } else {
  1254. control_event_descriptors_changed(lst);
  1255. smartlist_free(lst);
  1256. log_fn(LOG_DEBUG, "Added router to list");
  1257. return 1;
  1258. }
  1259. }
  1260. /** Given a string <b>s</b> containing some routerdescs, parse it and put the
  1261. * routers into our directory. If <b>from_cache</b> is false, the routers
  1262. * have come from the network: cache them.
  1263. *
  1264. * If <b>requested_fingerprints</b> is provided, it must contain a list of
  1265. * uppercased identity fingerprints. Do not update any router whose
  1266. * fingerprint is not on the list; after updating a router, remove its
  1267. * fingerprint from the list.
  1268. */
  1269. void
  1270. router_load_routers_from_string(const char *s, int from_cache,
  1271. smartlist_t *requested_fingerprints)
  1272. {
  1273. smartlist_t *routers = smartlist_create(), *changed = smartlist_create();
  1274. char fp[HEX_DIGEST_LEN+1];
  1275. const char *msg;
  1276. router_parse_list_from_string(&s, routers);
  1277. routers_update_status_from_networkstatus(routers, !from_cache);
  1278. SMARTLIST_FOREACH(routers, routerinfo_t *, ri,
  1279. {
  1280. base16_encode(fp, sizeof(fp), ri->identity_digest, DIGEST_LEN);
  1281. if (requested_fingerprints) {
  1282. if (smartlist_string_isin(requested_fingerprints, fp)) {
  1283. smartlist_string_remove(requested_fingerprints, fp);
  1284. } else {
  1285. char *requested =
  1286. smartlist_join_strings(requested_fingerprints," ",0,NULL);
  1287. log_fn(LOG_WARN, "We received a router descriptor with a fingerprint (%s) that we never requested. (We asked for: %s.) Dropping.", fp, requested);
  1288. tor_free(requested);
  1289. routerinfo_free(ri);
  1290. continue;
  1291. }
  1292. }
  1293. if (router_add_to_routerlist(ri, &msg, from_cache) >= 0)
  1294. smartlist_add(changed, ri);
  1295. });
  1296. control_event_descriptors_changed(changed);
  1297. router_rebuild_store(0);
  1298. smartlist_free(routers);
  1299. smartlist_free(changed);
  1300. }
  1301. /** Helper: return a newly allocated string containing the name of the filename
  1302. * where we plan to cache <b>ns</b>. */
  1303. static char *
  1304. networkstatus_get_cache_filename(const networkstatus_t *ns)
  1305. {
  1306. const char *datadir = get_options()->DataDirectory;
  1307. size_t len = strlen(datadir)+64;
  1308. char fp[HEX_DIGEST_LEN+1];
  1309. char *fn = tor_malloc(len+1);
  1310. base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
  1311. tor_snprintf(fn, len, "%s/cached-status/%s",datadir,fp);
  1312. return fn;
  1313. }
  1314. /** Helper for smartlist_sort: Compare two networkstatus objects by
  1315. * publication date. */
  1316. static int
  1317. _compare_networkstatus_published_on(const void **_a, const void **_b)
  1318. {
  1319. const networkstatus_t *a = *_a, *b = *_b;
  1320. if (a->published_on < b->published_on)
  1321. return -1;
  1322. else if (a->published_on > b->published_on)
  1323. return 1;
  1324. else
  1325. return 0;
  1326. }
  1327. /** How far in the future do we allow a network-status to get before removing
  1328. * it? (seconds) */
  1329. #define NETWORKSTATUS_ALLOW_SKEW (48*60*60)
  1330. /** Given a string <b>s</b> containing a network status that we received at
  1331. * <b>arrived_at</b> from <b>source</b>, try to parse it, see if we want to
  1332. * store it, and put it into our cache is necessary.
  1333. *
  1334. * If <b>source</b> is NS_FROM_DIR or NS_FROM_CACHE, do not replace our
  1335. * own networkstatus_t (if we're a directory server).
  1336. *
  1337. * If <b>source</b> is NS_FROM_CACHE, do not write our networkstatus_t to the
  1338. * cache.
  1339. *
  1340. * If <b>requested_fingerprints</b> is provided, it must contain a list of
  1341. * uppercased identity fingerprints. Do not update any networkstatus whose
  1342. * fingerprint is not on the list; after updating a networkstatus, remove its
  1343. * fingerprint from the list.
  1344. *
  1345. * Return 0 on success, -1 on failure.
  1346. *
  1347. * Callers should make sure that routers_update_all_from_networkstatus() is
  1348. * invoked after this function succeeds.
  1349. */
  1350. int
  1351. router_set_networkstatus(const char *s, time_t arrived_at,
  1352. networkstatus_source_t source, smartlist_t *requested_fingerprints)
  1353. {
  1354. networkstatus_t *ns;
  1355. int i, found;
  1356. time_t now;
  1357. int skewed = 0;
  1358. trusted_dir_server_t *trusted_dir;
  1359. char fp[HEX_DIGEST_LEN+1];
  1360. char published[ISO_TIME_LEN+1];
  1361. ns = networkstatus_parse_from_string(s);
  1362. if (!ns) {
  1363. log_fn(LOG_WARN, "Couldn't parse network status.");
  1364. return -1;
  1365. }
  1366. if (!(trusted_dir=router_get_trusteddirserver_by_digest(ns->identity_digest))) {
  1367. log_fn(LOG_INFO, "Network status was signed, but not by an authoritative directory we recognize.");
  1368. networkstatus_free(ns);
  1369. return -1;
  1370. }
  1371. now = time(NULL);
  1372. if (arrived_at > now)
  1373. arrived_at = now;
  1374. ns->received_on = arrived_at;
  1375. format_iso_time(published, ns->published_on);
  1376. if (ns->published_on > now + NETWORKSTATUS_ALLOW_SKEW) {
  1377. log_fn(LOG_WARN, "Network status from %s was published in the future (%s GMT). Somebody is skewed here: check your clock. Not caching.", trusted_dir->description, published);
  1378. skewed = 1;
  1379. }
  1380. if (!networkstatus_list)
  1381. networkstatus_list = smartlist_create();
  1382. if (source == NS_FROM_DIR && router_digest_is_me(ns->identity_digest)) {
  1383. /* Don't replace our own networkstatus when we get it from somebody else. */
  1384. networkstatus_free(ns);
  1385. return 0;
  1386. }
  1387. base16_encode(fp, HEX_DIGEST_LEN+1, ns->identity_digest, DIGEST_LEN);
  1388. if (requested_fingerprints) {
  1389. if (smartlist_string_isin(requested_fingerprints, fp)) {
  1390. smartlist_string_remove(requested_fingerprints, fp);
  1391. } else {
  1392. char *requested = smartlist_join_strings(requested_fingerprints," ",0,NULL);
  1393. log_fn(LOG_WARN, "We received a network status with a fingerprint (%s) that we never requested. (We asked for: %s.) Dropping.", fp, requested);
  1394. tor_free(requested);
  1395. return 0;
  1396. }
  1397. }
  1398. if (source != NS_FROM_CACHE)
  1399. trusted_dir->n_networkstatus_failures = 0;
  1400. found = 0;
  1401. for (i=0; i < smartlist_len(networkstatus_list); ++i) {
  1402. networkstatus_t *old_ns = smartlist_get(networkstatus_list, i);
  1403. if (!memcmp(old_ns->identity_digest, ns->identity_digest, DIGEST_LEN)) {
  1404. if (!memcmp(old_ns->networkstatus_digest,
  1405. ns->networkstatus_digest, DIGEST_LEN)) {
  1406. /* Same one we had before. */
  1407. networkstatus_free(ns);
  1408. log_fn(LOG_INFO,
  1409. "Not replacing network-status from %s (published %s); "
  1410. "we already have it.",
  1411. trusted_dir->description, published);
  1412. if (old_ns->received_on < arrived_at) {
  1413. if (source != NS_FROM_CACHE) {
  1414. char *fn = networkstatus_get_cache_filename(old_ns);
  1415. /* We use mtime to tell when it arrived, so update that. */
  1416. touch_file(fn);
  1417. tor_free(fn);
  1418. }
  1419. old_ns->received_on = arrived_at;
  1420. }
  1421. return 0;
  1422. } else if (old_ns->published_on >= ns->published_on) {
  1423. char old_published[ISO_TIME_LEN+1];
  1424. format_iso_time(old_published, old_ns->published_on);
  1425. log_fn(LOG_INFO,
  1426. "Not replacing network-status from %s (published %s);"
  1427. " we have a newer one (published %s) for this authority.",
  1428. trusted_dir->description, published,
  1429. old_published);
  1430. networkstatus_free(ns);
  1431. return 0;
  1432. } else {
  1433. networkstatus_free(old_ns);
  1434. smartlist_set(networkstatus_list, i, ns);
  1435. found = 1;
  1436. break;
  1437. }
  1438. }
  1439. }
  1440. if (!found)
  1441. smartlist_add(networkstatus_list, ns);
  1442. log_fn(LOG_INFO, "Setting networkstatus %s %s (published %s)",
  1443. source == NS_FROM_CACHE?"cached from":
  1444. (source==NS_FROM_DIR?"downloaded from":"generated for"),
  1445. trusted_dir->description, published);
  1446. networkstatus_list_has_changed = 1;
  1447. smartlist_sort(networkstatus_list, _compare_networkstatus_published_on);
  1448. if (source != NS_FROM_CACHE && !skewed) {
  1449. char *fn = networkstatus_get_cache_filename(ns);
  1450. if (write_str_to_file(fn, s, 0)<0) {
  1451. log_fn(LOG_NOTICE, "Couldn't write cached network status to \"%s\"", fn);
  1452. }
  1453. tor_free(fn);
  1454. }
  1455. networkstatus_list_update_recent(now);
  1456. if (get_options()->DirPort && !skewed)
  1457. dirserv_set_cached_networkstatus_v2(s, fp, ns->published_on);
  1458. return 0;
  1459. }
  1460. /** How old do we allow a network-status to get before removing it completely? */
  1461. #define MAX_NETWORKSTATUS_AGE (10*24*60*60)
  1462. /** Remove all very-old network_status_t objects from memory and from the
  1463. * disk cache. */
  1464. void
  1465. networkstatus_list_clean(time_t now)
  1466. {
  1467. int i;
  1468. if (!networkstatus_list)
  1469. return;
  1470. for (i = 0; i < smartlist_len(networkstatus_list); ++i) {
  1471. networkstatus_t *ns = smartlist_get(networkstatus_list, i);
  1472. char *fname = NULL;;
  1473. if (ns->published_on + MAX_NETWORKSTATUS_AGE > now)
  1474. continue;
  1475. /* Okay, this one is too old. Remove it from the list, and delete it
  1476. * from the cache. */
  1477. smartlist_del(networkstatus_list, i--);
  1478. fname = networkstatus_get_cache_filename(ns);
  1479. if (file_status(fname) == FN_FILE) {
  1480. log_fn(LOG_INFO, "Removing too-old networkstatus in %s", fname);
  1481. unlink(fname);
  1482. }
  1483. tor_free(fname);
  1484. if (get_options()->DirPort) {
  1485. char fp[HEX_DIGEST_LEN+1];
  1486. base16_encode(fp, sizeof(fp), ns->identity_digest, DIGEST_LEN);
  1487. dirserv_set_cached_networkstatus_v2(NULL, fp, 0);
  1488. }
  1489. networkstatus_free(ns);
  1490. }
  1491. }
  1492. /** Helper for bsearching a list of routerstatus_t pointers.*/
  1493. static int
  1494. _compare_digest_to_routerstatus_entry(const void *_key, const void **_member)
  1495. {
  1496. const char *key = _key;
  1497. const routerstatus_t *rs = *_member;
  1498. return memcmp(key, rs->identity_digest, DIGEST_LEN);
  1499. }
  1500. /** Return the entry in <b>ns</b> for the identity digest <b>digest</b>, or
  1501. * NULL if none was found. */
  1502. static routerstatus_t *
  1503. networkstatus_find_entry(networkstatus_t *ns, const char *digest)
  1504. {
  1505. return smartlist_bsearch(ns->entries, digest,
  1506. _compare_digest_to_routerstatus_entry);
  1507. }
  1508. /** Return the consensus view of the status of the router whose digest is
  1509. * <b>digest</b>, or NULL if we don't know about any such router. */
  1510. local_routerstatus_t *
  1511. router_get_combined_status_by_digest(const char *digest)
  1512. {
  1513. if (!routerstatus_list)
  1514. return NULL;
  1515. return smartlist_bsearch(routerstatus_list, digest,
  1516. _compare_digest_to_routerstatus_entry);
  1517. }
  1518. /* XXXX These should be configurable, perhaps? NM */
  1519. #define AUTHORITY_NS_CACHE_INTERVAL 10*60
  1520. #define NONAUTHORITY_NS_CACHE_INTERVAL 15*60
  1521. /** We are a directory server, and so cache network_status documents.
  1522. * Initiate downloads as needed to update them. For authorities, this means
  1523. * asking each trusted directory for its network-status. For caches, this means
  1524. * asking a random authority for all network-statuses.
  1525. */
  1526. static void
  1527. update_networkstatus_cache_downloads(time_t now)
  1528. {
  1529. int authority = authdir_mode(get_options());
  1530. int interval =
  1531. authority ? AUTHORITY_NS_CACHE_INTERVAL : NONAUTHORITY_NS_CACHE_INTERVAL;
  1532. if (last_networkstatus_download_attempted + interval >= now)
  1533. return;
  1534. if (!trusted_dir_servers)
  1535. return;
  1536. last_networkstatus_download_attempted = now;
  1537. if (authority) {
  1538. /* An authority launches a separate connection for everybody. */
  1539. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  1540. {
  1541. char resource[HEX_DIGEST_LEN+6];
  1542. if (router_digest_is_me(ds->digest))
  1543. continue;
  1544. if (connection_get_by_type_addr_port_purpose(
  1545. CONN_TYPE_DIR, ds->addr, ds->dir_port,
  1546. DIR_PURPOSE_FETCH_NETWORKSTATUS)) {
  1547. /* We are already fetching this one. */
  1548. continue;
  1549. }
  1550. strlcpy(resource, "fp/", sizeof(resource));
  1551. base16_encode(resource+3, sizeof(resource)-3, ds->digest, DIGEST_LEN);
  1552. strlcat(resource, ".z", sizeof(resource));
  1553. directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS,resource,1);
  1554. });
  1555. } else {
  1556. /* A non-authority cache launches one connection to a random authority. */
  1557. /* (Check whether we're currently fetching network-status objects.) */
  1558. if (!connection_get_by_type_purpose(CONN_TYPE_DIR,
  1559. DIR_PURPOSE_FETCH_NETWORKSTATUS))
  1560. directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS,"all.z",1);
  1561. }
  1562. }
  1563. /*XXXX Should these be configurable? NM*/
  1564. /** How old (in seconds) can a network-status be before we try replacing it? */
  1565. #define NETWORKSTATUS_MAX_VALIDITY (48*60*60)
  1566. /** How long (in seconds) does a client wait after getting a network status
  1567. * before downloading the next in sequence? */
  1568. #define NETWORKSTATUS_CLIENT_DL_INTERVAL (30*60)
  1569. /* How many times do we allow a networkstatus download to fail before we
  1570. * assume that the authority isn't publishing? */
  1571. #define NETWORKSTATUS_N_ALLOWABLE_FAILURES 3
  1572. /** We are not a directory cache or authority. Update our network-status list
  1573. * by launching a new directory fetch for enough network-status documents "as
  1574. * necessary". See function comments for implementation details.
  1575. */
  1576. static void
  1577. update_networkstatus_client_downloads(time_t now)
  1578. {
  1579. int n_live = 0, needed = 0, n_running_dirservers, n_dirservers, i;
  1580. int most_recent_idx = -1;
  1581. trusted_dir_server_t *most_recent = NULL;
  1582. time_t most_recent_received = 0;
  1583. char *resource, *cp;
  1584. size_t resource_len;
  1585. if (connection_get_by_type_purpose(CONN_TYPE_DIR,
  1586. DIR_PURPOSE_FETCH_NETWORKSTATUS))
  1587. return;
  1588. /* This is a little tricky. We want to download enough network-status
  1589. * objects so that we have at least half of them under
  1590. * NETWORKSTATUS_MAX_VALIDITY publication time. We want to download a new
  1591. * *one* if the most recent one's publication time is under
  1592. * NETWORKSTATUS_CLIENT_DL_INTERVAL.
  1593. */
  1594. if (!trusted_dir_servers || !smartlist_len(trusted_dir_servers))
  1595. return;
  1596. n_dirservers = n_running_dirservers = smartlist_len(trusted_dir_servers);
  1597. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  1598. {
  1599. networkstatus_t *ns = networkstatus_get_by_digest(ds->digest);
  1600. if (!ns)
  1601. continue;
  1602. if (ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES) {
  1603. --n_running_dirservers;
  1604. continue;
  1605. }
  1606. if (ns->published_on > now-NETWORKSTATUS_MAX_VALIDITY)
  1607. ++n_live;
  1608. if (!most_recent || ns->received_on > most_recent_received) {
  1609. most_recent_idx = ds_sl_idx; /* magic variable from FOREACH */
  1610. most_recent = ds;
  1611. most_recent_received = ns->received_on;
  1612. }
  1613. });
  1614. /* Download enough so we have at least half live, but no more than all the
  1615. * trusted dirservers we know.
  1616. */
  1617. if (n_live < (n_dirservers/2)+1)
  1618. needed = (n_dirservers/2)+1-n_live;
  1619. if (needed > n_running_dirservers)
  1620. needed = n_running_dirservers;
  1621. if (needed)
  1622. log_fn(LOG_INFO, "For %d/%d running directory servers, we have %d live"
  1623. " network-status documents. Downloading %d.",
  1624. n_running_dirservers, n_dirservers, n_live, needed);
  1625. /* Also, download at least 1 every NETWORKSTATUS_CLIENT_DL_INTERVAL. */
  1626. if (n_running_dirservers &&
  1627. most_recent_received < now-NETWORKSTATUS_CLIENT_DL_INTERVAL && needed < 1) {
  1628. log_fn(LOG_INFO, "Our most recent network-status document (from %s) "
  1629. "is %d seconds old; downloading another.",
  1630. most_recent?most_recent->description:"nobody",
  1631. (int)(now-most_recent_received));
  1632. needed = 1;
  1633. }
  1634. if (!needed)
  1635. return;
  1636. /* If no networkstatus was found, choose a dirserver at random as "most
  1637. * recent". */
  1638. if (most_recent_idx<0)
  1639. most_recent_idx = crypto_pseudo_rand_int(n_dirservers);
  1640. /* Build a request string for all the resources we want. */
  1641. resource_len = needed * (HEX_DIGEST_LEN+1) + 6;
  1642. resource = tor_malloc(resource_len);
  1643. memcpy(resource, "fp/", 3);
  1644. cp = resource+3;
  1645. for (i = most_recent_idx+1; needed; ++i) {
  1646. trusted_dir_server_t *ds;
  1647. if (i >= n_dirservers)
  1648. i = 0;
  1649. ds = smartlist_get(trusted_dir_servers, i);
  1650. if (ds->n_networkstatus_failures > NETWORKSTATUS_N_ALLOWABLE_FAILURES)
  1651. continue;
  1652. base16_encode(cp, HEX_DIGEST_LEN+1, ds->digest, DIGEST_LEN);
  1653. cp += HEX_DIGEST_LEN;
  1654. --needed;
  1655. if (needed)
  1656. *cp++ = '+';
  1657. }
  1658. memcpy(cp, ".z", 3);
  1659. directory_get_from_dirserver(DIR_PURPOSE_FETCH_NETWORKSTATUS, resource, 1);
  1660. tor_free(resource);
  1661. }
  1662. /*DOCDOC*/
  1663. void
  1664. update_networkstatus_downloads(time_t now)
  1665. {
  1666. or_options_t *options = get_options();
  1667. if (server_mode(options) && options->DirPort)
  1668. update_networkstatus_cache_downloads(time(NULL));
  1669. else
  1670. update_networkstatus_client_downloads(time(NULL));
  1671. }
  1672. /** Decide whether a given addr:port is definitely accepted,
  1673. * definitely rejected, probably accepted, or probably rejected by a
  1674. * given policy. If <b>addr</b> is 0, we don't know the IP of the
  1675. * target address. If <b>port</b> is 0, we don't know the port of the
  1676. * target address.
  1677. *
  1678. * For now, the algorithm is pretty simple: we look for definite and
  1679. * uncertain matches. The first definite match is what we guess; if
  1680. * it was preceded by no uncertain matches of the opposite policy,
  1681. * then the guess is definite; otherwise it is probable. (If we
  1682. * have a known addr and port, all matches are definite; if we have an
  1683. * unknown addr/port, any address/port ranges other than "all" are
  1684. * uncertain.)
  1685. *
  1686. * We could do better by assuming that some ranges never match typical
  1687. * addresses (127.0.0.1, and so on). But we'll try this for now.
  1688. */
  1689. addr_policy_result_t
  1690. router_compare_addr_to_addr_policy(uint32_t addr, uint16_t port,
  1691. addr_policy_t *policy)
  1692. {
  1693. int maybe_reject = 0;
  1694. int maybe_accept = 0;
  1695. int match = 0;
  1696. int maybe = 0;
  1697. addr_policy_t *tmpe;
  1698. for (tmpe=policy; tmpe; tmpe=tmpe->next) {
  1699. maybe = 0;
  1700. if (!addr) {
  1701. /* Address is unknown. */
  1702. if ((port >= tmpe->prt_min && port <= tmpe->prt_max) ||
  1703. (!port && tmpe->prt_min<=1 && tmpe->prt_max>=65535)) {
  1704. /* The port definitely matches. */
  1705. if (tmpe->msk == 0) {
  1706. match = 1;
  1707. } else {
  1708. maybe = 1;
  1709. }
  1710. } else if (!port) {
  1711. /* The port maybe matches. */
  1712. maybe = 1;
  1713. }
  1714. } else {
  1715. /* Address is known */
  1716. if ((addr & tmpe->msk) == (tmpe->addr & tmpe->msk)) {
  1717. if (port >= tmpe->prt_min && port <= tmpe->prt_max) {
  1718. /* Exact match for the policy */
  1719. match = 1;
  1720. } else if (!port) {
  1721. maybe = 1;
  1722. }
  1723. }
  1724. }
  1725. if (maybe) {
  1726. if (tmpe->policy_type == ADDR_POLICY_REJECT)
  1727. maybe_reject = 1;
  1728. else
  1729. maybe_accept = 1;
  1730. }
  1731. if (match) {
  1732. if (tmpe->policy_type == ADDR_POLICY_ACCEPT) {
  1733. /* If we already hit a clause that might trigger a 'reject', than we
  1734. * can't be sure of this certain 'accept'.*/
  1735. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
  1736. } else {
  1737. return maybe_accept ? ADDR_POLICY_PROBABLY_REJECTED : ADDR_POLICY_REJECTED;
  1738. }
  1739. }
  1740. }
  1741. /* accept all by default. */
  1742. return maybe_reject ? ADDR_POLICY_PROBABLY_ACCEPTED : ADDR_POLICY_ACCEPTED;
  1743. }
  1744. /** Return 1 if all running sufficiently-stable routers will reject
  1745. * addr:port, return 0 if any might accept it. */
  1746. int
  1747. router_exit_policy_all_routers_reject(uint32_t addr, uint16_t port,
  1748. int need_uptime)
  1749. {
  1750. addr_policy_result_t r;
  1751. if (!routerlist) return 1;
  1752. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  1753. {
  1754. if (router->is_running &&
  1755. !router_is_unreliable(router, need_uptime, 0)) {
  1756. r = router_compare_addr_to_addr_policy(addr, port, router->exit_policy);
  1757. if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED)
  1758. return 0; /* this one could be ok. good enough. */
  1759. }
  1760. });
  1761. return 1; /* all will reject. */
  1762. }
  1763. /**
  1764. * If <b>policy</b> implicitly allows connections to any port in the
  1765. * IP set <b>addr</b>/<b>mask</b>, then set *<b>policy_out</b> to the
  1766. * part of the policy that allows it, and return 1. Else return 0.
  1767. *
  1768. * A policy allows an IP:Port combination <em>implicitly</em> if
  1769. * it is included in a *: pattern, or in a fallback pattern.
  1770. */
  1771. static int
  1772. policy_includes_addr_mask_implicitly(addr_policy_t *policy,
  1773. uint32_t addr, uint32_t mask,
  1774. addr_policy_t **policy_out)
  1775. {
  1776. uint32_t addr2;
  1777. tor_assert(policy_out);
  1778. addr &= mask;
  1779. addr2 = addr | ~mask;
  1780. for (; policy; policy=policy->next) {
  1781. /* Does this policy cover all of the address range we're looking at? */
  1782. /* Boolean logic time: range X is contained in range Y if, for
  1783. * each bit B, all possible values of B in X are values of B in Y.
  1784. * In "addr", we have every fixed bit set to its value, and every
  1785. * free bit set to 0. In "addr2", we have every fixed bit set to
  1786. * its value, and every free bit set to 1. So if addr and addr2 are
  1787. * both in the policy, the range is covered by the policy.
  1788. */
  1789. uint32_t p_addr = policy->addr & policy->msk;
  1790. if (p_addr == (addr & policy->msk) &&
  1791. p_addr == (addr2 & policy->msk) &&
  1792. (policy->prt_min <= 1 && policy->prt_max == 65535)) {
  1793. return 0;
  1794. }
  1795. /* Does this policy cover some of the address range we're looking at? */
  1796. /* Boolean logic time: range X and range Y intersect if there is
  1797. * some z such that z & Xmask == Xaddr and z & Ymask == Yaddr.
  1798. * This is FALSE iff there is some bit b where Xmask == yMask == 1
  1799. * and Xaddr != Yaddr. So if X intersects with Y iff at every
  1800. * place where Xmask&Ymask==1, Xaddr == Yaddr, or equivalently,
  1801. * Xaddr&Xmask&Ymask == Yaddr&Xmask&Ymask.
  1802. */
  1803. if ((policy->addr & policy->msk & mask) == (addr & policy->msk) &&
  1804. policy->policy_type == ADDR_POLICY_ACCEPT) {
  1805. *policy_out = policy;
  1806. return 1;
  1807. }
  1808. }
  1809. *policy_out = NULL;
  1810. return 1;
  1811. }
  1812. /** If <b>policy</b> implicitly allows connections to any port on
  1813. * 127.*, 192.168.*, etc, then warn (if <b>warn</b> is set) and return
  1814. * true. Else return false.
  1815. **/
  1816. int
  1817. exit_policy_implicitly_allows_local_networks(addr_policy_t *policy,
  1818. int warn)
  1819. {
  1820. addr_policy_t *p;
  1821. int r=0,i;
  1822. static struct {
  1823. uint32_t addr; uint32_t mask; const char *network;
  1824. } private_networks[] = {
  1825. { 0x7f000000, 0xff000000, "localhost (127.0.0.0/8)" },
  1826. { 0x0a000000, 0xff000000, "addresses in private network 10.0.0.0/8" },
  1827. { 0xa9fe0000, 0xffff0000, "addresses in private network 169.254.0.0/16" },
  1828. { 0xac100000, 0xfff00000, "addresses in private network 172.16.0.0/12" },
  1829. { 0xc0a80000, 0xffff0000, "addresses in private network 192.168.0.0/16" },
  1830. { 0,0,NULL},
  1831. };
  1832. for (i=0; private_networks[i].addr; ++i) {
  1833. p = NULL;
  1834. /* log_fn(LOG_INFO,"Checking network %s", private_networks[i].network); */
  1835. if (policy_includes_addr_mask_implicitly(
  1836. policy, private_networks[i].addr, private_networks[i].mask, &p)) {
  1837. if (warn)
  1838. log_fn(LOG_WARN, "Exit policy %s implicitly accepts %s",
  1839. p?p->string:"(default)",
  1840. private_networks[i].network);
  1841. r = 1;
  1842. }
  1843. }
  1844. return r;
  1845. }
  1846. /** Return true iff <b>router</b> does not permit exit streams.
  1847. */
  1848. int
  1849. router_exit_policy_rejects_all(routerinfo_t *router)
  1850. {
  1851. return router_compare_addr_to_addr_policy(0, 0, router->exit_policy)
  1852. == ADDR_POLICY_REJECTED;
  1853. }
  1854. /** Add to the list of authorized directory servers one at
  1855. * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
  1856. * <b>address</b> is NULL, add ourself. */
  1857. void
  1858. add_trusted_dir_server(const char *nickname, const char *address,
  1859. uint16_t port, const char *digest, int supports_v1)
  1860. {
  1861. trusted_dir_server_t *ent;
  1862. uint32_t a;
  1863. char *hostname = NULL;
  1864. size_t dlen;
  1865. if (!trusted_dir_servers)
  1866. trusted_dir_servers = smartlist_create();
  1867. if (!address) { /* The address is us; we should guess. */
  1868. if (resolve_my_address(get_options(), &a, &hostname) < 0) {
  1869. log_fn(LOG_WARN, "Couldn't find a suitable address. Returning.");
  1870. return;
  1871. }
  1872. } else {
  1873. if (tor_lookup_hostname(address, &a)) {
  1874. log_fn(LOG_WARN, "Unable to lookup address for directory server at %s",
  1875. address);
  1876. return;
  1877. }
  1878. hostname = tor_strdup(address);
  1879. a = ntohl(a);
  1880. }
  1881. ent = tor_malloc_zero(sizeof(trusted_dir_server_t));
  1882. ent->nickname = nickname ? tor_strdup(nickname) : NULL;
  1883. ent->address = hostname;
  1884. ent->addr = a;
  1885. ent->dir_port = port;
  1886. ent->is_running = 1;
  1887. ent->supports_v1_protocol = supports_v1;
  1888. memcpy(ent->digest, digest, DIGEST_LEN);
  1889. dlen = 64 + strlen(hostname) + (nickname?strlen(nickname):0);
  1890. ent->description = tor_malloc(dlen);
  1891. if (nickname)
  1892. tor_snprintf(ent->description, dlen, "directory server \"%s\" at %s:%d",
  1893. nickname, hostname, (int)port);
  1894. else
  1895. tor_snprintf(ent->description, dlen, "directory server at %s:%d",
  1896. hostname, (int)port);
  1897. smartlist_add(trusted_dir_servers, ent);
  1898. }
  1899. /** Free storage held in <b>ds</b> */
  1900. void
  1901. trusted_dir_server_free(trusted_dir_server_t *ds)
  1902. {
  1903. tor_free(ds->nickname);
  1904. tor_free(ds->description);
  1905. tor_free(ds->address);
  1906. tor_free(ds);
  1907. }
  1908. /** Remove all members from the list of trusted dir servers. */
  1909. void
  1910. clear_trusted_dir_servers(void)
  1911. {
  1912. if (trusted_dir_servers) {
  1913. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  1914. trusted_dir_server_free(ent));
  1915. smartlist_clear(trusted_dir_servers);
  1916. } else {
  1917. trusted_dir_servers = smartlist_create();
  1918. }
  1919. }
  1920. /** Return the network status with a given identity digest. */
  1921. networkstatus_t *
  1922. networkstatus_get_by_digest(const char *digest)
  1923. {
  1924. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  1925. {
  1926. if (!memcmp(ns->identity_digest, digest, DIGEST_LEN))
  1927. return ns;
  1928. });
  1929. return NULL;
  1930. }
  1931. /** If the network-status list has changed since the last time we called this
  1932. * function, update the status of every router from the network-status list.
  1933. */
  1934. void
  1935. routers_update_all_from_networkstatus(void)
  1936. {
  1937. #define SELF_OPINION_INTERVAL 90*60
  1938. routerinfo_t *me;
  1939. time_t now;
  1940. if (!routerlist || !networkstatus_list ||
  1941. (!networkstatus_list_has_changed && !routerstatus_list_has_changed))
  1942. return;
  1943. now = time(NULL);
  1944. if (networkstatus_list_has_changed)
  1945. routerstatus_list_update_from_networkstatus(now);
  1946. routers_update_status_from_networkstatus(routerlist->routers, 0);
  1947. me = router_get_my_routerinfo();
  1948. if (me && !have_warned_about_unverified_status) {
  1949. int n_recent = 0, n_listing = 0, n_valid = 0, n_named = 0;
  1950. routerstatus_t *rs;
  1951. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  1952. {
  1953. if (ns->received_on + SELF_OPINION_INTERVAL < now)
  1954. continue;
  1955. ++n_recent;
  1956. if (!(rs = networkstatus_find_entry(ns, me->identity_digest)))
  1957. continue;
  1958. ++n_listing;
  1959. if (rs->is_valid)
  1960. ++n_valid;
  1961. if (rs->is_named)
  1962. ++n_named;
  1963. });
  1964. if (n_recent >= 2 && n_listing >= 2) {
  1965. if (n_valid <= n_recent/2) {
  1966. log_fn(LOG_WARN, "%d/%d recent directory servers list us as invalid. Please consider sending your identity fingerprint to the tor-ops.",
  1967. n_recent-n_valid, n_recent);
  1968. have_warned_about_unverified_status = 1;
  1969. } else if (n_named <= n_recent/2) {
  1970. log_fn(LOG_WARN, "%d/%d recent directory servers list us as unnamed. Please consider sending your identity fingerprint to the tor-ops.",
  1971. n_recent-n_valid, n_recent);
  1972. have_warned_about_unverified_status = 1;
  1973. }
  1974. }
  1975. }
  1976. helper_nodes_set_status_from_directory();
  1977. if (!have_warned_about_old_version) {
  1978. int n_recent = 0;
  1979. int n_recommended = 0;
  1980. int is_server = server_mode(get_options());
  1981. version_status_t consensus = VS_RECOMMENDED;
  1982. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  1983. {
  1984. version_status_t vs;
  1985. if (!ns->recommends_versions ||
  1986. ns->received_on + SELF_OPINION_INTERVAL < now )
  1987. continue;
  1988. vs = tor_version_is_obsolete(
  1989. VERSION, is_server ? ns->server_versions : ns->client_versions);
  1990. if (vs == VS_RECOMMENDED)
  1991. ++n_recommended;
  1992. if (n_recent++ == 0) {
  1993. consensus = vs;
  1994. } else if (consensus != vs) {
  1995. consensus = version_status_join(consensus, vs);
  1996. }
  1997. });
  1998. if (n_recent > 2 && n_recommended < n_recent/2) {
  1999. if (consensus == VS_NEW || consensus == VS_NEW_IN_SERIES) {
  2000. if (!have_warned_about_new_version) {
  2001. log_fn(LOG_NOTICE, "This version of Tor (%s) is newer than any recommended version%s, according to %d/%d recent network statuses.",
  2002. VERSION, consensus == VS_NEW_IN_SERIES ? " in its series" : "",
  2003. n_recent-n_recommended, n_recent);
  2004. have_warned_about_new_version = 1;
  2005. }
  2006. } else {
  2007. log_fn(LOG_NOTICE, "This version of Tor (%s) is %s, according to %d/%d recent network statuses.",
  2008. VERSION, consensus == VS_OLD ? "obsolete" : "not recommended",
  2009. n_recent-n_recommended, n_recent);
  2010. have_warned_about_old_version = 1;
  2011. }
  2012. } else {
  2013. log_fn(LOG_INFO, "%d/%d recent directories think my version is ok.",
  2014. n_recommended, n_recent);
  2015. }
  2016. }
  2017. routerstatus_list_has_changed = 0;
  2018. }
  2019. /** Allow any network-status newer than this to influence our view of who's
  2020. * running. */
  2021. #define DEFAULT_RUNNING_INTERVAL 60*60
  2022. /** If possible, always allow at least this many network-statuses to influence
  2023. * our view of who's running. */
  2024. #define MIN_TO_INFLUENCE_RUNNING 3
  2025. /** Change the is_recent field of each member of networkstatus_list so that
  2026. * all members more recent than DEFAULT_RUNNING_INTERVAL are recent, and
  2027. * at least the MIN_TO_INFLUENCE_RUNNING most recent members are resent, and no
  2028. * others are recent. Set networkstatus_list_has_changed if anything happeed.
  2029. */
  2030. void
  2031. networkstatus_list_update_recent(time_t now)
  2032. {
  2033. int n_statuses, n_recent, changed, i;
  2034. char published[ISO_TIME_LEN+1];
  2035. if (!networkstatus_list)
  2036. return;
  2037. n_statuses = smartlist_len(networkstatus_list);
  2038. n_recent = 0;
  2039. changed = 0;
  2040. for (i=n_statuses-1; i >= 0; --i) {
  2041. networkstatus_t *ns = smartlist_get(networkstatus_list, i);
  2042. trusted_dir_server_t *ds =
  2043. router_get_trusteddirserver_by_digest(ns->identity_digest);
  2044. const char *src = ds?ds->description:ns->source_address;
  2045. if (n_recent < MIN_TO_INFLUENCE_RUNNING ||
  2046. ns->published_on + DEFAULT_RUNNING_INTERVAL > now) {
  2047. if (!ns->is_recent) {
  2048. format_iso_time(published, ns->published_on);
  2049. log_fn(LOG_INFO,
  2050. "Networkstatus from %s (published %s) is now \"recent\"",
  2051. src, published);
  2052. changed = 1;
  2053. }
  2054. ns->is_recent = 1;
  2055. ++n_recent;
  2056. } else {
  2057. if (ns->is_recent) {
  2058. format_iso_time(published, ns->published_on);
  2059. log_fn(LOG_INFO,
  2060. "Networkstatus from %s (published %s) is no longer \"recent\"",
  2061. src, published);
  2062. changed = 1;
  2063. ns->is_recent = 0;
  2064. }
  2065. }
  2066. }
  2067. if (changed)
  2068. networkstatus_list_has_changed = 1;
  2069. }
  2070. /** Update our view of router status (as stored in routerstatus_list) from
  2071. * the current set of network status documents (as stored in networkstatus_list).
  2072. * Do nothing unless the network status list has changed since the last time
  2073. * this function was called.
  2074. */
  2075. static void
  2076. routerstatus_list_update_from_networkstatus(time_t now)
  2077. {
  2078. or_options_t *options = get_options();
  2079. int n_trusted, n_statuses, n_recent=0, n_naming=0;
  2080. int n_distinct = 0;
  2081. int i, warned;
  2082. int *index, *size;
  2083. networkstatus_t **networkstatus;
  2084. smartlist_t *result;
  2085. strmap_t *name_map;
  2086. char conflict[DIGEST_LEN];
  2087. networkstatus_list_update_recent(now);
  2088. if (!networkstatus_list_has_changed)
  2089. return;
  2090. if (!networkstatus_list)
  2091. networkstatus_list = smartlist_create();
  2092. if (!routerstatus_list)
  2093. routerstatus_list = smartlist_create();
  2094. if (!trusted_dir_servers)
  2095. trusted_dir_servers = smartlist_create();
  2096. if (!warned_conflicts)
  2097. warned_conflicts = smartlist_create();
  2098. n_trusted = smartlist_len(trusted_dir_servers);
  2099. n_statuses = smartlist_len(networkstatus_list);
  2100. if (n_statuses < (n_trusted/2)+1) {
  2101. /* Not enough statuses to adjust status. */
  2102. log_fn(LOG_NOTICE,"Not enough statuses to update router status list. (%d/%d)",
  2103. n_statuses, n_trusted);
  2104. return;
  2105. }
  2106. log_fn(LOG_INFO, "Rebuilding router status list.");
  2107. index = tor_malloc(sizeof(int)*n_statuses);
  2108. size = tor_malloc(sizeof(int)*n_statuses);
  2109. networkstatus = tor_malloc(sizeof(networkstatus_t *)*n_statuses);
  2110. for (i = 0; i < n_statuses; ++i) {
  2111. index[i] = 0;
  2112. networkstatus[i] = smartlist_get(networkstatus_list, i);
  2113. size[i] = smartlist_len(networkstatus[i]->entries);
  2114. if (networkstatus[i]->binds_names)
  2115. ++n_naming;
  2116. if (networkstatus[i]->is_recent)
  2117. ++n_recent;
  2118. }
  2119. name_map = strmap_new();
  2120. memset(conflict, 0xff, sizeof(conflict));
  2121. for (i = 0; i < n_statuses; ++i) {
  2122. if (!networkstatus[i]->binds_names)
  2123. continue;
  2124. SMARTLIST_FOREACH(networkstatus[i]->entries, routerstatus_t *, rs,
  2125. {
  2126. const char *other_digest;
  2127. if (!rs->is_named)
  2128. continue;
  2129. other_digest = strmap_get_lc(name_map, rs->nickname);
  2130. warned = smartlist_string_isin(warned_conflicts, rs->nickname);
  2131. if (!other_digest) {
  2132. strmap_set_lc(name_map, rs->nickname, rs->identity_digest);
  2133. if (warned)
  2134. smartlist_string_remove(warned_conflicts, rs->nickname);
  2135. } else if (memcmp(other_digest, rs->identity_digest, DIGEST_LEN) &&
  2136. other_digest != conflict) {
  2137. if (!warned) {
  2138. int should_warn = options->DirPort && options->AuthoritativeDir;
  2139. char fp1[HEX_DIGEST_LEN+1];
  2140. char fp2[HEX_DIGEST_LEN+1];
  2141. base16_encode(fp1, sizeof(fp1), other_digest, DIGEST_LEN);
  2142. base16_encode(fp2, sizeof(fp2), rs->identity_digest, DIGEST_LEN);
  2143. log_fn(should_warn ? LOG_WARN : LOG_INFO,
  2144. "Naming authorities disagree about which key goes with %s. ($%s vs $%s)",
  2145. rs->nickname, fp1, fp2);
  2146. strmap_set_lc(name_map, rs->nickname, conflict);
  2147. smartlist_add(warned_conflicts, tor_strdup(rs->nickname));
  2148. }
  2149. } else {
  2150. if (warned)
  2151. smartlist_string_remove(warned_conflicts, rs->nickname);
  2152. }
  2153. });
  2154. }
  2155. result = smartlist_create();
  2156. /* Iterate through all of the sorted routerstatus lists in step.
  2157. * Invariants:
  2158. * - For 0 <= i < n_statuses: index[i] is an index into
  2159. * networkstatus[i]->entries, which has size[i] elements.
  2160. * - For i1, i2, j such that 0 <= i1 < n_statuses, 0 <= i2 < n_statues, 0 <=
  2161. * j < index[i1], networkstatus[i1]->entries[j]->identity_digest <
  2162. * networkstatus[i2]->entries[index[i2]]->identity_digest.
  2163. *
  2164. * (That is, the indices are always advanced past lower digest before
  2165. * higher.)
  2166. */
  2167. while (1) {
  2168. int n_running=0, n_named=0, n_valid=0, n_listing=0;
  2169. const char *the_name = NULL;
  2170. local_routerstatus_t *rs_out, *rs_old;
  2171. routerstatus_t *rs, *most_recent;
  2172. networkstatus_t *ns;
  2173. const char *lowest = NULL;
  2174. /* Find out which of the digests appears first. */
  2175. for (i = 0; i < n_statuses; ++i) {
  2176. if (index[i] < size[i]) {
  2177. rs = smartlist_get(networkstatus[i]->entries, index[i]);
  2178. if (!lowest || memcmp(rs->identity_digest, lowest, DIGEST_LEN)<0)
  2179. lowest = rs->identity_digest;
  2180. }
  2181. }
  2182. if (!lowest) {
  2183. /* We're out of routers. Great! */
  2184. break;
  2185. }
  2186. /* Okay. The routers at networkstatus[i]->entries[index[i]] whose digests
  2187. * match "lowest" are next in order. Iterate over them, incrementing those
  2188. * index[i] as we go. */
  2189. ++n_distinct;
  2190. most_recent = NULL;
  2191. for (i = 0; i < n_statuses; ++i) {
  2192. if (index[i] >= size[i])
  2193. continue;
  2194. ns = networkstatus[i];
  2195. rs = smartlist_get(ns->entries, index[i]);
  2196. if (memcmp(rs->identity_digest, lowest, DIGEST_LEN))
  2197. continue;
  2198. ++index[i];
  2199. ++n_listing;
  2200. if (!most_recent || rs->published_on > most_recent->published_on)
  2201. most_recent = rs;
  2202. if (rs->is_named && ns->binds_names) {
  2203. if (!the_name)
  2204. the_name = rs->nickname;
  2205. if (!strcasecmp(rs->nickname, the_name)) {
  2206. ++n_named;
  2207. } else if (strcmp(the_name,"**mismatch**")) {
  2208. char hd[HEX_DIGEST_LEN+1];
  2209. base16_encode(hd, HEX_DIGEST_LEN+1, rs->identity_digest, DIGEST_LEN);
  2210. if (! smartlist_string_isin(warned_conflicts, hd)) {
  2211. log_fn(LOG_WARN, "Naming authorities disagree about nicknames for $%s (\"%s\" vs \"%s\")",
  2212. hd, the_name, rs->nickname);
  2213. smartlist_add(warned_conflicts, tor_strdup(hd));
  2214. }
  2215. the_name = "**mismatch**";
  2216. }
  2217. }
  2218. if (rs->is_valid)
  2219. ++n_valid;
  2220. if (rs->is_running && ns->is_recent)
  2221. ++n_running;
  2222. }
  2223. rs_out = tor_malloc_zero(sizeof(local_routerstatus_t));
  2224. memcpy(&rs_out->status, most_recent, sizeof(routerstatus_t));
  2225. if ((rs_old = router_get_combined_status_by_digest(lowest))) {
  2226. rs_out->n_download_failures = rs_old->n_download_failures;
  2227. rs_out->next_attempt_at = rs_old->next_attempt_at;
  2228. rs_out->name_lookup_warned = rs_old->name_lookup_warned;
  2229. }
  2230. smartlist_add(result, rs_out);
  2231. log_fn(LOG_DEBUG, "Router '%s' is listed by %d/%d directories, "
  2232. "named by %d/%d, validated by %d/%d, and %d/%d recent directories "
  2233. "think it's running.",
  2234. rs_out->status.nickname,
  2235. n_listing, n_statuses, n_named, n_naming, n_valid, n_statuses,
  2236. n_running, n_recent);
  2237. rs_out->status.is_named = 0;
  2238. if (the_name && strcmp(the_name, "**mismatch**") && n_named > 0) {
  2239. const char *d = strmap_get_lc(name_map, the_name);
  2240. if (d && d != conflict)
  2241. rs_out->status.is_named = 1;
  2242. if (smartlist_string_isin(warned_conflicts, rs_out->status.nickname))
  2243. smartlist_string_remove(warned_conflicts, rs_out->status.nickname);
  2244. }
  2245. if (rs_out->status.is_named)
  2246. strlcpy(rs_out->status.nickname, the_name, sizeof(rs_out->status.nickname));
  2247. rs_out->status.is_valid = n_valid > n_statuses/2;
  2248. rs_out->status.is_running = n_running > n_recent/2;
  2249. }
  2250. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  2251. local_routerstatus_free(rs));
  2252. smartlist_free(routerstatus_list);
  2253. routerstatus_list = result;
  2254. tor_free(networkstatus);
  2255. tor_free(index);
  2256. tor_free(size);
  2257. strmap_free(name_map, NULL);
  2258. networkstatus_list_has_changed = 0;
  2259. routerstatus_list_has_changed = 1;
  2260. }
  2261. /** Given a list <b>routers</b> of routerinfo_t *, update each routers's
  2262. * is_named, is_verified, and is_running fields according to our current
  2263. * networkstatus_t documents. */
  2264. void
  2265. routers_update_status_from_networkstatus(smartlist_t *routers, int reset_failures)
  2266. {
  2267. trusted_dir_server_t *ds;
  2268. local_routerstatus_t *rs;
  2269. or_options_t *options = get_options();
  2270. int authdir = options->AuthoritativeDir;
  2271. int namingdir = options->AuthoritativeDir &&
  2272. options->NamingAuthoritativeDir;
  2273. if (!routerstatus_list)
  2274. return;
  2275. SMARTLIST_FOREACH(routers, routerinfo_t *, router,
  2276. {
  2277. rs = router_get_combined_status_by_digest(router->identity_digest);
  2278. ds = router_get_trusteddirserver_by_digest(router->identity_digest);
  2279. if (!rs)
  2280. continue;
  2281. if (reset_failures) {
  2282. rs->n_download_failures = 0;
  2283. rs->next_attempt_at = 0;
  2284. }
  2285. if (!namingdir)
  2286. router->is_named = rs->status.is_named;
  2287. if (!authdir) {
  2288. /* If we're an authdir, don't believe others. */
  2289. router->is_verified = rs->status.is_valid;
  2290. router->is_running = rs->status.is_running;
  2291. }
  2292. if (router->is_running && ds) {
  2293. ds->n_networkstatus_failures = 0;
  2294. }
  2295. });
  2296. }
  2297. /** Return new list of ID fingerprints for superseded routers. A router is
  2298. * superseded if any network-status has a router with a different digest
  2299. * published more recently, or if it is listed in the network-status but not
  2300. * in the router list.
  2301. */
  2302. static smartlist_t *
  2303. router_list_downloadable(void)
  2304. {
  2305. #define MAX_OLD_SERVER_DOWNLOAD_RATE 2*60*60
  2306. int n_conns, i, n_downloadable = 0;
  2307. int n_uptodate=0,n_skip_old=0;
  2308. connection_t **carray;
  2309. smartlist_t *superseded = smartlist_create();
  2310. smartlist_t *downloading;
  2311. time_t now = time(NULL);
  2312. int mirror = server_mode(get_options()) && get_options()->DirPort;
  2313. if (!routerstatus_list)
  2314. return superseded;
  2315. get_connection_array(&carray, &n_conns);
  2316. routerstatus_list_update_from_networkstatus(now);
  2317. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  2318. {
  2319. if (rs->next_attempt_at < now) {
  2320. rs->should_download = 1;
  2321. ++n_downloadable;
  2322. } else {
  2323. /*
  2324. char fp[HEX_DIGEST_LEN+1];
  2325. base16_encode(fp, HEX_DIGEST_LEN+1, rs->status.identity_digest, DIGEST_LEN);
  2326. log_fn(LOG_NOTICE, "Not yet ready to download %s (%d more seconds)", fp,
  2327. (int)(rs->next_attempt_at-now));
  2328. */
  2329. rs->should_download = 0;
  2330. }
  2331. });
  2332. downloading = smartlist_create();
  2333. for (i = 0; i < n_conns; ++i) {
  2334. connection_t *conn = carray[i];
  2335. if (conn->type == CONN_TYPE_DIR &&
  2336. conn->purpose == DIR_PURPOSE_FETCH_SERVERDESC &&
  2337. !conn->marked_for_close) {
  2338. if (!strcmpstart(conn->requested_resource, "all"))
  2339. n_downloadable = 0;
  2340. dir_split_resource_into_fingerprints(conn->requested_resource,
  2341. downloading, NULL);
  2342. }
  2343. }
  2344. /*
  2345. log_fn(LOG_NOTICE, "%d downloads already in progress",
  2346. smartlist_len(downloading));
  2347. smartlist_sort_strings(downloading);
  2348. */
  2349. if (n_downloadable) {
  2350. SMARTLIST_FOREACH(downloading, const char *, dl,
  2351. {
  2352. char d[DIGEST_LEN];
  2353. local_routerstatus_t *rs;
  2354. base16_decode(d, DIGEST_LEN, dl, strlen(dl));
  2355. if ((rs = router_get_combined_status_by_digest(d)) && rs->should_download) {
  2356. rs->should_download = 0;
  2357. --n_downloadable;
  2358. // log_fn(LOG_NOTICE, "%s is in-progress; not fetching", dl);
  2359. }
  2360. });
  2361. }
  2362. SMARTLIST_FOREACH(downloading, char *, cp, tor_free(cp));
  2363. smartlist_free(downloading);
  2364. if (!n_downloadable)
  2365. return superseded;
  2366. if (routerlist) {
  2367. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
  2368. {
  2369. local_routerstatus_t *rs;
  2370. if (!(rs = router_get_combined_status_by_digest(ri->identity_digest)) ||
  2371. !rs->should_download) {
  2372. // log_fn(LOG_NOTICE, "No status for %s", fp);
  2373. continue;
  2374. }
  2375. /* Change this "or" to be an "and" once dirs generate hashes right.
  2376. * Remove the version check once older versions are uncommon.
  2377. * XXXXX. NM */
  2378. if (!memcmp(ri->signed_descriptor_digest, rs->status.descriptor_digest,
  2379. DIGEST_LEN) ||
  2380. rs->status.published_on <= ri->published_on) {
  2381. ++n_uptodate;
  2382. rs->should_download = 0;
  2383. --n_downloadable;
  2384. } else if (!mirror &&
  2385. ri->platform &&
  2386. !tor_version_as_new_as(ri->platform, "0.1.1.6-alpha") &&
  2387. ri->published_on + MAX_OLD_SERVER_DOWNLOAD_RATE > now) {
  2388. /* Same digest, or date is up-to-date, or we have a comparatively recent
  2389. * server with an old version.
  2390. * No need to download it. */
  2391. // log_fn(LOG_NOTICE, "Up-to-date status for %s", fp);
  2392. ++n_skip_old;
  2393. rs->should_download = 0;
  2394. --n_downloadable;
  2395. } /* else {
  2396. char t1[ISO_TIME_LEN+1];
  2397. char t2[ISO_TIME_LEN+1];
  2398. format_iso_time(t1, rs->satus.published_on);
  2399. format_iso_time(t2, ri->published_on);
  2400. log_fn(LOG_NOTICE, "Out-of-date status for %s %s (%d %d) [%s %s]", fp,
  2401. ri->nickname,
  2402. !memcmp(ri->signed_descriptor_digest,rs->status.descriptor_digest,
  2403. DIGEST_LEN),
  2404. rs->published_on < ri->published_on,
  2405. t1, t2);
  2406. } */
  2407. });
  2408. }
  2409. if (n_skip_old)
  2410. log_fn(LOG_INFO, "Skipped %d updatable pre-0.1.1.6 servers.", n_skip_old);
  2411. if (!n_downloadable)
  2412. return superseded;
  2413. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  2414. {
  2415. if (rs->should_download) {
  2416. char *fp = tor_malloc(HEX_DIGEST_LEN+1);
  2417. base16_encode(fp, HEX_DIGEST_LEN+1, rs->status.identity_digest, DIGEST_LEN);
  2418. smartlist_add(superseded, fp);
  2419. }
  2420. });
  2421. return superseded;
  2422. }
  2423. /** Initiate new router downloads as needed.
  2424. *
  2425. * We only allow one router descriptor download at a time.
  2426. * If we have less than two network-status documents, we ask
  2427. * a directory for "all descriptors."
  2428. * Otherwise, we ask for all descriptors that we think are different
  2429. * from what we have.
  2430. */
  2431. void
  2432. update_router_descriptor_downloads(time_t now)
  2433. {
  2434. #define MAX_DL_PER_REQUEST 128
  2435. #define MIN_DL_PER_REQUEST 4
  2436. #define MIN_REQUESTS 3
  2437. #define MAX_DL_TO_DELAY 16
  2438. #define MAX_CLIENT_INTERVAL_WITHOUT_REQUEST 10*60
  2439. #define MAX_SERVER_INTERVAL_WITHOUT_REQUEST 1*60
  2440. smartlist_t *downloadable = NULL;
  2441. int get_all = 0;
  2442. int dirserv = server_mode(get_options()) && get_options()->DirPort;
  2443. int should_delay, n_downloadable;
  2444. if (!networkstatus_list || smartlist_len(networkstatus_list)<2)
  2445. get_all = 1;
  2446. if (get_all) {
  2447. log_fn(LOG_NOTICE, "Launching request for all routers");
  2448. last_routerdesc_download_attempted = now;
  2449. directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,"all.z",1);
  2450. return;
  2451. }
  2452. downloadable = router_list_downloadable();
  2453. n_downloadable = smartlist_len(downloadable);
  2454. if (n_downloadable >= MAX_DL_TO_DELAY)
  2455. should_delay = 0;
  2456. else if (n_downloadable == 0)
  2457. should_delay = 1;
  2458. else if (dirserv)
  2459. should_delay = (last_routerdesc_download_attempted +
  2460. MAX_SERVER_INTERVAL_WITHOUT_REQUEST) < now;
  2461. else
  2462. should_delay = (last_routerdesc_download_attempted +
  2463. MAX_CLIENT_INTERVAL_WITHOUT_REQUEST) < now;
  2464. if (! should_delay) {
  2465. int i, j, n_per_request=MAX_DL_PER_REQUEST;
  2466. size_t r_len = MAX_DL_PER_REQUEST*(HEX_DIGEST_LEN+1)+16;
  2467. char *resource = tor_malloc(r_len);
  2468. if (! dirserv) {
  2469. n_per_request = (n_downloadable+MIN_REQUESTS-1) / MIN_REQUESTS;
  2470. if (n_per_request > MAX_DL_PER_REQUEST)
  2471. n_per_request = MAX_DL_PER_REQUEST;
  2472. if (n_per_request < MIN_DL_PER_REQUEST)
  2473. n_per_request = MIN_DL_PER_REQUEST;
  2474. }
  2475. log_fn(LOG_INFO, "Launching %d request%s for %d router%s, %d at a time",
  2476. (n_downloadable+n_per_request-1)/n_per_request,
  2477. n_downloadable>n_per_request?"s":"",
  2478. n_downloadable, n_downloadable>1?"s":"", n_per_request);
  2479. for (i=0; i < n_downloadable; i += n_per_request) {
  2480. char *cp = resource;
  2481. memcpy(resource, "fp/", 3);
  2482. cp = resource + 3;
  2483. for (j=i; j < i+n_per_request && j < n_downloadable; ++j) {
  2484. memcpy(cp, smartlist_get(downloadable, j), HEX_DIGEST_LEN);
  2485. cp += HEX_DIGEST_LEN;
  2486. *cp++ = '+';
  2487. }
  2488. memcpy(cp-1, ".z", 3);
  2489. directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,resource,1);
  2490. }
  2491. last_routerdesc_download_attempted = now;
  2492. tor_free(resource);
  2493. }
  2494. SMARTLIST_FOREACH(downloadable, char *, c, tor_free(c));
  2495. smartlist_free(downloadable);
  2496. }
  2497. /** Return true iff we have enough networkstatus and router information to
  2498. * start building circuits. Right now, this means "at least 2 networkstatus
  2499. * documents, and at least 1/4 of expected routers." */
  2500. int
  2501. router_have_minimum_dir_info(void)
  2502. {
  2503. int tot = 0, avg;
  2504. if (!networkstatus_list || smartlist_len(networkstatus_list)<2 ||
  2505. !routerlist)
  2506. return 0;
  2507. SMARTLIST_FOREACH(networkstatus_list, networkstatus_t *, ns,
  2508. tot += smartlist_len(ns->entries));
  2509. avg = tot / smartlist_len(networkstatus_list);
  2510. return smartlist_len(routerlist->routers) > (avg/4);
  2511. }
  2512. /** Reset the descriptor download failure count on all routers, so that we
  2513. * can retry any long-failed routers immediately.
  2514. */
  2515. void
  2516. router_reset_descriptor_download_failures(void)
  2517. {
  2518. if (!routerstatus_list)
  2519. return;
  2520. SMARTLIST_FOREACH(routerstatus_list, local_routerstatus_t *, rs,
  2521. {
  2522. rs->n_download_failures = 0;
  2523. rs->next_attempt_at = 0;
  2524. });
  2525. last_routerdesc_download_attempted = 0;
  2526. }