routerlist.c 197 KB

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