routerlist.c 98 KB

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