routerlist.c 168 KB

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