routerlist.c 196 KB

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