routerlist.c 126 KB

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