routerlist.c 182 KB

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