routerlist.c 202 KB

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