routerlist.c 188 KB

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