routerlist.c 170 KB

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