routerlist.c 182 KB

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