routerlist.c 100 KB

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