routerlist.c 154 KB

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