routerlist.c 154 KB

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