routerlist.c 196 KB

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