routerlist.c 172 KB

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