routerlist.c 148 KB

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