routerlist.c 172 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2013, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file routerlist.c
  8. * \brief Code to
  9. * maintain and access the global list of routerinfos for known
  10. * servers.
  11. **/
  12. #define ROUTERLIST_PRIVATE
  13. #include "or.h"
  14. #include "circuitstats.h"
  15. #include "config.h"
  16. #include "connection.h"
  17. #include "control.h"
  18. #include "directory.h"
  19. #include "dirserv.h"
  20. #include "dirvote.h"
  21. #include "entrynodes.h"
  22. #include "geoip.h"
  23. #include "hibernate.h"
  24. #include "main.h"
  25. #include "microdesc.h"
  26. #include "networkstatus.h"
  27. #include "nodelist.h"
  28. #include "policies.h"
  29. #include "reasons.h"
  30. #include "rendcommon.h"
  31. #include "rendservice.h"
  32. #include "rephist.h"
  33. #include "router.h"
  34. #include "routerlist.h"
  35. #include "routerparse.h"
  36. #include "routerset.h"
  37. // #define DEBUG_ROUTERLIST
  38. /****************************************************************************/
  39. /* static function prototypes */
  40. static int compute_weighted_bandwidths(const smartlist_t *sl,
  41. bandwidth_weight_rule_t rule,
  42. u64_dbl_t **bandwidths_out);
  43. static const routerstatus_t *router_pick_directory_server_impl(
  44. dirinfo_type_t auth, int flags);
  45. static const routerstatus_t *router_pick_trusteddirserver_impl(
  46. const smartlist_t *sourcelist, dirinfo_type_t auth,
  47. int flags, int *n_busy_out);
  48. static const routerstatus_t *router_pick_dirserver_generic(
  49. smartlist_t *sourcelist,
  50. dirinfo_type_t type, int flags);
  51. static void mark_all_dirservers_up(smartlist_t *server_list);
  52. static int router_nickname_matches(const routerinfo_t *router,
  53. const char *nickname);
  54. static void dir_server_free(dir_server_t *ds);
  55. static int signed_desc_digest_is_recognized(signed_descriptor_t *desc);
  56. static const char *signed_descriptor_get_body_impl(
  57. const signed_descriptor_t *desc,
  58. int with_annotations);
  59. static void list_pending_downloads(digestmap_t *result,
  60. int purpose, const char *prefix);
  61. static void launch_dummy_descriptor_download_as_needed(time_t now,
  62. const or_options_t *options);
  63. DECLARE_TYPED_DIGESTMAP_FNS(sdmap_, digest_sd_map_t, signed_descriptor_t)
  64. DECLARE_TYPED_DIGESTMAP_FNS(rimap_, digest_ri_map_t, routerinfo_t)
  65. DECLARE_TYPED_DIGESTMAP_FNS(eimap_, digest_ei_map_t, extrainfo_t)
  66. #define SDMAP_FOREACH(map, keyvar, valvar) \
  67. DIGESTMAP_FOREACH(sdmap_to_digestmap(map), keyvar, signed_descriptor_t *, \
  68. valvar)
  69. #define RIMAP_FOREACH(map, keyvar, valvar) \
  70. DIGESTMAP_FOREACH(rimap_to_digestmap(map), keyvar, routerinfo_t *, valvar)
  71. #define EIMAP_FOREACH(map, keyvar, valvar) \
  72. DIGESTMAP_FOREACH(eimap_to_digestmap(map), keyvar, extrainfo_t *, valvar)
  73. /****************************************************************************/
  74. /** Global list of a dir_server_t object for each directory
  75. * authority. */
  76. static smartlist_t *trusted_dir_servers = NULL;
  77. /** Global list of dir_server_t objects for all directory authorities
  78. * and all fallback directory servers. */
  79. static smartlist_t *fallback_dir_servers = NULL;
  80. /** List of for a given authority, and download status for latest certificate.
  81. */
  82. typedef struct cert_list_t {
  83. download_status_t dl_status;
  84. smartlist_t *certs;
  85. } cert_list_t;
  86. /** Map from v3 identity key digest to cert_list_t. */
  87. static digestmap_t *trusted_dir_certs = NULL;
  88. /** True iff any key certificate in at least one member of
  89. * <b>trusted_dir_certs</b> has changed since we last flushed the
  90. * certificates to disk. */
  91. static int trusted_dir_servers_certs_changed = 0;
  92. /** Global list of all of the routers that we know about. */
  93. static routerlist_t *routerlist = NULL;
  94. /** List of strings for nicknames we've already warned about and that are
  95. * still unknown / unavailable. */
  96. static smartlist_t *warned_nicknames = NULL;
  97. /** The last time we tried to download any routerdesc, or 0 for "never". We
  98. * use this to rate-limit download attempts when the number of routerdescs to
  99. * download is low. */
  100. static time_t last_descriptor_download_attempted = 0;
  101. /** When we last computed the weights to use for bandwidths on directory
  102. * requests, what were the total weighted bandwidth, and our share of that
  103. * bandwidth? Used to determine what fraction of directory requests we should
  104. * expect to see.
  105. *
  106. * @{ */
  107. static uint64_t sl_last_total_weighted_bw = 0,
  108. sl_last_weighted_bw_of_me = 0;
  109. /**@}*/
  110. /** Return the number of directory authorities whose type matches some bit set
  111. * in <b>type</b> */
  112. int
  113. get_n_authorities(dirinfo_type_t type)
  114. {
  115. int n = 0;
  116. if (!trusted_dir_servers)
  117. return 0;
  118. SMARTLIST_FOREACH(trusted_dir_servers, dir_server_t *, ds,
  119. if (ds->type & type)
  120. ++n);
  121. return n;
  122. }
  123. #define get_n_v2_authorities() get_n_authorities(V2_DIRINFO)
  124. /** Helper: Return the cert_list_t for an authority whose authority ID is
  125. * <b>id_digest</b>, allocating a new list if necessary. */
  126. static cert_list_t *
  127. get_cert_list(const char *id_digest)
  128. {
  129. cert_list_t *cl;
  130. if (!trusted_dir_certs)
  131. trusted_dir_certs = digestmap_new();
  132. cl = digestmap_get(trusted_dir_certs, id_digest);
  133. if (!cl) {
  134. cl = tor_malloc_zero(sizeof(cert_list_t));
  135. cl->dl_status.schedule = DL_SCHED_CONSENSUS;
  136. cl->certs = smartlist_new();
  137. digestmap_set(trusted_dir_certs, id_digest, cl);
  138. }
  139. return cl;
  140. }
  141. /** Reload the cached v3 key certificates from the cached-certs file in
  142. * the data directory. Return 0 on success, -1 on failure. */
  143. int
  144. trusted_dirs_reload_certs(void)
  145. {
  146. char *filename;
  147. char *contents;
  148. int r;
  149. filename = get_datadir_fname("cached-certs");
  150. contents = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
  151. tor_free(filename);
  152. if (!contents)
  153. return 0;
  154. r = trusted_dirs_load_certs_from_string(contents, 1, 1);
  155. tor_free(contents);
  156. return r;
  157. }
  158. /** Helper: return true iff we already have loaded the exact cert
  159. * <b>cert</b>. */
  160. static INLINE int
  161. already_have_cert(authority_cert_t *cert)
  162. {
  163. cert_list_t *cl = get_cert_list(cert->cache_info.identity_digest);
  164. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, c,
  165. {
  166. if (tor_memeq(c->cache_info.signed_descriptor_digest,
  167. cert->cache_info.signed_descriptor_digest,
  168. DIGEST_LEN))
  169. return 1;
  170. });
  171. return 0;
  172. }
  173. /** Load a bunch of new key certificates from the string <b>contents</b>. If
  174. * <b>from_store</b> is true, the certificates are from the cache, and we
  175. * don't need to flush them to disk. If <b>flush</b> is true, we need
  176. * to flush any changed certificates to disk now. Return 0 on success, -1
  177. * if any certs fail to parse. */
  178. int
  179. trusted_dirs_load_certs_from_string(const char *contents, int from_store,
  180. int flush)
  181. {
  182. dir_server_t *ds;
  183. const char *s, *eos;
  184. int failure_code = 0;
  185. for (s = contents; *s; s = eos) {
  186. authority_cert_t *cert = authority_cert_parse_from_string(s, &eos);
  187. cert_list_t *cl;
  188. if (!cert) {
  189. failure_code = -1;
  190. break;
  191. }
  192. ds = trusteddirserver_get_by_v3_auth_digest(
  193. cert->cache_info.identity_digest);
  194. log_debug(LD_DIR, "Parsed certificate for %s",
  195. ds ? ds->nickname : "unknown authority");
  196. if (already_have_cert(cert)) {
  197. /* we already have this one. continue. */
  198. log_info(LD_DIR, "Skipping %s certificate for %s that we "
  199. "already have.",
  200. from_store ? "cached" : "downloaded",
  201. ds ? ds->nickname : "an old or new authority");
  202. /* a duplicate on a download should be treated as a failure, since it
  203. * probably means we wanted a different secret key or we are trying to
  204. * replace an expired cert that has not in fact been updated. */
  205. if (!from_store) {
  206. if (authdir_mode(get_options())) {
  207. log_warn(LD_DIR,
  208. "Got a certificate for %s, but we already have it. "
  209. "Maybe they haven't updated it. Waiting for a while.",
  210. ds ? ds->nickname : "an old or new authority");
  211. } else {
  212. log_info(LD_DIR,
  213. "Got a certificate for %s, but we already have it. "
  214. "Maybe they haven't updated it. Waiting for a while.",
  215. ds ? ds->nickname : "an old or new authority");
  216. }
  217. authority_cert_dl_failed(cert->cache_info.identity_digest, 404);
  218. }
  219. authority_cert_free(cert);
  220. continue;
  221. }
  222. if (ds) {
  223. log_info(LD_DIR, "Adding %s certificate for directory authority %s with "
  224. "signing key %s", from_store ? "cached" : "downloaded",
  225. ds->nickname, hex_str(cert->signing_key_digest,DIGEST_LEN));
  226. } else {
  227. int adding = directory_caches_unknown_auth_certs(get_options());
  228. log_info(LD_DIR, "%s %s certificate for unrecognized directory "
  229. "authority with signing key %s",
  230. adding ? "Adding" : "Not adding",
  231. from_store ? "cached" : "downloaded",
  232. hex_str(cert->signing_key_digest,DIGEST_LEN));
  233. if (!adding) {
  234. authority_cert_free(cert);
  235. continue;
  236. }
  237. }
  238. cl = get_cert_list(cert->cache_info.identity_digest);
  239. smartlist_add(cl->certs, cert);
  240. if (ds && cert->cache_info.published_on > ds->addr_current_at) {
  241. /* Check to see whether we should update our view of the authority's
  242. * address. */
  243. if (cert->addr && cert->dir_port &&
  244. (ds->addr != cert->addr ||
  245. ds->dir_port != cert->dir_port)) {
  246. char *a = tor_dup_ip(cert->addr);
  247. log_notice(LD_DIR, "Updating address for directory authority %s "
  248. "from %s:%d to %s:%d based on certificate.",
  249. ds->nickname, ds->address, (int)ds->dir_port,
  250. a, cert->dir_port);
  251. tor_free(a);
  252. ds->addr = cert->addr;
  253. ds->dir_port = cert->dir_port;
  254. }
  255. ds->addr_current_at = cert->cache_info.published_on;
  256. }
  257. if (!from_store)
  258. trusted_dir_servers_certs_changed = 1;
  259. }
  260. if (flush)
  261. trusted_dirs_flush_certs_to_disk();
  262. /* call this even if failure_code is <0, since some certs might have
  263. * succeeded. */
  264. networkstatus_note_certs_arrived();
  265. return failure_code;
  266. }
  267. /** Save all v3 key certificates to the cached-certs file. */
  268. void
  269. trusted_dirs_flush_certs_to_disk(void)
  270. {
  271. char *filename;
  272. smartlist_t *chunks;
  273. if (!trusted_dir_servers_certs_changed || !trusted_dir_certs)
  274. return;
  275. chunks = smartlist_new();
  276. DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
  277. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
  278. {
  279. sized_chunk_t *c = tor_malloc(sizeof(sized_chunk_t));
  280. c->bytes = cert->cache_info.signed_descriptor_body;
  281. c->len = cert->cache_info.signed_descriptor_len;
  282. smartlist_add(chunks, c);
  283. });
  284. } DIGESTMAP_FOREACH_END;
  285. filename = get_datadir_fname("cached-certs");
  286. if (write_chunks_to_file(filename, chunks, 0)) {
  287. log_warn(LD_FS, "Error writing certificates to disk.");
  288. }
  289. tor_free(filename);
  290. SMARTLIST_FOREACH(chunks, sized_chunk_t *, c, tor_free(c));
  291. smartlist_free(chunks);
  292. trusted_dir_servers_certs_changed = 0;
  293. }
  294. /** Remove all v3 authority certificates that have been superseded for more
  295. * than 48 hours. (If the most recent cert was published more than 48 hours
  296. * ago, then we aren't going to get any consensuses signed with older
  297. * keys.) */
  298. static void
  299. trusted_dirs_remove_old_certs(void)
  300. {
  301. time_t now = time(NULL);
  302. #define DEAD_CERT_LIFETIME (2*24*60*60)
  303. #define OLD_CERT_LIFETIME (7*24*60*60)
  304. #define CERT_EXPIRY_SKEW (60*60)
  305. if (!trusted_dir_certs)
  306. return;
  307. DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
  308. authority_cert_t *newest = NULL;
  309. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
  310. if (!newest || (cert->cache_info.published_on >
  311. newest->cache_info.published_on))
  312. newest = cert);
  313. if (newest) {
  314. const time_t newest_published = newest->cache_info.published_on;
  315. SMARTLIST_FOREACH_BEGIN(cl->certs, authority_cert_t *, cert) {
  316. int expired;
  317. time_t cert_published;
  318. if (newest == cert)
  319. continue;
  320. expired = now > cert->expires;
  321. cert_published = cert->cache_info.published_on;
  322. /* Store expired certs for 48 hours after a newer arrives;
  323. */
  324. if (expired ?
  325. (newest_published + DEAD_CERT_LIFETIME < now) :
  326. (cert_published + OLD_CERT_LIFETIME < newest_published)) {
  327. SMARTLIST_DEL_CURRENT(cl->certs, cert);
  328. authority_cert_free(cert);
  329. trusted_dir_servers_certs_changed = 1;
  330. }
  331. } SMARTLIST_FOREACH_END(cert);
  332. }
  333. } DIGESTMAP_FOREACH_END;
  334. #undef OLD_CERT_LIFETIME
  335. trusted_dirs_flush_certs_to_disk();
  336. }
  337. /** Return the newest v3 authority certificate whose v3 authority identity key
  338. * has digest <b>id_digest</b>. Return NULL if no such authority is known,
  339. * or it has no certificate. */
  340. authority_cert_t *
  341. authority_cert_get_newest_by_id(const char *id_digest)
  342. {
  343. cert_list_t *cl;
  344. authority_cert_t *best = NULL;
  345. if (!trusted_dir_certs ||
  346. !(cl = digestmap_get(trusted_dir_certs, id_digest)))
  347. return NULL;
  348. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
  349. {
  350. if (!best || cert->cache_info.published_on > best->cache_info.published_on)
  351. best = cert;
  352. });
  353. return best;
  354. }
  355. /** Return the newest v3 authority certificate whose directory signing key has
  356. * digest <b>sk_digest</b>. Return NULL if no such certificate is known.
  357. */
  358. authority_cert_t *
  359. authority_cert_get_by_sk_digest(const char *sk_digest)
  360. {
  361. authority_cert_t *c;
  362. if (!trusted_dir_certs)
  363. return NULL;
  364. if ((c = get_my_v3_authority_cert()) &&
  365. tor_memeq(c->signing_key_digest, sk_digest, DIGEST_LEN))
  366. return c;
  367. if ((c = get_my_v3_legacy_cert()) &&
  368. tor_memeq(c->signing_key_digest, sk_digest, DIGEST_LEN))
  369. return c;
  370. DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
  371. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
  372. {
  373. if (tor_memeq(cert->signing_key_digest, sk_digest, DIGEST_LEN))
  374. return cert;
  375. });
  376. } DIGESTMAP_FOREACH_END;
  377. return NULL;
  378. }
  379. /** Return the v3 authority certificate with signing key matching
  380. * <b>sk_digest</b>, for the authority with identity digest <b>id_digest</b>.
  381. * Return NULL if no such authority is known. */
  382. authority_cert_t *
  383. authority_cert_get_by_digests(const char *id_digest,
  384. const char *sk_digest)
  385. {
  386. cert_list_t *cl;
  387. if (!trusted_dir_certs ||
  388. !(cl = digestmap_get(trusted_dir_certs, id_digest)))
  389. return NULL;
  390. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
  391. if (tor_memeq(cert->signing_key_digest, sk_digest, DIGEST_LEN))
  392. return cert; );
  393. return NULL;
  394. }
  395. /** Add every known authority_cert_t to <b>certs_out</b>. */
  396. void
  397. authority_cert_get_all(smartlist_t *certs_out)
  398. {
  399. tor_assert(certs_out);
  400. if (!trusted_dir_certs)
  401. return;
  402. DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
  403. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, c,
  404. smartlist_add(certs_out, c));
  405. } DIGESTMAP_FOREACH_END;
  406. }
  407. /** Called when an attempt to download a certificate with the authority with
  408. * ID <b>id_digest</b> fails with HTTP response code <b>status</b>: remember
  409. * the failure, so we don't try again immediately. */
  410. void
  411. authority_cert_dl_failed(const char *id_digest, int status)
  412. {
  413. cert_list_t *cl;
  414. if (!trusted_dir_certs ||
  415. !(cl = digestmap_get(trusted_dir_certs, id_digest)))
  416. return;
  417. download_status_failed(&cl->dl_status, status);
  418. }
  419. /** Return true iff when we've been getting enough failures when trying to
  420. * download the certificate with ID digest <b>id_digest</b> that we're willing
  421. * to start bugging the user about it. */
  422. int
  423. authority_cert_dl_looks_uncertain(const char *id_digest)
  424. {
  425. #define N_AUTH_CERT_DL_FAILURES_TO_BUG_USER 2
  426. cert_list_t *cl;
  427. int n_failures;
  428. if (!trusted_dir_certs ||
  429. !(cl = digestmap_get(trusted_dir_certs, id_digest)))
  430. return 0;
  431. n_failures = download_status_get_n_failures(&cl->dl_status);
  432. return n_failures >= N_AUTH_CERT_DL_FAILURES_TO_BUG_USER;
  433. }
  434. /** How many times will we try to fetch a certificate before giving up? */
  435. #define MAX_CERT_DL_FAILURES 8
  436. /** Try to download any v3 authority certificates that we may be missing. If
  437. * <b>status</b> is provided, try to get all the ones that were used to sign
  438. * <b>status</b>. Additionally, try to have a non-expired certificate for
  439. * every V3 authority in trusted_dir_servers. Don't fetch certificates we
  440. * already have.
  441. **/
  442. void
  443. authority_certs_fetch_missing(networkstatus_t *status, time_t now)
  444. {
  445. digestmap_t *pending;
  446. authority_cert_t *cert;
  447. smartlist_t *missing_digests;
  448. char *resource = NULL;
  449. cert_list_t *cl;
  450. const int cache = directory_caches_unknown_auth_certs(get_options());
  451. if (should_delay_dir_fetches(get_options()))
  452. return;
  453. pending = digestmap_new();
  454. missing_digests = smartlist_new();
  455. list_pending_downloads(pending, DIR_PURPOSE_FETCH_CERTIFICATE, "fp/");
  456. if (status) {
  457. SMARTLIST_FOREACH_BEGIN(status->voters, networkstatus_voter_info_t *,
  458. voter) {
  459. if (!smartlist_len(voter->sigs))
  460. continue; /* This authority never signed this consensus, so don't
  461. * go looking for a cert with key digest 0000000000. */
  462. if (!cache &&
  463. !trusteddirserver_get_by_v3_auth_digest(voter->identity_digest))
  464. continue; /* We are not a cache, and we don't know this authority.*/
  465. cl = get_cert_list(voter->identity_digest);
  466. SMARTLIST_FOREACH_BEGIN(voter->sigs, document_signature_t *, sig) {
  467. cert = authority_cert_get_by_digests(voter->identity_digest,
  468. sig->signing_key_digest);
  469. if (cert) {
  470. if (now < cert->expires)
  471. download_status_reset(&cl->dl_status);
  472. continue;
  473. }
  474. if (download_status_is_ready(&cl->dl_status, now,
  475. MAX_CERT_DL_FAILURES) &&
  476. !digestmap_get(pending, voter->identity_digest)) {
  477. log_info(LD_DIR, "We're missing a certificate from authority "
  478. "with signing key %s: launching request.",
  479. hex_str(sig->signing_key_digest, DIGEST_LEN));
  480. smartlist_add(missing_digests, sig->identity_digest);
  481. }
  482. } SMARTLIST_FOREACH_END(sig);
  483. } SMARTLIST_FOREACH_END(voter);
  484. }
  485. SMARTLIST_FOREACH_BEGIN(trusted_dir_servers, dir_server_t *, ds) {
  486. int found = 0;
  487. if (!(ds->type & V3_DIRINFO))
  488. continue;
  489. if (smartlist_contains_digest(missing_digests, ds->v3_identity_digest))
  490. continue;
  491. cl = get_cert_list(ds->v3_identity_digest);
  492. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert, {
  493. if (now < cert->expires) {
  494. /* It's not expired, and we weren't looking for something to
  495. * verify a consensus with. Call it done. */
  496. download_status_reset(&cl->dl_status);
  497. found = 1;
  498. break;
  499. }
  500. });
  501. if (!found &&
  502. download_status_is_ready(&cl->dl_status, now,MAX_CERT_DL_FAILURES) &&
  503. !digestmap_get(pending, ds->v3_identity_digest)) {
  504. log_info(LD_DIR, "No current certificate known for authority %s; "
  505. "launching request.", ds->nickname);
  506. smartlist_add(missing_digests, ds->v3_identity_digest);
  507. }
  508. } SMARTLIST_FOREACH_END(ds);
  509. if (!smartlist_len(missing_digests)) {
  510. goto done;
  511. } else {
  512. smartlist_t *fps = smartlist_new();
  513. smartlist_add(fps, tor_strdup("fp/"));
  514. SMARTLIST_FOREACH(missing_digests, const char *, d, {
  515. char *fp;
  516. if (digestmap_get(pending, d))
  517. continue;
  518. fp = tor_malloc(HEX_DIGEST_LEN+2);
  519. base16_encode(fp, HEX_DIGEST_LEN+1, d, DIGEST_LEN);
  520. fp[HEX_DIGEST_LEN] = '+';
  521. fp[HEX_DIGEST_LEN+1] = '\0';
  522. smartlist_add(fps, fp);
  523. });
  524. if (smartlist_len(fps) == 1) {
  525. /* we didn't add any: they were all pending */
  526. SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
  527. smartlist_free(fps);
  528. goto done;
  529. }
  530. resource = smartlist_join_strings(fps, "", 0, NULL);
  531. resource[strlen(resource)-1] = '\0';
  532. SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
  533. smartlist_free(fps);
  534. }
  535. directory_get_from_dirserver(DIR_PURPOSE_FETCH_CERTIFICATE, 0,
  536. resource, PDS_RETRY_IF_NO_SERVERS);
  537. done:
  538. tor_free(resource);
  539. smartlist_free(missing_digests);
  540. digestmap_free(pending, NULL);
  541. }
  542. /* Router descriptor storage.
  543. *
  544. * Routerdescs are stored in a big file, named "cached-descriptors". As new
  545. * routerdescs arrive, we append them to a journal file named
  546. * "cached-descriptors.new".
  547. *
  548. * From time to time, we replace "cached-descriptors" with a new file
  549. * containing only the live, non-superseded descriptors, and clear
  550. * cached-routers.new.
  551. *
  552. * On startup, we read both files.
  553. */
  554. /** Helper: return 1 iff the router log is so big we want to rebuild the
  555. * store. */
  556. static int
  557. router_should_rebuild_store(desc_store_t *store)
  558. {
  559. if (store->store_len > (1<<16))
  560. return (store->journal_len > store->store_len / 2 ||
  561. store->bytes_dropped > store->store_len / 2);
  562. else
  563. return store->journal_len > (1<<15);
  564. }
  565. /** Return the desc_store_t in <b>rl</b> that should be used to store
  566. * <b>sd</b>. */
  567. static INLINE desc_store_t *
  568. desc_get_store(routerlist_t *rl, const signed_descriptor_t *sd)
  569. {
  570. if (sd->is_extrainfo)
  571. return &rl->extrainfo_store;
  572. else
  573. return &rl->desc_store;
  574. }
  575. /** Add the signed_descriptor_t in <b>desc</b> to the router
  576. * journal; change its saved_location to SAVED_IN_JOURNAL and set its
  577. * offset appropriately. */
  578. static int
  579. signed_desc_append_to_journal(signed_descriptor_t *desc,
  580. desc_store_t *store)
  581. {
  582. char *fname = get_datadir_fname_suffix(store->fname_base, ".new");
  583. const char *body = signed_descriptor_get_body_impl(desc,1);
  584. size_t len = desc->signed_descriptor_len + desc->annotations_len;
  585. if (append_bytes_to_file(fname, body, len, 1)) {
  586. log_warn(LD_FS, "Unable to store router descriptor");
  587. tor_free(fname);
  588. return -1;
  589. }
  590. desc->saved_location = SAVED_IN_JOURNAL;
  591. tor_free(fname);
  592. desc->saved_offset = store->journal_len;
  593. store->journal_len += len;
  594. return 0;
  595. }
  596. /** Sorting helper: return &lt;0, 0, or &gt;0 depending on whether the
  597. * signed_descriptor_t* in *<b>a</b> is older, the same age as, or newer than
  598. * the signed_descriptor_t* in *<b>b</b>. */
  599. static int
  600. compare_signed_descriptors_by_age_(const void **_a, const void **_b)
  601. {
  602. const signed_descriptor_t *r1 = *_a, *r2 = *_b;
  603. return (int)(r1->published_on - r2->published_on);
  604. }
  605. #define RRS_FORCE 1
  606. #define RRS_DONT_REMOVE_OLD 2
  607. /** If the journal of <b>store</b> is too long, or if RRS_FORCE is set in
  608. * <b>flags</b>, then atomically replace the saved router store with the
  609. * routers currently in our routerlist, and clear the journal. Unless
  610. * RRS_DONT_REMOVE_OLD is set in <b>flags</b>, delete expired routers before
  611. * rebuilding the store. Return 0 on success, -1 on failure.
  612. */
  613. static int
  614. router_rebuild_store(int flags, desc_store_t *store)
  615. {
  616. smartlist_t *chunk_list = NULL;
  617. char *fname = NULL, *fname_tmp = NULL;
  618. int r = -1;
  619. off_t offset = 0;
  620. smartlist_t *signed_descriptors = NULL;
  621. int nocache=0;
  622. size_t total_expected_len = 0;
  623. int had_any;
  624. int force = flags & RRS_FORCE;
  625. if (!force && !router_should_rebuild_store(store)) {
  626. r = 0;
  627. goto done;
  628. }
  629. if (!routerlist) {
  630. r = 0;
  631. goto done;
  632. }
  633. if (store->type == EXTRAINFO_STORE)
  634. had_any = !eimap_isempty(routerlist->extra_info_map);
  635. else
  636. had_any = (smartlist_len(routerlist->routers)+
  637. smartlist_len(routerlist->old_routers))>0;
  638. /* Don't save deadweight. */
  639. if (!(flags & RRS_DONT_REMOVE_OLD))
  640. routerlist_remove_old_routers();
  641. log_info(LD_DIR, "Rebuilding %s cache", store->description);
  642. fname = get_datadir_fname(store->fname_base);
  643. fname_tmp = get_datadir_fname_suffix(store->fname_base, ".tmp");
  644. chunk_list = smartlist_new();
  645. /* We sort the routers by age to enhance locality on disk. */
  646. signed_descriptors = smartlist_new();
  647. if (store->type == EXTRAINFO_STORE) {
  648. eimap_iter_t *iter;
  649. for (iter = eimap_iter_init(routerlist->extra_info_map);
  650. !eimap_iter_done(iter);
  651. iter = eimap_iter_next(routerlist->extra_info_map, iter)) {
  652. const char *key;
  653. extrainfo_t *ei;
  654. eimap_iter_get(iter, &key, &ei);
  655. smartlist_add(signed_descriptors, &ei->cache_info);
  656. }
  657. } else {
  658. SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
  659. smartlist_add(signed_descriptors, sd));
  660. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
  661. smartlist_add(signed_descriptors, &ri->cache_info));
  662. }
  663. smartlist_sort(signed_descriptors, compare_signed_descriptors_by_age_);
  664. /* Now, add the appropriate members to chunk_list */
  665. SMARTLIST_FOREACH_BEGIN(signed_descriptors, signed_descriptor_t *, sd) {
  666. sized_chunk_t *c;
  667. const char *body = signed_descriptor_get_body_impl(sd, 1);
  668. if (!body) {
  669. log_warn(LD_BUG, "No descriptor available for router.");
  670. goto done;
  671. }
  672. if (sd->do_not_cache) {
  673. ++nocache;
  674. continue;
  675. }
  676. c = tor_malloc(sizeof(sized_chunk_t));
  677. c->bytes = body;
  678. c->len = sd->signed_descriptor_len + sd->annotations_len;
  679. total_expected_len += c->len;
  680. smartlist_add(chunk_list, c);
  681. } SMARTLIST_FOREACH_END(sd);
  682. if (write_chunks_to_file(fname_tmp, chunk_list, 1)<0) {
  683. log_warn(LD_FS, "Error writing router store to disk.");
  684. goto done;
  685. }
  686. /* Our mmap is now invalid. */
  687. if (store->mmap) {
  688. tor_munmap_file(store->mmap);
  689. store->mmap = NULL;
  690. }
  691. if (replace_file(fname_tmp, fname)<0) {
  692. log_warn(LD_FS, "Error replacing old router store: %s", strerror(errno));
  693. goto done;
  694. }
  695. errno = 0;
  696. store->mmap = tor_mmap_file(fname);
  697. if (! store->mmap) {
  698. if (errno == ERANGE) {
  699. /* empty store.*/
  700. if (total_expected_len) {
  701. log_warn(LD_FS, "We wrote some bytes to a new descriptor file at '%s',"
  702. " but when we went to mmap it, it was empty!", fname);
  703. } else if (had_any) {
  704. log_info(LD_FS, "We just removed every descriptor in '%s'. This is "
  705. "okay if we're just starting up after a long time. "
  706. "Otherwise, it's a bug.", fname);
  707. }
  708. } else {
  709. log_warn(LD_FS, "Unable to mmap new descriptor file at '%s'.",fname);
  710. }
  711. }
  712. log_info(LD_DIR, "Reconstructing pointers into cache");
  713. offset = 0;
  714. SMARTLIST_FOREACH_BEGIN(signed_descriptors, signed_descriptor_t *, sd) {
  715. if (sd->do_not_cache)
  716. continue;
  717. sd->saved_location = SAVED_IN_CACHE;
  718. if (store->mmap) {
  719. tor_free(sd->signed_descriptor_body); // sets it to null
  720. sd->saved_offset = offset;
  721. }
  722. offset += sd->signed_descriptor_len + sd->annotations_len;
  723. signed_descriptor_get_body(sd); /* reconstruct and assert */
  724. } SMARTLIST_FOREACH_END(sd);
  725. tor_free(fname);
  726. fname = get_datadir_fname_suffix(store->fname_base, ".new");
  727. write_str_to_file(fname, "", 1);
  728. r = 0;
  729. store->store_len = (size_t) offset;
  730. store->journal_len = 0;
  731. store->bytes_dropped = 0;
  732. done:
  733. smartlist_free(signed_descriptors);
  734. tor_free(fname);
  735. tor_free(fname_tmp);
  736. if (chunk_list) {
  737. SMARTLIST_FOREACH(chunk_list, sized_chunk_t *, c, tor_free(c));
  738. smartlist_free(chunk_list);
  739. }
  740. return r;
  741. }
  742. /** Helper: Reload a cache file and its associated journal, setting metadata
  743. * appropriately. If <b>extrainfo</b> is true, reload the extrainfo store;
  744. * else reload the router descriptor store. */
  745. static int
  746. router_reload_router_list_impl(desc_store_t *store)
  747. {
  748. char *fname = NULL, *altname = NULL, *contents = NULL;
  749. struct stat st;
  750. int read_from_old_location = 0;
  751. int extrainfo = (store->type == EXTRAINFO_STORE);
  752. time_t now = time(NULL);
  753. store->journal_len = store->store_len = 0;
  754. fname = get_datadir_fname(store->fname_base);
  755. if (store->fname_alt_base)
  756. altname = get_datadir_fname(store->fname_alt_base);
  757. if (store->mmap) /* get rid of it first */
  758. tor_munmap_file(store->mmap);
  759. store->mmap = NULL;
  760. store->mmap = tor_mmap_file(fname);
  761. if (!store->mmap && altname && file_status(altname) == FN_FILE) {
  762. read_from_old_location = 1;
  763. log_notice(LD_DIR, "Couldn't read %s; trying to load routers from old "
  764. "location %s.", fname, altname);
  765. if ((store->mmap = tor_mmap_file(altname)))
  766. read_from_old_location = 1;
  767. }
  768. if (altname && !read_from_old_location) {
  769. remove_file_if_very_old(altname, now);
  770. }
  771. if (store->mmap) {
  772. store->store_len = store->mmap->size;
  773. if (extrainfo)
  774. router_load_extrainfo_from_string(store->mmap->data,
  775. store->mmap->data+store->mmap->size,
  776. SAVED_IN_CACHE, NULL, 0);
  777. else
  778. router_load_routers_from_string(store->mmap->data,
  779. store->mmap->data+store->mmap->size,
  780. SAVED_IN_CACHE, NULL, 0, NULL);
  781. }
  782. tor_free(fname);
  783. fname = get_datadir_fname_suffix(store->fname_base, ".new");
  784. if (file_status(fname) == FN_FILE)
  785. contents = read_file_to_str(fname, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
  786. if (read_from_old_location) {
  787. tor_free(altname);
  788. altname = get_datadir_fname_suffix(store->fname_alt_base, ".new");
  789. if (!contents)
  790. contents = read_file_to_str(altname, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
  791. else
  792. remove_file_if_very_old(altname, now);
  793. }
  794. if (contents) {
  795. if (extrainfo)
  796. router_load_extrainfo_from_string(contents, NULL,SAVED_IN_JOURNAL,
  797. NULL, 0);
  798. else
  799. router_load_routers_from_string(contents, NULL, SAVED_IN_JOURNAL,
  800. NULL, 0, NULL);
  801. store->journal_len = (size_t) st.st_size;
  802. tor_free(contents);
  803. }
  804. tor_free(fname);
  805. tor_free(altname);
  806. if (store->journal_len || read_from_old_location) {
  807. /* Always clear the journal on startup.*/
  808. router_rebuild_store(RRS_FORCE, store);
  809. } else if (!extrainfo) {
  810. /* Don't cache expired routers. (This is in an else because
  811. * router_rebuild_store() also calls remove_old_routers().) */
  812. routerlist_remove_old_routers();
  813. }
  814. return 0;
  815. }
  816. /** Load all cached router descriptors and extra-info documents from the
  817. * store. Return 0 on success and -1 on failure.
  818. */
  819. int
  820. router_reload_router_list(void)
  821. {
  822. routerlist_t *rl = router_get_routerlist();
  823. if (router_reload_router_list_impl(&rl->desc_store))
  824. return -1;
  825. if (router_reload_router_list_impl(&rl->extrainfo_store))
  826. return -1;
  827. return 0;
  828. }
  829. /** Return a smartlist containing a list of dir_server_t * for all
  830. * known trusted dirservers. Callers must not modify the list or its
  831. * contents.
  832. */
  833. const smartlist_t *
  834. router_get_trusted_dir_servers(void)
  835. {
  836. if (!trusted_dir_servers)
  837. trusted_dir_servers = smartlist_new();
  838. return trusted_dir_servers;
  839. }
  840. const smartlist_t *
  841. router_get_fallback_dir_servers(void)
  842. {
  843. if (!fallback_dir_servers)
  844. fallback_dir_servers = smartlist_new();
  845. return fallback_dir_servers;
  846. }
  847. /** Try to find a running dirserver that supports operations of <b>type</b>.
  848. *
  849. * If there are no running dirservers in our routerlist and the
  850. * <b>PDS_RETRY_IF_NO_SERVERS</b> flag is set, set all the authoritative ones
  851. * as running again, and pick one.
  852. *
  853. * If the <b>PDS_IGNORE_FASCISTFIREWALL</b> flag is set, then include
  854. * dirservers that we can't reach.
  855. *
  856. * If the <b>PDS_ALLOW_SELF</b> flag is not set, then don't include ourself
  857. * (if we're a dirserver).
  858. *
  859. * Don't pick an authority if any non-authority is viable; try to avoid using
  860. * servers that have returned 503 recently.
  861. */
  862. const routerstatus_t *
  863. router_pick_directory_server(dirinfo_type_t type, int flags)
  864. {
  865. const routerstatus_t *choice;
  866. if (get_options()->PreferTunneledDirConns)
  867. flags |= PDS_PREFER_TUNNELED_DIR_CONNS_;
  868. if (!routerlist)
  869. return NULL;
  870. choice = router_pick_directory_server_impl(type, flags);
  871. if (choice || !(flags & PDS_RETRY_IF_NO_SERVERS))
  872. return choice;
  873. log_info(LD_DIR,
  874. "No reachable router entries for dirservers. "
  875. "Trying them all again.");
  876. /* mark all authdirservers as up again */
  877. mark_all_dirservers_up(fallback_dir_servers);
  878. /* try again */
  879. choice = router_pick_directory_server_impl(type, flags);
  880. return choice;
  881. }
  882. /** Try to determine which fraction of v2 and v3 directory requests aimed at
  883. * caches will be sent to us. Set *<b>v2_share_out</b> and
  884. * *<b>v3_share_out</b> to the fractions of v2 and v3 protocol shares we
  885. * expect to see, respectively. Return 0 on success, negative on failure. */
  886. int
  887. router_get_my_share_of_directory_requests(double *v2_share_out,
  888. double *v3_share_out)
  889. {
  890. const routerinfo_t *me = router_get_my_routerinfo();
  891. const routerstatus_t *rs;
  892. const int pds_flags = PDS_ALLOW_SELF|PDS_IGNORE_FASCISTFIREWALL;
  893. *v2_share_out = *v3_share_out = 0.0;
  894. if (!me)
  895. return -1;
  896. rs = router_get_consensus_status_by_id(me->cache_info.identity_digest);
  897. if (!rs)
  898. return -1;
  899. /* Calling for side effect */
  900. /* XXXX This is a bit of a kludge */
  901. if (rs->is_v2_dir) {
  902. sl_last_total_weighted_bw = 0;
  903. router_pick_directory_server(V2_DIRINFO, pds_flags);
  904. if (sl_last_total_weighted_bw != 0) {
  905. *v2_share_out = U64_TO_DBL(sl_last_weighted_bw_of_me) /
  906. U64_TO_DBL(sl_last_total_weighted_bw);
  907. }
  908. }
  909. {
  910. sl_last_total_weighted_bw = 0;
  911. router_pick_directory_server(V3_DIRINFO, pds_flags);
  912. if (sl_last_total_weighted_bw != 0) {
  913. *v3_share_out = U64_TO_DBL(sl_last_weighted_bw_of_me) /
  914. U64_TO_DBL(sl_last_total_weighted_bw);
  915. }
  916. }
  917. return 0;
  918. }
  919. /** Return the dir_server_t for the directory authority whose identity
  920. * key hashes to <b>digest</b>, or NULL if no such authority is known.
  921. */
  922. dir_server_t *
  923. router_get_trusteddirserver_by_digest(const char *digest)
  924. {
  925. if (!trusted_dir_servers)
  926. return NULL;
  927. SMARTLIST_FOREACH(trusted_dir_servers, dir_server_t *, ds,
  928. {
  929. if (tor_memeq(ds->digest, digest, DIGEST_LEN))
  930. return ds;
  931. });
  932. return NULL;
  933. }
  934. /** Return the dir_server_t for the fallback dirserver whose identity
  935. * key hashes to <b>digest</b>, or NULL if no such authority is known.
  936. */
  937. dir_server_t *
  938. router_get_fallback_dirserver_by_digest(const char *digest)
  939. {
  940. if (!trusted_dir_servers)
  941. return NULL;
  942. SMARTLIST_FOREACH(trusted_dir_servers, dir_server_t *, ds,
  943. {
  944. if (tor_memeq(ds->digest, digest, DIGEST_LEN))
  945. return ds;
  946. });
  947. return NULL;
  948. }
  949. /** Return the dir_server_t for the directory authority whose
  950. * v3 identity key hashes to <b>digest</b>, or NULL if no such authority
  951. * is known.
  952. */
  953. dir_server_t *
  954. trusteddirserver_get_by_v3_auth_digest(const char *digest)
  955. {
  956. if (!trusted_dir_servers)
  957. return NULL;
  958. SMARTLIST_FOREACH(trusted_dir_servers, dir_server_t *, ds,
  959. {
  960. if (tor_memeq(ds->v3_identity_digest, digest, DIGEST_LEN) &&
  961. (ds->type & V3_DIRINFO))
  962. return ds;
  963. });
  964. return NULL;
  965. }
  966. /** Try to find a running directory authority. Flags are as for
  967. * router_pick_directory_server.
  968. */
  969. const routerstatus_t *
  970. router_pick_trusteddirserver(dirinfo_type_t type, int flags)
  971. {
  972. return router_pick_dirserver_generic(trusted_dir_servers, type, flags);
  973. }
  974. /** Try to find a running fallback directory Flags are as for
  975. * router_pick_directory_server.
  976. */
  977. const routerstatus_t *
  978. router_pick_fallback_dirserver(dirinfo_type_t type, int flags)
  979. {
  980. return router_pick_dirserver_generic(fallback_dir_servers, type, flags);
  981. }
  982. /** Try to find a running fallback directory Flags are as for
  983. * router_pick_directory_server.
  984. */
  985. static const routerstatus_t *
  986. router_pick_dirserver_generic(smartlist_t *sourcelist,
  987. dirinfo_type_t type, int flags)
  988. {
  989. const routerstatus_t *choice;
  990. int busy = 0;
  991. if (get_options()->PreferTunneledDirConns)
  992. flags |= PDS_PREFER_TUNNELED_DIR_CONNS_;
  993. choice = router_pick_trusteddirserver_impl(sourcelist, type, flags, &busy);
  994. if (choice || !(flags & PDS_RETRY_IF_NO_SERVERS))
  995. return choice;
  996. if (busy) {
  997. /* If the reason that we got no server is that servers are "busy",
  998. * we must be excluding good servers because we already have serverdesc
  999. * fetches with them. Do not mark down servers up because of this. */
  1000. tor_assert((flags & (PDS_NO_EXISTING_SERVERDESC_FETCH|
  1001. PDS_NO_EXISTING_MICRODESC_FETCH)));
  1002. return NULL;
  1003. }
  1004. log_info(LD_DIR,
  1005. "No dirservers are reachable. Trying them all again.");
  1006. mark_all_dirservers_up(sourcelist);
  1007. return router_pick_trusteddirserver_impl(sourcelist, type, flags, NULL);
  1008. }
  1009. /** How long do we avoid using a directory server after it's given us a 503? */
  1010. #define DIR_503_TIMEOUT (60*60)
  1011. /** Pick a random running valid directory server/mirror from our
  1012. * routerlist. Arguments are as for router_pick_directory_server(), except
  1013. * that RETRY_IF_NO_SERVERS is ignored, and:
  1014. *
  1015. * If the PDS_PREFER_TUNNELED_DIR_CONNS_ flag is set, prefer directory servers
  1016. * that we can use with BEGINDIR.
  1017. */
  1018. static const routerstatus_t *
  1019. router_pick_directory_server_impl(dirinfo_type_t type, int flags)
  1020. {
  1021. const or_options_t *options = get_options();
  1022. const node_t *result;
  1023. smartlist_t *direct, *tunnel;
  1024. smartlist_t *trusted_direct, *trusted_tunnel;
  1025. smartlist_t *overloaded_direct, *overloaded_tunnel;
  1026. time_t now = time(NULL);
  1027. const networkstatus_t *consensus = networkstatus_get_latest_consensus();
  1028. int requireother = ! (flags & PDS_ALLOW_SELF);
  1029. int fascistfirewall = ! (flags & PDS_IGNORE_FASCISTFIREWALL);
  1030. int prefer_tunnel = (flags & PDS_PREFER_TUNNELED_DIR_CONNS_);
  1031. int try_excluding = 1, n_excluded = 0;
  1032. if (!consensus)
  1033. return NULL;
  1034. retry_without_exclude:
  1035. direct = smartlist_new();
  1036. tunnel = smartlist_new();
  1037. trusted_direct = smartlist_new();
  1038. trusted_tunnel = smartlist_new();
  1039. overloaded_direct = smartlist_new();
  1040. overloaded_tunnel = smartlist_new();
  1041. /* Find all the running dirservers we know about. */
  1042. SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), const node_t *, node) {
  1043. int is_trusted;
  1044. int is_overloaded;
  1045. tor_addr_t addr;
  1046. const routerstatus_t *status = node->rs;
  1047. const country_t country = node->country;
  1048. if (!status)
  1049. continue;
  1050. if (!node->is_running || !status->dir_port || !node->is_valid)
  1051. continue;
  1052. if (node->is_bad_directory)
  1053. continue;
  1054. if (requireother && router_digest_is_me(node->identity))
  1055. continue;
  1056. is_trusted = router_digest_is_trusted_dir(node->identity);
  1057. if ((type & V2_DIRINFO) && !(node->rs->is_v2_dir || is_trusted))
  1058. continue;
  1059. if ((type & EXTRAINFO_DIRINFO) &&
  1060. !router_supports_extrainfo(node->identity, 0))
  1061. continue;
  1062. if ((type & MICRODESC_DIRINFO) && !is_trusted &&
  1063. !node->rs->version_supports_microdesc_cache)
  1064. continue;
  1065. if (try_excluding &&
  1066. routerset_contains_routerstatus(options->ExcludeNodes, status,
  1067. country)) {
  1068. ++n_excluded;
  1069. continue;
  1070. }
  1071. /* XXXX IP6 proposal 118 */
  1072. tor_addr_from_ipv4h(&addr, node->rs->addr);
  1073. is_overloaded = status->last_dir_503_at + DIR_503_TIMEOUT > now;
  1074. if (prefer_tunnel &&
  1075. (!fascistfirewall ||
  1076. fascist_firewall_allows_address_or(&addr, status->or_port)))
  1077. smartlist_add(is_trusted ? trusted_tunnel :
  1078. is_overloaded ? overloaded_tunnel : tunnel, (void*)node);
  1079. else if (!fascistfirewall ||
  1080. fascist_firewall_allows_address_dir(&addr, status->dir_port))
  1081. smartlist_add(is_trusted ? trusted_direct :
  1082. is_overloaded ? overloaded_direct : direct, (void*)node);
  1083. } SMARTLIST_FOREACH_END(node);
  1084. if (smartlist_len(tunnel)) {
  1085. result = node_sl_choose_by_bandwidth(tunnel, WEIGHT_FOR_DIR);
  1086. } else if (smartlist_len(overloaded_tunnel)) {
  1087. result = node_sl_choose_by_bandwidth(overloaded_tunnel,
  1088. WEIGHT_FOR_DIR);
  1089. } else if (smartlist_len(trusted_tunnel)) {
  1090. /* FFFF We don't distinguish between trusteds and overloaded trusteds
  1091. * yet. Maybe one day we should. */
  1092. /* FFFF We also don't load balance over authorities yet. I think this
  1093. * is a feature, but it could easily be a bug. -RD */
  1094. result = smartlist_choose(trusted_tunnel);
  1095. } else if (smartlist_len(direct)) {
  1096. result = node_sl_choose_by_bandwidth(direct, WEIGHT_FOR_DIR);
  1097. } else if (smartlist_len(overloaded_direct)) {
  1098. result = node_sl_choose_by_bandwidth(overloaded_direct,
  1099. WEIGHT_FOR_DIR);
  1100. } else {
  1101. result = smartlist_choose(trusted_direct);
  1102. }
  1103. smartlist_free(direct);
  1104. smartlist_free(tunnel);
  1105. smartlist_free(trusted_direct);
  1106. smartlist_free(trusted_tunnel);
  1107. smartlist_free(overloaded_direct);
  1108. smartlist_free(overloaded_tunnel);
  1109. if (result == NULL && try_excluding && !options->StrictNodes && n_excluded) {
  1110. /* If we got no result, and we are excluding nodes, and StrictNodes is
  1111. * not set, try again without excluding nodes. */
  1112. try_excluding = 0;
  1113. n_excluded = 0;
  1114. goto retry_without_exclude;
  1115. }
  1116. return result ? result->rs : NULL;
  1117. }
  1118. /** Pick a random element from a list of dir_server_t, weighting by their
  1119. * <b>weight</b> field. */
  1120. static const dir_server_t *
  1121. dirserver_choose_by_weight(const smartlist_t *servers, double authority_weight)
  1122. {
  1123. int n = smartlist_len(servers);
  1124. int i;
  1125. u64_dbl_t *weights;
  1126. const dir_server_t *ds;
  1127. weights = tor_malloc(sizeof(u64_dbl_t) * n);
  1128. for (i = 0; i < n; ++i) {
  1129. ds = smartlist_get(servers, i);
  1130. weights[i].dbl = ds->weight;
  1131. if (ds->is_authority)
  1132. weights[i].dbl *= authority_weight;
  1133. }
  1134. scale_array_elements_to_u64(weights, n, NULL);
  1135. i = choose_array_element_by_weight(weights, n);
  1136. tor_free(weights);
  1137. return (i < 0) ? NULL : smartlist_get(servers, i);
  1138. }
  1139. /** Choose randomly from among the dir_server_ts in sourcelist that
  1140. * are up. Flags are as for router_pick_directory_server_impl().
  1141. */
  1142. static const routerstatus_t *
  1143. router_pick_trusteddirserver_impl(const smartlist_t *sourcelist,
  1144. dirinfo_type_t type, int flags,
  1145. int *n_busy_out)
  1146. {
  1147. const or_options_t *options = get_options();
  1148. smartlist_t *direct, *tunnel;
  1149. smartlist_t *overloaded_direct, *overloaded_tunnel;
  1150. const routerinfo_t *me = router_get_my_routerinfo();
  1151. const routerstatus_t *result = NULL;
  1152. time_t now = time(NULL);
  1153. const int requireother = ! (flags & PDS_ALLOW_SELF);
  1154. const int fascistfirewall = ! (flags & PDS_IGNORE_FASCISTFIREWALL);
  1155. const int prefer_tunnel = (flags & PDS_PREFER_TUNNELED_DIR_CONNS_);
  1156. const int no_serverdesc_fetching =(flags & PDS_NO_EXISTING_SERVERDESC_FETCH);
  1157. const int no_microdesc_fetching =(flags & PDS_NO_EXISTING_MICRODESC_FETCH);
  1158. const double auth_weight = (sourcelist == fallback_dir_servers) ?
  1159. options->DirAuthorityFallbackRate : 1.0;
  1160. smartlist_t *pick_from;
  1161. int n_busy = 0;
  1162. int try_excluding = 1, n_excluded = 0;
  1163. if (!sourcelist)
  1164. return NULL;
  1165. retry_without_exclude:
  1166. direct = smartlist_new();
  1167. tunnel = smartlist_new();
  1168. overloaded_direct = smartlist_new();
  1169. overloaded_tunnel = smartlist_new();
  1170. SMARTLIST_FOREACH_BEGIN(sourcelist, const dir_server_t *, d)
  1171. {
  1172. int is_overloaded =
  1173. d->fake_status.last_dir_503_at + DIR_503_TIMEOUT > now;
  1174. tor_addr_t addr;
  1175. if (!d->is_running) continue;
  1176. if ((type & d->type) == 0)
  1177. continue;
  1178. if ((type & EXTRAINFO_DIRINFO) &&
  1179. !router_supports_extrainfo(d->digest, 1))
  1180. continue;
  1181. if (requireother && me && router_digest_is_me(d->digest))
  1182. continue;
  1183. if (try_excluding &&
  1184. routerset_contains_routerstatus(options->ExcludeNodes,
  1185. &d->fake_status, -1)) {
  1186. ++n_excluded;
  1187. continue;
  1188. }
  1189. /* XXXX IP6 proposal 118 */
  1190. tor_addr_from_ipv4h(&addr, d->addr);
  1191. if (no_serverdesc_fetching) {
  1192. if (connection_get_by_type_addr_port_purpose(
  1193. CONN_TYPE_DIR, &addr, d->dir_port, DIR_PURPOSE_FETCH_SERVERDESC)
  1194. || connection_get_by_type_addr_port_purpose(
  1195. CONN_TYPE_DIR, &addr, d->dir_port, DIR_PURPOSE_FETCH_EXTRAINFO)) {
  1196. //log_debug(LD_DIR, "We have an existing connection to fetch "
  1197. // "descriptor from %s; delaying",d->description);
  1198. ++n_busy;
  1199. continue;
  1200. }
  1201. }
  1202. if (no_microdesc_fetching) {
  1203. if (connection_get_by_type_addr_port_purpose(
  1204. CONN_TYPE_DIR, &addr, d->dir_port, DIR_PURPOSE_FETCH_MICRODESC)) {
  1205. ++n_busy;
  1206. continue;
  1207. }
  1208. }
  1209. if (prefer_tunnel &&
  1210. d->or_port &&
  1211. (!fascistfirewall ||
  1212. fascist_firewall_allows_address_or(&addr, d->or_port)))
  1213. smartlist_add(is_overloaded ? overloaded_tunnel : tunnel, (void*)d);
  1214. else if (!fascistfirewall ||
  1215. fascist_firewall_allows_address_dir(&addr, d->dir_port))
  1216. smartlist_add(is_overloaded ? overloaded_direct : direct, (void*)d);
  1217. }
  1218. SMARTLIST_FOREACH_END(d);
  1219. if (smartlist_len(tunnel)) {
  1220. pick_from = tunnel;
  1221. } else if (smartlist_len(overloaded_tunnel)) {
  1222. pick_from = overloaded_tunnel;
  1223. } else if (smartlist_len(direct)) {
  1224. pick_from = direct;
  1225. } else {
  1226. pick_from = overloaded_direct;
  1227. }
  1228. {
  1229. const dir_server_t *selection =
  1230. dirserver_choose_by_weight(pick_from, auth_weight);
  1231. if (selection)
  1232. result = &selection->fake_status;
  1233. }
  1234. if (n_busy_out)
  1235. *n_busy_out = n_busy;
  1236. smartlist_free(direct);
  1237. smartlist_free(tunnel);
  1238. smartlist_free(overloaded_direct);
  1239. smartlist_free(overloaded_tunnel);
  1240. if (result == NULL && try_excluding && !options->StrictNodes && n_excluded) {
  1241. /* If we got no result, and we are excluding nodes, and StrictNodes is
  1242. * not set, try again without excluding nodes. */
  1243. try_excluding = 0;
  1244. n_excluded = 0;
  1245. goto retry_without_exclude;
  1246. }
  1247. return result;
  1248. }
  1249. /** Mark as running every dir_server_t in <b>server_list</b>. */
  1250. static void
  1251. mark_all_dirservers_up(smartlist_t *server_list)
  1252. {
  1253. if (server_list) {
  1254. SMARTLIST_FOREACH_BEGIN(server_list, dir_server_t *, dir) {
  1255. routerstatus_t *rs;
  1256. node_t *node;
  1257. dir->is_running = 1;
  1258. download_status_reset(&dir->v2_ns_dl_status);
  1259. node = node_get_mutable_by_id(dir->digest);
  1260. if (node)
  1261. node->is_running = 1;
  1262. rs = router_get_mutable_consensus_status_by_id(dir->digest);
  1263. if (rs) {
  1264. rs->last_dir_503_at = 0;
  1265. control_event_networkstatus_changed_single(rs);
  1266. }
  1267. } SMARTLIST_FOREACH_END(dir);
  1268. }
  1269. router_dir_info_changed();
  1270. }
  1271. /** Return true iff r1 and r2 have the same address and OR port. */
  1272. int
  1273. routers_have_same_or_addrs(const routerinfo_t *r1, const routerinfo_t *r2)
  1274. {
  1275. return r1->addr == r2->addr && r1->or_port == r2->or_port &&
  1276. tor_addr_eq(&r1->ipv6_addr, &r2->ipv6_addr) &&
  1277. r1->ipv6_orport == r2->ipv6_orport;
  1278. }
  1279. /** Reset all internal variables used to count failed downloads of network
  1280. * status objects. */
  1281. void
  1282. router_reset_status_download_failures(void)
  1283. {
  1284. mark_all_dirservers_up(fallback_dir_servers);
  1285. }
  1286. /** Given a <b>router</b>, add every node_t in its family (including the
  1287. * node itself!) to <b>sl</b>.
  1288. *
  1289. * Note the type mismatch: This function takes a routerinfo, but adds nodes
  1290. * to the smartlist!
  1291. */
  1292. static void
  1293. routerlist_add_node_and_family(smartlist_t *sl, const routerinfo_t *router)
  1294. {
  1295. /* XXXX MOVE ? */
  1296. node_t fake_node;
  1297. const node_t *node = node_get_by_id(router->cache_info.identity_digest);;
  1298. if (node == NULL) {
  1299. memset(&fake_node, 0, sizeof(fake_node));
  1300. fake_node.ri = (routerinfo_t *)router;
  1301. memcpy(fake_node.identity, router->cache_info.identity_digest, DIGEST_LEN);
  1302. node = &fake_node;
  1303. }
  1304. nodelist_add_node_and_family(sl, node);
  1305. }
  1306. /** Return 1 iff any member of the (possibly NULL) comma-separated list
  1307. * <b>list</b> is an acceptable nickname or hexdigest for <b>router</b>. Else
  1308. * return 0.
  1309. */
  1310. int
  1311. router_nickname_is_in_list(const routerinfo_t *router, const char *list)
  1312. {
  1313. smartlist_t *nickname_list;
  1314. int v = 0;
  1315. if (!list)
  1316. return 0; /* definitely not */
  1317. tor_assert(router);
  1318. nickname_list = smartlist_new();
  1319. smartlist_split_string(nickname_list, list, ",",
  1320. SPLIT_SKIP_SPACE|SPLIT_STRIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1321. SMARTLIST_FOREACH(nickname_list, const char *, cp,
  1322. if (router_nickname_matches(router, cp)) {v=1;break;});
  1323. SMARTLIST_FOREACH(nickname_list, char *, cp, tor_free(cp));
  1324. smartlist_free(nickname_list);
  1325. return v;
  1326. }
  1327. /** Add every suitable node from our nodelist to <b>sl</b>, so that
  1328. * we can pick a node for a circuit.
  1329. */
  1330. static void
  1331. router_add_running_nodes_to_smartlist(smartlist_t *sl, int allow_invalid,
  1332. int need_uptime, int need_capacity,
  1333. int need_guard, int need_desc)
  1334. { /* XXXX MOVE */
  1335. SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), const node_t *, node) {
  1336. if (!node->is_running ||
  1337. (!node->is_valid && !allow_invalid))
  1338. continue;
  1339. if (need_desc && !(node->ri || (node->rs && node->md)))
  1340. continue;
  1341. if (node->ri && node->ri->purpose != ROUTER_PURPOSE_GENERAL)
  1342. continue;
  1343. if (node_is_unreliable(node, need_uptime, need_capacity, need_guard))
  1344. continue;
  1345. smartlist_add(sl, (void *)node);
  1346. } SMARTLIST_FOREACH_END(node);
  1347. }
  1348. /** Look through the routerlist until we find a router that has my key.
  1349. Return it. */
  1350. const routerinfo_t *
  1351. routerlist_find_my_routerinfo(void)
  1352. {
  1353. if (!routerlist)
  1354. return NULL;
  1355. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  1356. {
  1357. if (router_is_me(router))
  1358. return router;
  1359. });
  1360. return NULL;
  1361. }
  1362. /** Return the smaller of the router's configured BandwidthRate
  1363. * and its advertised capacity. */
  1364. uint32_t
  1365. router_get_advertised_bandwidth(const routerinfo_t *router)
  1366. {
  1367. if (router->bandwidthcapacity < router->bandwidthrate)
  1368. return router->bandwidthcapacity;
  1369. return router->bandwidthrate;
  1370. }
  1371. /** Do not weight any declared bandwidth more than this much when picking
  1372. * routers by bandwidth. */
  1373. #define DEFAULT_MAX_BELIEVABLE_BANDWIDTH 10000000 /* 10 MB/sec */
  1374. /** Return the smaller of the router's configured BandwidthRate
  1375. * and its advertised capacity, capped by max-believe-bw. */
  1376. uint32_t
  1377. router_get_advertised_bandwidth_capped(const routerinfo_t *router)
  1378. {
  1379. uint32_t result = router->bandwidthcapacity;
  1380. if (result > router->bandwidthrate)
  1381. result = router->bandwidthrate;
  1382. if (result > DEFAULT_MAX_BELIEVABLE_BANDWIDTH)
  1383. result = DEFAULT_MAX_BELIEVABLE_BANDWIDTH;
  1384. return result;
  1385. }
  1386. /** Given an array of double/uint64_t unions that are currently being used as
  1387. * doubles, convert them to uint64_t, and try to scale them linearly so as to
  1388. * much of the range of uint64_t. If <b>total_out</b> is provided, set it to
  1389. * the sum of all elements in the array _before_ scaling. */
  1390. /* private */ void
  1391. scale_array_elements_to_u64(u64_dbl_t *entries, int n_entries,
  1392. uint64_t *total_out)
  1393. {
  1394. double total = 0.0;
  1395. double scale_factor;
  1396. int i;
  1397. /* big, but far away from overflowing an int64_t */
  1398. #define SCALE_TO_U64_MAX (INT64_MAX / 4)
  1399. for (i = 0; i < n_entries; ++i)
  1400. total += entries[i].dbl;
  1401. scale_factor = SCALE_TO_U64_MAX / total;
  1402. for (i = 0; i < n_entries; ++i)
  1403. entries[i].u64 = tor_llround(entries[i].dbl * scale_factor);
  1404. if (total_out)
  1405. *total_out = (uint64_t) total;
  1406. #undef SCALE_TO_U64_MAX
  1407. }
  1408. /** Time-invariant 64-bit greater-than; works on two integers in the range
  1409. * (0,INT64_MAX). */
  1410. #if SIZEOF_VOID_P == 8
  1411. #define gt_i64_timei(a,b) ((a) > (b))
  1412. #else
  1413. static INLINE int
  1414. gt_i64_timei(uint64_t a, uint64_t b)
  1415. {
  1416. int64_t diff = (int64_t) (b - a);
  1417. int res = diff >> 63;
  1418. return res & 1;
  1419. }
  1420. #endif
  1421. /** Pick a random element of <b>n_entries</b>-element array <b>entries</b>,
  1422. * choosing each element with a probability proportional to its (uint64_t)
  1423. * value, and return the index of that element. If all elements are 0, choose
  1424. * an index at random. Return -1 on error.
  1425. */
  1426. /* private */ int
  1427. choose_array_element_by_weight(const u64_dbl_t *entries, int n_entries)
  1428. {
  1429. int i, i_chosen=-1, n_chosen=0;
  1430. uint64_t total_so_far = 0;
  1431. uint64_t rand_val;
  1432. uint64_t total = 0;
  1433. for (i = 0; i < n_entries; ++i)
  1434. total += entries[i].u64;
  1435. if (n_entries < 1)
  1436. return -1;
  1437. if (total == 0)
  1438. return crypto_rand_int(n_entries);
  1439. tor_assert(total < INT64_MAX);
  1440. rand_val = crypto_rand_uint64(total);
  1441. for (i = 0; i < n_entries; ++i) {
  1442. total_so_far += entries[i].u64;
  1443. if (gt_i64_timei(total_so_far, rand_val)) {
  1444. i_chosen = i;
  1445. n_chosen++;
  1446. /* Set rand_val to INT64_MAX rather than stopping the loop. This way,
  1447. * the time we spend in the loop does not leak which element we chose. */
  1448. rand_val = INT64_MAX;
  1449. }
  1450. }
  1451. tor_assert(total_so_far == total);
  1452. tor_assert(n_chosen == 1);
  1453. tor_assert(i_chosen >= 0);
  1454. tor_assert(i_chosen < n_entries);
  1455. return i_chosen;
  1456. }
  1457. /** When weighting bridges, enforce these values as lower and upper
  1458. * bound for believable bandwidth, because there is no way for us
  1459. * to verify a bridge's bandwidth currently. */
  1460. #define BRIDGE_MIN_BELIEVABLE_BANDWIDTH 20000 /* 20 kB/sec */
  1461. #define BRIDGE_MAX_BELIEVABLE_BANDWIDTH 100000 /* 100 kB/sec */
  1462. /** Return the smaller of the router's configured BandwidthRate
  1463. * and its advertised capacity, making sure to stay within the
  1464. * interval between bridge-min-believe-bw and
  1465. * bridge-max-believe-bw. */
  1466. static uint32_t
  1467. bridge_get_advertised_bandwidth_bounded(routerinfo_t *router)
  1468. {
  1469. uint32_t result = router->bandwidthcapacity;
  1470. if (result > router->bandwidthrate)
  1471. result = router->bandwidthrate;
  1472. if (result > BRIDGE_MAX_BELIEVABLE_BANDWIDTH)
  1473. result = BRIDGE_MAX_BELIEVABLE_BANDWIDTH;
  1474. else if (result < BRIDGE_MIN_BELIEVABLE_BANDWIDTH)
  1475. result = BRIDGE_MIN_BELIEVABLE_BANDWIDTH;
  1476. return result;
  1477. }
  1478. /** Return bw*1000, unless bw*1000 would overflow, in which case return
  1479. * INT32_MAX. */
  1480. static INLINE int32_t
  1481. kb_to_bytes(uint32_t bw)
  1482. {
  1483. return (bw > (INT32_MAX/1000)) ? INT32_MAX : bw*1000;
  1484. }
  1485. /** Helper function:
  1486. * choose a random element of smartlist <b>sl</b> of nodes, weighted by
  1487. * the advertised bandwidth of each element using the consensus
  1488. * bandwidth weights.
  1489. *
  1490. * If <b>rule</b>==WEIGHT_FOR_EXIT. we're picking an exit node: consider all
  1491. * nodes' bandwidth equally regardless of their Exit status, since there may
  1492. * be some in the list because they exit to obscure ports. If
  1493. * <b>rule</b>==NO_WEIGHTING, we're picking a non-exit node: weight
  1494. * exit-node's bandwidth less depending on the smallness of the fraction of
  1495. * Exit-to-total bandwidth. If <b>rule</b>==WEIGHT_FOR_GUARD, we're picking a
  1496. * guard node: consider all guard's bandwidth equally. Otherwise, weight
  1497. * guards proportionally less.
  1498. */
  1499. static const node_t *
  1500. smartlist_choose_node_by_bandwidth_weights(const smartlist_t *sl,
  1501. bandwidth_weight_rule_t rule)
  1502. {
  1503. u64_dbl_t *bandwidths=NULL;
  1504. if (compute_weighted_bandwidths(sl, rule, &bandwidths) < 0)
  1505. return NULL;
  1506. scale_array_elements_to_u64(bandwidths, smartlist_len(sl),
  1507. &sl_last_total_weighted_bw);
  1508. {
  1509. int idx = choose_array_element_by_weight(bandwidths,
  1510. smartlist_len(sl));
  1511. tor_free(bandwidths);
  1512. return idx < 0 ? NULL : smartlist_get(sl, idx);
  1513. }
  1514. }
  1515. /** Given a list of routers and a weighting rule as in
  1516. * smartlist_choose_node_by_bandwidth_weights, compute weighted bandwidth
  1517. * values for each node and store them in a freshly allocated
  1518. * *<b>bandwidths_out</b> of the same length as <b>sl</b>, and holding results
  1519. * as doubles. Return 0 on success, -1 on failure. */
  1520. static int
  1521. compute_weighted_bandwidths(const smartlist_t *sl,
  1522. bandwidth_weight_rule_t rule,
  1523. u64_dbl_t **bandwidths_out)
  1524. {
  1525. int64_t weight_scale;
  1526. double Wg = -1, Wm = -1, We = -1, Wd = -1;
  1527. double Wgb = -1, Wmb = -1, Web = -1, Wdb = -1;
  1528. uint64_t weighted_bw = 0;
  1529. u64_dbl_t *bandwidths;
  1530. /* Can't choose exit and guard at same time */
  1531. tor_assert(rule == NO_WEIGHTING ||
  1532. rule == WEIGHT_FOR_EXIT ||
  1533. rule == WEIGHT_FOR_GUARD ||
  1534. rule == WEIGHT_FOR_MID ||
  1535. rule == WEIGHT_FOR_DIR);
  1536. if (smartlist_len(sl) == 0) {
  1537. log_info(LD_CIRC,
  1538. "Empty routerlist passed in to consensus weight node "
  1539. "selection for rule %s",
  1540. bandwidth_weight_rule_to_string(rule));
  1541. return -1;
  1542. }
  1543. weight_scale = networkstatus_get_weight_scale_param(NULL);
  1544. if (rule == WEIGHT_FOR_GUARD) {
  1545. Wg = networkstatus_get_bw_weight(NULL, "Wgg", -1);
  1546. Wm = networkstatus_get_bw_weight(NULL, "Wgm", -1); /* Bridges */
  1547. We = 0;
  1548. Wd = networkstatus_get_bw_weight(NULL, "Wgd", -1);
  1549. Wgb = networkstatus_get_bw_weight(NULL, "Wgb", -1);
  1550. Wmb = networkstatus_get_bw_weight(NULL, "Wmb", -1);
  1551. Web = networkstatus_get_bw_weight(NULL, "Web", -1);
  1552. Wdb = networkstatus_get_bw_weight(NULL, "Wdb", -1);
  1553. } else if (rule == WEIGHT_FOR_MID) {
  1554. Wg = networkstatus_get_bw_weight(NULL, "Wmg", -1);
  1555. Wm = networkstatus_get_bw_weight(NULL, "Wmm", -1);
  1556. We = networkstatus_get_bw_weight(NULL, "Wme", -1);
  1557. Wd = networkstatus_get_bw_weight(NULL, "Wmd", -1);
  1558. Wgb = networkstatus_get_bw_weight(NULL, "Wgb", -1);
  1559. Wmb = networkstatus_get_bw_weight(NULL, "Wmb", -1);
  1560. Web = networkstatus_get_bw_weight(NULL, "Web", -1);
  1561. Wdb = networkstatus_get_bw_weight(NULL, "Wdb", -1);
  1562. } else if (rule == WEIGHT_FOR_EXIT) {
  1563. // Guards CAN be exits if they have weird exit policies
  1564. // They are d then I guess...
  1565. We = networkstatus_get_bw_weight(NULL, "Wee", -1);
  1566. Wm = networkstatus_get_bw_weight(NULL, "Wem", -1); /* Odd exit policies */
  1567. Wd = networkstatus_get_bw_weight(NULL, "Wed", -1);
  1568. Wg = networkstatus_get_bw_weight(NULL, "Weg", -1); /* Odd exit policies */
  1569. Wgb = networkstatus_get_bw_weight(NULL, "Wgb", -1);
  1570. Wmb = networkstatus_get_bw_weight(NULL, "Wmb", -1);
  1571. Web = networkstatus_get_bw_weight(NULL, "Web", -1);
  1572. Wdb = networkstatus_get_bw_weight(NULL, "Wdb", -1);
  1573. } else if (rule == WEIGHT_FOR_DIR) {
  1574. We = networkstatus_get_bw_weight(NULL, "Wbe", -1);
  1575. Wm = networkstatus_get_bw_weight(NULL, "Wbm", -1);
  1576. Wd = networkstatus_get_bw_weight(NULL, "Wbd", -1);
  1577. Wg = networkstatus_get_bw_weight(NULL, "Wbg", -1);
  1578. Wgb = Wmb = Web = Wdb = weight_scale;
  1579. } else if (rule == NO_WEIGHTING) {
  1580. Wg = Wm = We = Wd = weight_scale;
  1581. Wgb = Wmb = Web = Wdb = weight_scale;
  1582. }
  1583. if (Wg < 0 || Wm < 0 || We < 0 || Wd < 0 || Wgb < 0 || Wmb < 0 || Wdb < 0
  1584. || Web < 0) {
  1585. log_debug(LD_CIRC,
  1586. "Got negative bandwidth weights. Defaulting to old selection"
  1587. " algorithm.");
  1588. return -1; // Use old algorithm.
  1589. }
  1590. Wg /= weight_scale;
  1591. Wm /= weight_scale;
  1592. We /= weight_scale;
  1593. Wd /= weight_scale;
  1594. Wgb /= weight_scale;
  1595. Wmb /= weight_scale;
  1596. Web /= weight_scale;
  1597. Wdb /= weight_scale;
  1598. bandwidths = tor_malloc_zero(sizeof(u64_dbl_t)*smartlist_len(sl));
  1599. // Cycle through smartlist and total the bandwidth.
  1600. SMARTLIST_FOREACH_BEGIN(sl, const node_t *, node) {
  1601. int is_exit = 0, is_guard = 0, is_dir = 0, this_bw = 0, is_me = 0;
  1602. double weight = 1;
  1603. is_exit = node->is_exit && ! node->is_bad_exit;
  1604. is_guard = node->is_possible_guard;
  1605. is_dir = node_is_dir(node);
  1606. if (node->rs) {
  1607. if (!node->rs->has_bandwidth) {
  1608. tor_free(bandwidths);
  1609. /* This should never happen, unless all the authorites downgrade
  1610. * to 0.2.0 or rogue routerstatuses get inserted into our consensus. */
  1611. log_warn(LD_BUG,
  1612. "Consensus is not listing bandwidths. Defaulting back to "
  1613. "old router selection algorithm.");
  1614. return -1;
  1615. }
  1616. this_bw = kb_to_bytes(node->rs->bandwidth);
  1617. } else if (node->ri) {
  1618. /* bridge or other descriptor not in our consensus */
  1619. this_bw = bridge_get_advertised_bandwidth_bounded(node->ri);
  1620. } else {
  1621. /* We can't use this one. */
  1622. continue;
  1623. }
  1624. is_me = router_digest_is_me(node->identity);
  1625. if (is_guard && is_exit) {
  1626. weight = (is_dir ? Wdb*Wd : Wd);
  1627. } else if (is_guard) {
  1628. weight = (is_dir ? Wgb*Wg : Wg);
  1629. } else if (is_exit) {
  1630. weight = (is_dir ? Web*We : We);
  1631. } else { // middle
  1632. weight = (is_dir ? Wmb*Wm : Wm);
  1633. }
  1634. /* These should be impossible; but overflows here would be bad, so let's
  1635. * make sure. */
  1636. if (this_bw < 0)
  1637. this_bw = 0;
  1638. if (weight < 0.0)
  1639. weight = 0.0;
  1640. bandwidths[node_sl_idx].dbl = weight*this_bw + 0.5;
  1641. if (is_me)
  1642. sl_last_weighted_bw_of_me = (uint64_t) bandwidths[node_sl_idx].dbl;
  1643. } SMARTLIST_FOREACH_END(node);
  1644. log_debug(LD_CIRC, "Generated weighted bandwidths for rule %s based "
  1645. "on weights "
  1646. "Wg=%f Wm=%f We=%f Wd=%f with total bw "U64_FORMAT,
  1647. bandwidth_weight_rule_to_string(rule),
  1648. Wg, Wm, We, Wd, U64_PRINTF_ARG(weighted_bw));
  1649. *bandwidths_out = bandwidths;
  1650. return 0;
  1651. }
  1652. /** For all nodes in <b>sl</b>, return the fraction of those nodes, weighted
  1653. * by their weighted bandwidths with rule <b>rule</b>, for which we have
  1654. * descriptors. */
  1655. double
  1656. frac_nodes_with_descriptors(const smartlist_t *sl,
  1657. bandwidth_weight_rule_t rule)
  1658. {
  1659. u64_dbl_t *bandwidths = NULL;
  1660. double total, present;
  1661. if (smartlist_len(sl) == 0)
  1662. return 0.0;
  1663. if (compute_weighted_bandwidths(sl, rule, &bandwidths) < 0) {
  1664. int n_with_descs = 0;
  1665. SMARTLIST_FOREACH(sl, const node_t *, node, {
  1666. if (node_has_descriptor(node))
  1667. n_with_descs++;
  1668. });
  1669. return ((double)n_with_descs) / (double)smartlist_len(sl);
  1670. }
  1671. total = present = 0.0;
  1672. SMARTLIST_FOREACH_BEGIN(sl, const node_t *, node) {
  1673. const double bw = bandwidths[node_sl_idx].dbl;
  1674. total += bw;
  1675. if (node_has_descriptor(node))
  1676. present += bw;
  1677. } SMARTLIST_FOREACH_END(node);
  1678. tor_free(bandwidths);
  1679. if (total < 1.0)
  1680. return 0;
  1681. return present / total;
  1682. }
  1683. /** Helper function:
  1684. * choose a random node_t element of smartlist <b>sl</b>, weighted by
  1685. * the advertised bandwidth of each element.
  1686. *
  1687. * If <b>rule</b>==WEIGHT_FOR_EXIT. we're picking an exit node: consider all
  1688. * nodes' bandwidth equally regardless of their Exit status, since there may
  1689. * be some in the list because they exit to obscure ports. If
  1690. * <b>rule</b>==NO_WEIGHTING, we're picking a non-exit node: weight
  1691. * exit-node's bandwidth less depending on the smallness of the fraction of
  1692. * Exit-to-total bandwidth. If <b>rule</b>==WEIGHT_FOR_GUARD, we're picking a
  1693. * guard node: consider all guard's bandwidth equally. Otherwise, weight
  1694. * guards proportionally less.
  1695. */
  1696. static const node_t *
  1697. smartlist_choose_node_by_bandwidth(const smartlist_t *sl,
  1698. bandwidth_weight_rule_t rule)
  1699. {
  1700. unsigned int i;
  1701. u64_dbl_t *bandwidths;
  1702. int is_exit;
  1703. int is_guard;
  1704. int is_fast;
  1705. double total_nonexit_bw = 0, total_exit_bw = 0;
  1706. double total_nonguard_bw = 0, total_guard_bw = 0;
  1707. double exit_weight;
  1708. double guard_weight;
  1709. int n_unknown = 0;
  1710. bitarray_t *fast_bits;
  1711. bitarray_t *exit_bits;
  1712. bitarray_t *guard_bits;
  1713. int me_idx = -1;
  1714. // This function does not support WEIGHT_FOR_DIR
  1715. // or WEIGHT_FOR_MID
  1716. if (rule == WEIGHT_FOR_DIR || rule == WEIGHT_FOR_MID) {
  1717. rule = NO_WEIGHTING;
  1718. }
  1719. /* Can't choose exit and guard at same time */
  1720. tor_assert(rule == NO_WEIGHTING ||
  1721. rule == WEIGHT_FOR_EXIT ||
  1722. rule == WEIGHT_FOR_GUARD);
  1723. if (smartlist_len(sl) == 0) {
  1724. log_info(LD_CIRC,
  1725. "Empty routerlist passed in to old node selection for rule %s",
  1726. bandwidth_weight_rule_to_string(rule));
  1727. return NULL;
  1728. }
  1729. /* First count the total bandwidth weight, and make a list
  1730. * of each value. We use UINT64_MAX to indicate "unknown". */
  1731. bandwidths = tor_malloc_zero(sizeof(u64_dbl_t)*smartlist_len(sl));
  1732. fast_bits = bitarray_init_zero(smartlist_len(sl));
  1733. exit_bits = bitarray_init_zero(smartlist_len(sl));
  1734. guard_bits = bitarray_init_zero(smartlist_len(sl));
  1735. /* Iterate over all the routerinfo_t or routerstatus_t, and */
  1736. SMARTLIST_FOREACH_BEGIN(sl, const node_t *, node) {
  1737. /* first, learn what bandwidth we think i has */
  1738. int is_known = 1;
  1739. uint32_t this_bw = 0;
  1740. i = node_sl_idx;
  1741. if (router_digest_is_me(node->identity))
  1742. me_idx = node_sl_idx;
  1743. is_exit = node->is_exit;
  1744. is_guard = node->is_possible_guard;
  1745. if (node->rs) {
  1746. if (node->rs->has_bandwidth) {
  1747. this_bw = kb_to_bytes(node->rs->bandwidth);
  1748. } else { /* guess */
  1749. is_known = 0;
  1750. }
  1751. } else if (node->ri) {
  1752. /* Must be a bridge if we're willing to use it */
  1753. this_bw = bridge_get_advertised_bandwidth_bounded(node->ri);
  1754. }
  1755. if (is_exit)
  1756. bitarray_set(exit_bits, i);
  1757. if (is_guard)
  1758. bitarray_set(guard_bits, i);
  1759. if (node->is_fast)
  1760. bitarray_set(fast_bits, i);
  1761. if (is_known) {
  1762. bandwidths[i].dbl = this_bw;
  1763. if (is_guard)
  1764. total_guard_bw += this_bw;
  1765. else
  1766. total_nonguard_bw += this_bw;
  1767. if (is_exit)
  1768. total_exit_bw += this_bw;
  1769. else
  1770. total_nonexit_bw += this_bw;
  1771. } else {
  1772. ++n_unknown;
  1773. bandwidths[i].dbl = -1.0;
  1774. }
  1775. } SMARTLIST_FOREACH_END(node);
  1776. #define EPSILON .1
  1777. /* Now, fill in the unknown values. */
  1778. if (n_unknown) {
  1779. int32_t avg_fast, avg_slow;
  1780. if (total_exit_bw+total_nonexit_bw < EPSILON) {
  1781. /* if there's some bandwidth, there's at least one known router,
  1782. * so no worries about div by 0 here */
  1783. int n_known = smartlist_len(sl)-n_unknown;
  1784. avg_fast = avg_slow = (int32_t)
  1785. ((total_exit_bw+total_nonexit_bw)/((uint64_t) n_known));
  1786. } else {
  1787. avg_fast = 40000;
  1788. avg_slow = 20000;
  1789. }
  1790. for (i=0; i<(unsigned)smartlist_len(sl); ++i) {
  1791. if (bandwidths[i].dbl >= 0.0)
  1792. continue;
  1793. is_fast = bitarray_is_set(fast_bits, i);
  1794. is_exit = bitarray_is_set(exit_bits, i);
  1795. is_guard = bitarray_is_set(guard_bits, i);
  1796. bandwidths[i].dbl = is_fast ? avg_fast : avg_slow;
  1797. if (is_exit)
  1798. total_exit_bw += bandwidths[i].dbl;
  1799. else
  1800. total_nonexit_bw += bandwidths[i].dbl;
  1801. if (is_guard)
  1802. total_guard_bw += bandwidths[i].dbl;
  1803. else
  1804. total_nonguard_bw += bandwidths[i].dbl;
  1805. }
  1806. }
  1807. /* If there's no bandwidth at all, pick at random. */
  1808. if (total_exit_bw+total_nonexit_bw < EPSILON) {
  1809. tor_free(bandwidths);
  1810. tor_free(fast_bits);
  1811. tor_free(exit_bits);
  1812. tor_free(guard_bits);
  1813. return smartlist_choose(sl);
  1814. }
  1815. /* Figure out how to weight exits and guards */
  1816. {
  1817. double all_bw = U64_TO_DBL(total_exit_bw+total_nonexit_bw);
  1818. double exit_bw = U64_TO_DBL(total_exit_bw);
  1819. double guard_bw = U64_TO_DBL(total_guard_bw);
  1820. /*
  1821. * For detailed derivation of this formula, see
  1822. * http://archives.seul.org/or/dev/Jul-2007/msg00056.html
  1823. */
  1824. if (rule == WEIGHT_FOR_EXIT || total_exit_bw<EPSILON)
  1825. exit_weight = 1.0;
  1826. else
  1827. exit_weight = 1.0 - all_bw/(3.0*exit_bw);
  1828. if (rule == WEIGHT_FOR_GUARD || total_guard_bw<EPSILON)
  1829. guard_weight = 1.0;
  1830. else
  1831. guard_weight = 1.0 - all_bw/(3.0*guard_bw);
  1832. if (exit_weight <= 0.0)
  1833. exit_weight = 0.0;
  1834. if (guard_weight <= 0.0)
  1835. guard_weight = 0.0;
  1836. sl_last_weighted_bw_of_me = 0;
  1837. for (i=0; i < (unsigned)smartlist_len(sl); i++) {
  1838. tor_assert(bandwidths[i].dbl >= 0.0);
  1839. is_exit = bitarray_is_set(exit_bits, i);
  1840. is_guard = bitarray_is_set(guard_bits, i);
  1841. if (is_exit && is_guard)
  1842. bandwidths[i].dbl *= exit_weight * guard_weight;
  1843. else if (is_guard)
  1844. bandwidths[i].dbl *= guard_weight;
  1845. else if (is_exit)
  1846. bandwidths[i].dbl *= exit_weight;
  1847. if (i == (unsigned) me_idx)
  1848. sl_last_weighted_bw_of_me = (uint64_t) bandwidths[i].dbl;
  1849. }
  1850. }
  1851. #if 0
  1852. log_debug(LD_CIRC, "Total weighted bw = "U64_FORMAT
  1853. ", exit bw = "U64_FORMAT
  1854. ", nonexit bw = "U64_FORMAT", exit weight = %f "
  1855. "(for exit == %d)"
  1856. ", guard bw = "U64_FORMAT
  1857. ", nonguard bw = "U64_FORMAT", guard weight = %f "
  1858. "(for guard == %d)",
  1859. U64_PRINTF_ARG(total_bw),
  1860. U64_PRINTF_ARG(total_exit_bw), U64_PRINTF_ARG(total_nonexit_bw),
  1861. exit_weight, (int)(rule == WEIGHT_FOR_EXIT),
  1862. U64_PRINTF_ARG(total_guard_bw), U64_PRINTF_ARG(total_nonguard_bw),
  1863. guard_weight, (int)(rule == WEIGHT_FOR_GUARD));
  1864. #endif
  1865. scale_array_elements_to_u64(bandwidths, smartlist_len(sl),
  1866. &sl_last_total_weighted_bw);
  1867. {
  1868. int idx = choose_array_element_by_weight(bandwidths,
  1869. smartlist_len(sl));
  1870. tor_free(bandwidths);
  1871. tor_free(fast_bits);
  1872. tor_free(exit_bits);
  1873. tor_free(guard_bits);
  1874. return idx < 0 ? NULL : smartlist_get(sl, idx);
  1875. }
  1876. }
  1877. /** Choose a random element of status list <b>sl</b>, weighted by
  1878. * the advertised bandwidth of each node */
  1879. const node_t *
  1880. node_sl_choose_by_bandwidth(const smartlist_t *sl,
  1881. bandwidth_weight_rule_t rule)
  1882. { /*XXXX MOVE */
  1883. const node_t *ret;
  1884. if ((ret = smartlist_choose_node_by_bandwidth_weights(sl, rule))) {
  1885. return ret;
  1886. } else {
  1887. return smartlist_choose_node_by_bandwidth(sl, rule);
  1888. }
  1889. }
  1890. /** Return a random running node from the nodelist. Never
  1891. * pick a node that is in
  1892. * <b>excludedsmartlist</b>, or which matches <b>excludedset</b>,
  1893. * even if they are the only nodes available.
  1894. * If <b>CRN_NEED_UPTIME</b> is set in flags and any router has more than
  1895. * a minimum uptime, return one of those.
  1896. * If <b>CRN_NEED_CAPACITY</b> is set in flags, weight your choice by the
  1897. * advertised capacity of each router.
  1898. * If <b>CRN_ALLOW_INVALID</b> is not set in flags, consider only Valid
  1899. * routers.
  1900. * If <b>CRN_NEED_GUARD</b> is set in flags, consider only Guard routers.
  1901. * If <b>CRN_WEIGHT_AS_EXIT</b> is set in flags, we weight bandwidths as if
  1902. * picking an exit node, otherwise we weight bandwidths for picking a relay
  1903. * node (that is, possibly discounting exit nodes).
  1904. * If <b>CRN_NEED_DESC</b> is set in flags, we only consider nodes that
  1905. * have a routerinfo or microdescriptor -- that is, enough info to be
  1906. * used to build a circuit.
  1907. */
  1908. const node_t *
  1909. router_choose_random_node(smartlist_t *excludedsmartlist,
  1910. routerset_t *excludedset,
  1911. router_crn_flags_t flags)
  1912. { /* XXXX MOVE */
  1913. const int need_uptime = (flags & CRN_NEED_UPTIME) != 0;
  1914. const int need_capacity = (flags & CRN_NEED_CAPACITY) != 0;
  1915. const int need_guard = (flags & CRN_NEED_GUARD) != 0;
  1916. const int allow_invalid = (flags & CRN_ALLOW_INVALID) != 0;
  1917. const int weight_for_exit = (flags & CRN_WEIGHT_AS_EXIT) != 0;
  1918. const int need_desc = (flags & CRN_NEED_DESC) != 0;
  1919. smartlist_t *sl=smartlist_new(),
  1920. *excludednodes=smartlist_new();
  1921. const node_t *choice = NULL;
  1922. const routerinfo_t *r;
  1923. bandwidth_weight_rule_t rule;
  1924. tor_assert(!(weight_for_exit && need_guard));
  1925. rule = weight_for_exit ? WEIGHT_FOR_EXIT :
  1926. (need_guard ? WEIGHT_FOR_GUARD : WEIGHT_FOR_MID);
  1927. /* Exclude relays that allow single hop exit circuits, if the user
  1928. * wants to (such relays might be risky) */
  1929. if (get_options()->ExcludeSingleHopRelays) {
  1930. SMARTLIST_FOREACH(nodelist_get_list(), node_t *, node,
  1931. if (node_allows_single_hop_exits(node)) {
  1932. smartlist_add(excludednodes, node);
  1933. });
  1934. }
  1935. if ((r = routerlist_find_my_routerinfo()))
  1936. routerlist_add_node_and_family(excludednodes, r);
  1937. router_add_running_nodes_to_smartlist(sl, allow_invalid,
  1938. need_uptime, need_capacity,
  1939. need_guard, need_desc);
  1940. smartlist_subtract(sl,excludednodes);
  1941. if (excludedsmartlist)
  1942. smartlist_subtract(sl,excludedsmartlist);
  1943. if (excludedset)
  1944. routerset_subtract_nodes(sl,excludedset);
  1945. // Always weight by bandwidth
  1946. choice = node_sl_choose_by_bandwidth(sl, rule);
  1947. smartlist_free(sl);
  1948. if (!choice && (need_uptime || need_capacity || need_guard)) {
  1949. /* try once more -- recurse but with fewer restrictions. */
  1950. log_info(LD_CIRC,
  1951. "We couldn't find any live%s%s%s routers; falling back "
  1952. "to list of all routers.",
  1953. need_capacity?", fast":"",
  1954. need_uptime?", stable":"",
  1955. need_guard?", guard":"");
  1956. flags &= ~ (CRN_NEED_UPTIME|CRN_NEED_CAPACITY|CRN_NEED_GUARD);
  1957. choice = router_choose_random_node(
  1958. excludedsmartlist, excludedset, flags);
  1959. }
  1960. smartlist_free(excludednodes);
  1961. if (!choice) {
  1962. log_warn(LD_CIRC,
  1963. "No available nodes when trying to choose node. Failing.");
  1964. }
  1965. return choice;
  1966. }
  1967. /** Helper: given an extended nickname in <b>hexdigest</b> try to decode it.
  1968. * Return 0 on success, -1 on failure. Store the result into the
  1969. * DIGEST_LEN-byte buffer at <b>digest_out</b>, the single character at
  1970. * <b>nickname_qualifier_char_out</b>, and the MAXNICKNAME_LEN+1-byte buffer
  1971. * at <b>nickname_out</b>.
  1972. *
  1973. * The recognized format is:
  1974. * HexName = Dollar? HexDigest NamePart?
  1975. * Dollar = '?'
  1976. * HexDigest = HexChar*20
  1977. * HexChar = 'a'..'f' | 'A'..'F' | '0'..'9'
  1978. * NamePart = QualChar Name
  1979. * QualChar = '=' | '~'
  1980. * Name = NameChar*(1..MAX_NICKNAME_LEN)
  1981. * NameChar = Any ASCII alphanumeric character
  1982. */
  1983. int
  1984. hex_digest_nickname_decode(const char *hexdigest,
  1985. char *digest_out,
  1986. char *nickname_qualifier_char_out,
  1987. char *nickname_out)
  1988. {
  1989. size_t len;
  1990. tor_assert(hexdigest);
  1991. if (hexdigest[0] == '$')
  1992. ++hexdigest;
  1993. len = strlen(hexdigest);
  1994. if (len < HEX_DIGEST_LEN) {
  1995. return -1;
  1996. } else if (len > HEX_DIGEST_LEN && (hexdigest[HEX_DIGEST_LEN] == '=' ||
  1997. hexdigest[HEX_DIGEST_LEN] == '~') &&
  1998. len <= HEX_DIGEST_LEN+1+MAX_NICKNAME_LEN) {
  1999. *nickname_qualifier_char_out = hexdigest[HEX_DIGEST_LEN];
  2000. strlcpy(nickname_out, hexdigest+HEX_DIGEST_LEN+1 , MAX_NICKNAME_LEN+1);
  2001. } else if (len == HEX_DIGEST_LEN) {
  2002. ;
  2003. } else {
  2004. return -1;
  2005. }
  2006. if (base16_decode(digest_out, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0)
  2007. return -1;
  2008. return 0;
  2009. }
  2010. /** Helper: Return true iff the <b>identity_digest</b> and <b>nickname</b>
  2011. * combination of a router, encoded in hexadecimal, matches <b>hexdigest</b>
  2012. * (which is optionally prefixed with a single dollar sign). Return false if
  2013. * <b>hexdigest</b> is malformed, or it doesn't match. */
  2014. int
  2015. hex_digest_nickname_matches(const char *hexdigest, const char *identity_digest,
  2016. const char *nickname, int is_named)
  2017. {
  2018. char digest[DIGEST_LEN];
  2019. char nn_char='\0';
  2020. char nn_buf[MAX_NICKNAME_LEN+1];
  2021. if (hex_digest_nickname_decode(hexdigest, digest, &nn_char, nn_buf) == -1)
  2022. return 0;
  2023. if (nn_char == '=' || nn_char == '~') {
  2024. if (!nickname)
  2025. return 0;
  2026. if (strcasecmp(nn_buf, nickname))
  2027. return 0;
  2028. if (nn_char == '=' && !is_named)
  2029. return 0;
  2030. }
  2031. return tor_memeq(digest, identity_digest, DIGEST_LEN);
  2032. }
  2033. /** Return true iff <b>router</b> is listed as named in the current
  2034. * consensus. */
  2035. int
  2036. router_is_named(const routerinfo_t *router)
  2037. {
  2038. const char *digest =
  2039. networkstatus_get_router_digest_by_nickname(router->nickname);
  2040. return (digest &&
  2041. tor_memeq(digest, router->cache_info.identity_digest, DIGEST_LEN));
  2042. }
  2043. /** Return true iff the digest of <b>router</b>'s identity key,
  2044. * encoded in hexadecimal, matches <b>hexdigest</b> (which is
  2045. * optionally prefixed with a single dollar sign). Return false if
  2046. * <b>hexdigest</b> is malformed, or it doesn't match. */
  2047. static INLINE int
  2048. router_hex_digest_matches(const routerinfo_t *router, const char *hexdigest)
  2049. {
  2050. return hex_digest_nickname_matches(hexdigest,
  2051. router->cache_info.identity_digest,
  2052. router->nickname,
  2053. router_is_named(router));
  2054. }
  2055. /** Return true if <b>router</b>'s nickname matches <b>nickname</b>
  2056. * (case-insensitive), or if <b>router's</b> identity key digest
  2057. * matches a hexadecimal value stored in <b>nickname</b>. Return
  2058. * false otherwise. */
  2059. static int
  2060. router_nickname_matches(const routerinfo_t *router, const char *nickname)
  2061. {
  2062. if (nickname[0]!='$' && !strcasecmp(router->nickname, nickname))
  2063. return 1;
  2064. return router_hex_digest_matches(router, nickname);
  2065. }
  2066. /** Return true iff <b>digest</b> is the digest of the identity key of a
  2067. * trusted directory matching at least one bit of <b>type</b>. If <b>type</b>
  2068. * is zero, any authority is okay. */
  2069. int
  2070. router_digest_is_trusted_dir_type(const char *digest, dirinfo_type_t type)
  2071. {
  2072. if (!trusted_dir_servers)
  2073. return 0;
  2074. if (authdir_mode(get_options()) && router_digest_is_me(digest))
  2075. return 1;
  2076. SMARTLIST_FOREACH(trusted_dir_servers, dir_server_t *, ent,
  2077. if (tor_memeq(digest, ent->digest, DIGEST_LEN)) {
  2078. return (!type) || ((type & ent->type) != 0);
  2079. });
  2080. return 0;
  2081. }
  2082. /** Return true iff <b>addr</b> is the address of one of our trusted
  2083. * directory authorities. */
  2084. int
  2085. router_addr_is_trusted_dir(uint32_t addr)
  2086. {
  2087. if (!trusted_dir_servers)
  2088. return 0;
  2089. SMARTLIST_FOREACH(trusted_dir_servers, dir_server_t *, ent,
  2090. if (ent->addr == addr)
  2091. return 1;
  2092. );
  2093. return 0;
  2094. }
  2095. /** If hexdigest is correctly formed, base16_decode it into
  2096. * digest, which must have DIGEST_LEN space in it.
  2097. * Return 0 on success, -1 on failure.
  2098. */
  2099. int
  2100. hexdigest_to_digest(const char *hexdigest, char *digest)
  2101. {
  2102. if (hexdigest[0]=='$')
  2103. ++hexdigest;
  2104. if (strlen(hexdigest) < HEX_DIGEST_LEN ||
  2105. base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
  2106. return -1;
  2107. return 0;
  2108. }
  2109. /** As router_get_by_id_digest,but return a pointer that you're allowed to
  2110. * modify */
  2111. routerinfo_t *
  2112. router_get_mutable_by_digest(const char *digest)
  2113. {
  2114. tor_assert(digest);
  2115. if (!routerlist) return NULL;
  2116. // routerlist_assert_ok(routerlist);
  2117. return rimap_get(routerlist->identity_map, digest);
  2118. }
  2119. /** Return the router in our routerlist whose 20-byte key digest
  2120. * is <b>digest</b>. Return NULL if no such router is known. */
  2121. const routerinfo_t *
  2122. router_get_by_id_digest(const char *digest)
  2123. {
  2124. return router_get_mutable_by_digest(digest);
  2125. }
  2126. /** Return the router in our routerlist whose 20-byte descriptor
  2127. * is <b>digest</b>. Return NULL if no such router is known. */
  2128. signed_descriptor_t *
  2129. router_get_by_descriptor_digest(const char *digest)
  2130. {
  2131. tor_assert(digest);
  2132. if (!routerlist) return NULL;
  2133. return sdmap_get(routerlist->desc_digest_map, digest);
  2134. }
  2135. /** Return the signed descriptor for the router in our routerlist whose
  2136. * 20-byte extra-info digest is <b>digest</b>. Return NULL if no such router
  2137. * is known. */
  2138. signed_descriptor_t *
  2139. router_get_by_extrainfo_digest(const char *digest)
  2140. {
  2141. tor_assert(digest);
  2142. if (!routerlist) return NULL;
  2143. return sdmap_get(routerlist->desc_by_eid_map, digest);
  2144. }
  2145. /** Return the signed descriptor for the extrainfo_t in our routerlist whose
  2146. * extra-info-digest is <b>digest</b>. Return NULL if no such extra-info
  2147. * document is known. */
  2148. signed_descriptor_t *
  2149. extrainfo_get_by_descriptor_digest(const char *digest)
  2150. {
  2151. extrainfo_t *ei;
  2152. tor_assert(digest);
  2153. if (!routerlist) return NULL;
  2154. ei = eimap_get(routerlist->extra_info_map, digest);
  2155. return ei ? &ei->cache_info : NULL;
  2156. }
  2157. /** Return a pointer to the signed textual representation of a descriptor.
  2158. * The returned string is not guaranteed to be NUL-terminated: the string's
  2159. * length will be in desc-\>signed_descriptor_len.
  2160. *
  2161. * If <b>with_annotations</b> is set, the returned string will include
  2162. * the annotations
  2163. * (if any) preceding the descriptor. This will increase the length of the
  2164. * string by desc-\>annotations_len.
  2165. *
  2166. * The caller must not free the string returned.
  2167. */
  2168. static const char *
  2169. signed_descriptor_get_body_impl(const signed_descriptor_t *desc,
  2170. int with_annotations)
  2171. {
  2172. const char *r = NULL;
  2173. size_t len = desc->signed_descriptor_len;
  2174. off_t offset = desc->saved_offset;
  2175. if (with_annotations)
  2176. len += desc->annotations_len;
  2177. else
  2178. offset += desc->annotations_len;
  2179. tor_assert(len > 32);
  2180. if (desc->saved_location == SAVED_IN_CACHE && routerlist) {
  2181. desc_store_t *store = desc_get_store(router_get_routerlist(), desc);
  2182. if (store && store->mmap) {
  2183. tor_assert(desc->saved_offset + len <= store->mmap->size);
  2184. r = store->mmap->data + offset;
  2185. } else if (store) {
  2186. log_err(LD_DIR, "We couldn't read a descriptor that is supposedly "
  2187. "mmaped in our cache. Is another process running in our data "
  2188. "directory? Exiting.");
  2189. exit(1);
  2190. }
  2191. }
  2192. if (!r) /* no mmap, or not in cache. */
  2193. r = desc->signed_descriptor_body +
  2194. (with_annotations ? 0 : desc->annotations_len);
  2195. tor_assert(r);
  2196. if (!with_annotations) {
  2197. if (fast_memcmp("router ", r, 7) && fast_memcmp("extra-info ", r, 11)) {
  2198. char *cp = tor_strndup(r, 64);
  2199. log_err(LD_DIR, "descriptor at %p begins with unexpected string %s. "
  2200. "Is another process running in our data directory? Exiting.",
  2201. desc, escaped(cp));
  2202. exit(1);
  2203. }
  2204. }
  2205. return r;
  2206. }
  2207. /** Return a pointer to the signed textual representation of a descriptor.
  2208. * The returned string is not guaranteed to be NUL-terminated: the string's
  2209. * length will be in desc-\>signed_descriptor_len.
  2210. *
  2211. * The caller must not free the string returned.
  2212. */
  2213. const char *
  2214. signed_descriptor_get_body(const signed_descriptor_t *desc)
  2215. {
  2216. return signed_descriptor_get_body_impl(desc, 0);
  2217. }
  2218. /** As signed_descriptor_get_body(), but points to the beginning of the
  2219. * annotations section rather than the beginning of the descriptor. */
  2220. const char *
  2221. signed_descriptor_get_annotations(const signed_descriptor_t *desc)
  2222. {
  2223. return signed_descriptor_get_body_impl(desc, 1);
  2224. }
  2225. /** Return the current list of all known routers. */
  2226. routerlist_t *
  2227. router_get_routerlist(void)
  2228. {
  2229. if (PREDICT_UNLIKELY(!routerlist)) {
  2230. routerlist = tor_malloc_zero(sizeof(routerlist_t));
  2231. routerlist->routers = smartlist_new();
  2232. routerlist->old_routers = smartlist_new();
  2233. routerlist->identity_map = rimap_new();
  2234. routerlist->desc_digest_map = sdmap_new();
  2235. routerlist->desc_by_eid_map = sdmap_new();
  2236. routerlist->extra_info_map = eimap_new();
  2237. routerlist->desc_store.fname_base = "cached-descriptors";
  2238. routerlist->desc_store.fname_alt_base = "cached-routers";
  2239. routerlist->extrainfo_store.fname_base = "cached-extrainfo";
  2240. routerlist->desc_store.type = ROUTER_STORE;
  2241. routerlist->extrainfo_store.type = EXTRAINFO_STORE;
  2242. routerlist->desc_store.description = "router descriptors";
  2243. routerlist->extrainfo_store.description = "extra-info documents";
  2244. }
  2245. return routerlist;
  2246. }
  2247. /** Free all storage held by <b>router</b>. */
  2248. void
  2249. routerinfo_free(routerinfo_t *router)
  2250. {
  2251. if (!router)
  2252. return;
  2253. tor_free(router->cache_info.signed_descriptor_body);
  2254. tor_free(router->address);
  2255. tor_free(router->nickname);
  2256. tor_free(router->platform);
  2257. tor_free(router->contact_info);
  2258. if (router->onion_pkey)
  2259. crypto_pk_free(router->onion_pkey);
  2260. tor_free(router->onion_curve25519_pkey);
  2261. if (router->identity_pkey)
  2262. crypto_pk_free(router->identity_pkey);
  2263. if (router->declared_family) {
  2264. SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
  2265. smartlist_free(router->declared_family);
  2266. }
  2267. addr_policy_list_free(router->exit_policy);
  2268. short_policy_free(router->ipv6_exit_policy);
  2269. memset(router, 77, sizeof(routerinfo_t));
  2270. tor_free(router);
  2271. }
  2272. /** Release all storage held by <b>extrainfo</b> */
  2273. void
  2274. extrainfo_free(extrainfo_t *extrainfo)
  2275. {
  2276. if (!extrainfo)
  2277. return;
  2278. tor_free(extrainfo->cache_info.signed_descriptor_body);
  2279. tor_free(extrainfo->pending_sig);
  2280. memset(extrainfo, 88, sizeof(extrainfo_t)); /* debug bad memory usage */
  2281. tor_free(extrainfo);
  2282. }
  2283. /** Release storage held by <b>sd</b>. */
  2284. static void
  2285. signed_descriptor_free(signed_descriptor_t *sd)
  2286. {
  2287. if (!sd)
  2288. return;
  2289. tor_free(sd->signed_descriptor_body);
  2290. memset(sd, 99, sizeof(signed_descriptor_t)); /* Debug bad mem usage */
  2291. tor_free(sd);
  2292. }
  2293. /** Extract a signed_descriptor_t from a general routerinfo, and free the
  2294. * routerinfo.
  2295. */
  2296. static signed_descriptor_t *
  2297. signed_descriptor_from_routerinfo(routerinfo_t *ri)
  2298. {
  2299. signed_descriptor_t *sd;
  2300. tor_assert(ri->purpose == ROUTER_PURPOSE_GENERAL);
  2301. sd = tor_malloc_zero(sizeof(signed_descriptor_t));
  2302. memcpy(sd, &(ri->cache_info), sizeof(signed_descriptor_t));
  2303. sd->routerlist_index = -1;
  2304. ri->cache_info.signed_descriptor_body = NULL;
  2305. routerinfo_free(ri);
  2306. return sd;
  2307. }
  2308. /** Helper: free the storage held by the extrainfo_t in <b>e</b>. */
  2309. static void
  2310. extrainfo_free_(void *e)
  2311. {
  2312. extrainfo_free(e);
  2313. }
  2314. /** Free all storage held by a routerlist <b>rl</b>. */
  2315. void
  2316. routerlist_free(routerlist_t *rl)
  2317. {
  2318. if (!rl)
  2319. return;
  2320. rimap_free(rl->identity_map, NULL);
  2321. sdmap_free(rl->desc_digest_map, NULL);
  2322. sdmap_free(rl->desc_by_eid_map, NULL);
  2323. eimap_free(rl->extra_info_map, extrainfo_free_);
  2324. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  2325. routerinfo_free(r));
  2326. SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
  2327. signed_descriptor_free(sd));
  2328. smartlist_free(rl->routers);
  2329. smartlist_free(rl->old_routers);
  2330. if (routerlist->desc_store.mmap)
  2331. tor_munmap_file(routerlist->desc_store.mmap);
  2332. if (routerlist->extrainfo_store.mmap)
  2333. tor_munmap_file(routerlist->extrainfo_store.mmap);
  2334. tor_free(rl);
  2335. router_dir_info_changed();
  2336. }
  2337. /** Log information about how much memory is being used for routerlist,
  2338. * at log level <b>severity</b>. */
  2339. void
  2340. dump_routerlist_mem_usage(int severity)
  2341. {
  2342. uint64_t livedescs = 0;
  2343. uint64_t olddescs = 0;
  2344. if (!routerlist)
  2345. return;
  2346. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, r,
  2347. livedescs += r->cache_info.signed_descriptor_len);
  2348. SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
  2349. olddescs += sd->signed_descriptor_len);
  2350. tor_log(severity, LD_DIR,
  2351. "In %d live descriptors: "U64_FORMAT" bytes. "
  2352. "In %d old descriptors: "U64_FORMAT" bytes.",
  2353. smartlist_len(routerlist->routers), U64_PRINTF_ARG(livedescs),
  2354. smartlist_len(routerlist->old_routers), U64_PRINTF_ARG(olddescs));
  2355. }
  2356. /** Debugging helper: If <b>idx</b> is nonnegative, assert that <b>ri</b> is
  2357. * in <b>sl</b> at position <b>idx</b>. Otherwise, search <b>sl</b> for
  2358. * <b>ri</b>. Return the index of <b>ri</b> in <b>sl</b>, or -1 if <b>ri</b>
  2359. * is not in <b>sl</b>. */
  2360. static INLINE int
  2361. routerlist_find_elt_(smartlist_t *sl, void *ri, int idx)
  2362. {
  2363. if (idx < 0) {
  2364. idx = -1;
  2365. SMARTLIST_FOREACH(sl, routerinfo_t *, r,
  2366. if (r == ri) {
  2367. idx = r_sl_idx;
  2368. break;
  2369. });
  2370. } else {
  2371. tor_assert(idx < smartlist_len(sl));
  2372. tor_assert(smartlist_get(sl, idx) == ri);
  2373. };
  2374. return idx;
  2375. }
  2376. /** Insert an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
  2377. * as needed. There must be no previous member of <b>rl</b> with the same
  2378. * identity digest as <b>ri</b>: If there is, call routerlist_replace
  2379. * instead.
  2380. */
  2381. static void
  2382. routerlist_insert(routerlist_t *rl, routerinfo_t *ri)
  2383. {
  2384. routerinfo_t *ri_old;
  2385. signed_descriptor_t *sd_old;
  2386. {
  2387. const routerinfo_t *ri_generated = router_get_my_routerinfo();
  2388. tor_assert(ri_generated != ri);
  2389. }
  2390. tor_assert(ri->cache_info.routerlist_index == -1);
  2391. ri_old = rimap_set(rl->identity_map, ri->cache_info.identity_digest, ri);
  2392. tor_assert(!ri_old);
  2393. sd_old = sdmap_set(rl->desc_digest_map,
  2394. ri->cache_info.signed_descriptor_digest,
  2395. &(ri->cache_info));
  2396. if (sd_old) {
  2397. int idx = sd_old->routerlist_index;
  2398. sd_old->routerlist_index = -1;
  2399. smartlist_del(rl->old_routers, idx);
  2400. if (idx < smartlist_len(rl->old_routers)) {
  2401. signed_descriptor_t *d = smartlist_get(rl->old_routers, idx);
  2402. d->routerlist_index = idx;
  2403. }
  2404. rl->desc_store.bytes_dropped += sd_old->signed_descriptor_len;
  2405. sdmap_remove(rl->desc_by_eid_map, sd_old->extra_info_digest);
  2406. signed_descriptor_free(sd_old);
  2407. }
  2408. if (!tor_digest_is_zero(ri->cache_info.extra_info_digest))
  2409. sdmap_set(rl->desc_by_eid_map, ri->cache_info.extra_info_digest,
  2410. &ri->cache_info);
  2411. smartlist_add(rl->routers, ri);
  2412. ri->cache_info.routerlist_index = smartlist_len(rl->routers) - 1;
  2413. nodelist_set_routerinfo(ri, NULL);
  2414. router_dir_info_changed();
  2415. #ifdef DEBUG_ROUTERLIST
  2416. routerlist_assert_ok(rl);
  2417. #endif
  2418. }
  2419. /** Adds the extrainfo_t <b>ei</b> to the routerlist <b>rl</b>, if there is a
  2420. * corresponding router in rl-\>routers or rl-\>old_routers. Return true iff
  2421. * we actually inserted <b>ei</b>. Free <b>ei</b> if it isn't inserted. */
  2422. static int
  2423. extrainfo_insert(routerlist_t *rl, extrainfo_t *ei)
  2424. {
  2425. int r = 0;
  2426. routerinfo_t *ri = rimap_get(rl->identity_map,
  2427. ei->cache_info.identity_digest);
  2428. signed_descriptor_t *sd =
  2429. sdmap_get(rl->desc_by_eid_map, ei->cache_info.signed_descriptor_digest);
  2430. extrainfo_t *ei_tmp;
  2431. {
  2432. extrainfo_t *ei_generated = router_get_my_extrainfo();
  2433. tor_assert(ei_generated != ei);
  2434. }
  2435. if (!ri) {
  2436. /* This router is unknown; we can't even verify the signature. Give up.*/
  2437. goto done;
  2438. }
  2439. if (routerinfo_incompatible_with_extrainfo(ri, ei, sd, NULL)) {
  2440. goto done;
  2441. }
  2442. /* Okay, if we make it here, we definitely have a router corresponding to
  2443. * this extrainfo. */
  2444. ei_tmp = eimap_set(rl->extra_info_map,
  2445. ei->cache_info.signed_descriptor_digest,
  2446. ei);
  2447. r = 1;
  2448. if (ei_tmp) {
  2449. rl->extrainfo_store.bytes_dropped +=
  2450. ei_tmp->cache_info.signed_descriptor_len;
  2451. extrainfo_free(ei_tmp);
  2452. }
  2453. done:
  2454. if (r == 0)
  2455. extrainfo_free(ei);
  2456. #ifdef DEBUG_ROUTERLIST
  2457. routerlist_assert_ok(rl);
  2458. #endif
  2459. return r;
  2460. }
  2461. #define should_cache_old_descriptors() \
  2462. directory_caches_dir_info(get_options())
  2463. /** If we're a directory cache and routerlist <b>rl</b> doesn't have
  2464. * a copy of router <b>ri</b> yet, add it to the list of old (not
  2465. * recommended but still served) descriptors. Else free it. */
  2466. static void
  2467. routerlist_insert_old(routerlist_t *rl, routerinfo_t *ri)
  2468. {
  2469. {
  2470. const routerinfo_t *ri_generated = router_get_my_routerinfo();
  2471. tor_assert(ri_generated != ri);
  2472. }
  2473. tor_assert(ri->cache_info.routerlist_index == -1);
  2474. if (should_cache_old_descriptors() &&
  2475. ri->purpose == ROUTER_PURPOSE_GENERAL &&
  2476. !sdmap_get(rl->desc_digest_map,
  2477. ri->cache_info.signed_descriptor_digest)) {
  2478. signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri);
  2479. sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  2480. smartlist_add(rl->old_routers, sd);
  2481. sd->routerlist_index = smartlist_len(rl->old_routers)-1;
  2482. if (!tor_digest_is_zero(sd->extra_info_digest))
  2483. sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
  2484. } else {
  2485. routerinfo_free(ri);
  2486. }
  2487. #ifdef DEBUG_ROUTERLIST
  2488. routerlist_assert_ok(rl);
  2489. #endif
  2490. }
  2491. /** Remove an item <b>ri</b> from the routerlist <b>rl</b>, updating indices
  2492. * as needed. If <b>idx</b> is nonnegative and smartlist_get(rl-&gt;routers,
  2493. * idx) == ri, we don't need to do a linear search over the list to decide
  2494. * which to remove. We fill the gap in rl-&gt;routers with a later element in
  2495. * the list, if any exists. <b>ri</b> is freed.
  2496. *
  2497. * If <b>make_old</b> is true, instead of deleting the router, we try adding
  2498. * it to rl-&gt;old_routers. */
  2499. void
  2500. routerlist_remove(routerlist_t *rl, routerinfo_t *ri, int make_old, time_t now)
  2501. {
  2502. routerinfo_t *ri_tmp;
  2503. extrainfo_t *ei_tmp;
  2504. int idx = ri->cache_info.routerlist_index;
  2505. tor_assert(0 <= idx && idx < smartlist_len(rl->routers));
  2506. tor_assert(smartlist_get(rl->routers, idx) == ri);
  2507. nodelist_remove_routerinfo(ri);
  2508. /* make sure the rephist module knows that it's not running */
  2509. rep_hist_note_router_unreachable(ri->cache_info.identity_digest, now);
  2510. ri->cache_info.routerlist_index = -1;
  2511. smartlist_del(rl->routers, idx);
  2512. if (idx < smartlist_len(rl->routers)) {
  2513. routerinfo_t *r = smartlist_get(rl->routers, idx);
  2514. r->cache_info.routerlist_index = idx;
  2515. }
  2516. ri_tmp = rimap_remove(rl->identity_map, ri->cache_info.identity_digest);
  2517. router_dir_info_changed();
  2518. tor_assert(ri_tmp == ri);
  2519. if (make_old && should_cache_old_descriptors() &&
  2520. ri->purpose == ROUTER_PURPOSE_GENERAL) {
  2521. signed_descriptor_t *sd;
  2522. sd = signed_descriptor_from_routerinfo(ri);
  2523. smartlist_add(rl->old_routers, sd);
  2524. sd->routerlist_index = smartlist_len(rl->old_routers)-1;
  2525. sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  2526. if (!tor_digest_is_zero(sd->extra_info_digest))
  2527. sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
  2528. } else {
  2529. signed_descriptor_t *sd_tmp;
  2530. sd_tmp = sdmap_remove(rl->desc_digest_map,
  2531. ri->cache_info.signed_descriptor_digest);
  2532. tor_assert(sd_tmp == &(ri->cache_info));
  2533. rl->desc_store.bytes_dropped += ri->cache_info.signed_descriptor_len;
  2534. ei_tmp = eimap_remove(rl->extra_info_map,
  2535. ri->cache_info.extra_info_digest);
  2536. if (ei_tmp) {
  2537. rl->extrainfo_store.bytes_dropped +=
  2538. ei_tmp->cache_info.signed_descriptor_len;
  2539. extrainfo_free(ei_tmp);
  2540. }
  2541. if (!tor_digest_is_zero(ri->cache_info.extra_info_digest))
  2542. sdmap_remove(rl->desc_by_eid_map, ri->cache_info.extra_info_digest);
  2543. routerinfo_free(ri);
  2544. }
  2545. #ifdef DEBUG_ROUTERLIST
  2546. routerlist_assert_ok(rl);
  2547. #endif
  2548. }
  2549. /** Remove a signed_descriptor_t <b>sd</b> from <b>rl</b>-\>old_routers, and
  2550. * adjust <b>rl</b> as appropriate. <b>idx</b> is -1, or the index of
  2551. * <b>sd</b>. */
  2552. static void
  2553. routerlist_remove_old(routerlist_t *rl, signed_descriptor_t *sd, int idx)
  2554. {
  2555. signed_descriptor_t *sd_tmp;
  2556. extrainfo_t *ei_tmp;
  2557. desc_store_t *store;
  2558. if (idx == -1) {
  2559. idx = sd->routerlist_index;
  2560. }
  2561. tor_assert(0 <= idx && idx < smartlist_len(rl->old_routers));
  2562. /* XXXX edmanm's bridge relay triggered the following assert while
  2563. * running 0.2.0.12-alpha. If anybody triggers this again, see if we
  2564. * can get a backtrace. */
  2565. tor_assert(smartlist_get(rl->old_routers, idx) == sd);
  2566. tor_assert(idx == sd->routerlist_index);
  2567. sd->routerlist_index = -1;
  2568. smartlist_del(rl->old_routers, idx);
  2569. if (idx < smartlist_len(rl->old_routers)) {
  2570. signed_descriptor_t *d = smartlist_get(rl->old_routers, idx);
  2571. d->routerlist_index = idx;
  2572. }
  2573. sd_tmp = sdmap_remove(rl->desc_digest_map,
  2574. sd->signed_descriptor_digest);
  2575. tor_assert(sd_tmp == sd);
  2576. store = desc_get_store(rl, sd);
  2577. if (store)
  2578. store->bytes_dropped += sd->signed_descriptor_len;
  2579. ei_tmp = eimap_remove(rl->extra_info_map,
  2580. sd->extra_info_digest);
  2581. if (ei_tmp) {
  2582. rl->extrainfo_store.bytes_dropped +=
  2583. ei_tmp->cache_info.signed_descriptor_len;
  2584. extrainfo_free(ei_tmp);
  2585. }
  2586. if (!tor_digest_is_zero(sd->extra_info_digest))
  2587. sdmap_remove(rl->desc_by_eid_map, sd->extra_info_digest);
  2588. signed_descriptor_free(sd);
  2589. #ifdef DEBUG_ROUTERLIST
  2590. routerlist_assert_ok(rl);
  2591. #endif
  2592. }
  2593. /** Remove <b>ri_old</b> from the routerlist <b>rl</b>, and replace it with
  2594. * <b>ri_new</b>, updating all index info. If <b>idx</b> is nonnegative and
  2595. * smartlist_get(rl-&gt;routers, idx) == ri, we don't need to do a linear
  2596. * search over the list to decide which to remove. We put ri_new in the same
  2597. * index as ri_old, if possible. ri is freed as appropriate.
  2598. *
  2599. * If should_cache_descriptors() is true, instead of deleting the router,
  2600. * we add it to rl-&gt;old_routers. */
  2601. static void
  2602. routerlist_replace(routerlist_t *rl, routerinfo_t *ri_old,
  2603. routerinfo_t *ri_new)
  2604. {
  2605. int idx;
  2606. int same_descriptors;
  2607. routerinfo_t *ri_tmp;
  2608. extrainfo_t *ei_tmp;
  2609. {
  2610. const routerinfo_t *ri_generated = router_get_my_routerinfo();
  2611. tor_assert(ri_generated != ri_new);
  2612. }
  2613. tor_assert(ri_old != ri_new);
  2614. tor_assert(ri_new->cache_info.routerlist_index == -1);
  2615. idx = ri_old->cache_info.routerlist_index;
  2616. tor_assert(0 <= idx && idx < smartlist_len(rl->routers));
  2617. tor_assert(smartlist_get(rl->routers, idx) == ri_old);
  2618. {
  2619. routerinfo_t *ri_old_tmp=NULL;
  2620. nodelist_set_routerinfo(ri_new, &ri_old_tmp);
  2621. tor_assert(ri_old == ri_old_tmp);
  2622. }
  2623. router_dir_info_changed();
  2624. if (idx >= 0) {
  2625. smartlist_set(rl->routers, idx, ri_new);
  2626. ri_old->cache_info.routerlist_index = -1;
  2627. ri_new->cache_info.routerlist_index = idx;
  2628. /* Check that ri_old is not in rl->routers anymore: */
  2629. tor_assert( routerlist_find_elt_(rl->routers, ri_old, -1) == -1 );
  2630. } else {
  2631. log_warn(LD_BUG, "Appending entry from routerlist_replace.");
  2632. routerlist_insert(rl, ri_new);
  2633. return;
  2634. }
  2635. if (tor_memneq(ri_old->cache_info.identity_digest,
  2636. ri_new->cache_info.identity_digest, DIGEST_LEN)) {
  2637. /* digests don't match; digestmap_set won't replace */
  2638. rimap_remove(rl->identity_map, ri_old->cache_info.identity_digest);
  2639. }
  2640. ri_tmp = rimap_set(rl->identity_map,
  2641. ri_new->cache_info.identity_digest, ri_new);
  2642. tor_assert(!ri_tmp || ri_tmp == ri_old);
  2643. sdmap_set(rl->desc_digest_map,
  2644. ri_new->cache_info.signed_descriptor_digest,
  2645. &(ri_new->cache_info));
  2646. if (!tor_digest_is_zero(ri_new->cache_info.extra_info_digest)) {
  2647. sdmap_set(rl->desc_by_eid_map, ri_new->cache_info.extra_info_digest,
  2648. &ri_new->cache_info);
  2649. }
  2650. same_descriptors = tor_memeq(ri_old->cache_info.signed_descriptor_digest,
  2651. ri_new->cache_info.signed_descriptor_digest,
  2652. DIGEST_LEN);
  2653. if (should_cache_old_descriptors() &&
  2654. ri_old->purpose == ROUTER_PURPOSE_GENERAL &&
  2655. !same_descriptors) {
  2656. /* ri_old is going to become a signed_descriptor_t and go into
  2657. * old_routers */
  2658. signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri_old);
  2659. smartlist_add(rl->old_routers, sd);
  2660. sd->routerlist_index = smartlist_len(rl->old_routers)-1;
  2661. sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  2662. if (!tor_digest_is_zero(sd->extra_info_digest))
  2663. sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
  2664. } else {
  2665. /* We're dropping ri_old. */
  2666. if (!same_descriptors) {
  2667. /* digests don't match; The sdmap_set above didn't replace */
  2668. sdmap_remove(rl->desc_digest_map,
  2669. ri_old->cache_info.signed_descriptor_digest);
  2670. if (tor_memneq(ri_old->cache_info.extra_info_digest,
  2671. ri_new->cache_info.extra_info_digest, DIGEST_LEN)) {
  2672. ei_tmp = eimap_remove(rl->extra_info_map,
  2673. ri_old->cache_info.extra_info_digest);
  2674. if (ei_tmp) {
  2675. rl->extrainfo_store.bytes_dropped +=
  2676. ei_tmp->cache_info.signed_descriptor_len;
  2677. extrainfo_free(ei_tmp);
  2678. }
  2679. }
  2680. if (!tor_digest_is_zero(ri_old->cache_info.extra_info_digest)) {
  2681. sdmap_remove(rl->desc_by_eid_map,
  2682. ri_old->cache_info.extra_info_digest);
  2683. }
  2684. }
  2685. rl->desc_store.bytes_dropped += ri_old->cache_info.signed_descriptor_len;
  2686. routerinfo_free(ri_old);
  2687. }
  2688. #ifdef DEBUG_ROUTERLIST
  2689. routerlist_assert_ok(rl);
  2690. #endif
  2691. }
  2692. /** Extract the descriptor <b>sd</b> from old_routerlist, and re-parse
  2693. * it as a fresh routerinfo_t. */
  2694. static routerinfo_t *
  2695. routerlist_reparse_old(routerlist_t *rl, signed_descriptor_t *sd)
  2696. {
  2697. routerinfo_t *ri;
  2698. const char *body;
  2699. body = signed_descriptor_get_annotations(sd);
  2700. ri = router_parse_entry_from_string(body,
  2701. body+sd->signed_descriptor_len+sd->annotations_len,
  2702. 0, 1, NULL);
  2703. if (!ri)
  2704. return NULL;
  2705. memcpy(&ri->cache_info, sd, sizeof(signed_descriptor_t));
  2706. sd->signed_descriptor_body = NULL; /* Steal reference. */
  2707. ri->cache_info.routerlist_index = -1;
  2708. routerlist_remove_old(rl, sd, -1);
  2709. return ri;
  2710. }
  2711. /** Free all memory held by the routerlist module. */
  2712. void
  2713. routerlist_free_all(void)
  2714. {
  2715. routerlist_free(routerlist);
  2716. routerlist = NULL;
  2717. if (warned_nicknames) {
  2718. SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
  2719. smartlist_free(warned_nicknames);
  2720. warned_nicknames = NULL;
  2721. }
  2722. clear_dir_servers();
  2723. smartlist_free(trusted_dir_servers);
  2724. smartlist_free(fallback_dir_servers);
  2725. trusted_dir_servers = fallback_dir_servers = NULL;
  2726. if (trusted_dir_certs) {
  2727. DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
  2728. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
  2729. authority_cert_free(cert));
  2730. smartlist_free(cl->certs);
  2731. tor_free(cl);
  2732. } DIGESTMAP_FOREACH_END;
  2733. digestmap_free(trusted_dir_certs, NULL);
  2734. trusted_dir_certs = NULL;
  2735. }
  2736. }
  2737. /** Forget that we have issued any router-related warnings, so that we'll
  2738. * warn again if we see the same errors. */
  2739. void
  2740. routerlist_reset_warnings(void)
  2741. {
  2742. if (!warned_nicknames)
  2743. warned_nicknames = smartlist_new();
  2744. SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
  2745. smartlist_clear(warned_nicknames); /* now the list is empty. */
  2746. networkstatus_reset_warnings();
  2747. }
  2748. /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
  2749. * older entries (if any) with the same key. Note: Callers should not hold
  2750. * their pointers to <b>router</b> if this function fails; <b>router</b>
  2751. * will either be inserted into the routerlist or freed. Similarly, even
  2752. * if this call succeeds, they should not hold their pointers to
  2753. * <b>router</b> after subsequent calls with other routerinfo's -- they
  2754. * might cause the original routerinfo to get freed.
  2755. *
  2756. * Returns the status for the operation. Might set *<b>msg</b> if it wants
  2757. * the poster of the router to know something.
  2758. *
  2759. * If <b>from_cache</b>, this descriptor came from our disk cache. If
  2760. * <b>from_fetch</b>, we received it in response to a request we made.
  2761. * (If both are false, that means it was uploaded to us as an auth dir
  2762. * server or via the controller.)
  2763. *
  2764. * This function should be called *after*
  2765. * routers_update_status_from_consensus_networkstatus; subsequently, you
  2766. * should call router_rebuild_store and routerlist_descriptors_added.
  2767. */
  2768. was_router_added_t
  2769. router_add_to_routerlist(routerinfo_t *router, const char **msg,
  2770. int from_cache, int from_fetch)
  2771. {
  2772. const char *id_digest;
  2773. const or_options_t *options = get_options();
  2774. int authdir = authdir_mode_handles_descs(options, router->purpose);
  2775. int authdir_believes_valid = 0;
  2776. routerinfo_t *old_router;
  2777. networkstatus_t *consensus =
  2778. networkstatus_get_latest_consensus_by_flavor(FLAV_NS);
  2779. const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
  2780. int in_consensus = 0;
  2781. tor_assert(msg);
  2782. if (!routerlist)
  2783. router_get_routerlist();
  2784. id_digest = router->cache_info.identity_digest;
  2785. old_router = router_get_mutable_by_digest(id_digest);
  2786. /* Make sure that we haven't already got this exact descriptor. */
  2787. if (sdmap_get(routerlist->desc_digest_map,
  2788. router->cache_info.signed_descriptor_digest)) {
  2789. /* If we have this descriptor already and the new descriptor is a bridge
  2790. * descriptor, replace it. If we had a bridge descriptor before and the
  2791. * new one is not a bridge descriptor, don't replace it. */
  2792. /* Only members of routerlist->identity_map can be bridges; we don't
  2793. * put bridges in old_routers. */
  2794. const int was_bridge = old_router &&
  2795. old_router->purpose == ROUTER_PURPOSE_BRIDGE;
  2796. if (routerinfo_is_a_configured_bridge(router) &&
  2797. router->purpose == ROUTER_PURPOSE_BRIDGE &&
  2798. !was_bridge) {
  2799. log_info(LD_DIR, "Replacing non-bridge descriptor with bridge "
  2800. "descriptor for router %s",
  2801. router_describe(router));
  2802. } else {
  2803. log_info(LD_DIR,
  2804. "Dropping descriptor that we already have for router %s",
  2805. router_describe(router));
  2806. *msg = "Router descriptor was not new.";
  2807. routerinfo_free(router);
  2808. return ROUTER_WAS_NOT_NEW;
  2809. }
  2810. }
  2811. if (authdir) {
  2812. if (authdir_wants_to_reject_router(router, msg,
  2813. !from_cache && !from_fetch,
  2814. &authdir_believes_valid)) {
  2815. tor_assert(*msg);
  2816. routerinfo_free(router);
  2817. return ROUTER_AUTHDIR_REJECTS;
  2818. }
  2819. } else if (from_fetch) {
  2820. /* Only check the descriptor digest against the network statuses when
  2821. * we are receiving in response to a fetch. */
  2822. if (!signed_desc_digest_is_recognized(&router->cache_info) &&
  2823. !routerinfo_is_a_configured_bridge(router)) {
  2824. /* We asked for it, so some networkstatus must have listed it when we
  2825. * did. Save it if we're a cache in case somebody else asks for it. */
  2826. log_info(LD_DIR,
  2827. "Received a no-longer-recognized descriptor for router %s",
  2828. router_describe(router));
  2829. *msg = "Router descriptor is not referenced by any network-status.";
  2830. /* Only journal this desc if we'll be serving it. */
  2831. if (!from_cache && should_cache_old_descriptors())
  2832. signed_desc_append_to_journal(&router->cache_info,
  2833. &routerlist->desc_store);
  2834. routerlist_insert_old(routerlist, router);
  2835. return ROUTER_NOT_IN_CONSENSUS_OR_NETWORKSTATUS;
  2836. }
  2837. }
  2838. /* We no longer need a router with this descriptor digest. */
  2839. SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
  2840. {
  2841. routerstatus_t *rs =
  2842. networkstatus_v2_find_mutable_entry(ns, id_digest);
  2843. if (rs && tor_memeq(rs->descriptor_digest,
  2844. router->cache_info.signed_descriptor_digest,
  2845. DIGEST_LEN))
  2846. rs->need_to_mirror = 0;
  2847. });
  2848. if (consensus) {
  2849. routerstatus_t *rs = networkstatus_vote_find_mutable_entry(
  2850. consensus, id_digest);
  2851. if (rs && tor_memeq(rs->descriptor_digest,
  2852. router->cache_info.signed_descriptor_digest,
  2853. DIGEST_LEN)) {
  2854. in_consensus = 1;
  2855. rs->need_to_mirror = 0;
  2856. }
  2857. }
  2858. if (router->purpose == ROUTER_PURPOSE_GENERAL &&
  2859. consensus && !in_consensus && !authdir) {
  2860. /* If it's a general router not listed in the consensus, then don't
  2861. * consider replacing the latest router with it. */
  2862. if (!from_cache && should_cache_old_descriptors())
  2863. signed_desc_append_to_journal(&router->cache_info,
  2864. &routerlist->desc_store);
  2865. routerlist_insert_old(routerlist, router);
  2866. *msg = "Skipping router descriptor: not in consensus.";
  2867. return ROUTER_NOT_IN_CONSENSUS;
  2868. }
  2869. /* If we're reading a bridge descriptor from our cache, and we don't
  2870. * recognize it as one of our currently configured bridges, drop the
  2871. * descriptor. Otherwise we could end up using it as one of our entry
  2872. * guards even if it isn't in our Bridge config lines. */
  2873. if (router->purpose == ROUTER_PURPOSE_BRIDGE && from_cache &&
  2874. !authdir_mode_bridge(options) &&
  2875. !routerinfo_is_a_configured_bridge(router)) {
  2876. log_info(LD_DIR, "Dropping bridge descriptor for %s because we have "
  2877. "no bridge configured at that address.",
  2878. safe_str_client(router_describe(router)));
  2879. *msg = "Router descriptor was not a configured bridge.";
  2880. routerinfo_free(router);
  2881. return ROUTER_WAS_NOT_WANTED;
  2882. }
  2883. /* If we have a router with the same identity key, choose the newer one. */
  2884. if (old_router) {
  2885. if (!in_consensus && (router->cache_info.published_on <=
  2886. old_router->cache_info.published_on)) {
  2887. /* Same key, but old. This one is not listed in the consensus. */
  2888. log_debug(LD_DIR, "Not-new descriptor for router %s",
  2889. router_describe(router));
  2890. /* Only journal this desc if we'll be serving it. */
  2891. if (!from_cache && should_cache_old_descriptors())
  2892. signed_desc_append_to_journal(&router->cache_info,
  2893. &routerlist->desc_store);
  2894. routerlist_insert_old(routerlist, router);
  2895. *msg = "Router descriptor was not new.";
  2896. return ROUTER_WAS_NOT_NEW;
  2897. } else {
  2898. /* Same key, and either new, or listed in the consensus. */
  2899. log_debug(LD_DIR, "Replacing entry for router %s",
  2900. router_describe(router));
  2901. routerlist_replace(routerlist, old_router, router);
  2902. if (!from_cache) {
  2903. signed_desc_append_to_journal(&router->cache_info,
  2904. &routerlist->desc_store);
  2905. }
  2906. directory_set_dirty();
  2907. *msg = authdir_believes_valid ? "Valid server updated" :
  2908. ("Invalid server updated. (This dirserver is marking your "
  2909. "server as unapproved.)");
  2910. return ROUTER_ADDED_SUCCESSFULLY;
  2911. }
  2912. }
  2913. if (!in_consensus && from_cache &&
  2914. router->cache_info.published_on < time(NULL) - OLD_ROUTER_DESC_MAX_AGE) {
  2915. *msg = "Router descriptor was really old.";
  2916. routerinfo_free(router);
  2917. return ROUTER_WAS_NOT_NEW;
  2918. }
  2919. /* We haven't seen a router with this identity before. Add it to the end of
  2920. * the list. */
  2921. routerlist_insert(routerlist, router);
  2922. if (!from_cache) {
  2923. signed_desc_append_to_journal(&router->cache_info,
  2924. &routerlist->desc_store);
  2925. }
  2926. directory_set_dirty();
  2927. return ROUTER_ADDED_SUCCESSFULLY;
  2928. }
  2929. /** Insert <b>ei</b> into the routerlist, or free it. Other arguments are
  2930. * as for router_add_to_routerlist(). Return ROUTER_ADDED_SUCCESSFULLY iff
  2931. * we actually inserted it, ROUTER_BAD_EI otherwise.
  2932. */
  2933. was_router_added_t
  2934. router_add_extrainfo_to_routerlist(extrainfo_t *ei, const char **msg,
  2935. int from_cache, int from_fetch)
  2936. {
  2937. int inserted;
  2938. (void)from_fetch;
  2939. if (msg) *msg = NULL;
  2940. /*XXXX023 Do something with msg */
  2941. inserted = extrainfo_insert(router_get_routerlist(), ei);
  2942. if (inserted && !from_cache)
  2943. signed_desc_append_to_journal(&ei->cache_info,
  2944. &routerlist->extrainfo_store);
  2945. if (inserted)
  2946. return ROUTER_ADDED_SUCCESSFULLY;
  2947. else
  2948. return ROUTER_BAD_EI;
  2949. }
  2950. /** Sorting helper: return &lt;0, 0, or &gt;0 depending on whether the
  2951. * signed_descriptor_t* in *<b>a</b> has an identity digest preceding, equal
  2952. * to, or later than that of *<b>b</b>. */
  2953. static int
  2954. compare_old_routers_by_identity_(const void **_a, const void **_b)
  2955. {
  2956. int i;
  2957. const signed_descriptor_t *r1 = *_a, *r2 = *_b;
  2958. if ((i = fast_memcmp(r1->identity_digest, r2->identity_digest, DIGEST_LEN)))
  2959. return i;
  2960. return (int)(r1->published_on - r2->published_on);
  2961. }
  2962. /** Internal type used to represent how long an old descriptor was valid,
  2963. * where it appeared in the list of old descriptors, and whether it's extra
  2964. * old. Used only by routerlist_remove_old_cached_routers_with_id(). */
  2965. struct duration_idx_t {
  2966. int duration;
  2967. int idx;
  2968. int old;
  2969. };
  2970. /** Sorting helper: compare two duration_idx_t by their duration. */
  2971. static int
  2972. compare_duration_idx_(const void *_d1, const void *_d2)
  2973. {
  2974. const struct duration_idx_t *d1 = _d1;
  2975. const struct duration_idx_t *d2 = _d2;
  2976. return d1->duration - d2->duration;
  2977. }
  2978. /** The range <b>lo</b> through <b>hi</b> inclusive of routerlist->old_routers
  2979. * must contain routerinfo_t with the same identity and with publication time
  2980. * in ascending order. Remove members from this range until there are no more
  2981. * than max_descriptors_per_router() remaining. Start by removing the oldest
  2982. * members from before <b>cutoff</b>, then remove members which were current
  2983. * for the lowest amount of time. The order of members of old_routers at
  2984. * indices <b>lo</b> or higher may be changed.
  2985. */
  2986. static void
  2987. routerlist_remove_old_cached_routers_with_id(time_t now,
  2988. time_t cutoff, int lo, int hi,
  2989. digestset_t *retain)
  2990. {
  2991. int i, n = hi-lo+1;
  2992. unsigned n_extra, n_rmv = 0;
  2993. struct duration_idx_t *lifespans;
  2994. uint8_t *rmv, *must_keep;
  2995. smartlist_t *lst = routerlist->old_routers;
  2996. #if 1
  2997. const char *ident;
  2998. tor_assert(hi < smartlist_len(lst));
  2999. tor_assert(lo <= hi);
  3000. ident = ((signed_descriptor_t*)smartlist_get(lst, lo))->identity_digest;
  3001. for (i = lo+1; i <= hi; ++i) {
  3002. signed_descriptor_t *r = smartlist_get(lst, i);
  3003. tor_assert(tor_memeq(ident, r->identity_digest, DIGEST_LEN));
  3004. }
  3005. #endif
  3006. /* Check whether we need to do anything at all. */
  3007. {
  3008. int mdpr = directory_caches_dir_info(get_options()) ? 2 : 1;
  3009. if (n <= mdpr)
  3010. return;
  3011. n_extra = n - mdpr;
  3012. }
  3013. lifespans = tor_malloc_zero(sizeof(struct duration_idx_t)*n);
  3014. rmv = tor_malloc_zero(sizeof(uint8_t)*n);
  3015. must_keep = tor_malloc_zero(sizeof(uint8_t)*n);
  3016. /* Set lifespans to contain the lifespan and index of each server. */
  3017. /* Set rmv[i-lo]=1 if we're going to remove a server for being too old. */
  3018. for (i = lo; i <= hi; ++i) {
  3019. signed_descriptor_t *r = smartlist_get(lst, i);
  3020. signed_descriptor_t *r_next;
  3021. lifespans[i-lo].idx = i;
  3022. if (r->last_listed_as_valid_until >= now ||
  3023. (retain && digestset_contains(retain, r->signed_descriptor_digest))) {
  3024. must_keep[i-lo] = 1;
  3025. }
  3026. if (i < hi) {
  3027. r_next = smartlist_get(lst, i+1);
  3028. tor_assert(r->published_on <= r_next->published_on);
  3029. lifespans[i-lo].duration = (int)(r_next->published_on - r->published_on);
  3030. } else {
  3031. r_next = NULL;
  3032. lifespans[i-lo].duration = INT_MAX;
  3033. }
  3034. if (!must_keep[i-lo] && r->published_on < cutoff && n_rmv < n_extra) {
  3035. ++n_rmv;
  3036. lifespans[i-lo].old = 1;
  3037. rmv[i-lo] = 1;
  3038. }
  3039. }
  3040. if (n_rmv < n_extra) {
  3041. /**
  3042. * We aren't removing enough servers for being old. Sort lifespans by
  3043. * the duration of liveness, and remove the ones we're not already going to
  3044. * remove based on how long they were alive.
  3045. **/
  3046. qsort(lifespans, n, sizeof(struct duration_idx_t), compare_duration_idx_);
  3047. for (i = 0; i < n && n_rmv < n_extra; ++i) {
  3048. if (!must_keep[lifespans[i].idx-lo] && !lifespans[i].old) {
  3049. rmv[lifespans[i].idx-lo] = 1;
  3050. ++n_rmv;
  3051. }
  3052. }
  3053. }
  3054. i = hi;
  3055. do {
  3056. if (rmv[i-lo])
  3057. routerlist_remove_old(routerlist, smartlist_get(lst, i), i);
  3058. } while (--i >= lo);
  3059. tor_free(must_keep);
  3060. tor_free(rmv);
  3061. tor_free(lifespans);
  3062. }
  3063. /** Deactivate any routers from the routerlist that are more than
  3064. * ROUTER_MAX_AGE seconds old and not recommended by any networkstatuses;
  3065. * remove old routers from the list of cached routers if we have too many.
  3066. */
  3067. void
  3068. routerlist_remove_old_routers(void)
  3069. {
  3070. int i, hi=-1;
  3071. const char *cur_id = NULL;
  3072. time_t now = time(NULL);
  3073. time_t cutoff;
  3074. routerinfo_t *router;
  3075. signed_descriptor_t *sd;
  3076. digestset_t *retain;
  3077. int caches = directory_caches_dir_info(get_options());
  3078. const networkstatus_t *consensus = networkstatus_get_latest_consensus();
  3079. const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
  3080. int have_enough_v2;
  3081. const or_options_t *options = get_options();
  3082. trusted_dirs_remove_old_certs();
  3083. if (!routerlist || !consensus)
  3084. return;
  3085. // routerlist_assert_ok(routerlist);
  3086. /* We need to guess how many router descriptors we will wind up wanting to
  3087. retain, so that we can be sure to allocate a large enough Bloom filter
  3088. to hold the digest set. Overestimating is fine; underestimating is bad.
  3089. */
  3090. {
  3091. /* We'll probably retain everything in the consensus. */
  3092. int n_max_retain = smartlist_len(consensus->routerstatus_list);
  3093. if (caches && networkstatus_v2_list) {
  3094. /* If we care about v2 statuses, we'll retain at most as many as are
  3095. listed any of the v2 statues. This will be at least the length of
  3096. the largest v2 networkstatus, and in the worst case, this set will be
  3097. equal to the sum of the lengths of all v2 consensuses. Take the
  3098. worst case.
  3099. */
  3100. SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
  3101. n_max_retain += smartlist_len(ns->entries));
  3102. }
  3103. retain = digestset_new(n_max_retain);
  3104. }
  3105. cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
  3106. /* Build a list of all the descriptors that _anybody_ lists. */
  3107. if (caches && networkstatus_v2_list) {
  3108. SMARTLIST_FOREACH_BEGIN(networkstatus_v2_list, networkstatus_v2_t *, ns) {
  3109. /* XXXX The inner loop here gets pretty expensive, and actually shows up
  3110. * on some profiles. It may be the reason digestmap_set shows up in
  3111. * profiles too. If instead we kept a per-descriptor digest count of
  3112. * how many networkstatuses recommended each descriptor, and changed
  3113. * that only when the networkstatuses changed, that would be a speed
  3114. * improvement, possibly 1-4% if it also removes digestmap_set from the
  3115. * profile. Not worth it for 0.1.2.x, though. The new directory
  3116. * system will obsolete this whole thing in 0.2.0.x. */
  3117. SMARTLIST_FOREACH_BEGIN(ns->entries, routerstatus_t *, rs) {
  3118. if (rs->published_on >= cutoff)
  3119. digestset_add(retain, rs->descriptor_digest);
  3120. } SMARTLIST_FOREACH_END(rs);
  3121. } SMARTLIST_FOREACH_END(ns);
  3122. }
  3123. /* Retain anything listed in the consensus. */
  3124. if (consensus) {
  3125. SMARTLIST_FOREACH(consensus->routerstatus_list, routerstatus_t *, rs,
  3126. if (rs->published_on >= cutoff)
  3127. digestset_add(retain, rs->descriptor_digest));
  3128. }
  3129. /* If we have a consensus, and nearly as many v2 networkstatuses as we want,
  3130. * we should consider pruning current routers that are too old and that
  3131. * nobody recommends. (If we don't have a consensus or enough v2
  3132. * networkstatuses, then we should get more before we decide to kill
  3133. * routers.) */
  3134. /* we set this to true iff we don't care about v2 info, or we have enough. */
  3135. have_enough_v2 = !caches ||
  3136. !(authdir_mode_any_main(options) || options->FetchV2Networkstatus) ||
  3137. (networkstatus_v2_list &&
  3138. smartlist_len(networkstatus_v2_list) > get_n_v2_authorities() / 2);
  3139. if (have_enough_v2 && consensus) {
  3140. cutoff = now - ROUTER_MAX_AGE;
  3141. /* Remove too-old unrecommended members of routerlist->routers. */
  3142. for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
  3143. router = smartlist_get(routerlist->routers, i);
  3144. if (router->cache_info.published_on <= cutoff &&
  3145. router->cache_info.last_listed_as_valid_until < now &&
  3146. !digestset_contains(retain,
  3147. router->cache_info.signed_descriptor_digest)) {
  3148. /* Too old: remove it. (If we're a cache, just move it into
  3149. * old_routers.) */
  3150. log_info(LD_DIR,
  3151. "Forgetting obsolete (too old) routerinfo for router %s",
  3152. router_describe(router));
  3153. routerlist_remove(routerlist, router, 1, now);
  3154. i--;
  3155. }
  3156. }
  3157. }
  3158. //routerlist_assert_ok(routerlist);
  3159. /* Remove far-too-old members of routerlist->old_routers. */
  3160. cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
  3161. for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
  3162. sd = smartlist_get(routerlist->old_routers, i);
  3163. if (sd->published_on <= cutoff &&
  3164. sd->last_listed_as_valid_until < now &&
  3165. !digestset_contains(retain, sd->signed_descriptor_digest)) {
  3166. /* Too old. Remove it. */
  3167. routerlist_remove_old(routerlist, sd, i--);
  3168. }
  3169. }
  3170. //routerlist_assert_ok(routerlist);
  3171. log_info(LD_DIR, "We have %d live routers and %d old router descriptors.",
  3172. smartlist_len(routerlist->routers),
  3173. smartlist_len(routerlist->old_routers));
  3174. /* Now we might have to look at routerlist->old_routers for extraneous
  3175. * members. (We'd keep all the members if we could, but we need to save
  3176. * space.) First, check whether we have too many router descriptors, total.
  3177. * We're okay with having too many for some given router, so long as the
  3178. * total number doesn't approach max_descriptors_per_router()*len(router).
  3179. */
  3180. if (smartlist_len(routerlist->old_routers) <
  3181. smartlist_len(routerlist->routers))
  3182. goto done;
  3183. /* Sort by identity, then fix indices. */
  3184. smartlist_sort(routerlist->old_routers, compare_old_routers_by_identity_);
  3185. /* Fix indices. */
  3186. for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
  3187. signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
  3188. r->routerlist_index = i;
  3189. }
  3190. /* Iterate through the list from back to front, so when we remove descriptors
  3191. * we don't mess up groups we haven't gotten to. */
  3192. for (i = smartlist_len(routerlist->old_routers)-1; i >= 0; --i) {
  3193. signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
  3194. if (!cur_id) {
  3195. cur_id = r->identity_digest;
  3196. hi = i;
  3197. }
  3198. if (tor_memneq(cur_id, r->identity_digest, DIGEST_LEN)) {
  3199. routerlist_remove_old_cached_routers_with_id(now,
  3200. cutoff, i+1, hi, retain);
  3201. cur_id = r->identity_digest;
  3202. hi = i;
  3203. }
  3204. }
  3205. if (hi>=0)
  3206. routerlist_remove_old_cached_routers_with_id(now, cutoff, 0, hi, retain);
  3207. //routerlist_assert_ok(routerlist);
  3208. done:
  3209. digestset_free(retain);
  3210. router_rebuild_store(RRS_DONT_REMOVE_OLD, &routerlist->desc_store);
  3211. router_rebuild_store(RRS_DONT_REMOVE_OLD,&routerlist->extrainfo_store);
  3212. }
  3213. /** We just added a new set of descriptors. Take whatever extra steps
  3214. * we need. */
  3215. void
  3216. routerlist_descriptors_added(smartlist_t *sl, int from_cache)
  3217. {
  3218. tor_assert(sl);
  3219. control_event_descriptors_changed(sl);
  3220. SMARTLIST_FOREACH_BEGIN(sl, routerinfo_t *, ri) {
  3221. if (ri->purpose == ROUTER_PURPOSE_BRIDGE)
  3222. learned_bridge_descriptor(ri, from_cache);
  3223. if (ri->needs_retest_if_added) {
  3224. ri->needs_retest_if_added = 0;
  3225. dirserv_single_reachability_test(approx_time(), ri);
  3226. }
  3227. } SMARTLIST_FOREACH_END(ri);
  3228. }
  3229. /**
  3230. * Code to parse a single router descriptor and insert it into the
  3231. * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
  3232. * descriptor was well-formed but could not be added; and 1 if the
  3233. * descriptor was added.
  3234. *
  3235. * If we don't add it and <b>msg</b> is not NULL, then assign to
  3236. * *<b>msg</b> a static string describing the reason for refusing the
  3237. * descriptor.
  3238. *
  3239. * This is used only by the controller.
  3240. */
  3241. int
  3242. router_load_single_router(const char *s, uint8_t purpose, int cache,
  3243. const char **msg)
  3244. {
  3245. routerinfo_t *ri;
  3246. was_router_added_t r;
  3247. smartlist_t *lst;
  3248. char annotation_buf[ROUTER_ANNOTATION_BUF_LEN];
  3249. tor_assert(msg);
  3250. *msg = NULL;
  3251. tor_snprintf(annotation_buf, sizeof(annotation_buf),
  3252. "@source controller\n"
  3253. "@purpose %s\n", router_purpose_to_string(purpose));
  3254. if (!(ri = router_parse_entry_from_string(s, NULL, 1, 0, annotation_buf))) {
  3255. log_warn(LD_DIR, "Error parsing router descriptor; dropping.");
  3256. *msg = "Couldn't parse router descriptor.";
  3257. return -1;
  3258. }
  3259. tor_assert(ri->purpose == purpose);
  3260. if (router_is_me(ri)) {
  3261. log_warn(LD_DIR, "Router's identity key matches mine; dropping.");
  3262. *msg = "Router's identity key matches mine.";
  3263. routerinfo_free(ri);
  3264. return 0;
  3265. }
  3266. if (!cache) /* obey the preference of the controller */
  3267. ri->cache_info.do_not_cache = 1;
  3268. lst = smartlist_new();
  3269. smartlist_add(lst, ri);
  3270. routers_update_status_from_consensus_networkstatus(lst, 0);
  3271. r = router_add_to_routerlist(ri, msg, 0, 0);
  3272. if (!WRA_WAS_ADDED(r)) {
  3273. /* we've already assigned to *msg now, and ri is already freed */
  3274. tor_assert(*msg);
  3275. if (r == ROUTER_AUTHDIR_REJECTS)
  3276. log_warn(LD_DIR, "Couldn't add router to list: %s Dropping.", *msg);
  3277. smartlist_free(lst);
  3278. return 0;
  3279. } else {
  3280. routerlist_descriptors_added(lst, 0);
  3281. smartlist_free(lst);
  3282. log_debug(LD_DIR, "Added router to list");
  3283. return 1;
  3284. }
  3285. }
  3286. /** Given a string <b>s</b> containing some routerdescs, parse it and put the
  3287. * routers into our directory. If saved_location is SAVED_NOWHERE, the routers
  3288. * are in response to a query to the network: cache them by adding them to
  3289. * the journal.
  3290. *
  3291. * Return the number of routers actually added.
  3292. *
  3293. * If <b>requested_fingerprints</b> is provided, it must contain a list of
  3294. * uppercased fingerprints. Do not update any router whose
  3295. * fingerprint is not on the list; after updating a router, remove its
  3296. * fingerprint from the list.
  3297. *
  3298. * If <b>descriptor_digests</b> is non-zero, then the requested_fingerprints
  3299. * are descriptor digests. Otherwise they are identity digests.
  3300. */
  3301. int
  3302. router_load_routers_from_string(const char *s, const char *eos,
  3303. saved_location_t saved_location,
  3304. smartlist_t *requested_fingerprints,
  3305. int descriptor_digests,
  3306. const char *prepend_annotations)
  3307. {
  3308. smartlist_t *routers = smartlist_new(), *changed = smartlist_new();
  3309. char fp[HEX_DIGEST_LEN+1];
  3310. const char *msg;
  3311. int from_cache = (saved_location != SAVED_NOWHERE);
  3312. int allow_annotations = (saved_location != SAVED_NOWHERE);
  3313. int any_changed = 0;
  3314. router_parse_list_from_string(&s, eos, routers, saved_location, 0,
  3315. allow_annotations, prepend_annotations);
  3316. routers_update_status_from_consensus_networkstatus(routers, !from_cache);
  3317. log_info(LD_DIR, "%d elements to add", smartlist_len(routers));
  3318. SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
  3319. was_router_added_t r;
  3320. char d[DIGEST_LEN];
  3321. if (requested_fingerprints) {
  3322. base16_encode(fp, sizeof(fp), descriptor_digests ?
  3323. ri->cache_info.signed_descriptor_digest :
  3324. ri->cache_info.identity_digest,
  3325. DIGEST_LEN);
  3326. if (smartlist_contains_string(requested_fingerprints, fp)) {
  3327. smartlist_string_remove(requested_fingerprints, fp);
  3328. } else {
  3329. char *requested =
  3330. smartlist_join_strings(requested_fingerprints," ",0,NULL);
  3331. log_warn(LD_DIR,
  3332. "We received a router descriptor with a fingerprint (%s) "
  3333. "that we never requested. (We asked for: %s.) Dropping.",
  3334. fp, requested);
  3335. tor_free(requested);
  3336. routerinfo_free(ri);
  3337. continue;
  3338. }
  3339. }
  3340. memcpy(d, ri->cache_info.signed_descriptor_digest, DIGEST_LEN);
  3341. r = router_add_to_routerlist(ri, &msg, from_cache, !from_cache);
  3342. if (WRA_WAS_ADDED(r)) {
  3343. any_changed++;
  3344. smartlist_add(changed, ri);
  3345. routerlist_descriptors_added(changed, from_cache);
  3346. smartlist_clear(changed);
  3347. } else if (WRA_WAS_REJECTED(r)) {
  3348. download_status_t *dl_status;
  3349. dl_status = router_get_dl_status_by_descriptor_digest(d);
  3350. if (dl_status) {
  3351. log_info(LD_GENERAL, "Marking router %s as never downloadable",
  3352. hex_str(d, DIGEST_LEN));
  3353. download_status_mark_impossible(dl_status);
  3354. }
  3355. }
  3356. } SMARTLIST_FOREACH_END(ri);
  3357. routerlist_assert_ok(routerlist);
  3358. if (any_changed)
  3359. router_rebuild_store(0, &routerlist->desc_store);
  3360. smartlist_free(routers);
  3361. smartlist_free(changed);
  3362. return any_changed;
  3363. }
  3364. /** Parse one or more extrainfos from <b>s</b> (ending immediately before
  3365. * <b>eos</b> if <b>eos</b> is present). Other arguments are as for
  3366. * router_load_routers_from_string(). */
  3367. void
  3368. router_load_extrainfo_from_string(const char *s, const char *eos,
  3369. saved_location_t saved_location,
  3370. smartlist_t *requested_fingerprints,
  3371. int descriptor_digests)
  3372. {
  3373. smartlist_t *extrainfo_list = smartlist_new();
  3374. const char *msg;
  3375. int from_cache = (saved_location != SAVED_NOWHERE);
  3376. router_parse_list_from_string(&s, eos, extrainfo_list, saved_location, 1, 0,
  3377. NULL);
  3378. log_info(LD_DIR, "%d elements to add", smartlist_len(extrainfo_list));
  3379. SMARTLIST_FOREACH_BEGIN(extrainfo_list, extrainfo_t *, ei) {
  3380. was_router_added_t added =
  3381. router_add_extrainfo_to_routerlist(ei, &msg, from_cache, !from_cache);
  3382. if (WRA_WAS_ADDED(added) && requested_fingerprints) {
  3383. char fp[HEX_DIGEST_LEN+1];
  3384. base16_encode(fp, sizeof(fp), descriptor_digests ?
  3385. ei->cache_info.signed_descriptor_digest :
  3386. ei->cache_info.identity_digest,
  3387. DIGEST_LEN);
  3388. smartlist_string_remove(requested_fingerprints, fp);
  3389. /* We silently let people stuff us with extrainfos we didn't ask for,
  3390. * so long as we would have wanted them anyway. Since we always fetch
  3391. * all the extrainfos we want, and we never actually act on them
  3392. * inside Tor, this should be harmless. */
  3393. }
  3394. } SMARTLIST_FOREACH_END(ei);
  3395. routerlist_assert_ok(routerlist);
  3396. router_rebuild_store(0, &router_get_routerlist()->extrainfo_store);
  3397. smartlist_free(extrainfo_list);
  3398. }
  3399. /** Return true iff any networkstatus includes a descriptor whose digest
  3400. * is that of <b>desc</b>. */
  3401. static int
  3402. signed_desc_digest_is_recognized(signed_descriptor_t *desc)
  3403. {
  3404. const routerstatus_t *rs;
  3405. networkstatus_t *consensus = networkstatus_get_latest_consensus();
  3406. int caches = directory_caches_dir_info(get_options());
  3407. const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
  3408. if (consensus) {
  3409. rs = networkstatus_vote_find_entry(consensus, desc->identity_digest);
  3410. if (rs && tor_memeq(rs->descriptor_digest,
  3411. desc->signed_descriptor_digest, DIGEST_LEN))
  3412. return 1;
  3413. }
  3414. if (caches && networkstatus_v2_list) {
  3415. SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
  3416. {
  3417. if (!(rs = networkstatus_v2_find_entry(ns, desc->identity_digest)))
  3418. continue;
  3419. if (tor_memeq(rs->descriptor_digest,
  3420. desc->signed_descriptor_digest, DIGEST_LEN))
  3421. return 1;
  3422. });
  3423. }
  3424. return 0;
  3425. }
  3426. /** Update downloads for router descriptors and/or microdescriptors as
  3427. * appropriate. */
  3428. void
  3429. update_all_descriptor_downloads(time_t now)
  3430. {
  3431. if (get_options()->DisableNetwork)
  3432. return;
  3433. update_router_descriptor_downloads(now);
  3434. update_microdesc_downloads(now);
  3435. launch_dummy_descriptor_download_as_needed(now, get_options());
  3436. }
  3437. /** Clear all our timeouts for fetching v2 and v3 directory stuff, and then
  3438. * give it all a try again. */
  3439. void
  3440. routerlist_retry_directory_downloads(time_t now)
  3441. {
  3442. router_reset_status_download_failures();
  3443. router_reset_descriptor_download_failures();
  3444. if (get_options()->DisableNetwork)
  3445. return;
  3446. update_networkstatus_downloads(now);
  3447. update_all_descriptor_downloads(now);
  3448. }
  3449. /** Return true iff <b>router</b> does not permit exit streams.
  3450. */
  3451. int
  3452. router_exit_policy_rejects_all(const routerinfo_t *router)
  3453. {
  3454. return router->policy_is_reject_star;
  3455. }
  3456. /** Create an directory server at <b>address</b>:<b>port</b>, with OR identity
  3457. * key <b>digest</b>. If <b>address</b> is NULL, add ourself. If
  3458. * <b>is_authority</b>, this is a directory authority. Return the new
  3459. * directory server entry on success or NULL on failure. */
  3460. static dir_server_t *
  3461. dir_server_new(int is_authority,
  3462. const char *nickname,
  3463. const tor_addr_t *addr,
  3464. const char *hostname,
  3465. uint16_t dir_port, uint16_t or_port,
  3466. const char *digest, const char *v3_auth_digest,
  3467. dirinfo_type_t type,
  3468. double weight)
  3469. {
  3470. dir_server_t *ent;
  3471. uint32_t a;
  3472. char *hostname_ = NULL;
  3473. if (weight < 0)
  3474. return NULL;
  3475. if (tor_addr_family(addr) == AF_INET)
  3476. a = tor_addr_to_ipv4h(addr);
  3477. else
  3478. return NULL; /*XXXX Support IPv6 */
  3479. if (!hostname)
  3480. hostname_ = tor_dup_addr(addr);
  3481. else
  3482. hostname_ = tor_strdup(hostname);
  3483. ent = tor_malloc_zero(sizeof(dir_server_t));
  3484. ent->nickname = nickname ? tor_strdup(nickname) : NULL;
  3485. ent->address = hostname_;
  3486. ent->addr = a;
  3487. ent->dir_port = dir_port;
  3488. ent->or_port = or_port;
  3489. ent->is_running = 1;
  3490. ent->is_authority = is_authority;
  3491. ent->type = type;
  3492. ent->weight = weight;
  3493. memcpy(ent->digest, digest, DIGEST_LEN);
  3494. if (v3_auth_digest && (type & V3_DIRINFO))
  3495. memcpy(ent->v3_identity_digest, v3_auth_digest, DIGEST_LEN);
  3496. if (nickname)
  3497. tor_asprintf(&ent->description, "directory server \"%s\" at %s:%d",
  3498. nickname, hostname, (int)dir_port);
  3499. else
  3500. tor_asprintf(&ent->description, "directory server at %s:%d",
  3501. hostname, (int)dir_port);
  3502. ent->fake_status.addr = ent->addr;
  3503. memcpy(ent->fake_status.identity_digest, digest, DIGEST_LEN);
  3504. if (nickname)
  3505. strlcpy(ent->fake_status.nickname, nickname,
  3506. sizeof(ent->fake_status.nickname));
  3507. else
  3508. ent->fake_status.nickname[0] = '\0';
  3509. ent->fake_status.dir_port = ent->dir_port;
  3510. ent->fake_status.or_port = ent->or_port;
  3511. return ent;
  3512. }
  3513. /** Create an authoritative directory server at
  3514. * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
  3515. * <b>address</b> is NULL, add ourself. Return the new trusted directory
  3516. * server entry on success or NULL if we couldn't add it. */
  3517. dir_server_t *
  3518. trusted_dir_server_new(const char *nickname, const char *address,
  3519. uint16_t dir_port, uint16_t or_port,
  3520. const char *digest, const char *v3_auth_digest,
  3521. dirinfo_type_t type, double weight)
  3522. {
  3523. uint32_t a;
  3524. tor_addr_t addr;
  3525. char *hostname=NULL;
  3526. dir_server_t *result;
  3527. if (!address) { /* The address is us; we should guess. */
  3528. if (resolve_my_address(LOG_WARN, get_options(), &a, &hostname) < 0) {
  3529. log_warn(LD_CONFIG,
  3530. "Couldn't find a suitable address when adding ourself as a "
  3531. "trusted directory server.");
  3532. return NULL;
  3533. }
  3534. } else {
  3535. if (tor_lookup_hostname(address, &a)) {
  3536. log_warn(LD_CONFIG,
  3537. "Unable to lookup address for directory server at '%s'",
  3538. address);
  3539. return NULL;
  3540. }
  3541. hostname = tor_strdup(address);
  3542. }
  3543. tor_addr_from_ipv4h(&addr, a);
  3544. result = dir_server_new(1, nickname, &addr, hostname,
  3545. dir_port, or_port, digest,
  3546. v3_auth_digest, type, weight);
  3547. tor_free(hostname);
  3548. return result;
  3549. }
  3550. /** Return a new dir_server_t for a fallback directory server at
  3551. * <b>addr</b>:<b>or_port</b>/<b>dir_port</b>, with identity key digest
  3552. * <b>id_digest</b> */
  3553. dir_server_t *
  3554. fallback_dir_server_new(const tor_addr_t *addr,
  3555. uint16_t dir_port, uint16_t or_port,
  3556. const char *id_digest, double weight)
  3557. {
  3558. return dir_server_new(0, NULL, addr, NULL, dir_port, or_port, id_digest,
  3559. NULL, ALL_DIRINFO, weight);
  3560. }
  3561. /** Add a directory server to the global list(s). */
  3562. void
  3563. dir_server_add(dir_server_t *ent)
  3564. {
  3565. if (!trusted_dir_servers)
  3566. trusted_dir_servers = smartlist_new();
  3567. if (!fallback_dir_servers)
  3568. fallback_dir_servers = smartlist_new();
  3569. if (ent->is_authority)
  3570. smartlist_add(trusted_dir_servers, ent);
  3571. smartlist_add(fallback_dir_servers, ent);
  3572. router_dir_info_changed();
  3573. }
  3574. /** Free storage held in <b>cert</b>. */
  3575. void
  3576. authority_cert_free(authority_cert_t *cert)
  3577. {
  3578. if (!cert)
  3579. return;
  3580. tor_free(cert->cache_info.signed_descriptor_body);
  3581. crypto_pk_free(cert->signing_key);
  3582. crypto_pk_free(cert->identity_key);
  3583. tor_free(cert);
  3584. }
  3585. /** Free storage held in <b>ds</b>. */
  3586. static void
  3587. dir_server_free(dir_server_t *ds)
  3588. {
  3589. if (!ds)
  3590. return;
  3591. tor_free(ds->nickname);
  3592. tor_free(ds->description);
  3593. tor_free(ds->address);
  3594. tor_free(ds);
  3595. }
  3596. /** Remove all members from the list of dir servers. */
  3597. void
  3598. clear_dir_servers(void)
  3599. {
  3600. if (fallback_dir_servers) {
  3601. SMARTLIST_FOREACH(fallback_dir_servers, dir_server_t *, ent,
  3602. dir_server_free(ent));
  3603. smartlist_clear(fallback_dir_servers);
  3604. } else {
  3605. fallback_dir_servers = smartlist_new();
  3606. }
  3607. if (trusted_dir_servers) {
  3608. smartlist_clear(trusted_dir_servers);
  3609. } else {
  3610. trusted_dir_servers = smartlist_new();
  3611. }
  3612. router_dir_info_changed();
  3613. }
  3614. /** Return 1 if any trusted dir server supports v1 directories,
  3615. * else return 0. */
  3616. int
  3617. any_trusted_dir_is_v1_authority(void)
  3618. {
  3619. if (trusted_dir_servers)
  3620. return get_n_authorities(V1_DIRINFO) > 0;
  3621. return 0;
  3622. }
  3623. /** For every current directory connection whose purpose is <b>purpose</b>,
  3624. * and where the resource being downloaded begins with <b>prefix</b>, split
  3625. * rest of the resource into base16 fingerprints (or base64 fingerprints if
  3626. * purpose==DIR_PURPPOSE_FETCH_MICRODESC), decode them, and set the
  3627. * corresponding elements of <b>result</b> to a nonzero value.
  3628. */
  3629. static void
  3630. list_pending_downloads(digestmap_t *result,
  3631. int purpose, const char *prefix)
  3632. {
  3633. const size_t p_len = strlen(prefix);
  3634. smartlist_t *tmp = smartlist_new();
  3635. smartlist_t *conns = get_connection_array();
  3636. int flags = DSR_HEX;
  3637. if (purpose == DIR_PURPOSE_FETCH_MICRODESC)
  3638. flags = DSR_DIGEST256|DSR_BASE64;
  3639. tor_assert(result);
  3640. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  3641. if (conn->type == CONN_TYPE_DIR &&
  3642. conn->purpose == purpose &&
  3643. !conn->marked_for_close) {
  3644. const char *resource = TO_DIR_CONN(conn)->requested_resource;
  3645. if (!strcmpstart(resource, prefix))
  3646. dir_split_resource_into_fingerprints(resource + p_len,
  3647. tmp, NULL, flags);
  3648. }
  3649. } SMARTLIST_FOREACH_END(conn);
  3650. SMARTLIST_FOREACH(tmp, char *, d,
  3651. {
  3652. digestmap_set(result, d, (void*)1);
  3653. tor_free(d);
  3654. });
  3655. smartlist_free(tmp);
  3656. }
  3657. /** For every router descriptor (or extra-info document if <b>extrainfo</b> is
  3658. * true) we are currently downloading by descriptor digest, set result[d] to
  3659. * (void*)1. */
  3660. static void
  3661. list_pending_descriptor_downloads(digestmap_t *result, int extrainfo)
  3662. {
  3663. int purpose =
  3664. extrainfo ? DIR_PURPOSE_FETCH_EXTRAINFO : DIR_PURPOSE_FETCH_SERVERDESC;
  3665. list_pending_downloads(result, purpose, "d/");
  3666. }
  3667. /** For every microdescriptor we are currently downloading by descriptor
  3668. * digest, set result[d] to (void*)1. (Note that microdescriptor digests
  3669. * are 256-bit, and digestmap_t only holds 160-bit digests, so we're only
  3670. * getting the first 20 bytes of each digest here.)
  3671. *
  3672. * XXXX Let there be a digestmap256_t, and use that instead.
  3673. */
  3674. void
  3675. list_pending_microdesc_downloads(digestmap_t *result)
  3676. {
  3677. list_pending_downloads(result, DIR_PURPOSE_FETCH_MICRODESC, "d/");
  3678. }
  3679. /** Launch downloads for all the descriptors whose digests or digests256
  3680. * are listed as digests[i] for lo <= i < hi. (Lo and hi may be out of
  3681. * range.) If <b>source</b> is given, download from <b>source</b>;
  3682. * otherwise, download from an appropriate random directory server.
  3683. */
  3684. static void
  3685. initiate_descriptor_downloads(const routerstatus_t *source,
  3686. int purpose,
  3687. smartlist_t *digests,
  3688. int lo, int hi, int pds_flags)
  3689. {
  3690. int i, n = hi-lo;
  3691. char *resource, *cp;
  3692. size_t r_len;
  3693. int digest_len = DIGEST_LEN, enc_digest_len = HEX_DIGEST_LEN;
  3694. char sep = '+';
  3695. int b64_256 = 0;
  3696. if (purpose == DIR_PURPOSE_FETCH_MICRODESC) {
  3697. /* Microdescriptors are downloaded by "-"-separated base64-encoded
  3698. * 256-bit digests. */
  3699. digest_len = DIGEST256_LEN;
  3700. enc_digest_len = BASE64_DIGEST256_LEN;
  3701. sep = '-';
  3702. b64_256 = 1;
  3703. }
  3704. if (n <= 0)
  3705. return;
  3706. if (lo < 0)
  3707. lo = 0;
  3708. if (hi > smartlist_len(digests))
  3709. hi = smartlist_len(digests);
  3710. r_len = 8 + (enc_digest_len+1)*n;
  3711. cp = resource = tor_malloc(r_len);
  3712. memcpy(cp, "d/", 2);
  3713. cp += 2;
  3714. for (i = lo; i < hi; ++i) {
  3715. if (b64_256) {
  3716. digest256_to_base64(cp, smartlist_get(digests, i));
  3717. } else {
  3718. base16_encode(cp, r_len-(cp-resource),
  3719. smartlist_get(digests,i), digest_len);
  3720. }
  3721. cp += enc_digest_len;
  3722. *cp++ = sep;
  3723. }
  3724. memcpy(cp-1, ".z", 3);
  3725. if (source) {
  3726. /* We know which authority we want. */
  3727. directory_initiate_command_routerstatus(source, purpose,
  3728. ROUTER_PURPOSE_GENERAL,
  3729. DIRIND_ONEHOP,
  3730. resource, NULL, 0, 0);
  3731. } else {
  3732. directory_get_from_dirserver(purpose, ROUTER_PURPOSE_GENERAL, resource,
  3733. pds_flags);
  3734. }
  3735. tor_free(resource);
  3736. }
  3737. /** Max amount of hashes to download per request.
  3738. * Since squid does not like URLs >= 4096 bytes we limit it to 96.
  3739. * 4096 - strlen(http://255.255.255.255/tor/server/d/.z) == 4058
  3740. * 4058/41 (40 for the hash and 1 for the + that separates them) => 98
  3741. * So use 96 because it's a nice number.
  3742. */
  3743. #define MAX_DL_PER_REQUEST 96
  3744. #define MAX_MICRODESC_DL_PER_REQUEST 92
  3745. /** Don't split our requests so finely that we are requesting fewer than
  3746. * this number per server. */
  3747. #define MIN_DL_PER_REQUEST 4
  3748. /** To prevent a single screwy cache from confusing us by selective reply,
  3749. * try to split our requests into at least this many requests. */
  3750. #define MIN_REQUESTS 3
  3751. /** If we want fewer than this many descriptors, wait until we
  3752. * want more, or until MAX_CLIENT_INTERVAL_WITHOUT_REQUEST has
  3753. * passed. */
  3754. #define MAX_DL_TO_DELAY 16
  3755. /** When directory clients have only a few servers to request, they batch
  3756. * them until they have more, or until this amount of time has passed. */
  3757. #define MAX_CLIENT_INTERVAL_WITHOUT_REQUEST (10*60)
  3758. /** Given a <b>purpose</b> (FETCH_MICRODESC or FETCH_SERVERDESC) and a list of
  3759. * router descriptor digests or microdescriptor digest256s in
  3760. * <b>downloadable</b>, decide whether to delay fetching until we have more.
  3761. * If we don't want to delay, launch one or more requests to the appropriate
  3762. * directory authorities.
  3763. */
  3764. void
  3765. launch_descriptor_downloads(int purpose,
  3766. smartlist_t *downloadable,
  3767. const routerstatus_t *source, time_t now)
  3768. {
  3769. int should_delay = 0, n_downloadable;
  3770. const or_options_t *options = get_options();
  3771. const char *descname;
  3772. tor_assert(purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
  3773. purpose == DIR_PURPOSE_FETCH_MICRODESC);
  3774. descname = (purpose == DIR_PURPOSE_FETCH_SERVERDESC) ?
  3775. "routerdesc" : "microdesc";
  3776. n_downloadable = smartlist_len(downloadable);
  3777. if (!directory_fetches_dir_info_early(options)) {
  3778. if (n_downloadable >= MAX_DL_TO_DELAY) {
  3779. log_debug(LD_DIR,
  3780. "There are enough downloadable %ss to launch requests.",
  3781. descname);
  3782. should_delay = 0;
  3783. } else {
  3784. should_delay = (last_descriptor_download_attempted +
  3785. MAX_CLIENT_INTERVAL_WITHOUT_REQUEST) > now;
  3786. if (!should_delay && n_downloadable) {
  3787. if (last_descriptor_download_attempted) {
  3788. log_info(LD_DIR,
  3789. "There are not many downloadable %ss, but we've "
  3790. "been waiting long enough (%d seconds). Downloading.",
  3791. descname,
  3792. (int)(now-last_descriptor_download_attempted));
  3793. } else {
  3794. log_info(LD_DIR,
  3795. "There are not many downloadable %ss, but we haven't "
  3796. "tried downloading descriptors recently. Downloading.",
  3797. descname);
  3798. }
  3799. }
  3800. }
  3801. }
  3802. if (! should_delay && n_downloadable) {
  3803. int i, n_per_request;
  3804. const char *req_plural = "", *rtr_plural = "";
  3805. int pds_flags = PDS_RETRY_IF_NO_SERVERS;
  3806. if (! authdir_mode_any_nonhidserv(options)) {
  3807. /* If we wind up going to the authorities, we want to only open one
  3808. * connection to each authority at a time, so that we don't overload
  3809. * them. We do this by setting PDS_NO_EXISTING_SERVERDESC_FETCH
  3810. * regardless of whether we're a cache or not; it gets ignored if we're
  3811. * not calling router_pick_trusteddirserver.
  3812. *
  3813. * Setting this flag can make initiate_descriptor_downloads() ignore
  3814. * requests. We need to make sure that we do in fact call
  3815. * update_router_descriptor_downloads() later on, once the connections
  3816. * have succeeded or failed.
  3817. */
  3818. pds_flags |= (purpose == DIR_PURPOSE_FETCH_MICRODESC) ?
  3819. PDS_NO_EXISTING_MICRODESC_FETCH :
  3820. PDS_NO_EXISTING_SERVERDESC_FETCH;
  3821. }
  3822. n_per_request = CEIL_DIV(n_downloadable, MIN_REQUESTS);
  3823. if (purpose == DIR_PURPOSE_FETCH_MICRODESC) {
  3824. if (n_per_request > MAX_MICRODESC_DL_PER_REQUEST)
  3825. n_per_request = MAX_MICRODESC_DL_PER_REQUEST;
  3826. } else {
  3827. if (n_per_request > MAX_DL_PER_REQUEST)
  3828. n_per_request = MAX_DL_PER_REQUEST;
  3829. }
  3830. if (n_per_request < MIN_DL_PER_REQUEST)
  3831. n_per_request = MIN_DL_PER_REQUEST;
  3832. if (n_downloadable > n_per_request)
  3833. req_plural = rtr_plural = "s";
  3834. else if (n_downloadable > 1)
  3835. rtr_plural = "s";
  3836. log_info(LD_DIR,
  3837. "Launching %d request%s for %d %s%s, %d at a time",
  3838. CEIL_DIV(n_downloadable, n_per_request), req_plural,
  3839. n_downloadable, descname, rtr_plural, n_per_request);
  3840. smartlist_sort_digests(downloadable);
  3841. for (i=0; i < n_downloadable; i += n_per_request) {
  3842. initiate_descriptor_downloads(source, purpose,
  3843. downloadable, i, i+n_per_request,
  3844. pds_flags);
  3845. }
  3846. last_descriptor_download_attempted = now;
  3847. }
  3848. }
  3849. /** Launch downloads for router status as needed, using the strategy used by
  3850. * authorities and caches: based on the v2 networkstatuses we have, download
  3851. * every descriptor we don't have but would serve, from a random authority
  3852. * that lists it. */
  3853. static void
  3854. update_router_descriptor_cache_downloads_v2(time_t now)
  3855. {
  3856. smartlist_t **downloadable; /* For each authority, what can we dl from it? */
  3857. smartlist_t **download_from; /* ... and, what will we dl from it? */
  3858. digestmap_t *map; /* Which descs are in progress, or assigned? */
  3859. int i, j, n;
  3860. int n_download;
  3861. const or_options_t *options = get_options();
  3862. const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
  3863. if (! directory_fetches_dir_info_early(options)) {
  3864. log_warn(LD_BUG, "Called update_router_descriptor_cache_downloads_v2() "
  3865. "on a non-dir-mirror?");
  3866. }
  3867. if (!networkstatus_v2_list || !smartlist_len(networkstatus_v2_list))
  3868. return;
  3869. map = digestmap_new();
  3870. n = smartlist_len(networkstatus_v2_list);
  3871. downloadable = tor_malloc_zero(sizeof(smartlist_t*) * n);
  3872. download_from = tor_malloc_zero(sizeof(smartlist_t*) * n);
  3873. /* Set map[d]=1 for the digest of every descriptor that we are currently
  3874. * downloading. */
  3875. list_pending_descriptor_downloads(map, 0);
  3876. /* For the digest of every descriptor that we don't have, and that we aren't
  3877. * downloading, add d to downloadable[i] if the i'th networkstatus knows
  3878. * about that descriptor, and we haven't already failed to get that
  3879. * descriptor from the corresponding authority.
  3880. */
  3881. n_download = 0;
  3882. SMARTLIST_FOREACH_BEGIN(networkstatus_v2_list, networkstatus_v2_t *, ns) {
  3883. dir_server_t *ds;
  3884. smartlist_t *dl;
  3885. dl = downloadable[ns_sl_idx] = smartlist_new();
  3886. download_from[ns_sl_idx] = smartlist_new();
  3887. if (ns->published_on + MAX_NETWORKSTATUS_AGE+10*60 < now) {
  3888. /* Don't download if the networkstatus is almost ancient. */
  3889. /* Actually, I suspect what's happening here is that we ask
  3890. * for the descriptor when we have a given networkstatus,
  3891. * and then we get a newer networkstatus, and then we receive
  3892. * the descriptor. Having a networkstatus actually expire is
  3893. * probably a rare event, and we'll probably be happiest if
  3894. * we take this clause out. -RD */
  3895. continue;
  3896. }
  3897. /* Don't try dirservers that we think are down -- we might have
  3898. * just tried them and just marked them as down. */
  3899. ds = router_get_trusteddirserver_by_digest(ns->identity_digest);
  3900. if (ds && !ds->is_running)
  3901. continue;
  3902. SMARTLIST_FOREACH_BEGIN(ns->entries, routerstatus_t * , rs) {
  3903. if (!rs->need_to_mirror)
  3904. continue;
  3905. if (router_get_by_descriptor_digest(rs->descriptor_digest)) {
  3906. log_warn(LD_BUG,
  3907. "We have a router descriptor, but need_to_mirror=1.");
  3908. rs->need_to_mirror = 0;
  3909. continue;
  3910. }
  3911. if (authdir_mode(options) && dirserv_would_reject_router(rs)) {
  3912. rs->need_to_mirror = 0;
  3913. continue;
  3914. }
  3915. if (digestmap_get(map, rs->descriptor_digest)) {
  3916. /* We're downloading it already. */
  3917. continue;
  3918. } else {
  3919. /* We could download it from this guy. */
  3920. smartlist_add(dl, rs->descriptor_digest);
  3921. ++n_download;
  3922. }
  3923. } SMARTLIST_FOREACH_END(rs);
  3924. } SMARTLIST_FOREACH_END(ns);
  3925. /* At random, assign descriptors to authorities such that:
  3926. * - if d is a member of some downloadable[x], d is a member of some
  3927. * download_from[y]. (Everything we want to download, we try to download
  3928. * from somebody.)
  3929. * - If d is a member of download_from[y], d is a member of downloadable[y].
  3930. * (We only try to download descriptors from authorities who claim to have
  3931. * them.)
  3932. * - No d is a member of download_from[x] and download_from[y] s.t. x != y.
  3933. * (We don't try to download anything from two authorities concurrently.)
  3934. */
  3935. while (n_download) {
  3936. int which_ns = crypto_rand_int(n);
  3937. smartlist_t *dl = downloadable[which_ns];
  3938. int idx;
  3939. char *d;
  3940. if (!smartlist_len(dl))
  3941. continue;
  3942. idx = crypto_rand_int(smartlist_len(dl));
  3943. d = smartlist_get(dl, idx);
  3944. if (! digestmap_get(map, d)) {
  3945. smartlist_add(download_from[which_ns], d);
  3946. digestmap_set(map, d, (void*) 1);
  3947. }
  3948. smartlist_del(dl, idx);
  3949. --n_download;
  3950. }
  3951. /* Now, we can actually launch our requests. */
  3952. for (i=0; i<n; ++i) {
  3953. networkstatus_v2_t *ns = smartlist_get(networkstatus_v2_list, i);
  3954. dir_server_t *ds =
  3955. router_get_trusteddirserver_by_digest(ns->identity_digest);
  3956. smartlist_t *dl = download_from[i];
  3957. int pds_flags = PDS_RETRY_IF_NO_SERVERS;
  3958. if (! authdir_mode_any_nonhidserv(options))
  3959. pds_flags |= PDS_NO_EXISTING_SERVERDESC_FETCH; /* XXXX ignored*/
  3960. if (!ds) {
  3961. log_info(LD_DIR, "Networkstatus with no corresponding authority!");
  3962. continue;
  3963. }
  3964. if (! smartlist_len(dl))
  3965. continue;
  3966. log_info(LD_DIR, "Requesting %d descriptors from authority \"%s\"",
  3967. smartlist_len(dl), ds->nickname);
  3968. for (j=0; j < smartlist_len(dl); j += MAX_DL_PER_REQUEST) {
  3969. initiate_descriptor_downloads(&(ds->fake_status),
  3970. DIR_PURPOSE_FETCH_SERVERDESC, dl, j,
  3971. j+MAX_DL_PER_REQUEST, pds_flags);
  3972. }
  3973. }
  3974. for (i=0; i<n; ++i) {
  3975. smartlist_free(download_from[i]);
  3976. smartlist_free(downloadable[i]);
  3977. }
  3978. tor_free(download_from);
  3979. tor_free(downloadable);
  3980. digestmap_free(map,NULL);
  3981. }
  3982. /** For any descriptor that we want that's currently listed in
  3983. * <b>consensus</b>, download it as appropriate. */
  3984. void
  3985. update_consensus_router_descriptor_downloads(time_t now, int is_vote,
  3986. networkstatus_t *consensus)
  3987. {
  3988. const or_options_t *options = get_options();
  3989. digestmap_t *map = NULL;
  3990. smartlist_t *no_longer_old = smartlist_new();
  3991. smartlist_t *downloadable = smartlist_new();
  3992. routerstatus_t *source = NULL;
  3993. int authdir = authdir_mode(options);
  3994. int n_delayed=0, n_have=0, n_would_reject=0, n_wouldnt_use=0,
  3995. n_inprogress=0, n_in_oldrouters=0;
  3996. if (directory_too_idle_to_fetch_descriptors(options, now))
  3997. goto done;
  3998. if (!consensus)
  3999. goto done;
  4000. if (is_vote) {
  4001. /* where's it from, so we know whom to ask for descriptors */
  4002. dir_server_t *ds;
  4003. networkstatus_voter_info_t *voter = smartlist_get(consensus->voters, 0);
  4004. tor_assert(voter);
  4005. ds = trusteddirserver_get_by_v3_auth_digest(voter->identity_digest);
  4006. if (ds)
  4007. source = &(ds->fake_status);
  4008. else
  4009. log_warn(LD_DIR, "couldn't lookup source from vote?");
  4010. }
  4011. map = digestmap_new();
  4012. list_pending_descriptor_downloads(map, 0);
  4013. SMARTLIST_FOREACH_BEGIN(consensus->routerstatus_list, void *, rsp) {
  4014. routerstatus_t *rs =
  4015. is_vote ? &(((vote_routerstatus_t *)rsp)->status) : rsp;
  4016. signed_descriptor_t *sd;
  4017. if ((sd = router_get_by_descriptor_digest(rs->descriptor_digest))) {
  4018. const routerinfo_t *ri;
  4019. ++n_have;
  4020. if (!(ri = router_get_by_id_digest(rs->identity_digest)) ||
  4021. tor_memneq(ri->cache_info.signed_descriptor_digest,
  4022. sd->signed_descriptor_digest, DIGEST_LEN)) {
  4023. /* We have a descriptor with this digest, but either there is no
  4024. * entry in routerlist with the same ID (!ri), or there is one,
  4025. * but the identity digest differs (memneq).
  4026. */
  4027. smartlist_add(no_longer_old, sd);
  4028. ++n_in_oldrouters; /* We have it in old_routers. */
  4029. }
  4030. continue; /* We have it already. */
  4031. }
  4032. if (digestmap_get(map, rs->descriptor_digest)) {
  4033. ++n_inprogress;
  4034. continue; /* We have an in-progress download. */
  4035. }
  4036. if (!download_status_is_ready(&rs->dl_status, now,
  4037. MAX_ROUTERDESC_DOWNLOAD_FAILURES)) {
  4038. ++n_delayed; /* Not ready for retry. */
  4039. continue;
  4040. }
  4041. if (authdir && dirserv_would_reject_router(rs)) {
  4042. ++n_would_reject;
  4043. continue; /* We would throw it out immediately. */
  4044. }
  4045. if (!directory_caches_dir_info(options) &&
  4046. !client_would_use_router(rs, now, options)) {
  4047. ++n_wouldnt_use;
  4048. continue; /* We would never use it ourself. */
  4049. }
  4050. if (is_vote && source) {
  4051. char time_bufnew[ISO_TIME_LEN+1];
  4052. char time_bufold[ISO_TIME_LEN+1];
  4053. const routerinfo_t *oldrouter;
  4054. oldrouter = router_get_by_id_digest(rs->identity_digest);
  4055. format_iso_time(time_bufnew, rs->published_on);
  4056. if (oldrouter)
  4057. format_iso_time(time_bufold, oldrouter->cache_info.published_on);
  4058. log_info(LD_DIR, "Learned about %s (%s vs %s) from %s's vote (%s)",
  4059. routerstatus_describe(rs),
  4060. time_bufnew,
  4061. oldrouter ? time_bufold : "none",
  4062. source->nickname, oldrouter ? "known" : "unknown");
  4063. }
  4064. smartlist_add(downloadable, rs->descriptor_digest);
  4065. } SMARTLIST_FOREACH_END(rsp);
  4066. if (!authdir_mode_handles_descs(options, ROUTER_PURPOSE_GENERAL)
  4067. && smartlist_len(no_longer_old)) {
  4068. routerlist_t *rl = router_get_routerlist();
  4069. log_info(LD_DIR, "%d router descriptors listed in consensus are "
  4070. "currently in old_routers; making them current.",
  4071. smartlist_len(no_longer_old));
  4072. SMARTLIST_FOREACH_BEGIN(no_longer_old, signed_descriptor_t *, sd) {
  4073. const char *msg;
  4074. was_router_added_t r;
  4075. routerinfo_t *ri = routerlist_reparse_old(rl, sd);
  4076. if (!ri) {
  4077. log_warn(LD_BUG, "Failed to re-parse a router.");
  4078. continue;
  4079. }
  4080. r = router_add_to_routerlist(ri, &msg, 1, 0);
  4081. if (WRA_WAS_OUTDATED(r)) {
  4082. log_warn(LD_DIR, "Couldn't add re-parsed router: %s",
  4083. msg?msg:"???");
  4084. }
  4085. } SMARTLIST_FOREACH_END(sd);
  4086. routerlist_assert_ok(rl);
  4087. }
  4088. log_info(LD_DIR,
  4089. "%d router descriptors downloadable. %d delayed; %d present "
  4090. "(%d of those were in old_routers); %d would_reject; "
  4091. "%d wouldnt_use; %d in progress.",
  4092. smartlist_len(downloadable), n_delayed, n_have, n_in_oldrouters,
  4093. n_would_reject, n_wouldnt_use, n_inprogress);
  4094. launch_descriptor_downloads(DIR_PURPOSE_FETCH_SERVERDESC,
  4095. downloadable, source, now);
  4096. digestmap_free(map, NULL);
  4097. done:
  4098. smartlist_free(downloadable);
  4099. smartlist_free(no_longer_old);
  4100. }
  4101. /** How often should we launch a server/authority request to be sure of getting
  4102. * a guess for our IP? */
  4103. /*XXXX024 this info should come from netinfo cells or something, or we should
  4104. * do this only when we aren't seeing incoming data. see bug 652. */
  4105. #define DUMMY_DOWNLOAD_INTERVAL (20*60)
  4106. /** As needed, launch a dummy router descriptor fetch to see if our
  4107. * address has changed. */
  4108. static void
  4109. launch_dummy_descriptor_download_as_needed(time_t now,
  4110. const or_options_t *options)
  4111. {
  4112. static time_t last_dummy_download = 0;
  4113. /* XXXX024 we could be smarter here; see notes on bug 652. */
  4114. /* If we're a server that doesn't have a configured address, we rely on
  4115. * directory fetches to learn when our address changes. So if we haven't
  4116. * tried to get any routerdescs in a long time, try a dummy fetch now. */
  4117. if (!options->Address &&
  4118. server_mode(options) &&
  4119. last_descriptor_download_attempted + DUMMY_DOWNLOAD_INTERVAL < now &&
  4120. last_dummy_download + DUMMY_DOWNLOAD_INTERVAL < now) {
  4121. last_dummy_download = now;
  4122. directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
  4123. ROUTER_PURPOSE_GENERAL, "authority.z",
  4124. PDS_RETRY_IF_NO_SERVERS);
  4125. }
  4126. }
  4127. /** Launch downloads for router status as needed. */
  4128. void
  4129. update_router_descriptor_downloads(time_t now)
  4130. {
  4131. const or_options_t *options = get_options();
  4132. if (should_delay_dir_fetches(options))
  4133. return;
  4134. if (!we_fetch_router_descriptors(options))
  4135. return;
  4136. if (directory_fetches_dir_info_early(options)) {
  4137. update_router_descriptor_cache_downloads_v2(now);
  4138. }
  4139. update_consensus_router_descriptor_downloads(now, 0,
  4140. networkstatus_get_reasonably_live_consensus(now, FLAV_NS));
  4141. }
  4142. /** Launch extrainfo downloads as needed. */
  4143. void
  4144. update_extrainfo_downloads(time_t now)
  4145. {
  4146. const or_options_t *options = get_options();
  4147. routerlist_t *rl;
  4148. smartlist_t *wanted;
  4149. digestmap_t *pending;
  4150. int old_routers, i;
  4151. int n_no_ei = 0, n_pending = 0, n_have = 0, n_delay = 0;
  4152. if (! options->DownloadExtraInfo)
  4153. return;
  4154. if (should_delay_dir_fetches(options))
  4155. return;
  4156. if (!router_have_minimum_dir_info())
  4157. return;
  4158. pending = digestmap_new();
  4159. list_pending_descriptor_downloads(pending, 1);
  4160. rl = router_get_routerlist();
  4161. wanted = smartlist_new();
  4162. for (old_routers = 0; old_routers < 2; ++old_routers) {
  4163. smartlist_t *lst = old_routers ? rl->old_routers : rl->routers;
  4164. for (i = 0; i < smartlist_len(lst); ++i) {
  4165. signed_descriptor_t *sd;
  4166. char *d;
  4167. if (old_routers)
  4168. sd = smartlist_get(lst, i);
  4169. else
  4170. sd = &((routerinfo_t*)smartlist_get(lst, i))->cache_info;
  4171. if (sd->is_extrainfo)
  4172. continue; /* This should never happen. */
  4173. if (old_routers && !router_get_by_id_digest(sd->identity_digest))
  4174. continue; /* Couldn't check the signature if we got it. */
  4175. if (sd->extrainfo_is_bogus)
  4176. continue;
  4177. d = sd->extra_info_digest;
  4178. if (tor_digest_is_zero(d)) {
  4179. ++n_no_ei;
  4180. continue;
  4181. }
  4182. if (eimap_get(rl->extra_info_map, d)) {
  4183. ++n_have;
  4184. continue;
  4185. }
  4186. if (!download_status_is_ready(&sd->ei_dl_status, now,
  4187. MAX_ROUTERDESC_DOWNLOAD_FAILURES)) {
  4188. ++n_delay;
  4189. continue;
  4190. }
  4191. if (digestmap_get(pending, d)) {
  4192. ++n_pending;
  4193. continue;
  4194. }
  4195. smartlist_add(wanted, d);
  4196. }
  4197. }
  4198. digestmap_free(pending, NULL);
  4199. log_info(LD_DIR, "Extrainfo download status: %d router with no ei, %d "
  4200. "with present ei, %d delaying, %d pending, %d downloadable.",
  4201. n_no_ei, n_have, n_delay, n_pending, smartlist_len(wanted));
  4202. smartlist_shuffle(wanted);
  4203. for (i = 0; i < smartlist_len(wanted); i += MAX_DL_PER_REQUEST) {
  4204. initiate_descriptor_downloads(NULL, DIR_PURPOSE_FETCH_EXTRAINFO,
  4205. wanted, i, i + MAX_DL_PER_REQUEST,
  4206. PDS_RETRY_IF_NO_SERVERS|PDS_NO_EXISTING_SERVERDESC_FETCH);
  4207. }
  4208. smartlist_free(wanted);
  4209. }
  4210. /** Reset the descriptor download failure count on all routers, so that we
  4211. * can retry any long-failed routers immediately.
  4212. */
  4213. void
  4214. router_reset_descriptor_download_failures(void)
  4215. {
  4216. networkstatus_reset_download_failures();
  4217. last_descriptor_download_attempted = 0;
  4218. if (!routerlist)
  4219. return;
  4220. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
  4221. {
  4222. download_status_reset(&ri->cache_info.ei_dl_status);
  4223. });
  4224. SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
  4225. {
  4226. download_status_reset(&sd->ei_dl_status);
  4227. });
  4228. }
  4229. /** Any changes in a router descriptor's publication time larger than this are
  4230. * automatically non-cosmetic. */
  4231. #define ROUTER_MAX_COSMETIC_TIME_DIFFERENCE (2*60*60)
  4232. /** We allow uptime to vary from how much it ought to be by this much. */
  4233. #define ROUTER_ALLOW_UPTIME_DRIFT (6*60*60)
  4234. /** Return true iff the only differences between r1 and r2 are such that
  4235. * would not cause a recent (post 0.1.1.6) dirserver to republish.
  4236. */
  4237. int
  4238. router_differences_are_cosmetic(const routerinfo_t *r1, const routerinfo_t *r2)
  4239. {
  4240. time_t r1pub, r2pub;
  4241. long time_difference;
  4242. tor_assert(r1 && r2);
  4243. /* r1 should be the one that was published first. */
  4244. if (r1->cache_info.published_on > r2->cache_info.published_on) {
  4245. const routerinfo_t *ri_tmp = r2;
  4246. r2 = r1;
  4247. r1 = ri_tmp;
  4248. }
  4249. /* If any key fields differ, they're different. */
  4250. if (strcasecmp(r1->address, r2->address) ||
  4251. strcasecmp(r1->nickname, r2->nickname) ||
  4252. r1->or_port != r2->or_port ||
  4253. !tor_addr_eq(&r1->ipv6_addr, &r2->ipv6_addr) ||
  4254. r1->ipv6_orport != r2->ipv6_orport ||
  4255. r1->dir_port != r2->dir_port ||
  4256. r1->purpose != r2->purpose ||
  4257. !crypto_pk_eq_keys(r1->onion_pkey, r2->onion_pkey) ||
  4258. !crypto_pk_eq_keys(r1->identity_pkey, r2->identity_pkey) ||
  4259. strcasecmp(r1->platform, r2->platform) ||
  4260. (r1->contact_info && !r2->contact_info) || /* contact_info is optional */
  4261. (!r1->contact_info && r2->contact_info) ||
  4262. (r1->contact_info && r2->contact_info &&
  4263. strcasecmp(r1->contact_info, r2->contact_info)) ||
  4264. r1->is_hibernating != r2->is_hibernating ||
  4265. cmp_addr_policies(r1->exit_policy, r2->exit_policy))
  4266. return 0;
  4267. if ((r1->declared_family == NULL) != (r2->declared_family == NULL))
  4268. return 0;
  4269. if (r1->declared_family && r2->declared_family) {
  4270. int i, n;
  4271. if (smartlist_len(r1->declared_family)!=smartlist_len(r2->declared_family))
  4272. return 0;
  4273. n = smartlist_len(r1->declared_family);
  4274. for (i=0; i < n; ++i) {
  4275. if (strcasecmp(smartlist_get(r1->declared_family, i),
  4276. smartlist_get(r2->declared_family, i)))
  4277. return 0;
  4278. }
  4279. }
  4280. /* Did bandwidth change a lot? */
  4281. if ((r1->bandwidthcapacity < r2->bandwidthcapacity/2) ||
  4282. (r2->bandwidthcapacity < r1->bandwidthcapacity/2))
  4283. return 0;
  4284. /* Did the bandwidthrate or bandwidthburst change? */
  4285. if ((r1->bandwidthrate != r2->bandwidthrate) ||
  4286. (r1->bandwidthburst != r2->bandwidthburst))
  4287. return 0;
  4288. /* Did more than 12 hours pass? */
  4289. if (r1->cache_info.published_on + ROUTER_MAX_COSMETIC_TIME_DIFFERENCE
  4290. < r2->cache_info.published_on)
  4291. return 0;
  4292. /* Did uptime fail to increase by approximately the amount we would think,
  4293. * give or take some slop? */
  4294. r1pub = r1->cache_info.published_on;
  4295. r2pub = r2->cache_info.published_on;
  4296. time_difference = labs(r2->uptime - (r1->uptime + (r2pub - r1pub)));
  4297. if (time_difference > ROUTER_ALLOW_UPTIME_DRIFT &&
  4298. time_difference > r1->uptime * .05 &&
  4299. time_difference > r2->uptime * .05)
  4300. return 0;
  4301. /* Otherwise, the difference is cosmetic. */
  4302. return 1;
  4303. }
  4304. /** Check whether <b>ri</b> (a.k.a. sd) is a router compatible with the
  4305. * extrainfo document
  4306. * <b>ei</b>. If no router is compatible with <b>ei</b>, <b>ei</b> should be
  4307. * dropped. Return 0 for "compatible", return 1 for "reject, and inform
  4308. * whoever uploaded <b>ei</b>, and return -1 for "reject silently.". If
  4309. * <b>msg</b> is present, set *<b>msg</b> to a description of the
  4310. * incompatibility (if any).
  4311. **/
  4312. int
  4313. routerinfo_incompatible_with_extrainfo(const routerinfo_t *ri,
  4314. extrainfo_t *ei,
  4315. signed_descriptor_t *sd,
  4316. const char **msg)
  4317. {
  4318. int digest_matches, r=1;
  4319. tor_assert(ri);
  4320. tor_assert(ei);
  4321. if (!sd)
  4322. sd = (signed_descriptor_t*)&ri->cache_info;
  4323. if (ei->bad_sig) {
  4324. if (msg) *msg = "Extrainfo signature was bad, or signed with wrong key.";
  4325. return 1;
  4326. }
  4327. digest_matches = tor_memeq(ei->cache_info.signed_descriptor_digest,
  4328. sd->extra_info_digest, DIGEST_LEN);
  4329. /* The identity must match exactly to have been generated at the same time
  4330. * by the same router. */
  4331. if (tor_memneq(ri->cache_info.identity_digest,
  4332. ei->cache_info.identity_digest,
  4333. DIGEST_LEN)) {
  4334. if (msg) *msg = "Extrainfo nickname or identity did not match routerinfo";
  4335. goto err; /* different servers */
  4336. }
  4337. if (ei->pending_sig) {
  4338. char signed_digest[128];
  4339. if (crypto_pk_public_checksig(ri->identity_pkey,
  4340. signed_digest, sizeof(signed_digest),
  4341. ei->pending_sig, ei->pending_sig_len) != DIGEST_LEN ||
  4342. tor_memneq(signed_digest, ei->cache_info.signed_descriptor_digest,
  4343. DIGEST_LEN)) {
  4344. ei->bad_sig = 1;
  4345. tor_free(ei->pending_sig);
  4346. if (msg) *msg = "Extrainfo signature bad, or signed with wrong key";
  4347. goto err; /* Bad signature, or no match. */
  4348. }
  4349. ei->cache_info.send_unencrypted = ri->cache_info.send_unencrypted;
  4350. tor_free(ei->pending_sig);
  4351. }
  4352. if (ei->cache_info.published_on < sd->published_on) {
  4353. if (msg) *msg = "Extrainfo published time did not match routerdesc";
  4354. goto err;
  4355. } else if (ei->cache_info.published_on > sd->published_on) {
  4356. if (msg) *msg = "Extrainfo published time did not match routerdesc";
  4357. r = -1;
  4358. goto err;
  4359. }
  4360. if (!digest_matches) {
  4361. if (msg) *msg = "Extrainfo digest did not match value from routerdesc";
  4362. goto err; /* Digest doesn't match declared value. */
  4363. }
  4364. return 0;
  4365. err:
  4366. if (digest_matches) {
  4367. /* This signature was okay, and the digest was right: This is indeed the
  4368. * corresponding extrainfo. But insanely, it doesn't match the routerinfo
  4369. * that lists it. Don't try to fetch this one again. */
  4370. sd->extrainfo_is_bogus = 1;
  4371. }
  4372. return r;
  4373. }
  4374. /** Assert that the internal representation of <b>rl</b> is
  4375. * self-consistent. */
  4376. void
  4377. routerlist_assert_ok(const routerlist_t *rl)
  4378. {
  4379. routerinfo_t *r2;
  4380. signed_descriptor_t *sd2;
  4381. if (!rl)
  4382. return;
  4383. SMARTLIST_FOREACH_BEGIN(rl->routers, routerinfo_t *, r) {
  4384. r2 = rimap_get(rl->identity_map, r->cache_info.identity_digest);
  4385. tor_assert(r == r2);
  4386. sd2 = sdmap_get(rl->desc_digest_map,
  4387. r->cache_info.signed_descriptor_digest);
  4388. tor_assert(&(r->cache_info) == sd2);
  4389. tor_assert(r->cache_info.routerlist_index == r_sl_idx);
  4390. /* XXXX
  4391. *
  4392. * Hoo boy. We need to fix this one, and the fix is a bit tricky, so
  4393. * commenting this out is just a band-aid.
  4394. *
  4395. * The problem is that, although well-behaved router descriptors
  4396. * should never have the same value for their extra_info_digest, it's
  4397. * possible for ill-behaved routers to claim whatever they like there.
  4398. *
  4399. * The real answer is to trash desc_by_eid_map and instead have
  4400. * something that indicates for a given extra-info digest we want,
  4401. * what its download status is. We'll do that as a part of routerlist
  4402. * refactoring once consensus directories are in. For now,
  4403. * this rep violation is probably harmless: an adversary can make us
  4404. * reset our retry count for an extrainfo, but that's not the end
  4405. * of the world. Changing the representation in 0.2.0.x would just
  4406. * destabilize the codebase.
  4407. if (!tor_digest_is_zero(r->cache_info.extra_info_digest)) {
  4408. signed_descriptor_t *sd3 =
  4409. sdmap_get(rl->desc_by_eid_map, r->cache_info.extra_info_digest);
  4410. tor_assert(sd3 == &(r->cache_info));
  4411. }
  4412. */
  4413. } SMARTLIST_FOREACH_END(r);
  4414. SMARTLIST_FOREACH_BEGIN(rl->old_routers, signed_descriptor_t *, sd) {
  4415. r2 = rimap_get(rl->identity_map, sd->identity_digest);
  4416. tor_assert(sd != &(r2->cache_info));
  4417. sd2 = sdmap_get(rl->desc_digest_map, sd->signed_descriptor_digest);
  4418. tor_assert(sd == sd2);
  4419. tor_assert(sd->routerlist_index == sd_sl_idx);
  4420. /* XXXX see above.
  4421. if (!tor_digest_is_zero(sd->extra_info_digest)) {
  4422. signed_descriptor_t *sd3 =
  4423. sdmap_get(rl->desc_by_eid_map, sd->extra_info_digest);
  4424. tor_assert(sd3 == sd);
  4425. }
  4426. */
  4427. } SMARTLIST_FOREACH_END(sd);
  4428. RIMAP_FOREACH(rl->identity_map, d, r) {
  4429. tor_assert(tor_memeq(r->cache_info.identity_digest, d, DIGEST_LEN));
  4430. } DIGESTMAP_FOREACH_END;
  4431. SDMAP_FOREACH(rl->desc_digest_map, d, sd) {
  4432. tor_assert(tor_memeq(sd->signed_descriptor_digest, d, DIGEST_LEN));
  4433. } DIGESTMAP_FOREACH_END;
  4434. SDMAP_FOREACH(rl->desc_by_eid_map, d, sd) {
  4435. tor_assert(!tor_digest_is_zero(d));
  4436. tor_assert(sd);
  4437. tor_assert(tor_memeq(sd->extra_info_digest, d, DIGEST_LEN));
  4438. } DIGESTMAP_FOREACH_END;
  4439. EIMAP_FOREACH(rl->extra_info_map, d, ei) {
  4440. signed_descriptor_t *sd;
  4441. tor_assert(tor_memeq(ei->cache_info.signed_descriptor_digest,
  4442. d, DIGEST_LEN));
  4443. sd = sdmap_get(rl->desc_by_eid_map,
  4444. ei->cache_info.signed_descriptor_digest);
  4445. // tor_assert(sd); // XXXX see above
  4446. if (sd) {
  4447. tor_assert(tor_memeq(ei->cache_info.signed_descriptor_digest,
  4448. sd->extra_info_digest, DIGEST_LEN));
  4449. }
  4450. } DIGESTMAP_FOREACH_END;
  4451. }
  4452. /** Allocate and return a new string representing the contact info
  4453. * and platform string for <b>router</b>,
  4454. * surrounded by quotes and using standard C escapes.
  4455. *
  4456. * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
  4457. * thread. Also, each call invalidates the last-returned value, so don't
  4458. * try log_warn(LD_GENERAL, "%s %s", esc_router_info(a), esc_router_info(b));
  4459. *
  4460. * If <b>router</b> is NULL, it just frees its internal memory and returns.
  4461. */
  4462. const char *
  4463. esc_router_info(const routerinfo_t *router)
  4464. {
  4465. static char *info=NULL;
  4466. char *esc_contact, *esc_platform;
  4467. tor_free(info);
  4468. if (!router)
  4469. return NULL; /* we're exiting; just free the memory we use */
  4470. esc_contact = esc_for_log(router->contact_info);
  4471. esc_platform = esc_for_log(router->platform);
  4472. tor_asprintf(&info, "Contact %s, Platform %s", esc_contact, esc_platform);
  4473. tor_free(esc_contact);
  4474. tor_free(esc_platform);
  4475. return info;
  4476. }
  4477. /** Helper for sorting: compare two routerinfos by their identity
  4478. * digest. */
  4479. static int
  4480. compare_routerinfo_by_id_digest_(const void **a, const void **b)
  4481. {
  4482. routerinfo_t *first = *(routerinfo_t **)a, *second = *(routerinfo_t **)b;
  4483. return fast_memcmp(first->cache_info.identity_digest,
  4484. second->cache_info.identity_digest,
  4485. DIGEST_LEN);
  4486. }
  4487. /** Sort a list of routerinfo_t in ascending order of identity digest. */
  4488. void
  4489. routers_sort_by_identity(smartlist_t *routers)
  4490. {
  4491. smartlist_sort(routers, compare_routerinfo_by_id_digest_);
  4492. }
  4493. /** Called when we change a node set, or when we reload the geoip IPv4 list:
  4494. * recompute all country info in all configuration node sets and in the
  4495. * routerlist. */
  4496. void
  4497. refresh_all_country_info(void)
  4498. {
  4499. const or_options_t *options = get_options();
  4500. if (options->EntryNodes)
  4501. routerset_refresh_countries(options->EntryNodes);
  4502. if (options->ExitNodes)
  4503. routerset_refresh_countries(options->ExitNodes);
  4504. if (options->ExcludeNodes)
  4505. routerset_refresh_countries(options->ExcludeNodes);
  4506. if (options->ExcludeExitNodes)
  4507. routerset_refresh_countries(options->ExcludeExitNodes);
  4508. if (options->ExcludeExitNodesUnion_)
  4509. routerset_refresh_countries(options->ExcludeExitNodesUnion_);
  4510. nodelist_refresh_countries();
  4511. }
  4512. /** Determine the routers that are responsible for <b>id</b> (binary) and
  4513. * add pointers to those routers' routerstatus_t to <b>responsible_dirs</b>.
  4514. * Return -1 if we're returning an empty smartlist, else return 0.
  4515. */
  4516. int
  4517. hid_serv_get_responsible_directories(smartlist_t *responsible_dirs,
  4518. const char *id)
  4519. {
  4520. int start, found, n_added = 0, i;
  4521. networkstatus_t *c = networkstatus_get_latest_consensus();
  4522. if (!c || !smartlist_len(c->routerstatus_list)) {
  4523. log_warn(LD_REND, "We don't have a consensus, so we can't perform v2 "
  4524. "rendezvous operations.");
  4525. return -1;
  4526. }
  4527. tor_assert(id);
  4528. start = networkstatus_vote_find_entry_idx(c, id, &found);
  4529. if (start == smartlist_len(c->routerstatus_list)) start = 0;
  4530. i = start;
  4531. do {
  4532. routerstatus_t *r = smartlist_get(c->routerstatus_list, i);
  4533. if (r->is_hs_dir) {
  4534. smartlist_add(responsible_dirs, r);
  4535. if (++n_added == REND_NUMBER_OF_CONSECUTIVE_REPLICAS)
  4536. return 0;
  4537. }
  4538. if (++i == smartlist_len(c->routerstatus_list))
  4539. i = 0;
  4540. } while (i != start);
  4541. /* Even though we don't have the desired number of hidden service
  4542. * directories, be happy if we got any. */
  4543. return smartlist_len(responsible_dirs) ? 0 : -1;
  4544. }
  4545. /** Return true if this node is currently acting as hidden service
  4546. * directory, false otherwise. */
  4547. int
  4548. hid_serv_acting_as_directory(void)
  4549. {
  4550. const routerinfo_t *me = router_get_my_routerinfo();
  4551. if (!me)
  4552. return 0;
  4553. if (!get_options()->HidServDirectoryV2) {
  4554. log_info(LD_REND, "We are not acting as hidden service directory, "
  4555. "because we have not been configured as such.");
  4556. return 0;
  4557. }
  4558. return 1;
  4559. }
  4560. /** Return true if this node is responsible for storing the descriptor ID
  4561. * in <b>query</b> and false otherwise. */
  4562. int
  4563. hid_serv_responsible_for_desc_id(const char *query)
  4564. {
  4565. const routerinfo_t *me;
  4566. routerstatus_t *last_rs;
  4567. const char *my_id, *last_id;
  4568. int result;
  4569. smartlist_t *responsible;
  4570. if (!hid_serv_acting_as_directory())
  4571. return 0;
  4572. if (!(me = router_get_my_routerinfo()))
  4573. return 0; /* This is redundant, but let's be paranoid. */
  4574. my_id = me->cache_info.identity_digest;
  4575. responsible = smartlist_new();
  4576. if (hid_serv_get_responsible_directories(responsible, query) < 0) {
  4577. smartlist_free(responsible);
  4578. return 0;
  4579. }
  4580. last_rs = smartlist_get(responsible, smartlist_len(responsible)-1);
  4581. last_id = last_rs->identity_digest;
  4582. result = rend_id_is_in_interval(my_id, query, last_id);
  4583. smartlist_free(responsible);
  4584. return result;
  4585. }