routerlist.c 145 KB

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