routerlist.c 174 KB

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