routerlist.c 181 KB

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