routerlist.c 170 KB

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