routerlist.c 123 KB

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