routerlist.c 178 KB

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