routerlist.c 214 KB

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