routerlist.c 186 KB

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