routerlist.c 190 KB

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