routerlist.c 202 KB

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