routerlist.c 184 KB

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