routerlist.c 198 KB

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