routerlist.c 161 KB

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