routerlist.c 169 KB

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