routerlist.c 166 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  4. * Copyright (c) 2007-2012, The Tor Project, Inc. */
  5. /* See LICENSE for licensing information */
  6. /**
  7. * \file routerlist.c
  8. * \brief Code to
  9. * maintain and access the global list of routerinfos for known
  10. * servers.
  11. **/
  12. #define ROUTERLIST_PRIVATE
  13. #include "or.h"
  14. #include "circuitbuild.h"
  15. #include "config.h"
  16. #include "connection.h"
  17. #include "control.h"
  18. #include "directory.h"
  19. #include "dirserv.h"
  20. #include "dirvote.h"
  21. #include "geoip.h"
  22. #include "hibernate.h"
  23. #include "main.h"
  24. #include "microdesc.h"
  25. #include "networkstatus.h"
  26. #include "nodelist.h"
  27. #include "policies.h"
  28. #include "reasons.h"
  29. #include "rendcommon.h"
  30. #include "rendservice.h"
  31. #include "rephist.h"
  32. #include "router.h"
  33. #include "routerlist.h"
  34. #include "routerparse.h"
  35. #include "routerset.h"
  36. // #define DEBUG_ROUTERLIST
  37. /****************************************************************************/
  38. /* static function prototypes */
  39. static const routerstatus_t *router_pick_directory_server_impl(
  40. dirinfo_type_t auth, int flags);
  41. static const routerstatus_t *router_pick_trusteddirserver_impl(
  42. dirinfo_type_t auth, int flags, int *n_busy_out);
  43. static void mark_all_trusteddirservers_up(void);
  44. static int router_nickname_matches(const routerinfo_t *router,
  45. const char *nickname);
  46. static void trusted_dir_server_free(trusted_dir_server_t *ds);
  47. static int signed_desc_digest_is_recognized(signed_descriptor_t *desc);
  48. static const char *signed_descriptor_get_body_impl(
  49. const signed_descriptor_t *desc,
  50. int with_annotations);
  51. static void list_pending_downloads(digestmap_t *result,
  52. int purpose, const char *prefix);
  53. static void launch_dummy_descriptor_download_as_needed(time_t now,
  54. const or_options_t *options);
  55. DECLARE_TYPED_DIGESTMAP_FNS(sdmap_, digest_sd_map_t, signed_descriptor_t)
  56. DECLARE_TYPED_DIGESTMAP_FNS(rimap_, digest_ri_map_t, routerinfo_t)
  57. DECLARE_TYPED_DIGESTMAP_FNS(eimap_, digest_ei_map_t, extrainfo_t)
  58. #define SDMAP_FOREACH(map, keyvar, valvar) \
  59. DIGESTMAP_FOREACH(sdmap_to_digestmap(map), keyvar, signed_descriptor_t *, \
  60. valvar)
  61. #define RIMAP_FOREACH(map, keyvar, valvar) \
  62. DIGESTMAP_FOREACH(rimap_to_digestmap(map), keyvar, routerinfo_t *, valvar)
  63. #define EIMAP_FOREACH(map, keyvar, valvar) \
  64. DIGESTMAP_FOREACH(eimap_to_digestmap(map), keyvar, extrainfo_t *, valvar)
  65. /****************************************************************************/
  66. /** Global list of a trusted_dir_server_t object for each trusted directory
  67. * server. */
  68. static smartlist_t *trusted_dir_servers = NULL;
  69. /** List of for a given authority, and download status for latest certificate.
  70. */
  71. typedef struct cert_list_t {
  72. download_status_t dl_status;
  73. smartlist_t *certs;
  74. } cert_list_t;
  75. /** Map from v3 identity key digest to cert_list_t. */
  76. static digestmap_t *trusted_dir_certs = NULL;
  77. /** True iff any key certificate in at least one member of
  78. * <b>trusted_dir_certs</b> has changed since we last flushed the
  79. * certificates to disk. */
  80. static int trusted_dir_servers_certs_changed = 0;
  81. /** Global list of all of the routers that we know about. */
  82. static routerlist_t *routerlist = NULL;
  83. /** List of strings for nicknames we've already warned about and that are
  84. * still unknown / unavailable. */
  85. static smartlist_t *warned_nicknames = NULL;
  86. /** The last time we tried to download any routerdesc, or 0 for "never". We
  87. * use this to rate-limit download attempts when the number of routerdescs to
  88. * download is low. */
  89. static time_t last_descriptor_download_attempted = 0;
  90. /** When we last computed the weights to use for bandwidths on directory
  91. * requests, what were the total weighted bandwidth, and our share of that
  92. * bandwidth? Used to determine what fraction of directory requests we should
  93. * expect to see.
  94. *
  95. * @{ */
  96. static uint64_t sl_last_total_weighted_bw = 0,
  97. sl_last_weighted_bw_of_me = 0;
  98. /**@}*/
  99. /** Return the number of directory authorities whose type matches some bit set
  100. * in <b>type</b> */
  101. int
  102. get_n_authorities(dirinfo_type_t type)
  103. {
  104. int n = 0;
  105. if (!trusted_dir_servers)
  106. return 0;
  107. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  108. if (ds->type & type)
  109. ++n);
  110. return n;
  111. }
  112. #define get_n_v2_authorities() get_n_authorities(V2_DIRINFO)
  113. /** Helper: Return the cert_list_t for an authority whose authority ID is
  114. * <b>id_digest</b>, allocating a new list if necessary. */
  115. static cert_list_t *
  116. get_cert_list(const char *id_digest)
  117. {
  118. cert_list_t *cl;
  119. if (!trusted_dir_certs)
  120. trusted_dir_certs = digestmap_new();
  121. cl = digestmap_get(trusted_dir_certs, id_digest);
  122. if (!cl) {
  123. cl = tor_malloc_zero(sizeof(cert_list_t));
  124. cl->dl_status.schedule = DL_SCHED_CONSENSUS;
  125. cl->certs = smartlist_new();
  126. digestmap_set(trusted_dir_certs, id_digest, cl);
  127. }
  128. return cl;
  129. }
  130. /** Reload the cached v3 key certificates from the cached-certs file in
  131. * the data directory. Return 0 on success, -1 on failure. */
  132. int
  133. trusted_dirs_reload_certs(void)
  134. {
  135. char *filename;
  136. char *contents;
  137. int r;
  138. filename = get_datadir_fname("cached-certs");
  139. contents = read_file_to_str(filename, RFTS_IGNORE_MISSING, NULL);
  140. tor_free(filename);
  141. if (!contents)
  142. return 0;
  143. r = trusted_dirs_load_certs_from_string(contents, 1, 1);
  144. tor_free(contents);
  145. return r;
  146. }
  147. /** Helper: return true iff we already have loaded the exact cert
  148. * <b>cert</b>. */
  149. static INLINE int
  150. already_have_cert(authority_cert_t *cert)
  151. {
  152. cert_list_t *cl = get_cert_list(cert->cache_info.identity_digest);
  153. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, c,
  154. {
  155. if (tor_memeq(c->cache_info.signed_descriptor_digest,
  156. cert->cache_info.signed_descriptor_digest,
  157. DIGEST_LEN))
  158. return 1;
  159. });
  160. return 0;
  161. }
  162. /** Load a bunch of new key certificates from the string <b>contents</b>. If
  163. * <b>from_store</b> is true, the certificates are from the cache, and we
  164. * don't need to flush them to disk. If <b>flush</b> is true, we need
  165. * to flush any changed certificates to disk now. Return 0 on success, -1
  166. * if any certs fail to parse. */
  167. int
  168. trusted_dirs_load_certs_from_string(const char *contents, int from_store,
  169. int flush)
  170. {
  171. trusted_dir_server_t *ds;
  172. const char *s, *eos;
  173. int failure_code = 0;
  174. for (s = contents; *s; s = eos) {
  175. authority_cert_t *cert = authority_cert_parse_from_string(s, &eos);
  176. cert_list_t *cl;
  177. if (!cert) {
  178. failure_code = -1;
  179. break;
  180. }
  181. ds = trusteddirserver_get_by_v3_auth_digest(
  182. cert->cache_info.identity_digest);
  183. log_debug(LD_DIR, "Parsed certificate for %s",
  184. ds ? ds->nickname : "unknown authority");
  185. if (already_have_cert(cert)) {
  186. /* we already have this one. continue. */
  187. log_info(LD_DIR, "Skipping %s certificate for %s that we "
  188. "already have.",
  189. from_store ? "cached" : "downloaded",
  190. ds ? ds->nickname : "an old or new authority");
  191. /* a duplicate on a download should be treated as a failure, since it
  192. * probably means we wanted a different secret key or we are trying to
  193. * replace an expired cert that has not in fact been updated. */
  194. if (!from_store) {
  195. if (authdir_mode(get_options())) {
  196. log_warn(LD_DIR,
  197. "Got a certificate for %s, but we already have it. "
  198. "Maybe they haven't updated it. Waiting for a while.",
  199. ds ? ds->nickname : "an old or new authority");
  200. } else {
  201. log_info(LD_DIR,
  202. "Got a certificate for %s, but we already have it. "
  203. "Maybe they haven't updated it. Waiting for a while.",
  204. ds ? ds->nickname : "an old or new authority");
  205. }
  206. authority_cert_dl_failed(cert->cache_info.identity_digest, 404);
  207. }
  208. authority_cert_free(cert);
  209. continue;
  210. }
  211. if (ds) {
  212. log_info(LD_DIR, "Adding %s certificate for directory authority %s with "
  213. "signing key %s", from_store ? "cached" : "downloaded",
  214. ds->nickname, hex_str(cert->signing_key_digest,DIGEST_LEN));
  215. } else {
  216. int adding = directory_caches_unknown_auth_certs(get_options());
  217. log_info(LD_DIR, "%s %s certificate for unrecognized directory "
  218. "authority with signing key %s",
  219. adding ? "Adding" : "Not adding",
  220. from_store ? "cached" : "downloaded",
  221. hex_str(cert->signing_key_digest,DIGEST_LEN));
  222. if (!adding) {
  223. authority_cert_free(cert);
  224. continue;
  225. }
  226. }
  227. cl = get_cert_list(cert->cache_info.identity_digest);
  228. smartlist_add(cl->certs, cert);
  229. if (ds && cert->cache_info.published_on > ds->addr_current_at) {
  230. /* Check to see whether we should update our view of the authority's
  231. * address. */
  232. if (cert->addr && cert->dir_port &&
  233. (ds->addr != cert->addr ||
  234. ds->dir_port != cert->dir_port)) {
  235. char *a = tor_dup_ip(cert->addr);
  236. log_notice(LD_DIR, "Updating address for directory authority %s "
  237. "from %s:%d to %s:%d based on certificate.",
  238. ds->nickname, ds->address, (int)ds->dir_port,
  239. a, cert->dir_port);
  240. tor_free(a);
  241. ds->addr = cert->addr;
  242. ds->dir_port = cert->dir_port;
  243. }
  244. ds->addr_current_at = cert->cache_info.published_on;
  245. }
  246. if (!from_store)
  247. trusted_dir_servers_certs_changed = 1;
  248. }
  249. if (flush)
  250. trusted_dirs_flush_certs_to_disk();
  251. /* call this even if failure_code is <0, since some certs might have
  252. * succeeded. */
  253. networkstatus_note_certs_arrived();
  254. return failure_code;
  255. }
  256. /** Save all v3 key certificates to the cached-certs file. */
  257. void
  258. trusted_dirs_flush_certs_to_disk(void)
  259. {
  260. char *filename;
  261. smartlist_t *chunks;
  262. if (!trusted_dir_servers_certs_changed || !trusted_dir_certs)
  263. return;
  264. chunks = smartlist_new();
  265. DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
  266. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
  267. {
  268. sized_chunk_t *c = tor_malloc(sizeof(sized_chunk_t));
  269. c->bytes = cert->cache_info.signed_descriptor_body;
  270. c->len = cert->cache_info.signed_descriptor_len;
  271. smartlist_add(chunks, c);
  272. });
  273. } DIGESTMAP_FOREACH_END;
  274. filename = get_datadir_fname("cached-certs");
  275. if (write_chunks_to_file(filename, chunks, 0)) {
  276. log_warn(LD_FS, "Error writing certificates to disk.");
  277. }
  278. tor_free(filename);
  279. SMARTLIST_FOREACH(chunks, sized_chunk_t *, c, tor_free(c));
  280. smartlist_free(chunks);
  281. trusted_dir_servers_certs_changed = 0;
  282. }
  283. /** Remove all v3 authority certificates that have been superseded for more
  284. * than 48 hours. (If the most recent cert was published more than 48 hours
  285. * ago, then we aren't going to get any consensuses signed with older
  286. * keys.) */
  287. static void
  288. trusted_dirs_remove_old_certs(void)
  289. {
  290. time_t now = time(NULL);
  291. #define DEAD_CERT_LIFETIME (2*24*60*60)
  292. #define OLD_CERT_LIFETIME (7*24*60*60)
  293. #define CERT_EXPIRY_SKEW (60*60)
  294. if (!trusted_dir_certs)
  295. return;
  296. DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
  297. authority_cert_t *newest = NULL;
  298. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
  299. if (!newest || (cert->cache_info.published_on >
  300. newest->cache_info.published_on))
  301. newest = cert);
  302. if (newest) {
  303. const time_t newest_published = newest->cache_info.published_on;
  304. SMARTLIST_FOREACH_BEGIN(cl->certs, authority_cert_t *, cert) {
  305. int expired;
  306. time_t cert_published;
  307. if (newest == cert)
  308. continue;
  309. expired = now > cert->expires;
  310. cert_published = cert->cache_info.published_on;
  311. /* Store expired certs for 48 hours after a newer arrives;
  312. */
  313. if (expired ?
  314. (newest_published + DEAD_CERT_LIFETIME < now) :
  315. (cert_published + OLD_CERT_LIFETIME < newest_published)) {
  316. SMARTLIST_DEL_CURRENT(cl->certs, cert);
  317. authority_cert_free(cert);
  318. trusted_dir_servers_certs_changed = 1;
  319. }
  320. } SMARTLIST_FOREACH_END(cert);
  321. }
  322. } DIGESTMAP_FOREACH_END;
  323. #undef OLD_CERT_LIFETIME
  324. trusted_dirs_flush_certs_to_disk();
  325. }
  326. /** Return the newest v3 authority certificate whose v3 authority identity key
  327. * has digest <b>id_digest</b>. Return NULL if no such authority is known,
  328. * or it has no certificate. */
  329. authority_cert_t *
  330. authority_cert_get_newest_by_id(const char *id_digest)
  331. {
  332. cert_list_t *cl;
  333. authority_cert_t *best = NULL;
  334. if (!trusted_dir_certs ||
  335. !(cl = digestmap_get(trusted_dir_certs, id_digest)))
  336. return NULL;
  337. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
  338. {
  339. if (!best || cert->cache_info.published_on > best->cache_info.published_on)
  340. best = cert;
  341. });
  342. return best;
  343. }
  344. /** Return the newest v3 authority certificate whose directory signing key has
  345. * digest <b>sk_digest</b>. Return NULL if no such certificate is known.
  346. */
  347. authority_cert_t *
  348. authority_cert_get_by_sk_digest(const char *sk_digest)
  349. {
  350. authority_cert_t *c;
  351. if (!trusted_dir_certs)
  352. return NULL;
  353. if ((c = get_my_v3_authority_cert()) &&
  354. tor_memeq(c->signing_key_digest, sk_digest, DIGEST_LEN))
  355. return c;
  356. if ((c = get_my_v3_legacy_cert()) &&
  357. tor_memeq(c->signing_key_digest, sk_digest, DIGEST_LEN))
  358. return c;
  359. DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
  360. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
  361. {
  362. if (tor_memeq(cert->signing_key_digest, sk_digest, DIGEST_LEN))
  363. return cert;
  364. });
  365. } DIGESTMAP_FOREACH_END;
  366. return NULL;
  367. }
  368. /** Return the v3 authority certificate with signing key matching
  369. * <b>sk_digest</b>, for the authority with identity digest <b>id_digest</b>.
  370. * Return NULL if no such authority is known. */
  371. authority_cert_t *
  372. authority_cert_get_by_digests(const char *id_digest,
  373. const char *sk_digest)
  374. {
  375. cert_list_t *cl;
  376. if (!trusted_dir_certs ||
  377. !(cl = digestmap_get(trusted_dir_certs, id_digest)))
  378. return NULL;
  379. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
  380. if (tor_memeq(cert->signing_key_digest, sk_digest, DIGEST_LEN))
  381. return cert; );
  382. return NULL;
  383. }
  384. /** Add every known authority_cert_t to <b>certs_out</b>. */
  385. void
  386. authority_cert_get_all(smartlist_t *certs_out)
  387. {
  388. tor_assert(certs_out);
  389. if (!trusted_dir_certs)
  390. return;
  391. DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
  392. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, c,
  393. smartlist_add(certs_out, c));
  394. } DIGESTMAP_FOREACH_END;
  395. }
  396. /** Called when an attempt to download a certificate with the authority with
  397. * ID <b>id_digest</b> fails with HTTP response code <b>status</b>: remember
  398. * the failure, so we don't try again immediately. */
  399. void
  400. authority_cert_dl_failed(const char *id_digest, int status)
  401. {
  402. cert_list_t *cl;
  403. if (!trusted_dir_certs ||
  404. !(cl = digestmap_get(trusted_dir_certs, id_digest)))
  405. return;
  406. download_status_failed(&cl->dl_status, status);
  407. }
  408. /** Return true iff when we've been getting enough failures when trying to
  409. * download the certificate with ID digest <b>id_digest</b> that we're willing
  410. * to start bugging the user about it. */
  411. int
  412. authority_cert_dl_looks_uncertain(const char *id_digest)
  413. {
  414. #define N_AUTH_CERT_DL_FAILURES_TO_BUG_USER 2
  415. cert_list_t *cl;
  416. int n_failures;
  417. if (!trusted_dir_certs ||
  418. !(cl = digestmap_get(trusted_dir_certs, id_digest)))
  419. return 0;
  420. n_failures = download_status_get_n_failures(&cl->dl_status);
  421. return n_failures >= N_AUTH_CERT_DL_FAILURES_TO_BUG_USER;
  422. }
  423. /** How many times will we try to fetch a certificate before giving up? */
  424. #define MAX_CERT_DL_FAILURES 8
  425. /** Try to download any v3 authority certificates that we may be missing. If
  426. * <b>status</b> is provided, try to get all the ones that were used to sign
  427. * <b>status</b>. Additionally, try to have a non-expired certificate for
  428. * every V3 authority in trusted_dir_servers. Don't fetch certificates we
  429. * already have.
  430. **/
  431. void
  432. authority_certs_fetch_missing(networkstatus_t *status, time_t now)
  433. {
  434. digestmap_t *pending;
  435. authority_cert_t *cert;
  436. smartlist_t *missing_digests;
  437. char *resource = NULL;
  438. cert_list_t *cl;
  439. const int cache = directory_caches_unknown_auth_certs(get_options());
  440. if (should_delay_dir_fetches(get_options()))
  441. return;
  442. pending = digestmap_new();
  443. missing_digests = smartlist_new();
  444. list_pending_downloads(pending, DIR_PURPOSE_FETCH_CERTIFICATE, "fp/");
  445. if (status) {
  446. SMARTLIST_FOREACH_BEGIN(status->voters, networkstatus_voter_info_t *,
  447. voter) {
  448. if (!smartlist_len(voter->sigs))
  449. continue; /* This authority never signed this consensus, so don't
  450. * go looking for a cert with key digest 0000000000. */
  451. if (!cache &&
  452. !trusteddirserver_get_by_v3_auth_digest(voter->identity_digest))
  453. continue; /* We are not a cache, and we don't know this authority.*/
  454. cl = get_cert_list(voter->identity_digest);
  455. SMARTLIST_FOREACH_BEGIN(voter->sigs, document_signature_t *, sig) {
  456. cert = authority_cert_get_by_digests(voter->identity_digest,
  457. sig->signing_key_digest);
  458. if (cert) {
  459. if (now < cert->expires)
  460. download_status_reset(&cl->dl_status);
  461. continue;
  462. }
  463. if (download_status_is_ready(&cl->dl_status, now,
  464. MAX_CERT_DL_FAILURES) &&
  465. !digestmap_get(pending, voter->identity_digest)) {
  466. log_info(LD_DIR, "We're missing a certificate from authority "
  467. "with signing key %s: launching request.",
  468. hex_str(sig->signing_key_digest, DIGEST_LEN));
  469. smartlist_add(missing_digests, sig->identity_digest);
  470. }
  471. } SMARTLIST_FOREACH_END(sig);
  472. } SMARTLIST_FOREACH_END(voter);
  473. }
  474. SMARTLIST_FOREACH_BEGIN(trusted_dir_servers, trusted_dir_server_t *, ds) {
  475. int found = 0;
  476. if (!(ds->type & V3_DIRINFO))
  477. continue;
  478. if (smartlist_digest_isin(missing_digests, ds->v3_identity_digest))
  479. continue;
  480. cl = get_cert_list(ds->v3_identity_digest);
  481. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert, {
  482. if (now < cert->expires) {
  483. /* It's not expired, and we weren't looking for something to
  484. * verify a consensus with. Call it done. */
  485. download_status_reset(&cl->dl_status);
  486. found = 1;
  487. break;
  488. }
  489. });
  490. if (!found &&
  491. download_status_is_ready(&cl->dl_status, now,MAX_CERT_DL_FAILURES) &&
  492. !digestmap_get(pending, ds->v3_identity_digest)) {
  493. log_info(LD_DIR, "No current certificate known for authority %s; "
  494. "launching request.", ds->nickname);
  495. smartlist_add(missing_digests, ds->v3_identity_digest);
  496. }
  497. } SMARTLIST_FOREACH_END(ds);
  498. if (!smartlist_len(missing_digests)) {
  499. goto done;
  500. } else {
  501. smartlist_t *fps = smartlist_new();
  502. smartlist_add(fps, tor_strdup("fp/"));
  503. SMARTLIST_FOREACH(missing_digests, const char *, d, {
  504. char *fp;
  505. if (digestmap_get(pending, d))
  506. continue;
  507. fp = tor_malloc(HEX_DIGEST_LEN+2);
  508. base16_encode(fp, HEX_DIGEST_LEN+1, d, DIGEST_LEN);
  509. fp[HEX_DIGEST_LEN] = '+';
  510. fp[HEX_DIGEST_LEN+1] = '\0';
  511. smartlist_add(fps, fp);
  512. });
  513. if (smartlist_len(fps) == 1) {
  514. /* we didn't add any: they were all pending */
  515. SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
  516. smartlist_free(fps);
  517. goto done;
  518. }
  519. resource = smartlist_join_strings(fps, "", 0, NULL);
  520. resource[strlen(resource)-1] = '\0';
  521. SMARTLIST_FOREACH(fps, char *, cp, tor_free(cp));
  522. smartlist_free(fps);
  523. }
  524. directory_get_from_dirserver(DIR_PURPOSE_FETCH_CERTIFICATE, 0,
  525. resource, PDS_RETRY_IF_NO_SERVERS);
  526. done:
  527. tor_free(resource);
  528. smartlist_free(missing_digests);
  529. digestmap_free(pending, NULL);
  530. }
  531. /* Router descriptor storage.
  532. *
  533. * Routerdescs are stored in a big file, named "cached-descriptors". As new
  534. * routerdescs arrive, we append them to a journal file named
  535. * "cached-descriptors.new".
  536. *
  537. * From time to time, we replace "cached-descriptors" with a new file
  538. * containing only the live, non-superseded descriptors, and clear
  539. * cached-routers.new.
  540. *
  541. * On startup, we read both files.
  542. */
  543. /** Helper: return 1 iff the router log is so big we want to rebuild the
  544. * store. */
  545. static int
  546. router_should_rebuild_store(desc_store_t *store)
  547. {
  548. if (store->store_len > (1<<16))
  549. return (store->journal_len > store->store_len / 2 ||
  550. store->bytes_dropped > store->store_len / 2);
  551. else
  552. return store->journal_len > (1<<15);
  553. }
  554. /** Return the desc_store_t in <b>rl</b> that should be used to store
  555. * <b>sd</b>. */
  556. static INLINE desc_store_t *
  557. desc_get_store(routerlist_t *rl, const signed_descriptor_t *sd)
  558. {
  559. if (sd->is_extrainfo)
  560. return &rl->extrainfo_store;
  561. else
  562. return &rl->desc_store;
  563. }
  564. /** Add the signed_descriptor_t in <b>desc</b> to the router
  565. * journal; change its saved_location to SAVED_IN_JOURNAL and set its
  566. * offset appropriately. */
  567. static int
  568. signed_desc_append_to_journal(signed_descriptor_t *desc,
  569. desc_store_t *store)
  570. {
  571. char *fname = get_datadir_fname_suffix(store->fname_base, ".new");
  572. const char *body = signed_descriptor_get_body_impl(desc,1);
  573. size_t len = desc->signed_descriptor_len + desc->annotations_len;
  574. if (append_bytes_to_file(fname, body, len, 1)) {
  575. log_warn(LD_FS, "Unable to store router descriptor");
  576. tor_free(fname);
  577. return -1;
  578. }
  579. desc->saved_location = SAVED_IN_JOURNAL;
  580. tor_free(fname);
  581. desc->saved_offset = store->journal_len;
  582. store->journal_len += len;
  583. return 0;
  584. }
  585. /** Sorting helper: return &lt;0, 0, or &gt;0 depending on whether the
  586. * signed_descriptor_t* in *<b>a</b> is older, the same age as, or newer than
  587. * the signed_descriptor_t* in *<b>b</b>. */
  588. static int
  589. compare_signed_descriptors_by_age_(const void **_a, const void **_b)
  590. {
  591. const signed_descriptor_t *r1 = *_a, *r2 = *_b;
  592. return (int)(r1->published_on - r2->published_on);
  593. }
  594. #define RRS_FORCE 1
  595. #define RRS_DONT_REMOVE_OLD 2
  596. /** If the journal of <b>store</b> is too long, or if RRS_FORCE is set in
  597. * <b>flags</b>, then atomically replace the saved router store with the
  598. * routers currently in our routerlist, and clear the journal. Unless
  599. * RRS_DONT_REMOVE_OLD is set in <b>flags</b>, delete expired routers before
  600. * rebuilding the store. Return 0 on success, -1 on failure.
  601. */
  602. static int
  603. router_rebuild_store(int flags, desc_store_t *store)
  604. {
  605. smartlist_t *chunk_list = NULL;
  606. char *fname = NULL, *fname_tmp = NULL;
  607. int r = -1;
  608. off_t offset = 0;
  609. smartlist_t *signed_descriptors = NULL;
  610. int nocache=0;
  611. size_t total_expected_len = 0;
  612. int had_any;
  613. int force = flags & RRS_FORCE;
  614. if (!force && !router_should_rebuild_store(store)) {
  615. r = 0;
  616. goto done;
  617. }
  618. if (!routerlist) {
  619. r = 0;
  620. goto done;
  621. }
  622. if (store->type == EXTRAINFO_STORE)
  623. had_any = !eimap_isempty(routerlist->extra_info_map);
  624. else
  625. had_any = (smartlist_len(routerlist->routers)+
  626. smartlist_len(routerlist->old_routers))>0;
  627. /* Don't save deadweight. */
  628. if (!(flags & RRS_DONT_REMOVE_OLD))
  629. routerlist_remove_old_routers();
  630. log_info(LD_DIR, "Rebuilding %s cache", store->description);
  631. fname = get_datadir_fname(store->fname_base);
  632. fname_tmp = get_datadir_fname_suffix(store->fname_base, ".tmp");
  633. chunk_list = smartlist_new();
  634. /* We sort the routers by age to enhance locality on disk. */
  635. signed_descriptors = smartlist_new();
  636. if (store->type == EXTRAINFO_STORE) {
  637. eimap_iter_t *iter;
  638. for (iter = eimap_iter_init(routerlist->extra_info_map);
  639. !eimap_iter_done(iter);
  640. iter = eimap_iter_next(routerlist->extra_info_map, iter)) {
  641. const char *key;
  642. extrainfo_t *ei;
  643. eimap_iter_get(iter, &key, &ei);
  644. smartlist_add(signed_descriptors, &ei->cache_info);
  645. }
  646. } else {
  647. SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
  648. smartlist_add(signed_descriptors, sd));
  649. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
  650. smartlist_add(signed_descriptors, &ri->cache_info));
  651. }
  652. smartlist_sort(signed_descriptors, compare_signed_descriptors_by_age_);
  653. /* Now, add the appropriate members to chunk_list */
  654. SMARTLIST_FOREACH_BEGIN(signed_descriptors, signed_descriptor_t *, sd) {
  655. sized_chunk_t *c;
  656. const char *body = signed_descriptor_get_body_impl(sd, 1);
  657. if (!body) {
  658. log_warn(LD_BUG, "No descriptor available for router.");
  659. goto done;
  660. }
  661. if (sd->do_not_cache) {
  662. ++nocache;
  663. continue;
  664. }
  665. c = tor_malloc(sizeof(sized_chunk_t));
  666. c->bytes = body;
  667. c->len = sd->signed_descriptor_len + sd->annotations_len;
  668. total_expected_len += c->len;
  669. smartlist_add(chunk_list, c);
  670. } SMARTLIST_FOREACH_END(sd);
  671. if (write_chunks_to_file(fname_tmp, chunk_list, 1)<0) {
  672. log_warn(LD_FS, "Error writing router store to disk.");
  673. goto done;
  674. }
  675. /* Our mmap is now invalid. */
  676. if (store->mmap) {
  677. tor_munmap_file(store->mmap);
  678. store->mmap = NULL;
  679. }
  680. if (replace_file(fname_tmp, fname)<0) {
  681. log_warn(LD_FS, "Error replacing old router store: %s", strerror(errno));
  682. goto done;
  683. }
  684. errno = 0;
  685. store->mmap = tor_mmap_file(fname);
  686. if (! store->mmap) {
  687. if (errno == ERANGE) {
  688. /* empty store.*/
  689. if (total_expected_len) {
  690. log_warn(LD_FS, "We wrote some bytes to a new descriptor file at '%s',"
  691. " but when we went to mmap it, it was empty!", fname);
  692. } else if (had_any) {
  693. log_info(LD_FS, "We just removed every descriptor in '%s'. This is "
  694. "okay if we're just starting up after a long time. "
  695. "Otherwise, it's a bug.", fname);
  696. }
  697. } else {
  698. log_warn(LD_FS, "Unable to mmap new descriptor file at '%s'.",fname);
  699. }
  700. }
  701. log_info(LD_DIR, "Reconstructing pointers into cache");
  702. offset = 0;
  703. SMARTLIST_FOREACH_BEGIN(signed_descriptors, signed_descriptor_t *, sd) {
  704. if (sd->do_not_cache)
  705. continue;
  706. sd->saved_location = SAVED_IN_CACHE;
  707. if (store->mmap) {
  708. tor_free(sd->signed_descriptor_body); // sets it to null
  709. sd->saved_offset = offset;
  710. }
  711. offset += sd->signed_descriptor_len + sd->annotations_len;
  712. signed_descriptor_get_body(sd); /* reconstruct and assert */
  713. } SMARTLIST_FOREACH_END(sd);
  714. tor_free(fname);
  715. fname = get_datadir_fname_suffix(store->fname_base, ".new");
  716. write_str_to_file(fname, "", 1);
  717. r = 0;
  718. store->store_len = (size_t) offset;
  719. store->journal_len = 0;
  720. store->bytes_dropped = 0;
  721. done:
  722. smartlist_free(signed_descriptors);
  723. tor_free(fname);
  724. tor_free(fname_tmp);
  725. if (chunk_list) {
  726. SMARTLIST_FOREACH(chunk_list, sized_chunk_t *, c, tor_free(c));
  727. smartlist_free(chunk_list);
  728. }
  729. return r;
  730. }
  731. /** Helper: Reload a cache file and its associated journal, setting metadata
  732. * appropriately. If <b>extrainfo</b> is true, reload the extrainfo store;
  733. * else reload the router descriptor store. */
  734. static int
  735. router_reload_router_list_impl(desc_store_t *store)
  736. {
  737. char *fname = NULL, *altname = NULL, *contents = NULL;
  738. struct stat st;
  739. int read_from_old_location = 0;
  740. int extrainfo = (store->type == EXTRAINFO_STORE);
  741. time_t now = time(NULL);
  742. store->journal_len = store->store_len = 0;
  743. fname = get_datadir_fname(store->fname_base);
  744. if (store->fname_alt_base)
  745. altname = get_datadir_fname(store->fname_alt_base);
  746. if (store->mmap) /* get rid of it first */
  747. tor_munmap_file(store->mmap);
  748. store->mmap = NULL;
  749. store->mmap = tor_mmap_file(fname);
  750. if (!store->mmap && altname && file_status(altname) == FN_FILE) {
  751. read_from_old_location = 1;
  752. log_notice(LD_DIR, "Couldn't read %s; trying to load routers from old "
  753. "location %s.", fname, altname);
  754. if ((store->mmap = tor_mmap_file(altname)))
  755. read_from_old_location = 1;
  756. }
  757. if (altname && !read_from_old_location) {
  758. remove_file_if_very_old(altname, now);
  759. }
  760. if (store->mmap) {
  761. store->store_len = store->mmap->size;
  762. if (extrainfo)
  763. router_load_extrainfo_from_string(store->mmap->data,
  764. store->mmap->data+store->mmap->size,
  765. SAVED_IN_CACHE, NULL, 0);
  766. else
  767. router_load_routers_from_string(store->mmap->data,
  768. store->mmap->data+store->mmap->size,
  769. SAVED_IN_CACHE, NULL, 0, NULL);
  770. }
  771. tor_free(fname);
  772. fname = get_datadir_fname_suffix(store->fname_base, ".new");
  773. if (file_status(fname) == FN_FILE)
  774. contents = read_file_to_str(fname, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
  775. if (read_from_old_location) {
  776. tor_free(altname);
  777. altname = get_datadir_fname_suffix(store->fname_alt_base, ".new");
  778. if (!contents)
  779. contents = read_file_to_str(altname, RFTS_BIN|RFTS_IGNORE_MISSING, &st);
  780. else
  781. remove_file_if_very_old(altname, now);
  782. }
  783. if (contents) {
  784. if (extrainfo)
  785. router_load_extrainfo_from_string(contents, NULL,SAVED_IN_JOURNAL,
  786. NULL, 0);
  787. else
  788. router_load_routers_from_string(contents, NULL, SAVED_IN_JOURNAL,
  789. NULL, 0, NULL);
  790. store->journal_len = (size_t) st.st_size;
  791. tor_free(contents);
  792. }
  793. tor_free(fname);
  794. tor_free(altname);
  795. if (store->journal_len || read_from_old_location) {
  796. /* Always clear the journal on startup.*/
  797. router_rebuild_store(RRS_FORCE, store);
  798. } else if (!extrainfo) {
  799. /* Don't cache expired routers. (This is in an else because
  800. * router_rebuild_store() also calls remove_old_routers().) */
  801. routerlist_remove_old_routers();
  802. }
  803. return 0;
  804. }
  805. /** Load all cached router descriptors and extra-info documents from the
  806. * store. Return 0 on success and -1 on failure.
  807. */
  808. int
  809. router_reload_router_list(void)
  810. {
  811. routerlist_t *rl = router_get_routerlist();
  812. if (router_reload_router_list_impl(&rl->desc_store))
  813. return -1;
  814. if (router_reload_router_list_impl(&rl->extrainfo_store))
  815. return -1;
  816. return 0;
  817. }
  818. /** Return a smartlist containing a list of trusted_dir_server_t * for all
  819. * known trusted dirservers. Callers must not modify the list or its
  820. * contents.
  821. */
  822. smartlist_t *
  823. router_get_trusted_dir_servers(void)
  824. {
  825. if (!trusted_dir_servers)
  826. trusted_dir_servers = smartlist_new();
  827. return trusted_dir_servers;
  828. }
  829. /** Try to find a running dirserver that supports operations of <b>type</b>.
  830. *
  831. * If there are no running dirservers in our routerlist and the
  832. * <b>PDS_RETRY_IF_NO_SERVERS</b> flag is set, set all the authoritative ones
  833. * as running again, and pick one.
  834. *
  835. * If the <b>PDS_IGNORE_FASCISTFIREWALL</b> flag is set, then include
  836. * dirservers that we can't reach.
  837. *
  838. * If the <b>PDS_ALLOW_SELF</b> flag is not set, then don't include ourself
  839. * (if we're a dirserver).
  840. *
  841. * Don't pick an authority if any non-authority is viable; try to avoid using
  842. * servers that have returned 503 recently.
  843. */
  844. const routerstatus_t *
  845. router_pick_directory_server(dirinfo_type_t type, int flags)
  846. {
  847. const routerstatus_t *choice;
  848. if (get_options()->PreferTunneledDirConns)
  849. flags |= PDS_PREFER_TUNNELED_DIR_CONNS_;
  850. if (!routerlist)
  851. return NULL;
  852. choice = router_pick_directory_server_impl(type, flags);
  853. if (choice || !(flags & PDS_RETRY_IF_NO_SERVERS))
  854. return choice;
  855. log_info(LD_DIR,
  856. "No reachable router entries for dirservers. "
  857. "Trying them all again.");
  858. /* mark all authdirservers as up again */
  859. mark_all_trusteddirservers_up();
  860. /* try again */
  861. choice = router_pick_directory_server_impl(type, flags);
  862. return choice;
  863. }
  864. /** Try to determine which fraction of v2 and v3 directory requests aimed at
  865. * caches will be sent to us. Set *<b>v2_share_out</b> and
  866. * *<b>v3_share_out</b> to the fractions of v2 and v3 protocol shares we
  867. * expect to see, respectively. Return 0 on success, negative on failure. */
  868. int
  869. router_get_my_share_of_directory_requests(double *v2_share_out,
  870. double *v3_share_out)
  871. {
  872. const routerinfo_t *me = router_get_my_routerinfo();
  873. const routerstatus_t *rs;
  874. const int pds_flags = PDS_ALLOW_SELF|PDS_IGNORE_FASCISTFIREWALL;
  875. *v2_share_out = *v3_share_out = 0.0;
  876. if (!me)
  877. return -1;
  878. rs = router_get_consensus_status_by_id(me->cache_info.identity_digest);
  879. if (!rs)
  880. return -1;
  881. /* Calling for side effect */
  882. /* XXXX This is a bit of a kludge */
  883. if (rs->is_v2_dir) {
  884. sl_last_total_weighted_bw = 0;
  885. router_pick_directory_server(V2_DIRINFO, pds_flags);
  886. if (sl_last_total_weighted_bw != 0) {
  887. *v2_share_out = U64_TO_DBL(sl_last_weighted_bw_of_me) /
  888. U64_TO_DBL(sl_last_total_weighted_bw);
  889. }
  890. }
  891. {
  892. sl_last_total_weighted_bw = 0;
  893. router_pick_directory_server(V3_DIRINFO, pds_flags);
  894. if (sl_last_total_weighted_bw != 0) {
  895. *v3_share_out = U64_TO_DBL(sl_last_weighted_bw_of_me) /
  896. U64_TO_DBL(sl_last_total_weighted_bw);
  897. }
  898. }
  899. return 0;
  900. }
  901. /** Return the trusted_dir_server_t for the directory authority whose identity
  902. * key hashes to <b>digest</b>, or NULL if no such authority is known.
  903. */
  904. trusted_dir_server_t *
  905. router_get_trusteddirserver_by_digest(const char *digest)
  906. {
  907. if (!trusted_dir_servers)
  908. return NULL;
  909. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  910. {
  911. if (tor_memeq(ds->digest, digest, DIGEST_LEN))
  912. return ds;
  913. });
  914. return NULL;
  915. }
  916. /** Return the trusted_dir_server_t for the directory authority whose
  917. * v3 identity key hashes to <b>digest</b>, or NULL if no such authority
  918. * is known.
  919. */
  920. trusted_dir_server_t *
  921. trusteddirserver_get_by_v3_auth_digest(const char *digest)
  922. {
  923. if (!trusted_dir_servers)
  924. return NULL;
  925. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  926. {
  927. if (tor_memeq(ds->v3_identity_digest, digest, DIGEST_LEN) &&
  928. (ds->type & V3_DIRINFO))
  929. return ds;
  930. });
  931. return NULL;
  932. }
  933. /** Try to find a running trusted dirserver. Flags are as for
  934. * router_pick_directory_server.
  935. */
  936. const routerstatus_t *
  937. router_pick_trusteddirserver(dirinfo_type_t type, int flags)
  938. {
  939. const routerstatus_t *choice;
  940. int busy = 0;
  941. if (get_options()->PreferTunneledDirConns)
  942. flags |= PDS_PREFER_TUNNELED_DIR_CONNS_;
  943. choice = router_pick_trusteddirserver_impl(type, flags, &busy);
  944. if (choice || !(flags & PDS_RETRY_IF_NO_SERVERS))
  945. return choice;
  946. if (busy) {
  947. /* If the reason that we got no server is that servers are "busy",
  948. * we must be excluding good servers because we already have serverdesc
  949. * fetches with them. Do not mark down servers up because of this. */
  950. tor_assert((flags & (PDS_NO_EXISTING_SERVERDESC_FETCH|
  951. PDS_NO_EXISTING_MICRODESC_FETCH)));
  952. return NULL;
  953. }
  954. log_info(LD_DIR,
  955. "No trusted dirservers are reachable. Trying them all again.");
  956. mark_all_trusteddirservers_up();
  957. return router_pick_trusteddirserver_impl(type, flags, NULL);
  958. }
  959. /** How long do we avoid using a directory server after it's given us a 503? */
  960. #define DIR_503_TIMEOUT (60*60)
  961. /** Pick a random running valid directory server/mirror from our
  962. * routerlist. Arguments are as for router_pick_directory_server(), except
  963. * that RETRY_IF_NO_SERVERS is ignored, and:
  964. *
  965. * If the PDS_PREFER_TUNNELED_DIR_CONNS_ flag is set, prefer directory servers
  966. * that we can use with BEGINDIR.
  967. */
  968. static const routerstatus_t *
  969. router_pick_directory_server_impl(dirinfo_type_t type, int flags)
  970. {
  971. const or_options_t *options = get_options();
  972. const node_t *result;
  973. smartlist_t *direct, *tunnel;
  974. smartlist_t *trusted_direct, *trusted_tunnel;
  975. smartlist_t *overloaded_direct, *overloaded_tunnel;
  976. time_t now = time(NULL);
  977. const networkstatus_t *consensus = networkstatus_get_latest_consensus();
  978. int requireother = ! (flags & PDS_ALLOW_SELF);
  979. int fascistfirewall = ! (flags & PDS_IGNORE_FASCISTFIREWALL);
  980. int prefer_tunnel = (flags & PDS_PREFER_TUNNELED_DIR_CONNS_);
  981. int try_excluding = 1, n_excluded = 0;
  982. if (!consensus)
  983. return NULL;
  984. retry_without_exclude:
  985. direct = smartlist_new();
  986. tunnel = smartlist_new();
  987. trusted_direct = smartlist_new();
  988. trusted_tunnel = smartlist_new();
  989. overloaded_direct = smartlist_new();
  990. overloaded_tunnel = smartlist_new();
  991. /* Find all the running dirservers we know about. */
  992. SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), const node_t *, node) {
  993. int is_trusted;
  994. int is_overloaded;
  995. tor_addr_t addr;
  996. const routerstatus_t *status = node->rs;
  997. const country_t country = node->country;
  998. if (!status)
  999. continue;
  1000. if (!node->is_running || !status->dir_port || !node->is_valid)
  1001. continue;
  1002. if (node->is_bad_directory)
  1003. continue;
  1004. if (requireother && router_digest_is_me(node->identity))
  1005. continue;
  1006. is_trusted = router_digest_is_trusted_dir(node->identity);
  1007. if ((type & V2_DIRINFO) && !(node->rs->is_v2_dir || is_trusted))
  1008. continue;
  1009. if ((type & EXTRAINFO_DIRINFO) &&
  1010. !router_supports_extrainfo(node->identity, 0))
  1011. continue;
  1012. if ((type & MICRODESC_DIRINFO) && !is_trusted &&
  1013. !node->rs->version_supports_microdesc_cache)
  1014. continue;
  1015. if (try_excluding &&
  1016. routerset_contains_routerstatus(options->ExcludeNodes, status,
  1017. country)) {
  1018. ++n_excluded;
  1019. continue;
  1020. }
  1021. /* XXXX IP6 proposal 118 */
  1022. tor_addr_from_ipv4h(&addr, node->rs->addr);
  1023. is_overloaded = status->last_dir_503_at + DIR_503_TIMEOUT > now;
  1024. if (prefer_tunnel &&
  1025. (!fascistfirewall ||
  1026. fascist_firewall_allows_address_or(&addr, status->or_port)))
  1027. smartlist_add(is_trusted ? trusted_tunnel :
  1028. is_overloaded ? overloaded_tunnel : tunnel, (void*)node);
  1029. else if (!fascistfirewall ||
  1030. fascist_firewall_allows_address_dir(&addr, status->dir_port))
  1031. smartlist_add(is_trusted ? trusted_direct :
  1032. is_overloaded ? overloaded_direct : direct, (void*)node);
  1033. } SMARTLIST_FOREACH_END(node);
  1034. if (smartlist_len(tunnel)) {
  1035. result = node_sl_choose_by_bandwidth(tunnel, WEIGHT_FOR_DIR);
  1036. } else if (smartlist_len(overloaded_tunnel)) {
  1037. result = node_sl_choose_by_bandwidth(overloaded_tunnel,
  1038. WEIGHT_FOR_DIR);
  1039. } else if (smartlist_len(trusted_tunnel)) {
  1040. /* FFFF We don't distinguish between trusteds and overloaded trusteds
  1041. * yet. Maybe one day we should. */
  1042. /* FFFF We also don't load balance over authorities yet. I think this
  1043. * is a feature, but it could easily be a bug. -RD */
  1044. result = smartlist_choose(trusted_tunnel);
  1045. } else if (smartlist_len(direct)) {
  1046. result = node_sl_choose_by_bandwidth(direct, WEIGHT_FOR_DIR);
  1047. } else if (smartlist_len(overloaded_direct)) {
  1048. result = node_sl_choose_by_bandwidth(overloaded_direct,
  1049. WEIGHT_FOR_DIR);
  1050. } else {
  1051. result = smartlist_choose(trusted_direct);
  1052. }
  1053. smartlist_free(direct);
  1054. smartlist_free(tunnel);
  1055. smartlist_free(trusted_direct);
  1056. smartlist_free(trusted_tunnel);
  1057. smartlist_free(overloaded_direct);
  1058. smartlist_free(overloaded_tunnel);
  1059. if (result == NULL && try_excluding && !options->StrictNodes && n_excluded) {
  1060. /* If we got no result, and we are excluding nodes, and StrictNodes is
  1061. * not set, try again without excluding nodes. */
  1062. try_excluding = 0;
  1063. n_excluded = 0;
  1064. goto retry_without_exclude;
  1065. }
  1066. return result ? result->rs : NULL;
  1067. }
  1068. /** Choose randomly from among the trusted dirservers that are up. Flags
  1069. * are as for router_pick_directory_server_impl().
  1070. */
  1071. static const routerstatus_t *
  1072. router_pick_trusteddirserver_impl(dirinfo_type_t type, int flags,
  1073. int *n_busy_out)
  1074. {
  1075. const or_options_t *options = get_options();
  1076. smartlist_t *direct, *tunnel;
  1077. smartlist_t *overloaded_direct, *overloaded_tunnel;
  1078. const routerinfo_t *me = router_get_my_routerinfo();
  1079. const routerstatus_t *result;
  1080. time_t now = time(NULL);
  1081. const int requireother = ! (flags & PDS_ALLOW_SELF);
  1082. const int fascistfirewall = ! (flags & PDS_IGNORE_FASCISTFIREWALL);
  1083. const int prefer_tunnel = (flags & PDS_PREFER_TUNNELED_DIR_CONNS_);
  1084. const int no_serverdesc_fetching =(flags & PDS_NO_EXISTING_SERVERDESC_FETCH);
  1085. const int no_microdesc_fetching =(flags & PDS_NO_EXISTING_MICRODESC_FETCH);
  1086. int n_busy = 0;
  1087. int try_excluding = 1, n_excluded = 0;
  1088. if (!trusted_dir_servers)
  1089. return NULL;
  1090. retry_without_exclude:
  1091. direct = smartlist_new();
  1092. tunnel = smartlist_new();
  1093. overloaded_direct = smartlist_new();
  1094. overloaded_tunnel = smartlist_new();
  1095. SMARTLIST_FOREACH_BEGIN(trusted_dir_servers, trusted_dir_server_t *, d)
  1096. {
  1097. int is_overloaded =
  1098. d->fake_status.last_dir_503_at + DIR_503_TIMEOUT > now;
  1099. tor_addr_t addr;
  1100. if (!d->is_running) continue;
  1101. if ((type & d->type) == 0)
  1102. continue;
  1103. if ((type & EXTRAINFO_DIRINFO) &&
  1104. !router_supports_extrainfo(d->digest, 1))
  1105. continue;
  1106. if (requireother && me && router_digest_is_me(d->digest))
  1107. continue;
  1108. if (try_excluding &&
  1109. routerset_contains_routerstatus(options->ExcludeNodes,
  1110. &d->fake_status, -1)) {
  1111. ++n_excluded;
  1112. continue;
  1113. }
  1114. /* XXXX IP6 proposal 118 */
  1115. tor_addr_from_ipv4h(&addr, d->addr);
  1116. if (no_serverdesc_fetching) {
  1117. if (connection_get_by_type_addr_port_purpose(
  1118. CONN_TYPE_DIR, &addr, d->dir_port, DIR_PURPOSE_FETCH_SERVERDESC)
  1119. || connection_get_by_type_addr_port_purpose(
  1120. CONN_TYPE_DIR, &addr, d->dir_port, DIR_PURPOSE_FETCH_EXTRAINFO)) {
  1121. //log_debug(LD_DIR, "We have an existing connection to fetch "
  1122. // "descriptor from %s; delaying",d->description);
  1123. ++n_busy;
  1124. continue;
  1125. }
  1126. }
  1127. if (no_microdesc_fetching) {
  1128. if (connection_get_by_type_addr_port_purpose(
  1129. CONN_TYPE_DIR, &addr, d->dir_port, DIR_PURPOSE_FETCH_MICRODESC)) {
  1130. ++n_busy;
  1131. continue;
  1132. }
  1133. }
  1134. if (prefer_tunnel &&
  1135. d->or_port &&
  1136. (!fascistfirewall ||
  1137. fascist_firewall_allows_address_or(&addr, d->or_port)))
  1138. smartlist_add(is_overloaded ? overloaded_tunnel : tunnel,
  1139. &d->fake_status);
  1140. else if (!fascistfirewall ||
  1141. fascist_firewall_allows_address_dir(&addr, d->dir_port))
  1142. smartlist_add(is_overloaded ? overloaded_direct : direct,
  1143. &d->fake_status);
  1144. }
  1145. SMARTLIST_FOREACH_END(d);
  1146. if (smartlist_len(tunnel)) {
  1147. result = smartlist_choose(tunnel);
  1148. } else if (smartlist_len(overloaded_tunnel)) {
  1149. result = smartlist_choose(overloaded_tunnel);
  1150. } else if (smartlist_len(direct)) {
  1151. result = smartlist_choose(direct);
  1152. } else {
  1153. result = smartlist_choose(overloaded_direct);
  1154. }
  1155. if (n_busy_out)
  1156. *n_busy_out = n_busy;
  1157. smartlist_free(direct);
  1158. smartlist_free(tunnel);
  1159. smartlist_free(overloaded_direct);
  1160. smartlist_free(overloaded_tunnel);
  1161. if (result == NULL && try_excluding && !options->StrictNodes && n_excluded) {
  1162. /* If we got no result, and we are excluding nodes, and StrictNodes is
  1163. * not set, try again without excluding nodes. */
  1164. try_excluding = 0;
  1165. n_excluded = 0;
  1166. goto retry_without_exclude;
  1167. }
  1168. return result;
  1169. }
  1170. /** Go through and mark the authoritative dirservers as up. */
  1171. static void
  1172. mark_all_trusteddirservers_up(void)
  1173. {
  1174. SMARTLIST_FOREACH(nodelist_get_list(), node_t *, node, {
  1175. if (router_digest_is_trusted_dir(node->identity))
  1176. node->is_running = 1;
  1177. });
  1178. if (trusted_dir_servers) {
  1179. SMARTLIST_FOREACH_BEGIN(trusted_dir_servers, trusted_dir_server_t *, dir) {
  1180. routerstatus_t *rs;
  1181. dir->is_running = 1;
  1182. download_status_reset(&dir->v2_ns_dl_status);
  1183. rs = router_get_mutable_consensus_status_by_id(dir->digest);
  1184. if (rs) {
  1185. rs->last_dir_503_at = 0;
  1186. control_event_networkstatus_changed_single(rs);
  1187. }
  1188. } SMARTLIST_FOREACH_END(dir);
  1189. }
  1190. router_dir_info_changed();
  1191. }
  1192. /** Return true iff r1 and r2 have the same address and OR port. */
  1193. int
  1194. routers_have_same_or_addrs(const routerinfo_t *r1, const routerinfo_t *r2)
  1195. {
  1196. return r1->addr == r2->addr && r1->or_port == r2->or_port &&
  1197. tor_addr_eq(&r1->ipv6_addr, &r2->ipv6_addr) &&
  1198. r1->ipv6_orport == r2->ipv6_orport;
  1199. }
  1200. /** Reset all internal variables used to count failed downloads of network
  1201. * status objects. */
  1202. void
  1203. router_reset_status_download_failures(void)
  1204. {
  1205. mark_all_trusteddirservers_up();
  1206. }
  1207. /** Given a <b>router</b>, add every node_t in its family (including the
  1208. * node itself!) to <b>sl</b>.
  1209. *
  1210. * Note the type mismatch: This function takes a routerinfo, but adds nodes
  1211. * to the smartlist!
  1212. */
  1213. static void
  1214. routerlist_add_node_and_family(smartlist_t *sl, const routerinfo_t *router)
  1215. {
  1216. /* XXXX MOVE ? */
  1217. node_t fake_node;
  1218. const node_t *node = node_get_by_id(router->cache_info.identity_digest);;
  1219. if (node == NULL) {
  1220. memset(&fake_node, 0, sizeof(fake_node));
  1221. fake_node.ri = (routerinfo_t *)router;
  1222. memcpy(fake_node.identity, router->cache_info.identity_digest, DIGEST_LEN);
  1223. node = &fake_node;
  1224. }
  1225. nodelist_add_node_and_family(sl, node);
  1226. }
  1227. /** Return 1 iff any member of the (possibly NULL) comma-separated list
  1228. * <b>list</b> is an acceptable nickname or hexdigest for <b>router</b>. Else
  1229. * return 0.
  1230. */
  1231. int
  1232. router_nickname_is_in_list(const routerinfo_t *router, const char *list)
  1233. {
  1234. smartlist_t *nickname_list;
  1235. int v = 0;
  1236. if (!list)
  1237. return 0; /* definitely not */
  1238. tor_assert(router);
  1239. nickname_list = smartlist_new();
  1240. smartlist_split_string(nickname_list, list, ",",
  1241. SPLIT_SKIP_SPACE|SPLIT_STRIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1242. SMARTLIST_FOREACH(nickname_list, const char *, cp,
  1243. if (router_nickname_matches(router, cp)) {v=1;break;});
  1244. SMARTLIST_FOREACH(nickname_list, char *, cp, tor_free(cp));
  1245. smartlist_free(nickname_list);
  1246. return v;
  1247. }
  1248. /** Add every suitable node from our nodelist to <b>sl</b>, so that
  1249. * we can pick a node for a circuit.
  1250. */
  1251. static void
  1252. router_add_running_nodes_to_smartlist(smartlist_t *sl, int allow_invalid,
  1253. int need_uptime, int need_capacity,
  1254. int need_guard, int need_desc)
  1255. { /* XXXX MOVE */
  1256. SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), const node_t *, node) {
  1257. if (!node->is_running ||
  1258. (!node->is_valid && !allow_invalid))
  1259. continue;
  1260. if (need_desc && !(node->ri || (node->rs && node->md)))
  1261. continue;
  1262. if (node->ri && node->ri->purpose != ROUTER_PURPOSE_GENERAL)
  1263. continue;
  1264. if (node_is_unreliable(node, need_uptime, need_capacity, need_guard))
  1265. continue;
  1266. smartlist_add(sl, (void *)node);
  1267. } SMARTLIST_FOREACH_END(node);
  1268. }
  1269. /** Look through the routerlist until we find a router that has my key.
  1270. Return it. */
  1271. const routerinfo_t *
  1272. routerlist_find_my_routerinfo(void)
  1273. {
  1274. if (!routerlist)
  1275. return NULL;
  1276. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, router,
  1277. {
  1278. if (router_is_me(router))
  1279. return router;
  1280. });
  1281. return NULL;
  1282. }
  1283. /** Return the smaller of the router's configured BandwidthRate
  1284. * and its advertised capacity. */
  1285. uint32_t
  1286. router_get_advertised_bandwidth(const routerinfo_t *router)
  1287. {
  1288. if (router->bandwidthcapacity < router->bandwidthrate)
  1289. return router->bandwidthcapacity;
  1290. return router->bandwidthrate;
  1291. }
  1292. /** Do not weight any declared bandwidth more than this much when picking
  1293. * routers by bandwidth. */
  1294. #define DEFAULT_MAX_BELIEVABLE_BANDWIDTH 10000000 /* 10 MB/sec */
  1295. /** Return the smaller of the router's configured BandwidthRate
  1296. * and its advertised capacity, capped by max-believe-bw. */
  1297. uint32_t
  1298. router_get_advertised_bandwidth_capped(const routerinfo_t *router)
  1299. {
  1300. uint32_t result = router->bandwidthcapacity;
  1301. if (result > router->bandwidthrate)
  1302. result = router->bandwidthrate;
  1303. if (result > DEFAULT_MAX_BELIEVABLE_BANDWIDTH)
  1304. result = DEFAULT_MAX_BELIEVABLE_BANDWIDTH;
  1305. return result;
  1306. }
  1307. /** Given an array of double/uint64_t unions that are currently being used as
  1308. * doubles, convert them to uint64_t, and try to scale them linearly so as to
  1309. * much of the range of uint64_t. If <b>total_out</b> is provided, set it to
  1310. * the sum of all elements in the array _before_ scaling. */
  1311. /* private */ void
  1312. scale_array_elements_to_u64(u64_dbl_t *entries, int n_entries,
  1313. uint64_t *total_out)
  1314. {
  1315. double total = 0.0;
  1316. double scale_factor;
  1317. int i;
  1318. /* big, but far away from overflowing an int64_t */
  1319. #define SCALE_TO_U64_MAX (INT64_MAX / 4)
  1320. for (i = 0; i < n_entries; ++i)
  1321. total += entries[i].dbl;
  1322. scale_factor = SCALE_TO_U64_MAX / total;
  1323. for (i = 0; i < n_entries; ++i)
  1324. entries[i].u64 = tor_llround(entries[i].dbl * scale_factor);
  1325. if (total_out)
  1326. *total_out = (uint64_t) total;
  1327. #undef SCALE_TO_U64_MAX
  1328. }
  1329. /** Time-invariant 64-bit greater-than; works on two integers in the range
  1330. * (0,INT64_MAX). */
  1331. #if SIZEOF_VOID_P == 8
  1332. #define gt_i64_timei(a,b) ((a) > (b))
  1333. #else
  1334. static INLINE int
  1335. gt_i64_timei(uint64_t a, uint64_t b)
  1336. {
  1337. int64_t diff = (int64_t) (b - a);
  1338. int res = diff >> 63;
  1339. return res & 1;
  1340. }
  1341. #endif
  1342. /** Pick a random element of <b>n_entries</b>-element array <b>entries</b>,
  1343. * choosing each element with a probability proportional to its (uint64_t)
  1344. * value, and return the index of that element. If all elements are 0, choose
  1345. * an index at random. Return -1 on error.
  1346. */
  1347. /* private */ int
  1348. choose_array_element_by_weight(const u64_dbl_t *entries, int n_entries)
  1349. {
  1350. int i, i_chosen=-1, n_chosen=0;
  1351. uint64_t total_so_far = 0;
  1352. uint64_t rand_val;
  1353. uint64_t total = 0;
  1354. for (i = 0; i < n_entries; ++i)
  1355. total += entries[i].u64;
  1356. if (n_entries < 1)
  1357. return -1;
  1358. if (total == 0)
  1359. return crypto_rand_int(n_entries);
  1360. tor_assert(total < INT64_MAX);
  1361. rand_val = crypto_rand_uint64(total);
  1362. for (i = 0; i < n_entries; ++i) {
  1363. total_so_far += entries[i].u64;
  1364. if (gt_i64_timei(total_so_far, rand_val)) {
  1365. i_chosen = i;
  1366. n_chosen++;
  1367. /* Set rand_val to INT64_MAX rather than stopping the loop. This way,
  1368. * the time we spend in the loop does not leak which element we chose. */
  1369. rand_val = INT64_MAX;
  1370. }
  1371. }
  1372. tor_assert(total_so_far == total);
  1373. tor_assert(n_chosen == 1);
  1374. tor_assert(i_chosen >= 0);
  1375. tor_assert(i_chosen < n_entries);
  1376. return i_chosen;
  1377. }
  1378. /** When weighting bridges, enforce these values as lower and upper
  1379. * bound for believable bandwidth, because there is no way for us
  1380. * to verify a bridge's bandwidth currently. */
  1381. #define BRIDGE_MIN_BELIEVABLE_BANDWIDTH 20000 /* 20 kB/sec */
  1382. #define BRIDGE_MAX_BELIEVABLE_BANDWIDTH 100000 /* 100 kB/sec */
  1383. /** Return the smaller of the router's configured BandwidthRate
  1384. * and its advertised capacity, making sure to stay within the
  1385. * interval between bridge-min-believe-bw and
  1386. * bridge-max-believe-bw. */
  1387. static uint32_t
  1388. bridge_get_advertised_bandwidth_bounded(routerinfo_t *router)
  1389. {
  1390. uint32_t result = router->bandwidthcapacity;
  1391. if (result > router->bandwidthrate)
  1392. result = router->bandwidthrate;
  1393. if (result > BRIDGE_MAX_BELIEVABLE_BANDWIDTH)
  1394. result = BRIDGE_MAX_BELIEVABLE_BANDWIDTH;
  1395. else if (result < BRIDGE_MIN_BELIEVABLE_BANDWIDTH)
  1396. result = BRIDGE_MIN_BELIEVABLE_BANDWIDTH;
  1397. return result;
  1398. }
  1399. /** Return bw*1000, unless bw*1000 would overflow, in which case return
  1400. * INT32_MAX. */
  1401. static INLINE int32_t
  1402. kb_to_bytes(uint32_t bw)
  1403. {
  1404. return (bw > (INT32_MAX/1000)) ? INT32_MAX : bw*1000;
  1405. }
  1406. /** Helper function:
  1407. * choose a random element of smartlist <b>sl</b> of nodes, weighted by
  1408. * the advertised bandwidth of each element using the consensus
  1409. * bandwidth weights.
  1410. *
  1411. * If <b>rule</b>==WEIGHT_FOR_EXIT. we're picking an exit node: consider all
  1412. * nodes' bandwidth equally regardless of their Exit status, since there may
  1413. * be some in the list because they exit to obscure ports. If
  1414. * <b>rule</b>==NO_WEIGHTING, we're picking a non-exit node: weight
  1415. * exit-node's bandwidth less depending on the smallness of the fraction of
  1416. * Exit-to-total bandwidth. If <b>rule</b>==WEIGHT_FOR_GUARD, we're picking a
  1417. * guard node: consider all guard's bandwidth equally. Otherwise, weight
  1418. * guards proportionally less.
  1419. */
  1420. static const node_t *
  1421. smartlist_choose_node_by_bandwidth_weights(smartlist_t *sl,
  1422. bandwidth_weight_rule_t rule)
  1423. {
  1424. int64_t weight_scale;
  1425. double Wg = -1, Wm = -1, We = -1, Wd = -1;
  1426. double Wgb = -1, Wmb = -1, Web = -1, Wdb = -1;
  1427. uint64_t weighted_bw = 0;
  1428. u64_dbl_t *bandwidths;
  1429. /* Can't choose exit and guard at same time */
  1430. tor_assert(rule == NO_WEIGHTING ||
  1431. rule == WEIGHT_FOR_EXIT ||
  1432. rule == WEIGHT_FOR_GUARD ||
  1433. rule == WEIGHT_FOR_MID ||
  1434. rule == WEIGHT_FOR_DIR);
  1435. if (smartlist_len(sl) == 0) {
  1436. log_info(LD_CIRC,
  1437. "Empty routerlist passed in to consensus weight node "
  1438. "selection for rule %s",
  1439. bandwidth_weight_rule_to_string(rule));
  1440. return NULL;
  1441. }
  1442. weight_scale = circuit_build_times_get_bw_scale(NULL);
  1443. if (rule == WEIGHT_FOR_GUARD) {
  1444. Wg = networkstatus_get_bw_weight(NULL, "Wgg", -1);
  1445. Wm = networkstatus_get_bw_weight(NULL, "Wgm", -1); /* Bridges */
  1446. We = 0;
  1447. Wd = networkstatus_get_bw_weight(NULL, "Wgd", -1);
  1448. Wgb = networkstatus_get_bw_weight(NULL, "Wgb", -1);
  1449. Wmb = networkstatus_get_bw_weight(NULL, "Wmb", -1);
  1450. Web = networkstatus_get_bw_weight(NULL, "Web", -1);
  1451. Wdb = networkstatus_get_bw_weight(NULL, "Wdb", -1);
  1452. } else if (rule == WEIGHT_FOR_MID) {
  1453. Wg = networkstatus_get_bw_weight(NULL, "Wmg", -1);
  1454. Wm = networkstatus_get_bw_weight(NULL, "Wmm", -1);
  1455. We = networkstatus_get_bw_weight(NULL, "Wme", -1);
  1456. Wd = networkstatus_get_bw_weight(NULL, "Wmd", -1);
  1457. Wgb = networkstatus_get_bw_weight(NULL, "Wgb", -1);
  1458. Wmb = networkstatus_get_bw_weight(NULL, "Wmb", -1);
  1459. Web = networkstatus_get_bw_weight(NULL, "Web", -1);
  1460. Wdb = networkstatus_get_bw_weight(NULL, "Wdb", -1);
  1461. } else if (rule == WEIGHT_FOR_EXIT) {
  1462. // Guards CAN be exits if they have weird exit policies
  1463. // They are d then I guess...
  1464. We = networkstatus_get_bw_weight(NULL, "Wee", -1);
  1465. Wm = networkstatus_get_bw_weight(NULL, "Wem", -1); /* Odd exit policies */
  1466. Wd = networkstatus_get_bw_weight(NULL, "Wed", -1);
  1467. Wg = networkstatus_get_bw_weight(NULL, "Weg", -1); /* Odd exit policies */
  1468. Wgb = networkstatus_get_bw_weight(NULL, "Wgb", -1);
  1469. Wmb = networkstatus_get_bw_weight(NULL, "Wmb", -1);
  1470. Web = networkstatus_get_bw_weight(NULL, "Web", -1);
  1471. Wdb = networkstatus_get_bw_weight(NULL, "Wdb", -1);
  1472. } else if (rule == WEIGHT_FOR_DIR) {
  1473. We = networkstatus_get_bw_weight(NULL, "Wbe", -1);
  1474. Wm = networkstatus_get_bw_weight(NULL, "Wbm", -1);
  1475. Wd = networkstatus_get_bw_weight(NULL, "Wbd", -1);
  1476. Wg = networkstatus_get_bw_weight(NULL, "Wbg", -1);
  1477. Wgb = Wmb = Web = Wdb = weight_scale;
  1478. } else if (rule == NO_WEIGHTING) {
  1479. Wg = Wm = We = Wd = weight_scale;
  1480. Wgb = Wmb = Web = Wdb = weight_scale;
  1481. }
  1482. if (Wg < 0 || Wm < 0 || We < 0 || Wd < 0 || Wgb < 0 || Wmb < 0 || Wdb < 0
  1483. || Web < 0) {
  1484. log_debug(LD_CIRC,
  1485. "Got negative bandwidth weights. Defaulting to old selection"
  1486. " algorithm.");
  1487. return NULL; // Use old algorithm.
  1488. }
  1489. Wg /= weight_scale;
  1490. Wm /= weight_scale;
  1491. We /= weight_scale;
  1492. Wd /= weight_scale;
  1493. Wgb /= weight_scale;
  1494. Wmb /= weight_scale;
  1495. Web /= weight_scale;
  1496. Wdb /= weight_scale;
  1497. bandwidths = tor_malloc_zero(sizeof(u64_dbl_t)*smartlist_len(sl));
  1498. // Cycle through smartlist and total the bandwidth.
  1499. SMARTLIST_FOREACH_BEGIN(sl, const node_t *, node) {
  1500. int is_exit = 0, is_guard = 0, is_dir = 0, this_bw = 0, is_me = 0;
  1501. double weight = 1;
  1502. is_exit = node->is_exit && ! node->is_bad_exit;
  1503. is_guard = node->is_possible_guard;
  1504. is_dir = node_is_dir(node);
  1505. if (node->rs) {
  1506. if (!node->rs->has_bandwidth) {
  1507. tor_free(bandwidths);
  1508. /* This should never happen, unless all the authorites downgrade
  1509. * to 0.2.0 or rogue routerstatuses get inserted into our consensus. */
  1510. log_warn(LD_BUG,
  1511. "Consensus is not listing bandwidths. Defaulting back to "
  1512. "old router selection algorithm.");
  1513. return NULL;
  1514. }
  1515. this_bw = kb_to_bytes(node->rs->bandwidth);
  1516. } else if (node->ri) {
  1517. /* bridge or other descriptor not in our consensus */
  1518. this_bw = bridge_get_advertised_bandwidth_bounded(node->ri);
  1519. } else {
  1520. /* We can't use this one. */
  1521. continue;
  1522. }
  1523. is_me = router_digest_is_me(node->identity);
  1524. if (is_guard && is_exit) {
  1525. weight = (is_dir ? Wdb*Wd : Wd);
  1526. } else if (is_guard) {
  1527. weight = (is_dir ? Wgb*Wg : Wg);
  1528. } else if (is_exit) {
  1529. weight = (is_dir ? Web*We : We);
  1530. } else { // middle
  1531. weight = (is_dir ? Wmb*Wm : Wm);
  1532. }
  1533. /* These should be impossible; but overflows here would be bad, so let's
  1534. * make sure. */
  1535. if (this_bw < 0)
  1536. this_bw = 0;
  1537. if (weight < 0.0)
  1538. weight = 0.0;
  1539. bandwidths[node_sl_idx].dbl = weight*this_bw + 0.5;
  1540. if (is_me)
  1541. sl_last_weighted_bw_of_me = (uint64_t) bandwidths[node_sl_idx].dbl;
  1542. } SMARTLIST_FOREACH_END(node);
  1543. log_debug(LD_CIRC, "Choosing node for rule %s based on weights "
  1544. "Wg=%f Wm=%f We=%f Wd=%f with total bw "U64_FORMAT,
  1545. bandwidth_weight_rule_to_string(rule),
  1546. Wg, Wm, We, Wd, U64_PRINTF_ARG(weighted_bw));
  1547. scale_array_elements_to_u64(bandwidths, smartlist_len(sl),
  1548. &sl_last_total_weighted_bw);
  1549. {
  1550. int idx = choose_array_element_by_weight(bandwidths,
  1551. smartlist_len(sl));
  1552. tor_free(bandwidths);
  1553. return idx < 0 ? NULL : smartlist_get(sl, idx);
  1554. }
  1555. }
  1556. /** Helper function:
  1557. * choose a random node_t element of smartlist <b>sl</b>, weighted by
  1558. * the advertised bandwidth of each element.
  1559. *
  1560. * If <b>rule</b>==WEIGHT_FOR_EXIT. we're picking an exit node: consider all
  1561. * nodes' bandwidth equally regardless of their Exit status, since there may
  1562. * be some in the list because they exit to obscure ports. If
  1563. * <b>rule</b>==NO_WEIGHTING, we're picking a non-exit node: weight
  1564. * exit-node's bandwidth less depending on the smallness of the fraction of
  1565. * Exit-to-total bandwidth. If <b>rule</b>==WEIGHT_FOR_GUARD, we're picking a
  1566. * guard node: consider all guard's bandwidth equally. Otherwise, weight
  1567. * guards proportionally less.
  1568. */
  1569. static const node_t *
  1570. smartlist_choose_node_by_bandwidth(smartlist_t *sl,
  1571. bandwidth_weight_rule_t rule)
  1572. {
  1573. unsigned int i;
  1574. u64_dbl_t *bandwidths;
  1575. int is_exit;
  1576. int is_guard;
  1577. int is_fast;
  1578. double total_nonexit_bw = 0, total_exit_bw = 0;
  1579. double total_nonguard_bw = 0, total_guard_bw = 0;
  1580. double exit_weight;
  1581. double guard_weight;
  1582. int n_unknown = 0;
  1583. bitarray_t *fast_bits;
  1584. bitarray_t *exit_bits;
  1585. bitarray_t *guard_bits;
  1586. int me_idx = -1;
  1587. // This function does not support WEIGHT_FOR_DIR
  1588. // or WEIGHT_FOR_MID
  1589. if (rule == WEIGHT_FOR_DIR || rule == WEIGHT_FOR_MID) {
  1590. rule = NO_WEIGHTING;
  1591. }
  1592. /* Can't choose exit and guard at same time */
  1593. tor_assert(rule == NO_WEIGHTING ||
  1594. rule == WEIGHT_FOR_EXIT ||
  1595. rule == WEIGHT_FOR_GUARD);
  1596. if (smartlist_len(sl) == 0) {
  1597. log_info(LD_CIRC,
  1598. "Empty routerlist passed in to old node selection for rule %s",
  1599. bandwidth_weight_rule_to_string(rule));
  1600. return NULL;
  1601. }
  1602. /* First count the total bandwidth weight, and make a list
  1603. * of each value. We use UINT64_MAX to indicate "unknown". */
  1604. bandwidths = tor_malloc_zero(sizeof(u64_dbl_t)*smartlist_len(sl));
  1605. fast_bits = bitarray_init_zero(smartlist_len(sl));
  1606. exit_bits = bitarray_init_zero(smartlist_len(sl));
  1607. guard_bits = bitarray_init_zero(smartlist_len(sl));
  1608. /* Iterate over all the routerinfo_t or routerstatus_t, and */
  1609. SMARTLIST_FOREACH_BEGIN(sl, const node_t *, node) {
  1610. /* first, learn what bandwidth we think i has */
  1611. int is_known = 1;
  1612. uint32_t this_bw = 0;
  1613. i = node_sl_idx;
  1614. if (router_digest_is_me(node->identity))
  1615. me_idx = node_sl_idx;
  1616. is_exit = node->is_exit;
  1617. is_guard = node->is_possible_guard;
  1618. if (node->rs) {
  1619. if (node->rs->has_bandwidth) {
  1620. this_bw = kb_to_bytes(node->rs->bandwidth);
  1621. } else { /* guess */
  1622. is_known = 0;
  1623. }
  1624. } else if (node->ri) {
  1625. /* Must be a bridge if we're willing to use it */
  1626. this_bw = bridge_get_advertised_bandwidth_bounded(node->ri);
  1627. }
  1628. if (is_exit)
  1629. bitarray_set(exit_bits, i);
  1630. if (is_guard)
  1631. bitarray_set(guard_bits, i);
  1632. if (node->is_fast)
  1633. bitarray_set(fast_bits, i);
  1634. if (is_known) {
  1635. bandwidths[i].dbl = this_bw;
  1636. if (is_guard)
  1637. total_guard_bw += this_bw;
  1638. else
  1639. total_nonguard_bw += this_bw;
  1640. if (is_exit)
  1641. total_exit_bw += this_bw;
  1642. else
  1643. total_nonexit_bw += this_bw;
  1644. } else {
  1645. ++n_unknown;
  1646. bandwidths[i].dbl = -1.0;
  1647. }
  1648. } SMARTLIST_FOREACH_END(node);
  1649. #define EPSILON .1
  1650. /* Now, fill in the unknown values. */
  1651. if (n_unknown) {
  1652. int32_t avg_fast, avg_slow;
  1653. if (total_exit_bw+total_nonexit_bw < EPSILON) {
  1654. /* if there's some bandwidth, there's at least one known router,
  1655. * so no worries about div by 0 here */
  1656. int n_known = smartlist_len(sl)-n_unknown;
  1657. avg_fast = avg_slow = (int32_t)
  1658. ((total_exit_bw+total_nonexit_bw)/((uint64_t) n_known));
  1659. } else {
  1660. avg_fast = 40000;
  1661. avg_slow = 20000;
  1662. }
  1663. for (i=0; i<(unsigned)smartlist_len(sl); ++i) {
  1664. if (bandwidths[i].dbl >= 0.0)
  1665. continue;
  1666. is_fast = bitarray_is_set(fast_bits, i);
  1667. is_exit = bitarray_is_set(exit_bits, i);
  1668. is_guard = bitarray_is_set(guard_bits, i);
  1669. bandwidths[i].dbl = is_fast ? avg_fast : avg_slow;
  1670. if (is_exit)
  1671. total_exit_bw += bandwidths[i].dbl;
  1672. else
  1673. total_nonexit_bw += bandwidths[i].dbl;
  1674. if (is_guard)
  1675. total_guard_bw += bandwidths[i].dbl;
  1676. else
  1677. total_nonguard_bw += bandwidths[i].dbl;
  1678. }
  1679. }
  1680. /* If there's no bandwidth at all, pick at random. */
  1681. if (total_exit_bw+total_nonexit_bw < EPSILON) {
  1682. tor_free(bandwidths);
  1683. tor_free(fast_bits);
  1684. tor_free(exit_bits);
  1685. tor_free(guard_bits);
  1686. return smartlist_choose(sl);
  1687. }
  1688. /* Figure out how to weight exits and guards */
  1689. {
  1690. double all_bw = U64_TO_DBL(total_exit_bw+total_nonexit_bw);
  1691. double exit_bw = U64_TO_DBL(total_exit_bw);
  1692. double guard_bw = U64_TO_DBL(total_guard_bw);
  1693. /*
  1694. * For detailed derivation of this formula, see
  1695. * http://archives.seul.org/or/dev/Jul-2007/msg00056.html
  1696. */
  1697. if (rule == WEIGHT_FOR_EXIT || total_exit_bw<EPSILON)
  1698. exit_weight = 1.0;
  1699. else
  1700. exit_weight = 1.0 - all_bw/(3.0*exit_bw);
  1701. if (rule == WEIGHT_FOR_GUARD || total_guard_bw<EPSILON)
  1702. guard_weight = 1.0;
  1703. else
  1704. guard_weight = 1.0 - all_bw/(3.0*guard_bw);
  1705. if (exit_weight <= 0.0)
  1706. exit_weight = 0.0;
  1707. if (guard_weight <= 0.0)
  1708. guard_weight = 0.0;
  1709. sl_last_weighted_bw_of_me = 0;
  1710. for (i=0; i < (unsigned)smartlist_len(sl); i++) {
  1711. tor_assert(bandwidths[i].dbl >= 0.0);
  1712. is_exit = bitarray_is_set(exit_bits, i);
  1713. is_guard = bitarray_is_set(guard_bits, i);
  1714. if (is_exit && is_guard)
  1715. bandwidths[i].dbl *= exit_weight * guard_weight;
  1716. else if (is_guard)
  1717. bandwidths[i].dbl *= guard_weight;
  1718. else if (is_exit)
  1719. bandwidths[i].dbl *= exit_weight;
  1720. if (i == (unsigned) me_idx)
  1721. sl_last_weighted_bw_of_me = (uint64_t) bandwidths[i].dbl;
  1722. }
  1723. }
  1724. #if 0
  1725. log_debug(LD_CIRC, "Total weighted bw = "U64_FORMAT
  1726. ", exit bw = "U64_FORMAT
  1727. ", nonexit bw = "U64_FORMAT", exit weight = %f "
  1728. "(for exit == %d)"
  1729. ", guard bw = "U64_FORMAT
  1730. ", nonguard bw = "U64_FORMAT", guard weight = %f "
  1731. "(for guard == %d)",
  1732. U64_PRINTF_ARG(total_bw),
  1733. U64_PRINTF_ARG(total_exit_bw), U64_PRINTF_ARG(total_nonexit_bw),
  1734. exit_weight, (int)(rule == WEIGHT_FOR_EXIT),
  1735. U64_PRINTF_ARG(total_guard_bw), U64_PRINTF_ARG(total_nonguard_bw),
  1736. guard_weight, (int)(rule == WEIGHT_FOR_GUARD));
  1737. #endif
  1738. scale_array_elements_to_u64(bandwidths, smartlist_len(sl),
  1739. &sl_last_total_weighted_bw);
  1740. {
  1741. int idx = choose_array_element_by_weight(bandwidths,
  1742. smartlist_len(sl));
  1743. tor_free(bandwidths);
  1744. tor_free(fast_bits);
  1745. tor_free(exit_bits);
  1746. tor_free(guard_bits);
  1747. return idx < 0 ? NULL : smartlist_get(sl, idx);
  1748. }
  1749. }
  1750. /** Choose a random element of status list <b>sl</b>, weighted by
  1751. * the advertised bandwidth of each node */
  1752. const node_t *
  1753. node_sl_choose_by_bandwidth(smartlist_t *sl,
  1754. bandwidth_weight_rule_t rule)
  1755. { /*XXXX MOVE */
  1756. const node_t *ret;
  1757. if ((ret = smartlist_choose_node_by_bandwidth_weights(sl, rule))) {
  1758. return ret;
  1759. } else {
  1760. return smartlist_choose_node_by_bandwidth(sl, rule);
  1761. }
  1762. }
  1763. /** Return a random running node from the nodelist. Never
  1764. * pick a node that is in
  1765. * <b>excludedsmartlist</b>, or which matches <b>excludedset</b>,
  1766. * even if they are the only nodes available.
  1767. * If <b>CRN_NEED_UPTIME</b> is set in flags and any router has more than
  1768. * a minimum uptime, return one of those.
  1769. * If <b>CRN_NEED_CAPACITY</b> is set in flags, weight your choice by the
  1770. * advertised capacity of each router.
  1771. * If <b>CRN_ALLOW_INVALID</b> is not set in flags, consider only Valid
  1772. * routers.
  1773. * If <b>CRN_NEED_GUARD</b> is set in flags, consider only Guard routers.
  1774. * If <b>CRN_WEIGHT_AS_EXIT</b> is set in flags, we weight bandwidths as if
  1775. * picking an exit node, otherwise we weight bandwidths for picking a relay
  1776. * node (that is, possibly discounting exit nodes).
  1777. * If <b>CRN_NEED_DESC</b> is set in flags, we only consider nodes that
  1778. * have a routerinfo or microdescriptor -- that is, enough info to be
  1779. * used to build a circuit.
  1780. */
  1781. const node_t *
  1782. router_choose_random_node(smartlist_t *excludedsmartlist,
  1783. routerset_t *excludedset,
  1784. router_crn_flags_t flags)
  1785. { /* XXXX MOVE */
  1786. const int need_uptime = (flags & CRN_NEED_UPTIME) != 0;
  1787. const int need_capacity = (flags & CRN_NEED_CAPACITY) != 0;
  1788. const int need_guard = (flags & CRN_NEED_GUARD) != 0;
  1789. const int allow_invalid = (flags & CRN_ALLOW_INVALID) != 0;
  1790. const int weight_for_exit = (flags & CRN_WEIGHT_AS_EXIT) != 0;
  1791. const int need_desc = (flags & CRN_NEED_DESC) != 0;
  1792. smartlist_t *sl=smartlist_new(),
  1793. *excludednodes=smartlist_new();
  1794. const node_t *choice = NULL;
  1795. const routerinfo_t *r;
  1796. bandwidth_weight_rule_t rule;
  1797. tor_assert(!(weight_for_exit && need_guard));
  1798. rule = weight_for_exit ? WEIGHT_FOR_EXIT :
  1799. (need_guard ? WEIGHT_FOR_GUARD : WEIGHT_FOR_MID);
  1800. /* Exclude relays that allow single hop exit circuits, if the user
  1801. * wants to (such relays might be risky) */
  1802. if (get_options()->ExcludeSingleHopRelays) {
  1803. SMARTLIST_FOREACH(nodelist_get_list(), node_t *, node,
  1804. if (node_allows_single_hop_exits(node)) {
  1805. smartlist_add(excludednodes, node);
  1806. });
  1807. }
  1808. if ((r = routerlist_find_my_routerinfo()))
  1809. routerlist_add_node_and_family(excludednodes, r);
  1810. router_add_running_nodes_to_smartlist(sl, allow_invalid,
  1811. need_uptime, need_capacity,
  1812. need_guard, need_desc);
  1813. smartlist_subtract(sl,excludednodes);
  1814. if (excludedsmartlist)
  1815. smartlist_subtract(sl,excludedsmartlist);
  1816. if (excludedset)
  1817. routerset_subtract_nodes(sl,excludedset);
  1818. // Always weight by bandwidth
  1819. choice = node_sl_choose_by_bandwidth(sl, rule);
  1820. smartlist_free(sl);
  1821. if (!choice && (need_uptime || need_capacity || need_guard)) {
  1822. /* try once more -- recurse but with fewer restrictions. */
  1823. log_info(LD_CIRC,
  1824. "We couldn't find any live%s%s%s routers; falling back "
  1825. "to list of all routers.",
  1826. need_capacity?", fast":"",
  1827. need_uptime?", stable":"",
  1828. need_guard?", guard":"");
  1829. flags &= ~ (CRN_NEED_UPTIME|CRN_NEED_CAPACITY|CRN_NEED_GUARD);
  1830. choice = router_choose_random_node(
  1831. excludedsmartlist, excludedset, flags);
  1832. }
  1833. smartlist_free(excludednodes);
  1834. if (!choice) {
  1835. log_warn(LD_CIRC,
  1836. "No available nodes when trying to choose node. Failing.");
  1837. }
  1838. return choice;
  1839. }
  1840. /** Helper: given an extended nickname in <b>hexdigest</b> try to decode it.
  1841. * Return 0 on success, -1 on failure. Store the result into the
  1842. * DIGEST_LEN-byte buffer at <b>digest_out</b>, the single character at
  1843. * <b>nickname_qualifier_char_out</b>, and the MAXNICKNAME_LEN+1-byte buffer
  1844. * at <b>nickname_out</b>.
  1845. *
  1846. * The recognized format is:
  1847. * HexName = Dollar? HexDigest NamePart?
  1848. * Dollar = '?'
  1849. * HexDigest = HexChar*20
  1850. * HexChar = 'a'..'f' | 'A'..'F' | '0'..'9'
  1851. * NamePart = QualChar Name
  1852. * QualChar = '=' | '~'
  1853. * Name = NameChar*(1..MAX_NICKNAME_LEN)
  1854. * NameChar = Any ASCII alphanumeric character
  1855. */
  1856. int
  1857. hex_digest_nickname_decode(const char *hexdigest,
  1858. char *digest_out,
  1859. char *nickname_qualifier_char_out,
  1860. char *nickname_out)
  1861. {
  1862. size_t len;
  1863. tor_assert(hexdigest);
  1864. if (hexdigest[0] == '$')
  1865. ++hexdigest;
  1866. len = strlen(hexdigest);
  1867. if (len < HEX_DIGEST_LEN) {
  1868. return -1;
  1869. } else if (len > HEX_DIGEST_LEN && (hexdigest[HEX_DIGEST_LEN] == '=' ||
  1870. hexdigest[HEX_DIGEST_LEN] == '~') &&
  1871. len <= HEX_DIGEST_LEN+1+MAX_NICKNAME_LEN) {
  1872. *nickname_qualifier_char_out = hexdigest[HEX_DIGEST_LEN];
  1873. strlcpy(nickname_out, hexdigest+HEX_DIGEST_LEN+1 , MAX_NICKNAME_LEN+1);
  1874. } else if (len == HEX_DIGEST_LEN) {
  1875. ;
  1876. } else {
  1877. return -1;
  1878. }
  1879. if (base16_decode(digest_out, DIGEST_LEN, hexdigest, HEX_DIGEST_LEN)<0)
  1880. return -1;
  1881. return 0;
  1882. }
  1883. /** Helper: Return true iff the <b>identity_digest</b> and <b>nickname</b>
  1884. * combination of a router, encoded in hexadecimal, matches <b>hexdigest</b>
  1885. * (which is optionally prefixed with a single dollar sign). Return false if
  1886. * <b>hexdigest</b> is malformed, or it doesn't match. */
  1887. int
  1888. hex_digest_nickname_matches(const char *hexdigest, const char *identity_digest,
  1889. const char *nickname, int is_named)
  1890. {
  1891. char digest[DIGEST_LEN];
  1892. char nn_char='\0';
  1893. char nn_buf[MAX_NICKNAME_LEN+1];
  1894. if (hex_digest_nickname_decode(hexdigest, digest, &nn_char, nn_buf) == -1)
  1895. return 0;
  1896. if (nn_char == '=' || nn_char == '~') {
  1897. if (!nickname)
  1898. return 0;
  1899. if (strcasecmp(nn_buf, nickname))
  1900. return 0;
  1901. if (nn_char == '=' && !is_named)
  1902. return 0;
  1903. }
  1904. return tor_memeq(digest, identity_digest, DIGEST_LEN);
  1905. }
  1906. /** Return true iff <b>router</b> is listed as named in the current
  1907. * consensus. */
  1908. int
  1909. router_is_named(const routerinfo_t *router)
  1910. {
  1911. const char *digest =
  1912. networkstatus_get_router_digest_by_nickname(router->nickname);
  1913. return (digest &&
  1914. tor_memeq(digest, router->cache_info.identity_digest, DIGEST_LEN));
  1915. }
  1916. /** Return true iff the digest of <b>router</b>'s identity key,
  1917. * encoded in hexadecimal, matches <b>hexdigest</b> (which is
  1918. * optionally prefixed with a single dollar sign). Return false if
  1919. * <b>hexdigest</b> is malformed, or it doesn't match. */
  1920. static INLINE int
  1921. router_hex_digest_matches(const routerinfo_t *router, const char *hexdigest)
  1922. {
  1923. return hex_digest_nickname_matches(hexdigest,
  1924. router->cache_info.identity_digest,
  1925. router->nickname,
  1926. router_is_named(router));
  1927. }
  1928. /** Return true if <b>router</b>'s nickname matches <b>nickname</b>
  1929. * (case-insensitive), or if <b>router's</b> identity key digest
  1930. * matches a hexadecimal value stored in <b>nickname</b>. Return
  1931. * false otherwise. */
  1932. static int
  1933. router_nickname_matches(const routerinfo_t *router, const char *nickname)
  1934. {
  1935. if (nickname[0]!='$' && !strcasecmp(router->nickname, nickname))
  1936. return 1;
  1937. return router_hex_digest_matches(router, nickname);
  1938. }
  1939. /** Return true iff <b>digest</b> is the digest of the identity key of a
  1940. * trusted directory matching at least one bit of <b>type</b>. If <b>type</b>
  1941. * is zero, any authority is okay. */
  1942. int
  1943. router_digest_is_trusted_dir_type(const char *digest, dirinfo_type_t type)
  1944. {
  1945. if (!trusted_dir_servers)
  1946. return 0;
  1947. if (authdir_mode(get_options()) && router_digest_is_me(digest))
  1948. return 1;
  1949. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  1950. if (tor_memeq(digest, ent->digest, DIGEST_LEN)) {
  1951. return (!type) || ((type & ent->type) != 0);
  1952. });
  1953. return 0;
  1954. }
  1955. /** Return true iff <b>addr</b> is the address of one of our trusted
  1956. * directory authorities. */
  1957. int
  1958. router_addr_is_trusted_dir(uint32_t addr)
  1959. {
  1960. if (!trusted_dir_servers)
  1961. return 0;
  1962. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  1963. if (ent->addr == addr)
  1964. return 1;
  1965. );
  1966. return 0;
  1967. }
  1968. /** If hexdigest is correctly formed, base16_decode it into
  1969. * digest, which must have DIGEST_LEN space in it.
  1970. * Return 0 on success, -1 on failure.
  1971. */
  1972. int
  1973. hexdigest_to_digest(const char *hexdigest, char *digest)
  1974. {
  1975. if (hexdigest[0]=='$')
  1976. ++hexdigest;
  1977. if (strlen(hexdigest) < HEX_DIGEST_LEN ||
  1978. base16_decode(digest,DIGEST_LEN,hexdigest,HEX_DIGEST_LEN) < 0)
  1979. return -1;
  1980. return 0;
  1981. }
  1982. /** As router_get_by_id_digest,but return a pointer that you're allowed to
  1983. * modify */
  1984. routerinfo_t *
  1985. router_get_mutable_by_digest(const char *digest)
  1986. {
  1987. tor_assert(digest);
  1988. if (!routerlist) return NULL;
  1989. // routerlist_assert_ok(routerlist);
  1990. return rimap_get(routerlist->identity_map, digest);
  1991. }
  1992. /** Return the router in our routerlist whose 20-byte key digest
  1993. * is <b>digest</b>. Return NULL if no such router is known. */
  1994. const routerinfo_t *
  1995. router_get_by_id_digest(const char *digest)
  1996. {
  1997. return router_get_mutable_by_digest(digest);
  1998. }
  1999. /** Return the router in our routerlist whose 20-byte descriptor
  2000. * is <b>digest</b>. Return NULL if no such router is known. */
  2001. signed_descriptor_t *
  2002. router_get_by_descriptor_digest(const char *digest)
  2003. {
  2004. tor_assert(digest);
  2005. if (!routerlist) return NULL;
  2006. return sdmap_get(routerlist->desc_digest_map, digest);
  2007. }
  2008. /** Return the signed descriptor for the router in our routerlist whose
  2009. * 20-byte extra-info digest is <b>digest</b>. Return NULL if no such router
  2010. * is known. */
  2011. signed_descriptor_t *
  2012. router_get_by_extrainfo_digest(const char *digest)
  2013. {
  2014. tor_assert(digest);
  2015. if (!routerlist) return NULL;
  2016. return sdmap_get(routerlist->desc_by_eid_map, digest);
  2017. }
  2018. /** Return the signed descriptor for the extrainfo_t in our routerlist whose
  2019. * extra-info-digest is <b>digest</b>. Return NULL if no such extra-info
  2020. * document is known. */
  2021. signed_descriptor_t *
  2022. extrainfo_get_by_descriptor_digest(const char *digest)
  2023. {
  2024. extrainfo_t *ei;
  2025. tor_assert(digest);
  2026. if (!routerlist) return NULL;
  2027. ei = eimap_get(routerlist->extra_info_map, digest);
  2028. return ei ? &ei->cache_info : NULL;
  2029. }
  2030. /** Return a pointer to the signed textual representation of a descriptor.
  2031. * The returned string is not guaranteed to be NUL-terminated: the string's
  2032. * length will be in desc-\>signed_descriptor_len.
  2033. *
  2034. * If <b>with_annotations</b> is set, the returned string will include
  2035. * the annotations
  2036. * (if any) preceding the descriptor. This will increase the length of the
  2037. * string by desc-\>annotations_len.
  2038. *
  2039. * The caller must not free the string returned.
  2040. */
  2041. static const char *
  2042. signed_descriptor_get_body_impl(const signed_descriptor_t *desc,
  2043. int with_annotations)
  2044. {
  2045. const char *r = NULL;
  2046. size_t len = desc->signed_descriptor_len;
  2047. off_t offset = desc->saved_offset;
  2048. if (with_annotations)
  2049. len += desc->annotations_len;
  2050. else
  2051. offset += desc->annotations_len;
  2052. tor_assert(len > 32);
  2053. if (desc->saved_location == SAVED_IN_CACHE && routerlist) {
  2054. desc_store_t *store = desc_get_store(router_get_routerlist(), desc);
  2055. if (store && store->mmap) {
  2056. tor_assert(desc->saved_offset + len <= store->mmap->size);
  2057. r = store->mmap->data + offset;
  2058. } else if (store) {
  2059. log_err(LD_DIR, "We couldn't read a descriptor that is supposedly "
  2060. "mmaped in our cache. Is another process running in our data "
  2061. "directory? Exiting.");
  2062. exit(1);
  2063. }
  2064. }
  2065. if (!r) /* no mmap, or not in cache. */
  2066. r = desc->signed_descriptor_body +
  2067. (with_annotations ? 0 : desc->annotations_len);
  2068. tor_assert(r);
  2069. if (!with_annotations) {
  2070. if (fast_memcmp("router ", r, 7) && fast_memcmp("extra-info ", r, 11)) {
  2071. char *cp = tor_strndup(r, 64);
  2072. log_err(LD_DIR, "descriptor at %p begins with unexpected string %s. "
  2073. "Is another process running in our data directory? Exiting.",
  2074. desc, escaped(cp));
  2075. exit(1);
  2076. }
  2077. }
  2078. return r;
  2079. }
  2080. /** Return a pointer to the signed textual representation of a descriptor.
  2081. * The returned string is not guaranteed to be NUL-terminated: the string's
  2082. * length will be in desc-\>signed_descriptor_len.
  2083. *
  2084. * The caller must not free the string returned.
  2085. */
  2086. const char *
  2087. signed_descriptor_get_body(const signed_descriptor_t *desc)
  2088. {
  2089. return signed_descriptor_get_body_impl(desc, 0);
  2090. }
  2091. /** As signed_descriptor_get_body(), but points to the beginning of the
  2092. * annotations section rather than the beginning of the descriptor. */
  2093. const char *
  2094. signed_descriptor_get_annotations(const signed_descriptor_t *desc)
  2095. {
  2096. return signed_descriptor_get_body_impl(desc, 1);
  2097. }
  2098. /** Return the current list of all known routers. */
  2099. routerlist_t *
  2100. router_get_routerlist(void)
  2101. {
  2102. if (PREDICT_UNLIKELY(!routerlist)) {
  2103. routerlist = tor_malloc_zero(sizeof(routerlist_t));
  2104. routerlist->routers = smartlist_new();
  2105. routerlist->old_routers = smartlist_new();
  2106. routerlist->identity_map = rimap_new();
  2107. routerlist->desc_digest_map = sdmap_new();
  2108. routerlist->desc_by_eid_map = sdmap_new();
  2109. routerlist->extra_info_map = eimap_new();
  2110. routerlist->desc_store.fname_base = "cached-descriptors";
  2111. routerlist->desc_store.fname_alt_base = "cached-routers";
  2112. routerlist->extrainfo_store.fname_base = "cached-extrainfo";
  2113. routerlist->desc_store.type = ROUTER_STORE;
  2114. routerlist->extrainfo_store.type = EXTRAINFO_STORE;
  2115. routerlist->desc_store.description = "router descriptors";
  2116. routerlist->extrainfo_store.description = "extra-info documents";
  2117. }
  2118. return routerlist;
  2119. }
  2120. /** Free all storage held by <b>router</b>. */
  2121. void
  2122. routerinfo_free(routerinfo_t *router)
  2123. {
  2124. if (!router)
  2125. return;
  2126. tor_free(router->cache_info.signed_descriptor_body);
  2127. tor_free(router->address);
  2128. tor_free(router->nickname);
  2129. tor_free(router->platform);
  2130. tor_free(router->contact_info);
  2131. if (router->onion_pkey)
  2132. crypto_pk_free(router->onion_pkey);
  2133. if (router->identity_pkey)
  2134. crypto_pk_free(router->identity_pkey);
  2135. if (router->declared_family) {
  2136. SMARTLIST_FOREACH(router->declared_family, char *, s, tor_free(s));
  2137. smartlist_free(router->declared_family);
  2138. }
  2139. addr_policy_list_free(router->exit_policy);
  2140. memset(router, 77, sizeof(routerinfo_t));
  2141. tor_free(router);
  2142. }
  2143. /** Release all storage held by <b>extrainfo</b> */
  2144. void
  2145. extrainfo_free(extrainfo_t *extrainfo)
  2146. {
  2147. if (!extrainfo)
  2148. return;
  2149. tor_free(extrainfo->cache_info.signed_descriptor_body);
  2150. tor_free(extrainfo->pending_sig);
  2151. memset(extrainfo, 88, sizeof(extrainfo_t)); /* debug bad memory usage */
  2152. tor_free(extrainfo);
  2153. }
  2154. /** Release storage held by <b>sd</b>. */
  2155. static void
  2156. signed_descriptor_free(signed_descriptor_t *sd)
  2157. {
  2158. if (!sd)
  2159. return;
  2160. tor_free(sd->signed_descriptor_body);
  2161. memset(sd, 99, sizeof(signed_descriptor_t)); /* Debug bad mem usage */
  2162. tor_free(sd);
  2163. }
  2164. /** Extract a signed_descriptor_t from a general routerinfo, and free the
  2165. * routerinfo.
  2166. */
  2167. static signed_descriptor_t *
  2168. signed_descriptor_from_routerinfo(routerinfo_t *ri)
  2169. {
  2170. signed_descriptor_t *sd;
  2171. tor_assert(ri->purpose == ROUTER_PURPOSE_GENERAL);
  2172. sd = tor_malloc_zero(sizeof(signed_descriptor_t));
  2173. memcpy(sd, &(ri->cache_info), sizeof(signed_descriptor_t));
  2174. sd->routerlist_index = -1;
  2175. ri->cache_info.signed_descriptor_body = NULL;
  2176. routerinfo_free(ri);
  2177. return sd;
  2178. }
  2179. /** Helper: free the storage held by the extrainfo_t in <b>e</b>. */
  2180. static void
  2181. extrainfo_free_(void *e)
  2182. {
  2183. extrainfo_free(e);
  2184. }
  2185. /** Free all storage held by a routerlist <b>rl</b>. */
  2186. void
  2187. routerlist_free(routerlist_t *rl)
  2188. {
  2189. if (!rl)
  2190. return;
  2191. rimap_free(rl->identity_map, NULL);
  2192. sdmap_free(rl->desc_digest_map, NULL);
  2193. sdmap_free(rl->desc_by_eid_map, NULL);
  2194. eimap_free(rl->extra_info_map, extrainfo_free_);
  2195. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  2196. routerinfo_free(r));
  2197. SMARTLIST_FOREACH(rl->old_routers, signed_descriptor_t *, sd,
  2198. signed_descriptor_free(sd));
  2199. smartlist_free(rl->routers);
  2200. smartlist_free(rl->old_routers);
  2201. if (routerlist->desc_store.mmap)
  2202. tor_munmap_file(routerlist->desc_store.mmap);
  2203. if (routerlist->extrainfo_store.mmap)
  2204. tor_munmap_file(routerlist->extrainfo_store.mmap);
  2205. tor_free(rl);
  2206. router_dir_info_changed();
  2207. }
  2208. /** Log information about how much memory is being used for routerlist,
  2209. * at log level <b>severity</b>. */
  2210. void
  2211. dump_routerlist_mem_usage(int severity)
  2212. {
  2213. uint64_t livedescs = 0;
  2214. uint64_t olddescs = 0;
  2215. if (!routerlist)
  2216. return;
  2217. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, r,
  2218. livedescs += r->cache_info.signed_descriptor_len);
  2219. SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
  2220. olddescs += sd->signed_descriptor_len);
  2221. log(severity, LD_DIR,
  2222. "In %d live descriptors: "U64_FORMAT" bytes. "
  2223. "In %d old descriptors: "U64_FORMAT" bytes.",
  2224. smartlist_len(routerlist->routers), U64_PRINTF_ARG(livedescs),
  2225. smartlist_len(routerlist->old_routers), U64_PRINTF_ARG(olddescs));
  2226. }
  2227. /** Debugging helper: If <b>idx</b> is nonnegative, assert that <b>ri</b> is
  2228. * in <b>sl</b> at position <b>idx</b>. Otherwise, search <b>sl</b> for
  2229. * <b>ri</b>. Return the index of <b>ri</b> in <b>sl</b>, or -1 if <b>ri</b>
  2230. * is not in <b>sl</b>. */
  2231. static INLINE int
  2232. routerlist_find_elt_(smartlist_t *sl, void *ri, int idx)
  2233. {
  2234. if (idx < 0) {
  2235. idx = -1;
  2236. SMARTLIST_FOREACH(sl, routerinfo_t *, r,
  2237. if (r == ri) {
  2238. idx = r_sl_idx;
  2239. break;
  2240. });
  2241. } else {
  2242. tor_assert(idx < smartlist_len(sl));
  2243. tor_assert(smartlist_get(sl, idx) == ri);
  2244. };
  2245. return idx;
  2246. }
  2247. /** Insert an item <b>ri</b> into the routerlist <b>rl</b>, updating indices
  2248. * as needed. There must be no previous member of <b>rl</b> with the same
  2249. * identity digest as <b>ri</b>: If there is, call routerlist_replace
  2250. * instead.
  2251. */
  2252. static void
  2253. routerlist_insert(routerlist_t *rl, routerinfo_t *ri)
  2254. {
  2255. routerinfo_t *ri_old;
  2256. signed_descriptor_t *sd_old;
  2257. {
  2258. const routerinfo_t *ri_generated = router_get_my_routerinfo();
  2259. tor_assert(ri_generated != ri);
  2260. }
  2261. tor_assert(ri->cache_info.routerlist_index == -1);
  2262. ri_old = rimap_set(rl->identity_map, ri->cache_info.identity_digest, ri);
  2263. tor_assert(!ri_old);
  2264. sd_old = sdmap_set(rl->desc_digest_map,
  2265. ri->cache_info.signed_descriptor_digest,
  2266. &(ri->cache_info));
  2267. if (sd_old) {
  2268. int idx = sd_old->routerlist_index;
  2269. sd_old->routerlist_index = -1;
  2270. smartlist_del(rl->old_routers, idx);
  2271. if (idx < smartlist_len(rl->old_routers)) {
  2272. signed_descriptor_t *d = smartlist_get(rl->old_routers, idx);
  2273. d->routerlist_index = idx;
  2274. }
  2275. rl->desc_store.bytes_dropped += sd_old->signed_descriptor_len;
  2276. sdmap_remove(rl->desc_by_eid_map, sd_old->extra_info_digest);
  2277. signed_descriptor_free(sd_old);
  2278. }
  2279. if (!tor_digest_is_zero(ri->cache_info.extra_info_digest))
  2280. sdmap_set(rl->desc_by_eid_map, ri->cache_info.extra_info_digest,
  2281. &ri->cache_info);
  2282. smartlist_add(rl->routers, ri);
  2283. ri->cache_info.routerlist_index = smartlist_len(rl->routers) - 1;
  2284. nodelist_set_routerinfo(ri, NULL);
  2285. router_dir_info_changed();
  2286. #ifdef DEBUG_ROUTERLIST
  2287. routerlist_assert_ok(rl);
  2288. #endif
  2289. }
  2290. /** Adds the extrainfo_t <b>ei</b> to the routerlist <b>rl</b>, if there is a
  2291. * corresponding router in rl-\>routers or rl-\>old_routers. Return true iff
  2292. * we actually inserted <b>ei</b>. Free <b>ei</b> if it isn't inserted. */
  2293. static int
  2294. extrainfo_insert(routerlist_t *rl, extrainfo_t *ei)
  2295. {
  2296. int r = 0;
  2297. routerinfo_t *ri = rimap_get(rl->identity_map,
  2298. ei->cache_info.identity_digest);
  2299. signed_descriptor_t *sd =
  2300. sdmap_get(rl->desc_by_eid_map, ei->cache_info.signed_descriptor_digest);
  2301. extrainfo_t *ei_tmp;
  2302. {
  2303. extrainfo_t *ei_generated = router_get_my_extrainfo();
  2304. tor_assert(ei_generated != ei);
  2305. }
  2306. if (!ri) {
  2307. /* This router is unknown; we can't even verify the signature. Give up.*/
  2308. goto done;
  2309. }
  2310. if (routerinfo_incompatible_with_extrainfo(ri, ei, sd, NULL)) {
  2311. goto done;
  2312. }
  2313. /* Okay, if we make it here, we definitely have a router corresponding to
  2314. * this extrainfo. */
  2315. ei_tmp = eimap_set(rl->extra_info_map,
  2316. ei->cache_info.signed_descriptor_digest,
  2317. ei);
  2318. r = 1;
  2319. if (ei_tmp) {
  2320. rl->extrainfo_store.bytes_dropped +=
  2321. ei_tmp->cache_info.signed_descriptor_len;
  2322. extrainfo_free(ei_tmp);
  2323. }
  2324. done:
  2325. if (r == 0)
  2326. extrainfo_free(ei);
  2327. #ifdef DEBUG_ROUTERLIST
  2328. routerlist_assert_ok(rl);
  2329. #endif
  2330. return r;
  2331. }
  2332. #define should_cache_old_descriptors() \
  2333. directory_caches_dir_info(get_options())
  2334. /** If we're a directory cache and routerlist <b>rl</b> doesn't have
  2335. * a copy of router <b>ri</b> yet, add it to the list of old (not
  2336. * recommended but still served) descriptors. Else free it. */
  2337. static void
  2338. routerlist_insert_old(routerlist_t *rl, routerinfo_t *ri)
  2339. {
  2340. {
  2341. const routerinfo_t *ri_generated = router_get_my_routerinfo();
  2342. tor_assert(ri_generated != ri);
  2343. }
  2344. tor_assert(ri->cache_info.routerlist_index == -1);
  2345. if (should_cache_old_descriptors() &&
  2346. ri->purpose == ROUTER_PURPOSE_GENERAL &&
  2347. !sdmap_get(rl->desc_digest_map,
  2348. ri->cache_info.signed_descriptor_digest)) {
  2349. signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri);
  2350. sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  2351. smartlist_add(rl->old_routers, sd);
  2352. sd->routerlist_index = smartlist_len(rl->old_routers)-1;
  2353. if (!tor_digest_is_zero(sd->extra_info_digest))
  2354. sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
  2355. } else {
  2356. routerinfo_free(ri);
  2357. }
  2358. #ifdef DEBUG_ROUTERLIST
  2359. routerlist_assert_ok(rl);
  2360. #endif
  2361. }
  2362. /** Remove an item <b>ri</b> from the routerlist <b>rl</b>, updating indices
  2363. * as needed. If <b>idx</b> is nonnegative and smartlist_get(rl-&gt;routers,
  2364. * idx) == ri, we don't need to do a linear search over the list to decide
  2365. * which to remove. We fill the gap in rl-&gt;routers with a later element in
  2366. * the list, if any exists. <b>ri</b> is freed.
  2367. *
  2368. * If <b>make_old</b> is true, instead of deleting the router, we try adding
  2369. * it to rl-&gt;old_routers. */
  2370. void
  2371. routerlist_remove(routerlist_t *rl, routerinfo_t *ri, int make_old, time_t now)
  2372. {
  2373. routerinfo_t *ri_tmp;
  2374. extrainfo_t *ei_tmp;
  2375. int idx = ri->cache_info.routerlist_index;
  2376. tor_assert(0 <= idx && idx < smartlist_len(rl->routers));
  2377. tor_assert(smartlist_get(rl->routers, idx) == ri);
  2378. nodelist_remove_routerinfo(ri);
  2379. /* make sure the rephist module knows that it's not running */
  2380. rep_hist_note_router_unreachable(ri->cache_info.identity_digest, now);
  2381. ri->cache_info.routerlist_index = -1;
  2382. smartlist_del(rl->routers, idx);
  2383. if (idx < smartlist_len(rl->routers)) {
  2384. routerinfo_t *r = smartlist_get(rl->routers, idx);
  2385. r->cache_info.routerlist_index = idx;
  2386. }
  2387. ri_tmp = rimap_remove(rl->identity_map, ri->cache_info.identity_digest);
  2388. router_dir_info_changed();
  2389. tor_assert(ri_tmp == ri);
  2390. if (make_old && should_cache_old_descriptors() &&
  2391. ri->purpose == ROUTER_PURPOSE_GENERAL) {
  2392. signed_descriptor_t *sd;
  2393. sd = signed_descriptor_from_routerinfo(ri);
  2394. smartlist_add(rl->old_routers, sd);
  2395. sd->routerlist_index = smartlist_len(rl->old_routers)-1;
  2396. sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  2397. if (!tor_digest_is_zero(sd->extra_info_digest))
  2398. sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
  2399. } else {
  2400. signed_descriptor_t *sd_tmp;
  2401. sd_tmp = sdmap_remove(rl->desc_digest_map,
  2402. ri->cache_info.signed_descriptor_digest);
  2403. tor_assert(sd_tmp == &(ri->cache_info));
  2404. rl->desc_store.bytes_dropped += ri->cache_info.signed_descriptor_len;
  2405. ei_tmp = eimap_remove(rl->extra_info_map,
  2406. ri->cache_info.extra_info_digest);
  2407. if (ei_tmp) {
  2408. rl->extrainfo_store.bytes_dropped +=
  2409. ei_tmp->cache_info.signed_descriptor_len;
  2410. extrainfo_free(ei_tmp);
  2411. }
  2412. if (!tor_digest_is_zero(ri->cache_info.extra_info_digest))
  2413. sdmap_remove(rl->desc_by_eid_map, ri->cache_info.extra_info_digest);
  2414. routerinfo_free(ri);
  2415. }
  2416. #ifdef DEBUG_ROUTERLIST
  2417. routerlist_assert_ok(rl);
  2418. #endif
  2419. }
  2420. /** Remove a signed_descriptor_t <b>sd</b> from <b>rl</b>-\>old_routers, and
  2421. * adjust <b>rl</b> as appropriate. <b>idx</b> is -1, or the index of
  2422. * <b>sd</b>. */
  2423. static void
  2424. routerlist_remove_old(routerlist_t *rl, signed_descriptor_t *sd, int idx)
  2425. {
  2426. signed_descriptor_t *sd_tmp;
  2427. extrainfo_t *ei_tmp;
  2428. desc_store_t *store;
  2429. if (idx == -1) {
  2430. idx = sd->routerlist_index;
  2431. }
  2432. tor_assert(0 <= idx && idx < smartlist_len(rl->old_routers));
  2433. /* XXXX edmanm's bridge relay triggered the following assert while
  2434. * running 0.2.0.12-alpha. If anybody triggers this again, see if we
  2435. * can get a backtrace. */
  2436. tor_assert(smartlist_get(rl->old_routers, idx) == sd);
  2437. tor_assert(idx == sd->routerlist_index);
  2438. sd->routerlist_index = -1;
  2439. smartlist_del(rl->old_routers, idx);
  2440. if (idx < smartlist_len(rl->old_routers)) {
  2441. signed_descriptor_t *d = smartlist_get(rl->old_routers, idx);
  2442. d->routerlist_index = idx;
  2443. }
  2444. sd_tmp = sdmap_remove(rl->desc_digest_map,
  2445. sd->signed_descriptor_digest);
  2446. tor_assert(sd_tmp == sd);
  2447. store = desc_get_store(rl, sd);
  2448. if (store)
  2449. store->bytes_dropped += sd->signed_descriptor_len;
  2450. ei_tmp = eimap_remove(rl->extra_info_map,
  2451. sd->extra_info_digest);
  2452. if (ei_tmp) {
  2453. rl->extrainfo_store.bytes_dropped +=
  2454. ei_tmp->cache_info.signed_descriptor_len;
  2455. extrainfo_free(ei_tmp);
  2456. }
  2457. if (!tor_digest_is_zero(sd->extra_info_digest))
  2458. sdmap_remove(rl->desc_by_eid_map, sd->extra_info_digest);
  2459. signed_descriptor_free(sd);
  2460. #ifdef DEBUG_ROUTERLIST
  2461. routerlist_assert_ok(rl);
  2462. #endif
  2463. }
  2464. /** Remove <b>ri_old</b> from the routerlist <b>rl</b>, and replace it with
  2465. * <b>ri_new</b>, updating all index info. If <b>idx</b> is nonnegative and
  2466. * smartlist_get(rl-&gt;routers, idx) == ri, we don't need to do a linear
  2467. * search over the list to decide which to remove. We put ri_new in the same
  2468. * index as ri_old, if possible. ri is freed as appropriate.
  2469. *
  2470. * If should_cache_descriptors() is true, instead of deleting the router,
  2471. * we add it to rl-&gt;old_routers. */
  2472. static void
  2473. routerlist_replace(routerlist_t *rl, routerinfo_t *ri_old,
  2474. routerinfo_t *ri_new)
  2475. {
  2476. int idx;
  2477. int same_descriptors;
  2478. routerinfo_t *ri_tmp;
  2479. extrainfo_t *ei_tmp;
  2480. {
  2481. const routerinfo_t *ri_generated = router_get_my_routerinfo();
  2482. tor_assert(ri_generated != ri_new);
  2483. }
  2484. tor_assert(ri_old != ri_new);
  2485. tor_assert(ri_new->cache_info.routerlist_index == -1);
  2486. idx = ri_old->cache_info.routerlist_index;
  2487. tor_assert(0 <= idx && idx < smartlist_len(rl->routers));
  2488. tor_assert(smartlist_get(rl->routers, idx) == ri_old);
  2489. {
  2490. routerinfo_t *ri_old_tmp=NULL;
  2491. nodelist_set_routerinfo(ri_new, &ri_old_tmp);
  2492. tor_assert(ri_old == ri_old_tmp);
  2493. }
  2494. router_dir_info_changed();
  2495. if (idx >= 0) {
  2496. smartlist_set(rl->routers, idx, ri_new);
  2497. ri_old->cache_info.routerlist_index = -1;
  2498. ri_new->cache_info.routerlist_index = idx;
  2499. /* Check that ri_old is not in rl->routers anymore: */
  2500. tor_assert( routerlist_find_elt_(rl->routers, ri_old, -1) == -1 );
  2501. } else {
  2502. log_warn(LD_BUG, "Appending entry from routerlist_replace.");
  2503. routerlist_insert(rl, ri_new);
  2504. return;
  2505. }
  2506. if (tor_memneq(ri_old->cache_info.identity_digest,
  2507. ri_new->cache_info.identity_digest, DIGEST_LEN)) {
  2508. /* digests don't match; digestmap_set won't replace */
  2509. rimap_remove(rl->identity_map, ri_old->cache_info.identity_digest);
  2510. }
  2511. ri_tmp = rimap_set(rl->identity_map,
  2512. ri_new->cache_info.identity_digest, ri_new);
  2513. tor_assert(!ri_tmp || ri_tmp == ri_old);
  2514. sdmap_set(rl->desc_digest_map,
  2515. ri_new->cache_info.signed_descriptor_digest,
  2516. &(ri_new->cache_info));
  2517. if (!tor_digest_is_zero(ri_new->cache_info.extra_info_digest)) {
  2518. sdmap_set(rl->desc_by_eid_map, ri_new->cache_info.extra_info_digest,
  2519. &ri_new->cache_info);
  2520. }
  2521. same_descriptors = tor_memeq(ri_old->cache_info.signed_descriptor_digest,
  2522. ri_new->cache_info.signed_descriptor_digest,
  2523. DIGEST_LEN);
  2524. if (should_cache_old_descriptors() &&
  2525. ri_old->purpose == ROUTER_PURPOSE_GENERAL &&
  2526. !same_descriptors) {
  2527. /* ri_old is going to become a signed_descriptor_t and go into
  2528. * old_routers */
  2529. signed_descriptor_t *sd = signed_descriptor_from_routerinfo(ri_old);
  2530. smartlist_add(rl->old_routers, sd);
  2531. sd->routerlist_index = smartlist_len(rl->old_routers)-1;
  2532. sdmap_set(rl->desc_digest_map, sd->signed_descriptor_digest, sd);
  2533. if (!tor_digest_is_zero(sd->extra_info_digest))
  2534. sdmap_set(rl->desc_by_eid_map, sd->extra_info_digest, sd);
  2535. } else {
  2536. /* We're dropping ri_old. */
  2537. if (!same_descriptors) {
  2538. /* digests don't match; The sdmap_set above didn't replace */
  2539. sdmap_remove(rl->desc_digest_map,
  2540. ri_old->cache_info.signed_descriptor_digest);
  2541. if (tor_memneq(ri_old->cache_info.extra_info_digest,
  2542. ri_new->cache_info.extra_info_digest, DIGEST_LEN)) {
  2543. ei_tmp = eimap_remove(rl->extra_info_map,
  2544. ri_old->cache_info.extra_info_digest);
  2545. if (ei_tmp) {
  2546. rl->extrainfo_store.bytes_dropped +=
  2547. ei_tmp->cache_info.signed_descriptor_len;
  2548. extrainfo_free(ei_tmp);
  2549. }
  2550. }
  2551. if (!tor_digest_is_zero(ri_old->cache_info.extra_info_digest)) {
  2552. sdmap_remove(rl->desc_by_eid_map,
  2553. ri_old->cache_info.extra_info_digest);
  2554. }
  2555. }
  2556. rl->desc_store.bytes_dropped += ri_old->cache_info.signed_descriptor_len;
  2557. routerinfo_free(ri_old);
  2558. }
  2559. #ifdef DEBUG_ROUTERLIST
  2560. routerlist_assert_ok(rl);
  2561. #endif
  2562. }
  2563. /** Extract the descriptor <b>sd</b> from old_routerlist, and re-parse
  2564. * it as a fresh routerinfo_t. */
  2565. static routerinfo_t *
  2566. routerlist_reparse_old(routerlist_t *rl, signed_descriptor_t *sd)
  2567. {
  2568. routerinfo_t *ri;
  2569. const char *body;
  2570. body = signed_descriptor_get_annotations(sd);
  2571. ri = router_parse_entry_from_string(body,
  2572. body+sd->signed_descriptor_len+sd->annotations_len,
  2573. 0, 1, NULL);
  2574. if (!ri)
  2575. return NULL;
  2576. memcpy(&ri->cache_info, sd, sizeof(signed_descriptor_t));
  2577. sd->signed_descriptor_body = NULL; /* Steal reference. */
  2578. ri->cache_info.routerlist_index = -1;
  2579. routerlist_remove_old(rl, sd, -1);
  2580. return ri;
  2581. }
  2582. /** Free all memory held by the routerlist module. */
  2583. void
  2584. routerlist_free_all(void)
  2585. {
  2586. routerlist_free(routerlist);
  2587. routerlist = NULL;
  2588. if (warned_nicknames) {
  2589. SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
  2590. smartlist_free(warned_nicknames);
  2591. warned_nicknames = NULL;
  2592. }
  2593. if (trusted_dir_servers) {
  2594. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ds,
  2595. trusted_dir_server_free(ds));
  2596. smartlist_free(trusted_dir_servers);
  2597. trusted_dir_servers = NULL;
  2598. }
  2599. if (trusted_dir_certs) {
  2600. DIGESTMAP_FOREACH(trusted_dir_certs, key, cert_list_t *, cl) {
  2601. SMARTLIST_FOREACH(cl->certs, authority_cert_t *, cert,
  2602. authority_cert_free(cert));
  2603. smartlist_free(cl->certs);
  2604. tor_free(cl);
  2605. } DIGESTMAP_FOREACH_END;
  2606. digestmap_free(trusted_dir_certs, NULL);
  2607. trusted_dir_certs = NULL;
  2608. }
  2609. }
  2610. /** Forget that we have issued any router-related warnings, so that we'll
  2611. * warn again if we see the same errors. */
  2612. void
  2613. routerlist_reset_warnings(void)
  2614. {
  2615. if (!warned_nicknames)
  2616. warned_nicknames = smartlist_new();
  2617. SMARTLIST_FOREACH(warned_nicknames, char *, cp, tor_free(cp));
  2618. smartlist_clear(warned_nicknames); /* now the list is empty. */
  2619. networkstatus_reset_warnings();
  2620. }
  2621. /** Add <b>router</b> to the routerlist, if we don't already have it. Replace
  2622. * older entries (if any) with the same key. Note: Callers should not hold
  2623. * their pointers to <b>router</b> if this function fails; <b>router</b>
  2624. * will either be inserted into the routerlist or freed. Similarly, even
  2625. * if this call succeeds, they should not hold their pointers to
  2626. * <b>router</b> after subsequent calls with other routerinfo's -- they
  2627. * might cause the original routerinfo to get freed.
  2628. *
  2629. * Returns the status for the operation. Might set *<b>msg</b> if it wants
  2630. * the poster of the router to know something.
  2631. *
  2632. * If <b>from_cache</b>, this descriptor came from our disk cache. If
  2633. * <b>from_fetch</b>, we received it in response to a request we made.
  2634. * (If both are false, that means it was uploaded to us as an auth dir
  2635. * server or via the controller.)
  2636. *
  2637. * This function should be called *after*
  2638. * routers_update_status_from_consensus_networkstatus; subsequently, you
  2639. * should call router_rebuild_store and routerlist_descriptors_added.
  2640. */
  2641. was_router_added_t
  2642. router_add_to_routerlist(routerinfo_t *router, const char **msg,
  2643. int from_cache, int from_fetch)
  2644. {
  2645. const char *id_digest;
  2646. const or_options_t *options = get_options();
  2647. int authdir = authdir_mode_handles_descs(options, router->purpose);
  2648. int authdir_believes_valid = 0;
  2649. routerinfo_t *old_router;
  2650. networkstatus_t *consensus =
  2651. networkstatus_get_latest_consensus_by_flavor(FLAV_NS);
  2652. const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
  2653. int in_consensus = 0;
  2654. tor_assert(msg);
  2655. if (!routerlist)
  2656. router_get_routerlist();
  2657. id_digest = router->cache_info.identity_digest;
  2658. old_router = router_get_mutable_by_digest(id_digest);
  2659. /* Make sure that we haven't already got this exact descriptor. */
  2660. if (sdmap_get(routerlist->desc_digest_map,
  2661. router->cache_info.signed_descriptor_digest)) {
  2662. /* If we have this descriptor already and the new descriptor is a bridge
  2663. * descriptor, replace it. If we had a bridge descriptor before and the
  2664. * new one is not a bridge descriptor, don't replace it. */
  2665. /* Only members of routerlist->identity_map can be bridges; we don't
  2666. * put bridges in old_routers. */
  2667. const int was_bridge = old_router &&
  2668. old_router->purpose == ROUTER_PURPOSE_BRIDGE;
  2669. if (routerinfo_is_a_configured_bridge(router) &&
  2670. router->purpose == ROUTER_PURPOSE_BRIDGE &&
  2671. !was_bridge) {
  2672. log_info(LD_DIR, "Replacing non-bridge descriptor with bridge "
  2673. "descriptor for router %s",
  2674. router_describe(router));
  2675. } else {
  2676. log_info(LD_DIR,
  2677. "Dropping descriptor that we already have for router %s",
  2678. router_describe(router));
  2679. *msg = "Router descriptor was not new.";
  2680. routerinfo_free(router);
  2681. return ROUTER_WAS_NOT_NEW;
  2682. }
  2683. }
  2684. if (authdir) {
  2685. if (authdir_wants_to_reject_router(router, msg,
  2686. !from_cache && !from_fetch,
  2687. &authdir_believes_valid)) {
  2688. tor_assert(*msg);
  2689. routerinfo_free(router);
  2690. return ROUTER_AUTHDIR_REJECTS;
  2691. }
  2692. } else if (from_fetch) {
  2693. /* Only check the descriptor digest against the network statuses when
  2694. * we are receiving in response to a fetch. */
  2695. if (!signed_desc_digest_is_recognized(&router->cache_info) &&
  2696. !routerinfo_is_a_configured_bridge(router)) {
  2697. /* We asked for it, so some networkstatus must have listed it when we
  2698. * did. Save it if we're a cache in case somebody else asks for it. */
  2699. log_info(LD_DIR,
  2700. "Received a no-longer-recognized descriptor for router %s",
  2701. router_describe(router));
  2702. *msg = "Router descriptor is not referenced by any network-status.";
  2703. /* Only journal this desc if we'll be serving it. */
  2704. if (!from_cache && should_cache_old_descriptors())
  2705. signed_desc_append_to_journal(&router->cache_info,
  2706. &routerlist->desc_store);
  2707. routerlist_insert_old(routerlist, router);
  2708. return ROUTER_NOT_IN_CONSENSUS_OR_NETWORKSTATUS;
  2709. }
  2710. }
  2711. /* We no longer need a router with this descriptor digest. */
  2712. SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
  2713. {
  2714. routerstatus_t *rs =
  2715. networkstatus_v2_find_mutable_entry(ns, id_digest);
  2716. if (rs && tor_memeq(rs->descriptor_digest,
  2717. router->cache_info.signed_descriptor_digest,
  2718. DIGEST_LEN))
  2719. rs->need_to_mirror = 0;
  2720. });
  2721. if (consensus) {
  2722. routerstatus_t *rs = networkstatus_vote_find_mutable_entry(
  2723. consensus, id_digest);
  2724. if (rs && tor_memeq(rs->descriptor_digest,
  2725. router->cache_info.signed_descriptor_digest,
  2726. DIGEST_LEN)) {
  2727. in_consensus = 1;
  2728. rs->need_to_mirror = 0;
  2729. }
  2730. }
  2731. if (router->purpose == ROUTER_PURPOSE_GENERAL &&
  2732. consensus && !in_consensus && !authdir) {
  2733. /* If it's a general router not listed in the consensus, then don't
  2734. * consider replacing the latest router with it. */
  2735. if (!from_cache && should_cache_old_descriptors())
  2736. signed_desc_append_to_journal(&router->cache_info,
  2737. &routerlist->desc_store);
  2738. routerlist_insert_old(routerlist, router);
  2739. *msg = "Skipping router descriptor: not in consensus.";
  2740. return ROUTER_NOT_IN_CONSENSUS;
  2741. }
  2742. /* If we're reading a bridge descriptor from our cache, and we don't
  2743. * recognize it as one of our currently configured bridges, drop the
  2744. * descriptor. Otherwise we could end up using it as one of our entry
  2745. * guards even if it isn't in our Bridge config lines. */
  2746. if (router->purpose == ROUTER_PURPOSE_BRIDGE && from_cache &&
  2747. !authdir_mode_bridge(options) &&
  2748. !routerinfo_is_a_configured_bridge(router)) {
  2749. log_info(LD_DIR, "Dropping bridge descriptor for %s because we have "
  2750. "no bridge configured at that address.",
  2751. safe_str_client(router_describe(router)));
  2752. *msg = "Router descriptor was not a configured bridge.";
  2753. routerinfo_free(router);
  2754. return ROUTER_WAS_NOT_WANTED;
  2755. }
  2756. /* If we have a router with the same identity key, choose the newer one. */
  2757. if (old_router) {
  2758. if (!in_consensus && (router->cache_info.published_on <=
  2759. old_router->cache_info.published_on)) {
  2760. /* Same key, but old. This one is not listed in the consensus. */
  2761. log_debug(LD_DIR, "Not-new descriptor for router %s",
  2762. router_describe(router));
  2763. /* Only journal this desc if we'll be serving it. */
  2764. if (!from_cache && should_cache_old_descriptors())
  2765. signed_desc_append_to_journal(&router->cache_info,
  2766. &routerlist->desc_store);
  2767. routerlist_insert_old(routerlist, router);
  2768. *msg = "Router descriptor was not new.";
  2769. return ROUTER_WAS_NOT_NEW;
  2770. } else {
  2771. /* Same key, and either new, or listed in the consensus. */
  2772. log_debug(LD_DIR, "Replacing entry for router %s",
  2773. router_describe(router));
  2774. routerlist_replace(routerlist, old_router, router);
  2775. if (!from_cache) {
  2776. signed_desc_append_to_journal(&router->cache_info,
  2777. &routerlist->desc_store);
  2778. }
  2779. directory_set_dirty();
  2780. *msg = authdir_believes_valid ? "Valid server updated" :
  2781. ("Invalid server updated. (This dirserver is marking your "
  2782. "server as unapproved.)");
  2783. return ROUTER_ADDED_SUCCESSFULLY;
  2784. }
  2785. }
  2786. if (!in_consensus && from_cache &&
  2787. router->cache_info.published_on < time(NULL) - OLD_ROUTER_DESC_MAX_AGE) {
  2788. *msg = "Router descriptor was really old.";
  2789. routerinfo_free(router);
  2790. return ROUTER_WAS_NOT_NEW;
  2791. }
  2792. /* We haven't seen a router with this identity before. Add it to the end of
  2793. * the list. */
  2794. routerlist_insert(routerlist, router);
  2795. if (!from_cache) {
  2796. signed_desc_append_to_journal(&router->cache_info,
  2797. &routerlist->desc_store);
  2798. }
  2799. directory_set_dirty();
  2800. return ROUTER_ADDED_SUCCESSFULLY;
  2801. }
  2802. /** Insert <b>ei</b> into the routerlist, or free it. Other arguments are
  2803. * as for router_add_to_routerlist(). Return ROUTER_ADDED_SUCCESSFULLY iff
  2804. * we actually inserted it, ROUTER_BAD_EI otherwise.
  2805. */
  2806. was_router_added_t
  2807. router_add_extrainfo_to_routerlist(extrainfo_t *ei, const char **msg,
  2808. int from_cache, int from_fetch)
  2809. {
  2810. int inserted;
  2811. (void)from_fetch;
  2812. if (msg) *msg = NULL;
  2813. /*XXXX023 Do something with msg */
  2814. inserted = extrainfo_insert(router_get_routerlist(), ei);
  2815. if (inserted && !from_cache)
  2816. signed_desc_append_to_journal(&ei->cache_info,
  2817. &routerlist->extrainfo_store);
  2818. if (inserted)
  2819. return ROUTER_ADDED_SUCCESSFULLY;
  2820. else
  2821. return ROUTER_BAD_EI;
  2822. }
  2823. /** Sorting helper: return &lt;0, 0, or &gt;0 depending on whether the
  2824. * signed_descriptor_t* in *<b>a</b> has an identity digest preceding, equal
  2825. * to, or later than that of *<b>b</b>. */
  2826. static int
  2827. compare_old_routers_by_identity_(const void **_a, const void **_b)
  2828. {
  2829. int i;
  2830. const signed_descriptor_t *r1 = *_a, *r2 = *_b;
  2831. if ((i = fast_memcmp(r1->identity_digest, r2->identity_digest, DIGEST_LEN)))
  2832. return i;
  2833. return (int)(r1->published_on - r2->published_on);
  2834. }
  2835. /** Internal type used to represent how long an old descriptor was valid,
  2836. * where it appeared in the list of old descriptors, and whether it's extra
  2837. * old. Used only by routerlist_remove_old_cached_routers_with_id(). */
  2838. struct duration_idx_t {
  2839. int duration;
  2840. int idx;
  2841. int old;
  2842. };
  2843. /** Sorting helper: compare two duration_idx_t by their duration. */
  2844. static int
  2845. compare_duration_idx_(const void *_d1, const void *_d2)
  2846. {
  2847. const struct duration_idx_t *d1 = _d1;
  2848. const struct duration_idx_t *d2 = _d2;
  2849. return d1->duration - d2->duration;
  2850. }
  2851. /** The range <b>lo</b> through <b>hi</b> inclusive of routerlist->old_routers
  2852. * must contain routerinfo_t with the same identity and with publication time
  2853. * in ascending order. Remove members from this range until there are no more
  2854. * than max_descriptors_per_router() remaining. Start by removing the oldest
  2855. * members from before <b>cutoff</b>, then remove members which were current
  2856. * for the lowest amount of time. The order of members of old_routers at
  2857. * indices <b>lo</b> or higher may be changed.
  2858. */
  2859. static void
  2860. routerlist_remove_old_cached_routers_with_id(time_t now,
  2861. time_t cutoff, int lo, int hi,
  2862. digestset_t *retain)
  2863. {
  2864. int i, n = hi-lo+1;
  2865. unsigned n_extra, n_rmv = 0;
  2866. struct duration_idx_t *lifespans;
  2867. uint8_t *rmv, *must_keep;
  2868. smartlist_t *lst = routerlist->old_routers;
  2869. #if 1
  2870. const char *ident;
  2871. tor_assert(hi < smartlist_len(lst));
  2872. tor_assert(lo <= hi);
  2873. ident = ((signed_descriptor_t*)smartlist_get(lst, lo))->identity_digest;
  2874. for (i = lo+1; i <= hi; ++i) {
  2875. signed_descriptor_t *r = smartlist_get(lst, i);
  2876. tor_assert(tor_memeq(ident, r->identity_digest, DIGEST_LEN));
  2877. }
  2878. #endif
  2879. /* Check whether we need to do anything at all. */
  2880. {
  2881. int mdpr = directory_caches_dir_info(get_options()) ? 2 : 1;
  2882. if (n <= mdpr)
  2883. return;
  2884. n_extra = n - mdpr;
  2885. }
  2886. lifespans = tor_malloc_zero(sizeof(struct duration_idx_t)*n);
  2887. rmv = tor_malloc_zero(sizeof(uint8_t)*n);
  2888. must_keep = tor_malloc_zero(sizeof(uint8_t)*n);
  2889. /* Set lifespans to contain the lifespan and index of each server. */
  2890. /* Set rmv[i-lo]=1 if we're going to remove a server for being too old. */
  2891. for (i = lo; i <= hi; ++i) {
  2892. signed_descriptor_t *r = smartlist_get(lst, i);
  2893. signed_descriptor_t *r_next;
  2894. lifespans[i-lo].idx = i;
  2895. if (r->last_listed_as_valid_until >= now ||
  2896. (retain && digestset_isin(retain, r->signed_descriptor_digest))) {
  2897. must_keep[i-lo] = 1;
  2898. }
  2899. if (i < hi) {
  2900. r_next = smartlist_get(lst, i+1);
  2901. tor_assert(r->published_on <= r_next->published_on);
  2902. lifespans[i-lo].duration = (int)(r_next->published_on - r->published_on);
  2903. } else {
  2904. r_next = NULL;
  2905. lifespans[i-lo].duration = INT_MAX;
  2906. }
  2907. if (!must_keep[i-lo] && r->published_on < cutoff && n_rmv < n_extra) {
  2908. ++n_rmv;
  2909. lifespans[i-lo].old = 1;
  2910. rmv[i-lo] = 1;
  2911. }
  2912. }
  2913. if (n_rmv < n_extra) {
  2914. /**
  2915. * We aren't removing enough servers for being old. Sort lifespans by
  2916. * the duration of liveness, and remove the ones we're not already going to
  2917. * remove based on how long they were alive.
  2918. **/
  2919. qsort(lifespans, n, sizeof(struct duration_idx_t), compare_duration_idx_);
  2920. for (i = 0; i < n && n_rmv < n_extra; ++i) {
  2921. if (!must_keep[lifespans[i].idx-lo] && !lifespans[i].old) {
  2922. rmv[lifespans[i].idx-lo] = 1;
  2923. ++n_rmv;
  2924. }
  2925. }
  2926. }
  2927. i = hi;
  2928. do {
  2929. if (rmv[i-lo])
  2930. routerlist_remove_old(routerlist, smartlist_get(lst, i), i);
  2931. } while (--i >= lo);
  2932. tor_free(must_keep);
  2933. tor_free(rmv);
  2934. tor_free(lifespans);
  2935. }
  2936. /** Deactivate any routers from the routerlist that are more than
  2937. * ROUTER_MAX_AGE seconds old and not recommended by any networkstatuses;
  2938. * remove old routers from the list of cached routers if we have too many.
  2939. */
  2940. void
  2941. routerlist_remove_old_routers(void)
  2942. {
  2943. int i, hi=-1;
  2944. const char *cur_id = NULL;
  2945. time_t now = time(NULL);
  2946. time_t cutoff;
  2947. routerinfo_t *router;
  2948. signed_descriptor_t *sd;
  2949. digestset_t *retain;
  2950. int caches = directory_caches_dir_info(get_options());
  2951. const networkstatus_t *consensus = networkstatus_get_latest_consensus();
  2952. const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
  2953. int have_enough_v2;
  2954. const or_options_t *options = get_options();
  2955. trusted_dirs_remove_old_certs();
  2956. if (!routerlist || !consensus)
  2957. return;
  2958. // routerlist_assert_ok(routerlist);
  2959. /* We need to guess how many router descriptors we will wind up wanting to
  2960. retain, so that we can be sure to allocate a large enough Bloom filter
  2961. to hold the digest set. Overestimating is fine; underestimating is bad.
  2962. */
  2963. {
  2964. /* We'll probably retain everything in the consensus. */
  2965. int n_max_retain = smartlist_len(consensus->routerstatus_list);
  2966. if (caches && networkstatus_v2_list) {
  2967. /* If we care about v2 statuses, we'll retain at most as many as are
  2968. listed any of the v2 statues. This will be at least the length of
  2969. the largest v2 networkstatus, and in the worst case, this set will be
  2970. equal to the sum of the lengths of all v2 consensuses. Take the
  2971. worst case.
  2972. */
  2973. SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
  2974. n_max_retain += smartlist_len(ns->entries));
  2975. }
  2976. retain = digestset_new(n_max_retain);
  2977. }
  2978. cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
  2979. /* Build a list of all the descriptors that _anybody_ lists. */
  2980. if (caches && networkstatus_v2_list) {
  2981. SMARTLIST_FOREACH_BEGIN(networkstatus_v2_list, networkstatus_v2_t *, ns) {
  2982. /* XXXX The inner loop here gets pretty expensive, and actually shows up
  2983. * on some profiles. It may be the reason digestmap_set shows up in
  2984. * profiles too. If instead we kept a per-descriptor digest count of
  2985. * how many networkstatuses recommended each descriptor, and changed
  2986. * that only when the networkstatuses changed, that would be a speed
  2987. * improvement, possibly 1-4% if it also removes digestmap_set from the
  2988. * profile. Not worth it for 0.1.2.x, though. The new directory
  2989. * system will obsolete this whole thing in 0.2.0.x. */
  2990. SMARTLIST_FOREACH_BEGIN(ns->entries, routerstatus_t *, rs) {
  2991. if (rs->published_on >= cutoff)
  2992. digestset_add(retain, rs->descriptor_digest);
  2993. } SMARTLIST_FOREACH_END(rs);
  2994. } SMARTLIST_FOREACH_END(ns);
  2995. }
  2996. /* Retain anything listed in the consensus. */
  2997. if (consensus) {
  2998. SMARTLIST_FOREACH(consensus->routerstatus_list, routerstatus_t *, rs,
  2999. if (rs->published_on >= cutoff)
  3000. digestset_add(retain, rs->descriptor_digest));
  3001. }
  3002. /* If we have a consensus, and nearly as many v2 networkstatuses as we want,
  3003. * we should consider pruning current routers that are too old and that
  3004. * nobody recommends. (If we don't have a consensus or enough v2
  3005. * networkstatuses, then we should get more before we decide to kill
  3006. * routers.) */
  3007. /* we set this to true iff we don't care about v2 info, or we have enough. */
  3008. have_enough_v2 = !caches ||
  3009. !(authdir_mode_any_main(options) || options->FetchV2Networkstatus) ||
  3010. (networkstatus_v2_list &&
  3011. smartlist_len(networkstatus_v2_list) > get_n_v2_authorities() / 2);
  3012. if (have_enough_v2 && consensus) {
  3013. cutoff = now - ROUTER_MAX_AGE;
  3014. /* Remove too-old unrecommended members of routerlist->routers. */
  3015. for (i = 0; i < smartlist_len(routerlist->routers); ++i) {
  3016. router = smartlist_get(routerlist->routers, i);
  3017. if (router->cache_info.published_on <= cutoff &&
  3018. router->cache_info.last_listed_as_valid_until < now &&
  3019. !digestset_isin(retain,
  3020. router->cache_info.signed_descriptor_digest)) {
  3021. /* Too old: remove it. (If we're a cache, just move it into
  3022. * old_routers.) */
  3023. log_info(LD_DIR,
  3024. "Forgetting obsolete (too old) routerinfo for router %s",
  3025. router_describe(router));
  3026. routerlist_remove(routerlist, router, 1, now);
  3027. i--;
  3028. }
  3029. }
  3030. }
  3031. //routerlist_assert_ok(routerlist);
  3032. /* Remove far-too-old members of routerlist->old_routers. */
  3033. cutoff = now - OLD_ROUTER_DESC_MAX_AGE;
  3034. for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
  3035. sd = smartlist_get(routerlist->old_routers, i);
  3036. if (sd->published_on <= cutoff &&
  3037. sd->last_listed_as_valid_until < now &&
  3038. !digestset_isin(retain, sd->signed_descriptor_digest)) {
  3039. /* Too old. Remove it. */
  3040. routerlist_remove_old(routerlist, sd, i--);
  3041. }
  3042. }
  3043. //routerlist_assert_ok(routerlist);
  3044. log_info(LD_DIR, "We have %d live routers and %d old router descriptors.",
  3045. smartlist_len(routerlist->routers),
  3046. smartlist_len(routerlist->old_routers));
  3047. /* Now we might have to look at routerlist->old_routers for extraneous
  3048. * members. (We'd keep all the members if we could, but we need to save
  3049. * space.) First, check whether we have too many router descriptors, total.
  3050. * We're okay with having too many for some given router, so long as the
  3051. * total number doesn't approach max_descriptors_per_router()*len(router).
  3052. */
  3053. if (smartlist_len(routerlist->old_routers) <
  3054. smartlist_len(routerlist->routers))
  3055. goto done;
  3056. /* Sort by identity, then fix indices. */
  3057. smartlist_sort(routerlist->old_routers, compare_old_routers_by_identity_);
  3058. /* Fix indices. */
  3059. for (i = 0; i < smartlist_len(routerlist->old_routers); ++i) {
  3060. signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
  3061. r->routerlist_index = i;
  3062. }
  3063. /* Iterate through the list from back to front, so when we remove descriptors
  3064. * we don't mess up groups we haven't gotten to. */
  3065. for (i = smartlist_len(routerlist->old_routers)-1; i >= 0; --i) {
  3066. signed_descriptor_t *r = smartlist_get(routerlist->old_routers, i);
  3067. if (!cur_id) {
  3068. cur_id = r->identity_digest;
  3069. hi = i;
  3070. }
  3071. if (tor_memneq(cur_id, r->identity_digest, DIGEST_LEN)) {
  3072. routerlist_remove_old_cached_routers_with_id(now,
  3073. cutoff, i+1, hi, retain);
  3074. cur_id = r->identity_digest;
  3075. hi = i;
  3076. }
  3077. }
  3078. if (hi>=0)
  3079. routerlist_remove_old_cached_routers_with_id(now, cutoff, 0, hi, retain);
  3080. //routerlist_assert_ok(routerlist);
  3081. done:
  3082. digestset_free(retain);
  3083. router_rebuild_store(RRS_DONT_REMOVE_OLD, &routerlist->desc_store);
  3084. router_rebuild_store(RRS_DONT_REMOVE_OLD,&routerlist->extrainfo_store);
  3085. }
  3086. /** We just added a new set of descriptors. Take whatever extra steps
  3087. * we need. */
  3088. void
  3089. routerlist_descriptors_added(smartlist_t *sl, int from_cache)
  3090. {
  3091. tor_assert(sl);
  3092. control_event_descriptors_changed(sl);
  3093. SMARTLIST_FOREACH_BEGIN(sl, routerinfo_t *, ri) {
  3094. if (ri->purpose == ROUTER_PURPOSE_BRIDGE)
  3095. learned_bridge_descriptor(ri, from_cache);
  3096. if (ri->needs_retest_if_added) {
  3097. ri->needs_retest_if_added = 0;
  3098. dirserv_single_reachability_test(approx_time(), ri);
  3099. }
  3100. } SMARTLIST_FOREACH_END(ri);
  3101. }
  3102. /**
  3103. * Code to parse a single router descriptor and insert it into the
  3104. * routerlist. Return -1 if the descriptor was ill-formed; 0 if the
  3105. * descriptor was well-formed but could not be added; and 1 if the
  3106. * descriptor was added.
  3107. *
  3108. * If we don't add it and <b>msg</b> is not NULL, then assign to
  3109. * *<b>msg</b> a static string describing the reason for refusing the
  3110. * descriptor.
  3111. *
  3112. * This is used only by the controller.
  3113. */
  3114. int
  3115. router_load_single_router(const char *s, uint8_t purpose, int cache,
  3116. const char **msg)
  3117. {
  3118. routerinfo_t *ri;
  3119. was_router_added_t r;
  3120. smartlist_t *lst;
  3121. char annotation_buf[ROUTER_ANNOTATION_BUF_LEN];
  3122. tor_assert(msg);
  3123. *msg = NULL;
  3124. tor_snprintf(annotation_buf, sizeof(annotation_buf),
  3125. "@source controller\n"
  3126. "@purpose %s\n", router_purpose_to_string(purpose));
  3127. if (!(ri = router_parse_entry_from_string(s, NULL, 1, 0, annotation_buf))) {
  3128. log_warn(LD_DIR, "Error parsing router descriptor; dropping.");
  3129. *msg = "Couldn't parse router descriptor.";
  3130. return -1;
  3131. }
  3132. tor_assert(ri->purpose == purpose);
  3133. if (router_is_me(ri)) {
  3134. log_warn(LD_DIR, "Router's identity key matches mine; dropping.");
  3135. *msg = "Router's identity key matches mine.";
  3136. routerinfo_free(ri);
  3137. return 0;
  3138. }
  3139. if (!cache) /* obey the preference of the controller */
  3140. ri->cache_info.do_not_cache = 1;
  3141. lst = smartlist_new();
  3142. smartlist_add(lst, ri);
  3143. routers_update_status_from_consensus_networkstatus(lst, 0);
  3144. r = router_add_to_routerlist(ri, msg, 0, 0);
  3145. if (!WRA_WAS_ADDED(r)) {
  3146. /* we've already assigned to *msg now, and ri is already freed */
  3147. tor_assert(*msg);
  3148. if (r == ROUTER_AUTHDIR_REJECTS)
  3149. log_warn(LD_DIR, "Couldn't add router to list: %s Dropping.", *msg);
  3150. smartlist_free(lst);
  3151. return 0;
  3152. } else {
  3153. routerlist_descriptors_added(lst, 0);
  3154. smartlist_free(lst);
  3155. log_debug(LD_DIR, "Added router to list");
  3156. return 1;
  3157. }
  3158. }
  3159. /** Given a string <b>s</b> containing some routerdescs, parse it and put the
  3160. * routers into our directory. If saved_location is SAVED_NOWHERE, the routers
  3161. * are in response to a query to the network: cache them by adding them to
  3162. * the journal.
  3163. *
  3164. * Return the number of routers actually added.
  3165. *
  3166. * If <b>requested_fingerprints</b> is provided, it must contain a list of
  3167. * uppercased fingerprints. Do not update any router whose
  3168. * fingerprint is not on the list; after updating a router, remove its
  3169. * fingerprint from the list.
  3170. *
  3171. * If <b>descriptor_digests</b> is non-zero, then the requested_fingerprints
  3172. * are descriptor digests. Otherwise they are identity digests.
  3173. */
  3174. int
  3175. router_load_routers_from_string(const char *s, const char *eos,
  3176. saved_location_t saved_location,
  3177. smartlist_t *requested_fingerprints,
  3178. int descriptor_digests,
  3179. const char *prepend_annotations)
  3180. {
  3181. smartlist_t *routers = smartlist_new(), *changed = smartlist_new();
  3182. char fp[HEX_DIGEST_LEN+1];
  3183. const char *msg;
  3184. int from_cache = (saved_location != SAVED_NOWHERE);
  3185. int allow_annotations = (saved_location != SAVED_NOWHERE);
  3186. int any_changed = 0;
  3187. router_parse_list_from_string(&s, eos, routers, saved_location, 0,
  3188. allow_annotations, prepend_annotations);
  3189. routers_update_status_from_consensus_networkstatus(routers, !from_cache);
  3190. log_info(LD_DIR, "%d elements to add", smartlist_len(routers));
  3191. SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
  3192. was_router_added_t r;
  3193. char d[DIGEST_LEN];
  3194. if (requested_fingerprints) {
  3195. base16_encode(fp, sizeof(fp), descriptor_digests ?
  3196. ri->cache_info.signed_descriptor_digest :
  3197. ri->cache_info.identity_digest,
  3198. DIGEST_LEN);
  3199. if (smartlist_string_isin(requested_fingerprints, fp)) {
  3200. smartlist_string_remove(requested_fingerprints, fp);
  3201. } else {
  3202. char *requested =
  3203. smartlist_join_strings(requested_fingerprints," ",0,NULL);
  3204. log_warn(LD_DIR,
  3205. "We received a router descriptor with a fingerprint (%s) "
  3206. "that we never requested. (We asked for: %s.) Dropping.",
  3207. fp, requested);
  3208. tor_free(requested);
  3209. routerinfo_free(ri);
  3210. continue;
  3211. }
  3212. }
  3213. memcpy(d, ri->cache_info.signed_descriptor_digest, DIGEST_LEN);
  3214. r = router_add_to_routerlist(ri, &msg, from_cache, !from_cache);
  3215. if (WRA_WAS_ADDED(r)) {
  3216. any_changed++;
  3217. smartlist_add(changed, ri);
  3218. routerlist_descriptors_added(changed, from_cache);
  3219. smartlist_clear(changed);
  3220. } else if (WRA_WAS_REJECTED(r)) {
  3221. download_status_t *dl_status;
  3222. dl_status = router_get_dl_status_by_descriptor_digest(d);
  3223. if (dl_status) {
  3224. log_info(LD_GENERAL, "Marking router %s as never downloadable",
  3225. hex_str(d, DIGEST_LEN));
  3226. download_status_mark_impossible(dl_status);
  3227. }
  3228. }
  3229. } SMARTLIST_FOREACH_END(ri);
  3230. routerlist_assert_ok(routerlist);
  3231. if (any_changed)
  3232. router_rebuild_store(0, &routerlist->desc_store);
  3233. smartlist_free(routers);
  3234. smartlist_free(changed);
  3235. return any_changed;
  3236. }
  3237. /** Parse one or more extrainfos from <b>s</b> (ending immediately before
  3238. * <b>eos</b> if <b>eos</b> is present). Other arguments are as for
  3239. * router_load_routers_from_string(). */
  3240. void
  3241. router_load_extrainfo_from_string(const char *s, const char *eos,
  3242. saved_location_t saved_location,
  3243. smartlist_t *requested_fingerprints,
  3244. int descriptor_digests)
  3245. {
  3246. smartlist_t *extrainfo_list = smartlist_new();
  3247. const char *msg;
  3248. int from_cache = (saved_location != SAVED_NOWHERE);
  3249. router_parse_list_from_string(&s, eos, extrainfo_list, saved_location, 1, 0,
  3250. NULL);
  3251. log_info(LD_DIR, "%d elements to add", smartlist_len(extrainfo_list));
  3252. SMARTLIST_FOREACH_BEGIN(extrainfo_list, extrainfo_t *, ei) {
  3253. was_router_added_t added =
  3254. router_add_extrainfo_to_routerlist(ei, &msg, from_cache, !from_cache);
  3255. if (WRA_WAS_ADDED(added) && requested_fingerprints) {
  3256. char fp[HEX_DIGEST_LEN+1];
  3257. base16_encode(fp, sizeof(fp), descriptor_digests ?
  3258. ei->cache_info.signed_descriptor_digest :
  3259. ei->cache_info.identity_digest,
  3260. DIGEST_LEN);
  3261. smartlist_string_remove(requested_fingerprints, fp);
  3262. /* We silently let people stuff us with extrainfos we didn't ask for,
  3263. * so long as we would have wanted them anyway. Since we always fetch
  3264. * all the extrainfos we want, and we never actually act on them
  3265. * inside Tor, this should be harmless. */
  3266. }
  3267. } SMARTLIST_FOREACH_END(ei);
  3268. routerlist_assert_ok(routerlist);
  3269. router_rebuild_store(0, &router_get_routerlist()->extrainfo_store);
  3270. smartlist_free(extrainfo_list);
  3271. }
  3272. /** Return true iff any networkstatus includes a descriptor whose digest
  3273. * is that of <b>desc</b>. */
  3274. static int
  3275. signed_desc_digest_is_recognized(signed_descriptor_t *desc)
  3276. {
  3277. const routerstatus_t *rs;
  3278. networkstatus_t *consensus = networkstatus_get_latest_consensus();
  3279. int caches = directory_caches_dir_info(get_options());
  3280. const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
  3281. if (consensus) {
  3282. rs = networkstatus_vote_find_entry(consensus, desc->identity_digest);
  3283. if (rs && tor_memeq(rs->descriptor_digest,
  3284. desc->signed_descriptor_digest, DIGEST_LEN))
  3285. return 1;
  3286. }
  3287. if (caches && networkstatus_v2_list) {
  3288. SMARTLIST_FOREACH(networkstatus_v2_list, networkstatus_v2_t *, ns,
  3289. {
  3290. if (!(rs = networkstatus_v2_find_entry(ns, desc->identity_digest)))
  3291. continue;
  3292. if (tor_memeq(rs->descriptor_digest,
  3293. desc->signed_descriptor_digest, DIGEST_LEN))
  3294. return 1;
  3295. });
  3296. }
  3297. return 0;
  3298. }
  3299. /** Update downloads for router descriptors and/or microdescriptors as
  3300. * appropriate. */
  3301. void
  3302. update_all_descriptor_downloads(time_t now)
  3303. {
  3304. if (get_options()->DisableNetwork)
  3305. return;
  3306. update_router_descriptor_downloads(now);
  3307. update_microdesc_downloads(now);
  3308. launch_dummy_descriptor_download_as_needed(now, get_options());
  3309. }
  3310. /** Clear all our timeouts for fetching v2 and v3 directory stuff, and then
  3311. * give it all a try again. */
  3312. void
  3313. routerlist_retry_directory_downloads(time_t now)
  3314. {
  3315. router_reset_status_download_failures();
  3316. router_reset_descriptor_download_failures();
  3317. if (get_options()->DisableNetwork)
  3318. return;
  3319. update_networkstatus_downloads(now);
  3320. update_all_descriptor_downloads(now);
  3321. }
  3322. /** Return true iff <b>router</b> does not permit exit streams.
  3323. */
  3324. int
  3325. router_exit_policy_rejects_all(const routerinfo_t *router)
  3326. {
  3327. return router->policy_is_reject_star;
  3328. }
  3329. /** Add to the list of authoritative directory servers one at
  3330. * <b>address</b>:<b>port</b>, with identity key <b>digest</b>. If
  3331. * <b>address</b> is NULL, add ourself. Return the new trusted directory
  3332. * server entry on success or NULL if we couldn't add it. */
  3333. trusted_dir_server_t *
  3334. add_trusted_dir_server(const char *nickname, const char *address,
  3335. uint16_t dir_port, uint16_t or_port,
  3336. const char *digest, const char *v3_auth_digest,
  3337. dirinfo_type_t type)
  3338. {
  3339. trusted_dir_server_t *ent;
  3340. uint32_t a;
  3341. char *hostname = NULL;
  3342. if (!trusted_dir_servers)
  3343. trusted_dir_servers = smartlist_new();
  3344. if (!address) { /* The address is us; we should guess. */
  3345. if (resolve_my_address(LOG_WARN, get_options(), &a, &hostname) < 0) {
  3346. log_warn(LD_CONFIG,
  3347. "Couldn't find a suitable address when adding ourself as a "
  3348. "trusted directory server.");
  3349. return NULL;
  3350. }
  3351. } else {
  3352. if (tor_lookup_hostname(address, &a)) {
  3353. log_warn(LD_CONFIG,
  3354. "Unable to lookup address for directory server at '%s'",
  3355. address);
  3356. return NULL;
  3357. }
  3358. hostname = tor_strdup(address);
  3359. }
  3360. ent = tor_malloc_zero(sizeof(trusted_dir_server_t));
  3361. ent->nickname = nickname ? tor_strdup(nickname) : NULL;
  3362. ent->address = hostname;
  3363. ent->addr = a;
  3364. ent->dir_port = dir_port;
  3365. ent->or_port = or_port;
  3366. ent->is_running = 1;
  3367. ent->type = type;
  3368. memcpy(ent->digest, digest, DIGEST_LEN);
  3369. if (v3_auth_digest && (type & V3_DIRINFO))
  3370. memcpy(ent->v3_identity_digest, v3_auth_digest, DIGEST_LEN);
  3371. if (nickname)
  3372. tor_asprintf(&ent->description, "directory server \"%s\" at %s:%d",
  3373. nickname, hostname, (int)dir_port);
  3374. else
  3375. tor_asprintf(&ent->description, "directory server at %s:%d",
  3376. hostname, (int)dir_port);
  3377. ent->fake_status.addr = ent->addr;
  3378. memcpy(ent->fake_status.identity_digest, digest, DIGEST_LEN);
  3379. if (nickname)
  3380. strlcpy(ent->fake_status.nickname, nickname,
  3381. sizeof(ent->fake_status.nickname));
  3382. else
  3383. ent->fake_status.nickname[0] = '\0';
  3384. ent->fake_status.dir_port = ent->dir_port;
  3385. ent->fake_status.or_port = ent->or_port;
  3386. smartlist_add(trusted_dir_servers, ent);
  3387. router_dir_info_changed();
  3388. return ent;
  3389. }
  3390. /** Free storage held in <b>cert</b>. */
  3391. void
  3392. authority_cert_free(authority_cert_t *cert)
  3393. {
  3394. if (!cert)
  3395. return;
  3396. tor_free(cert->cache_info.signed_descriptor_body);
  3397. crypto_pk_free(cert->signing_key);
  3398. crypto_pk_free(cert->identity_key);
  3399. tor_free(cert);
  3400. }
  3401. /** Free storage held in <b>ds</b>. */
  3402. static void
  3403. trusted_dir_server_free(trusted_dir_server_t *ds)
  3404. {
  3405. if (!ds)
  3406. return;
  3407. tor_free(ds->nickname);
  3408. tor_free(ds->description);
  3409. tor_free(ds->address);
  3410. tor_free(ds);
  3411. }
  3412. /** Remove all members from the list of trusted dir servers. */
  3413. void
  3414. clear_trusted_dir_servers(void)
  3415. {
  3416. if (trusted_dir_servers) {
  3417. SMARTLIST_FOREACH(trusted_dir_servers, trusted_dir_server_t *, ent,
  3418. trusted_dir_server_free(ent));
  3419. smartlist_clear(trusted_dir_servers);
  3420. } else {
  3421. trusted_dir_servers = smartlist_new();
  3422. }
  3423. router_dir_info_changed();
  3424. }
  3425. /** Return 1 if any trusted dir server supports v1 directories,
  3426. * else return 0. */
  3427. int
  3428. any_trusted_dir_is_v1_authority(void)
  3429. {
  3430. if (trusted_dir_servers)
  3431. return get_n_authorities(V1_DIRINFO) > 0;
  3432. return 0;
  3433. }
  3434. /** For every current directory connection whose purpose is <b>purpose</b>,
  3435. * and where the resource being downloaded begins with <b>prefix</b>, split
  3436. * rest of the resource into base16 fingerprints (or base64 fingerprints if
  3437. * purpose==DIR_PURPPOSE_FETCH_MICRODESC), decode them, and set the
  3438. * corresponding elements of <b>result</b> to a nonzero value.
  3439. */
  3440. static void
  3441. list_pending_downloads(digestmap_t *result,
  3442. int purpose, const char *prefix)
  3443. {
  3444. const size_t p_len = strlen(prefix);
  3445. smartlist_t *tmp = smartlist_new();
  3446. smartlist_t *conns = get_connection_array();
  3447. int flags = DSR_HEX;
  3448. if (purpose == DIR_PURPOSE_FETCH_MICRODESC)
  3449. flags = DSR_DIGEST256|DSR_BASE64;
  3450. tor_assert(result);
  3451. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
  3452. if (conn->type == CONN_TYPE_DIR &&
  3453. conn->purpose == purpose &&
  3454. !conn->marked_for_close) {
  3455. const char *resource = TO_DIR_CONN(conn)->requested_resource;
  3456. if (!strcmpstart(resource, prefix))
  3457. dir_split_resource_into_fingerprints(resource + p_len,
  3458. tmp, NULL, flags);
  3459. }
  3460. } SMARTLIST_FOREACH_END(conn);
  3461. SMARTLIST_FOREACH(tmp, char *, d,
  3462. {
  3463. digestmap_set(result, d, (void*)1);
  3464. tor_free(d);
  3465. });
  3466. smartlist_free(tmp);
  3467. }
  3468. /** For every router descriptor (or extra-info document if <b>extrainfo</b> is
  3469. * true) we are currently downloading by descriptor digest, set result[d] to
  3470. * (void*)1. */
  3471. static void
  3472. list_pending_descriptor_downloads(digestmap_t *result, int extrainfo)
  3473. {
  3474. int purpose =
  3475. extrainfo ? DIR_PURPOSE_FETCH_EXTRAINFO : DIR_PURPOSE_FETCH_SERVERDESC;
  3476. list_pending_downloads(result, purpose, "d/");
  3477. }
  3478. /** For every microdescriptor we are currently downloading by descriptor
  3479. * digest, set result[d] to (void*)1. (Note that microdescriptor digests
  3480. * are 256-bit, and digestmap_t only holds 160-bit digests, so we're only
  3481. * getting the first 20 bytes of each digest here.)
  3482. *
  3483. * XXXX Let there be a digestmap256_t, and use that instead.
  3484. */
  3485. void
  3486. list_pending_microdesc_downloads(digestmap_t *result)
  3487. {
  3488. list_pending_downloads(result, DIR_PURPOSE_FETCH_MICRODESC, "d/");
  3489. }
  3490. /** Launch downloads for all the descriptors whose digests or digests256
  3491. * are listed as digests[i] for lo <= i < hi. (Lo and hi may be out of
  3492. * range.) If <b>source</b> is given, download from <b>source</b>;
  3493. * otherwise, download from an appropriate random directory server.
  3494. */
  3495. static void
  3496. initiate_descriptor_downloads(const routerstatus_t *source,
  3497. int purpose,
  3498. smartlist_t *digests,
  3499. int lo, int hi, int pds_flags)
  3500. {
  3501. int i, n = hi-lo;
  3502. char *resource, *cp;
  3503. size_t r_len;
  3504. int digest_len = DIGEST_LEN, enc_digest_len = HEX_DIGEST_LEN;
  3505. char sep = '+';
  3506. int b64_256 = 0;
  3507. if (purpose == DIR_PURPOSE_FETCH_MICRODESC) {
  3508. /* Microdescriptors are downloaded by "-"-separated base64-encoded
  3509. * 256-bit digests. */
  3510. digest_len = DIGEST256_LEN;
  3511. enc_digest_len = BASE64_DIGEST256_LEN;
  3512. sep = '-';
  3513. b64_256 = 1;
  3514. }
  3515. if (n <= 0)
  3516. return;
  3517. if (lo < 0)
  3518. lo = 0;
  3519. if (hi > smartlist_len(digests))
  3520. hi = smartlist_len(digests);
  3521. r_len = 8 + (enc_digest_len+1)*n;
  3522. cp = resource = tor_malloc(r_len);
  3523. memcpy(cp, "d/", 2);
  3524. cp += 2;
  3525. for (i = lo; i < hi; ++i) {
  3526. if (b64_256) {
  3527. digest256_to_base64(cp, smartlist_get(digests, i));
  3528. } else {
  3529. base16_encode(cp, r_len-(cp-resource),
  3530. smartlist_get(digests,i), digest_len);
  3531. }
  3532. cp += enc_digest_len;
  3533. *cp++ = sep;
  3534. }
  3535. memcpy(cp-1, ".z", 3);
  3536. if (source) {
  3537. /* We know which authority we want. */
  3538. directory_initiate_command_routerstatus(source, purpose,
  3539. ROUTER_PURPOSE_GENERAL,
  3540. DIRIND_ONEHOP,
  3541. resource, NULL, 0, 0);
  3542. } else {
  3543. directory_get_from_dirserver(purpose, ROUTER_PURPOSE_GENERAL, resource,
  3544. pds_flags);
  3545. }
  3546. tor_free(resource);
  3547. }
  3548. /** Max amount of hashes to download per request.
  3549. * Since squid does not like URLs >= 4096 bytes we limit it to 96.
  3550. * 4096 - strlen(http://255.255.255.255/tor/server/d/.z) == 4058
  3551. * 4058/41 (40 for the hash and 1 for the + that separates them) => 98
  3552. * So use 96 because it's a nice number.
  3553. */
  3554. #define MAX_DL_PER_REQUEST 96
  3555. #define MAX_MICRODESC_DL_PER_REQUEST 92
  3556. /** Don't split our requests so finely that we are requesting fewer than
  3557. * this number per server. */
  3558. #define MIN_DL_PER_REQUEST 4
  3559. /** To prevent a single screwy cache from confusing us by selective reply,
  3560. * try to split our requests into at least this many requests. */
  3561. #define MIN_REQUESTS 3
  3562. /** If we want fewer than this many descriptors, wait until we
  3563. * want more, or until MAX_CLIENT_INTERVAL_WITHOUT_REQUEST has
  3564. * passed. */
  3565. #define MAX_DL_TO_DELAY 16
  3566. /** When directory clients have only a few servers to request, they batch
  3567. * them until they have more, or until this amount of time has passed. */
  3568. #define MAX_CLIENT_INTERVAL_WITHOUT_REQUEST (10*60)
  3569. /** Given a <b>purpose</b> (FETCH_MICRODESC or FETCH_SERVERDESC) and a list of
  3570. * router descriptor digests or microdescriptor digest256s in
  3571. * <b>downloadable</b>, decide whether to delay fetching until we have more.
  3572. * If we don't want to delay, launch one or more requests to the appropriate
  3573. * directory authorities.
  3574. */
  3575. void
  3576. launch_descriptor_downloads(int purpose,
  3577. smartlist_t *downloadable,
  3578. const routerstatus_t *source, time_t now)
  3579. {
  3580. int should_delay = 0, n_downloadable;
  3581. const or_options_t *options = get_options();
  3582. const char *descname;
  3583. tor_assert(purpose == DIR_PURPOSE_FETCH_SERVERDESC ||
  3584. purpose == DIR_PURPOSE_FETCH_MICRODESC);
  3585. descname = (purpose == DIR_PURPOSE_FETCH_SERVERDESC) ?
  3586. "routerdesc" : "microdesc";
  3587. n_downloadable = smartlist_len(downloadable);
  3588. if (!directory_fetches_dir_info_early(options)) {
  3589. if (n_downloadable >= MAX_DL_TO_DELAY) {
  3590. log_debug(LD_DIR,
  3591. "There are enough downloadable %ss to launch requests.",
  3592. descname);
  3593. should_delay = 0;
  3594. } else {
  3595. should_delay = (last_descriptor_download_attempted +
  3596. MAX_CLIENT_INTERVAL_WITHOUT_REQUEST) > now;
  3597. if (!should_delay && n_downloadable) {
  3598. if (last_descriptor_download_attempted) {
  3599. log_info(LD_DIR,
  3600. "There are not many downloadable %ss, but we've "
  3601. "been waiting long enough (%d seconds). Downloading.",
  3602. descname,
  3603. (int)(now-last_descriptor_download_attempted));
  3604. } else {
  3605. log_info(LD_DIR,
  3606. "There are not many downloadable %ss, but we haven't "
  3607. "tried downloading descriptors recently. Downloading.",
  3608. descname);
  3609. }
  3610. }
  3611. }
  3612. }
  3613. if (! should_delay && n_downloadable) {
  3614. int i, n_per_request;
  3615. const char *req_plural = "", *rtr_plural = "";
  3616. int pds_flags = PDS_RETRY_IF_NO_SERVERS;
  3617. if (! authdir_mode_any_nonhidserv(options)) {
  3618. /* If we wind up going to the authorities, we want to only open one
  3619. * connection to each authority at a time, so that we don't overload
  3620. * them. We do this by setting PDS_NO_EXISTING_SERVERDESC_FETCH
  3621. * regardless of whether we're a cache or not; it gets ignored if we're
  3622. * not calling router_pick_trusteddirserver.
  3623. *
  3624. * Setting this flag can make initiate_descriptor_downloads() ignore
  3625. * requests. We need to make sure that we do in fact call
  3626. * update_router_descriptor_downloads() later on, once the connections
  3627. * have succeeded or failed.
  3628. */
  3629. pds_flags |= (purpose == DIR_PURPOSE_FETCH_MICRODESC) ?
  3630. PDS_NO_EXISTING_MICRODESC_FETCH :
  3631. PDS_NO_EXISTING_SERVERDESC_FETCH;
  3632. }
  3633. n_per_request = CEIL_DIV(n_downloadable, MIN_REQUESTS);
  3634. if (purpose == DIR_PURPOSE_FETCH_MICRODESC) {
  3635. if (n_per_request > MAX_MICRODESC_DL_PER_REQUEST)
  3636. n_per_request = MAX_MICRODESC_DL_PER_REQUEST;
  3637. } else {
  3638. if (n_per_request > MAX_DL_PER_REQUEST)
  3639. n_per_request = MAX_DL_PER_REQUEST;
  3640. }
  3641. if (n_per_request < MIN_DL_PER_REQUEST)
  3642. n_per_request = MIN_DL_PER_REQUEST;
  3643. if (n_downloadable > n_per_request)
  3644. req_plural = rtr_plural = "s";
  3645. else if (n_downloadable > 1)
  3646. rtr_plural = "s";
  3647. log_info(LD_DIR,
  3648. "Launching %d request%s for %d %s%s, %d at a time",
  3649. CEIL_DIV(n_downloadable, n_per_request), req_plural,
  3650. n_downloadable, descname, rtr_plural, n_per_request);
  3651. smartlist_sort_digests(downloadable);
  3652. for (i=0; i < n_downloadable; i += n_per_request) {
  3653. initiate_descriptor_downloads(source, purpose,
  3654. downloadable, i, i+n_per_request,
  3655. pds_flags);
  3656. }
  3657. last_descriptor_download_attempted = now;
  3658. }
  3659. }
  3660. /** Launch downloads for router status as needed, using the strategy used by
  3661. * authorities and caches: based on the v2 networkstatuses we have, download
  3662. * every descriptor we don't have but would serve, from a random authority
  3663. * that lists it. */
  3664. static void
  3665. update_router_descriptor_cache_downloads_v2(time_t now)
  3666. {
  3667. smartlist_t **downloadable; /* For each authority, what can we dl from it? */
  3668. smartlist_t **download_from; /* ... and, what will we dl from it? */
  3669. digestmap_t *map; /* Which descs are in progress, or assigned? */
  3670. int i, j, n;
  3671. int n_download;
  3672. const or_options_t *options = get_options();
  3673. const smartlist_t *networkstatus_v2_list = networkstatus_get_v2_list();
  3674. if (! directory_fetches_dir_info_early(options)) {
  3675. log_warn(LD_BUG, "Called update_router_descriptor_cache_downloads_v2() "
  3676. "on a non-dir-mirror?");
  3677. }
  3678. if (!networkstatus_v2_list || !smartlist_len(networkstatus_v2_list))
  3679. return;
  3680. map = digestmap_new();
  3681. n = smartlist_len(networkstatus_v2_list);
  3682. downloadable = tor_malloc_zero(sizeof(smartlist_t*) * n);
  3683. download_from = tor_malloc_zero(sizeof(smartlist_t*) * n);
  3684. /* Set map[d]=1 for the digest of every descriptor that we are currently
  3685. * downloading. */
  3686. list_pending_descriptor_downloads(map, 0);
  3687. /* For the digest of every descriptor that we don't have, and that we aren't
  3688. * downloading, add d to downloadable[i] if the i'th networkstatus knows
  3689. * about that descriptor, and we haven't already failed to get that
  3690. * descriptor from the corresponding authority.
  3691. */
  3692. n_download = 0;
  3693. SMARTLIST_FOREACH_BEGIN(networkstatus_v2_list, networkstatus_v2_t *, ns) {
  3694. trusted_dir_server_t *ds;
  3695. smartlist_t *dl;
  3696. dl = downloadable[ns_sl_idx] = smartlist_new();
  3697. download_from[ns_sl_idx] = smartlist_new();
  3698. if (ns->published_on + MAX_NETWORKSTATUS_AGE+10*60 < now) {
  3699. /* Don't download if the networkstatus is almost ancient. */
  3700. /* Actually, I suspect what's happening here is that we ask
  3701. * for the descriptor when we have a given networkstatus,
  3702. * and then we get a newer networkstatus, and then we receive
  3703. * the descriptor. Having a networkstatus actually expire is
  3704. * probably a rare event, and we'll probably be happiest if
  3705. * we take this clause out. -RD */
  3706. continue;
  3707. }
  3708. /* Don't try dirservers that we think are down -- we might have
  3709. * just tried them and just marked them as down. */
  3710. ds = router_get_trusteddirserver_by_digest(ns->identity_digest);
  3711. if (ds && !ds->is_running)
  3712. continue;
  3713. SMARTLIST_FOREACH_BEGIN(ns->entries, routerstatus_t * , rs) {
  3714. if (!rs->need_to_mirror)
  3715. continue;
  3716. if (router_get_by_descriptor_digest(rs->descriptor_digest)) {
  3717. log_warn(LD_BUG,
  3718. "We have a router descriptor, but need_to_mirror=1.");
  3719. rs->need_to_mirror = 0;
  3720. continue;
  3721. }
  3722. if (authdir_mode(options) && dirserv_would_reject_router(rs)) {
  3723. rs->need_to_mirror = 0;
  3724. continue;
  3725. }
  3726. if (digestmap_get(map, rs->descriptor_digest)) {
  3727. /* We're downloading it already. */
  3728. continue;
  3729. } else {
  3730. /* We could download it from this guy. */
  3731. smartlist_add(dl, rs->descriptor_digest);
  3732. ++n_download;
  3733. }
  3734. } SMARTLIST_FOREACH_END(rs);
  3735. } SMARTLIST_FOREACH_END(ns);
  3736. /* At random, assign descriptors to authorities such that:
  3737. * - if d is a member of some downloadable[x], d is a member of some
  3738. * download_from[y]. (Everything we want to download, we try to download
  3739. * from somebody.)
  3740. * - If d is a member of download_from[y], d is a member of downloadable[y].
  3741. * (We only try to download descriptors from authorities who claim to have
  3742. * them.)
  3743. * - No d is a member of download_from[x] and download_from[y] s.t. x != y.
  3744. * (We don't try to download anything from two authorities concurrently.)
  3745. */
  3746. while (n_download) {
  3747. int which_ns = crypto_rand_int(n);
  3748. smartlist_t *dl = downloadable[which_ns];
  3749. int idx;
  3750. char *d;
  3751. if (!smartlist_len(dl))
  3752. continue;
  3753. idx = crypto_rand_int(smartlist_len(dl));
  3754. d = smartlist_get(dl, idx);
  3755. if (! digestmap_get(map, d)) {
  3756. smartlist_add(download_from[which_ns], d);
  3757. digestmap_set(map, d, (void*) 1);
  3758. }
  3759. smartlist_del(dl, idx);
  3760. --n_download;
  3761. }
  3762. /* Now, we can actually launch our requests. */
  3763. for (i=0; i<n; ++i) {
  3764. networkstatus_v2_t *ns = smartlist_get(networkstatus_v2_list, i);
  3765. trusted_dir_server_t *ds =
  3766. router_get_trusteddirserver_by_digest(ns->identity_digest);
  3767. smartlist_t *dl = download_from[i];
  3768. int pds_flags = PDS_RETRY_IF_NO_SERVERS;
  3769. if (! authdir_mode_any_nonhidserv(options))
  3770. pds_flags |= PDS_NO_EXISTING_SERVERDESC_FETCH; /* XXXX ignored*/
  3771. if (!ds) {
  3772. log_info(LD_DIR, "Networkstatus with no corresponding authority!");
  3773. continue;
  3774. }
  3775. if (! smartlist_len(dl))
  3776. continue;
  3777. log_info(LD_DIR, "Requesting %d descriptors from authority \"%s\"",
  3778. smartlist_len(dl), ds->nickname);
  3779. for (j=0; j < smartlist_len(dl); j += MAX_DL_PER_REQUEST) {
  3780. initiate_descriptor_downloads(&(ds->fake_status),
  3781. DIR_PURPOSE_FETCH_SERVERDESC, dl, j,
  3782. j+MAX_DL_PER_REQUEST, pds_flags);
  3783. }
  3784. }
  3785. for (i=0; i<n; ++i) {
  3786. smartlist_free(download_from[i]);
  3787. smartlist_free(downloadable[i]);
  3788. }
  3789. tor_free(download_from);
  3790. tor_free(downloadable);
  3791. digestmap_free(map,NULL);
  3792. }
  3793. /** For any descriptor that we want that's currently listed in
  3794. * <b>consensus</b>, download it as appropriate. */
  3795. void
  3796. update_consensus_router_descriptor_downloads(time_t now, int is_vote,
  3797. networkstatus_t *consensus)
  3798. {
  3799. const or_options_t *options = get_options();
  3800. digestmap_t *map = NULL;
  3801. smartlist_t *no_longer_old = smartlist_new();
  3802. smartlist_t *downloadable = smartlist_new();
  3803. routerstatus_t *source = NULL;
  3804. int authdir = authdir_mode(options);
  3805. int n_delayed=0, n_have=0, n_would_reject=0, n_wouldnt_use=0,
  3806. n_inprogress=0, n_in_oldrouters=0;
  3807. if (directory_too_idle_to_fetch_descriptors(options, now))
  3808. goto done;
  3809. if (!consensus)
  3810. goto done;
  3811. if (is_vote) {
  3812. /* where's it from, so we know whom to ask for descriptors */
  3813. trusted_dir_server_t *ds;
  3814. networkstatus_voter_info_t *voter = smartlist_get(consensus->voters, 0);
  3815. tor_assert(voter);
  3816. ds = trusteddirserver_get_by_v3_auth_digest(voter->identity_digest);
  3817. if (ds)
  3818. source = &(ds->fake_status);
  3819. else
  3820. log_warn(LD_DIR, "couldn't lookup source from vote?");
  3821. }
  3822. map = digestmap_new();
  3823. list_pending_descriptor_downloads(map, 0);
  3824. SMARTLIST_FOREACH_BEGIN(consensus->routerstatus_list, void *, rsp) {
  3825. routerstatus_t *rs =
  3826. is_vote ? &(((vote_routerstatus_t *)rsp)->status) : rsp;
  3827. signed_descriptor_t *sd;
  3828. if ((sd = router_get_by_descriptor_digest(rs->descriptor_digest))) {
  3829. const routerinfo_t *ri;
  3830. ++n_have;
  3831. if (!(ri = router_get_by_id_digest(rs->identity_digest)) ||
  3832. tor_memneq(ri->cache_info.signed_descriptor_digest,
  3833. sd->signed_descriptor_digest, DIGEST_LEN)) {
  3834. /* We have a descriptor with this digest, but either there is no
  3835. * entry in routerlist with the same ID (!ri), or there is one,
  3836. * but the identity digest differs (memcmp).
  3837. */
  3838. smartlist_add(no_longer_old, sd);
  3839. ++n_in_oldrouters; /* We have it in old_routers. */
  3840. }
  3841. continue; /* We have it already. */
  3842. }
  3843. if (digestmap_get(map, rs->descriptor_digest)) {
  3844. ++n_inprogress;
  3845. continue; /* We have an in-progress download. */
  3846. }
  3847. if (!download_status_is_ready(&rs->dl_status, now,
  3848. MAX_ROUTERDESC_DOWNLOAD_FAILURES)) {
  3849. ++n_delayed; /* Not ready for retry. */
  3850. continue;
  3851. }
  3852. if (authdir && dirserv_would_reject_router(rs)) {
  3853. ++n_would_reject;
  3854. continue; /* We would throw it out immediately. */
  3855. }
  3856. if (!directory_caches_dir_info(options) &&
  3857. !client_would_use_router(rs, now, options)) {
  3858. ++n_wouldnt_use;
  3859. continue; /* We would never use it ourself. */
  3860. }
  3861. if (is_vote && source) {
  3862. char time_bufnew[ISO_TIME_LEN+1];
  3863. char time_bufold[ISO_TIME_LEN+1];
  3864. const routerinfo_t *oldrouter;
  3865. oldrouter = router_get_by_id_digest(rs->identity_digest);
  3866. format_iso_time(time_bufnew, rs->published_on);
  3867. if (oldrouter)
  3868. format_iso_time(time_bufold, oldrouter->cache_info.published_on);
  3869. log_info(LD_DIR, "Learned about %s (%s vs %s) from %s's vote (%s)",
  3870. routerstatus_describe(rs),
  3871. time_bufnew,
  3872. oldrouter ? time_bufold : "none",
  3873. source->nickname, oldrouter ? "known" : "unknown");
  3874. }
  3875. smartlist_add(downloadable, rs->descriptor_digest);
  3876. } SMARTLIST_FOREACH_END(rsp);
  3877. if (!authdir_mode_handles_descs(options, ROUTER_PURPOSE_GENERAL)
  3878. && smartlist_len(no_longer_old)) {
  3879. routerlist_t *rl = router_get_routerlist();
  3880. log_info(LD_DIR, "%d router descriptors listed in consensus are "
  3881. "currently in old_routers; making them current.",
  3882. smartlist_len(no_longer_old));
  3883. SMARTLIST_FOREACH_BEGIN(no_longer_old, signed_descriptor_t *, sd) {
  3884. const char *msg;
  3885. was_router_added_t r;
  3886. routerinfo_t *ri = routerlist_reparse_old(rl, sd);
  3887. if (!ri) {
  3888. log_warn(LD_BUG, "Failed to re-parse a router.");
  3889. continue;
  3890. }
  3891. r = router_add_to_routerlist(ri, &msg, 1, 0);
  3892. if (WRA_WAS_OUTDATED(r)) {
  3893. log_warn(LD_DIR, "Couldn't add re-parsed router: %s",
  3894. msg?msg:"???");
  3895. }
  3896. } SMARTLIST_FOREACH_END(sd);
  3897. routerlist_assert_ok(rl);
  3898. }
  3899. log_info(LD_DIR,
  3900. "%d router descriptors downloadable. %d delayed; %d present "
  3901. "(%d of those were in old_routers); %d would_reject; "
  3902. "%d wouldnt_use; %d in progress.",
  3903. smartlist_len(downloadable), n_delayed, n_have, n_in_oldrouters,
  3904. n_would_reject, n_wouldnt_use, n_inprogress);
  3905. launch_descriptor_downloads(DIR_PURPOSE_FETCH_SERVERDESC,
  3906. downloadable, source, now);
  3907. digestmap_free(map, NULL);
  3908. done:
  3909. smartlist_free(downloadable);
  3910. smartlist_free(no_longer_old);
  3911. }
  3912. /** How often should we launch a server/authority request to be sure of getting
  3913. * a guess for our IP? */
  3914. /*XXXX024 this info should come from netinfo cells or something, or we should
  3915. * do this only when we aren't seeing incoming data. see bug 652. */
  3916. #define DUMMY_DOWNLOAD_INTERVAL (20*60)
  3917. /** As needed, launch a dummy router descriptor fetch to see if our
  3918. * address has changed. */
  3919. static void
  3920. launch_dummy_descriptor_download_as_needed(time_t now,
  3921. const or_options_t *options)
  3922. {
  3923. static time_t last_dummy_download = 0;
  3924. /* XXXX024 we could be smarter here; see notes on bug 652. */
  3925. /* If we're a server that doesn't have a configured address, we rely on
  3926. * directory fetches to learn when our address changes. So if we haven't
  3927. * tried to get any routerdescs in a long time, try a dummy fetch now. */
  3928. if (!options->Address &&
  3929. server_mode(options) &&
  3930. last_descriptor_download_attempted + DUMMY_DOWNLOAD_INTERVAL < now &&
  3931. last_dummy_download + DUMMY_DOWNLOAD_INTERVAL < now) {
  3932. last_dummy_download = now;
  3933. directory_get_from_dirserver(DIR_PURPOSE_FETCH_SERVERDESC,
  3934. ROUTER_PURPOSE_GENERAL, "authority.z",
  3935. PDS_RETRY_IF_NO_SERVERS);
  3936. }
  3937. }
  3938. /** Launch downloads for router status as needed. */
  3939. void
  3940. update_router_descriptor_downloads(time_t now)
  3941. {
  3942. const or_options_t *options = get_options();
  3943. if (should_delay_dir_fetches(options))
  3944. return;
  3945. if (!we_fetch_router_descriptors(options))
  3946. return;
  3947. if (directory_fetches_dir_info_early(options)) {
  3948. update_router_descriptor_cache_downloads_v2(now);
  3949. }
  3950. update_consensus_router_descriptor_downloads(now, 0,
  3951. networkstatus_get_reasonably_live_consensus(now, FLAV_NS));
  3952. }
  3953. /** Launch extrainfo downloads as needed. */
  3954. void
  3955. update_extrainfo_downloads(time_t now)
  3956. {
  3957. const or_options_t *options = get_options();
  3958. routerlist_t *rl;
  3959. smartlist_t *wanted;
  3960. digestmap_t *pending;
  3961. int old_routers, i;
  3962. int n_no_ei = 0, n_pending = 0, n_have = 0, n_delay = 0;
  3963. if (! options->DownloadExtraInfo)
  3964. return;
  3965. if (should_delay_dir_fetches(options))
  3966. return;
  3967. if (!router_have_minimum_dir_info())
  3968. return;
  3969. pending = digestmap_new();
  3970. list_pending_descriptor_downloads(pending, 1);
  3971. rl = router_get_routerlist();
  3972. wanted = smartlist_new();
  3973. for (old_routers = 0; old_routers < 2; ++old_routers) {
  3974. smartlist_t *lst = old_routers ? rl->old_routers : rl->routers;
  3975. for (i = 0; i < smartlist_len(lst); ++i) {
  3976. signed_descriptor_t *sd;
  3977. char *d;
  3978. if (old_routers)
  3979. sd = smartlist_get(lst, i);
  3980. else
  3981. sd = &((routerinfo_t*)smartlist_get(lst, i))->cache_info;
  3982. if (sd->is_extrainfo)
  3983. continue; /* This should never happen. */
  3984. if (old_routers && !router_get_by_id_digest(sd->identity_digest))
  3985. continue; /* Couldn't check the signature if we got it. */
  3986. if (sd->extrainfo_is_bogus)
  3987. continue;
  3988. d = sd->extra_info_digest;
  3989. if (tor_digest_is_zero(d)) {
  3990. ++n_no_ei;
  3991. continue;
  3992. }
  3993. if (eimap_get(rl->extra_info_map, d)) {
  3994. ++n_have;
  3995. continue;
  3996. }
  3997. if (!download_status_is_ready(&sd->ei_dl_status, now,
  3998. MAX_ROUTERDESC_DOWNLOAD_FAILURES)) {
  3999. ++n_delay;
  4000. continue;
  4001. }
  4002. if (digestmap_get(pending, d)) {
  4003. ++n_pending;
  4004. continue;
  4005. }
  4006. smartlist_add(wanted, d);
  4007. }
  4008. }
  4009. digestmap_free(pending, NULL);
  4010. log_info(LD_DIR, "Extrainfo download status: %d router with no ei, %d "
  4011. "with present ei, %d delaying, %d pending, %d downloadable.",
  4012. n_no_ei, n_have, n_delay, n_pending, smartlist_len(wanted));
  4013. smartlist_shuffle(wanted);
  4014. for (i = 0; i < smartlist_len(wanted); i += MAX_DL_PER_REQUEST) {
  4015. initiate_descriptor_downloads(NULL, DIR_PURPOSE_FETCH_EXTRAINFO,
  4016. wanted, i, i + MAX_DL_PER_REQUEST,
  4017. PDS_RETRY_IF_NO_SERVERS|PDS_NO_EXISTING_SERVERDESC_FETCH);
  4018. }
  4019. smartlist_free(wanted);
  4020. }
  4021. /** Reset the descriptor download failure count on all routers, so that we
  4022. * can retry any long-failed routers immediately.
  4023. */
  4024. void
  4025. router_reset_descriptor_download_failures(void)
  4026. {
  4027. networkstatus_reset_download_failures();
  4028. last_descriptor_download_attempted = 0;
  4029. if (!routerlist)
  4030. return;
  4031. SMARTLIST_FOREACH(routerlist->routers, routerinfo_t *, ri,
  4032. {
  4033. download_status_reset(&ri->cache_info.ei_dl_status);
  4034. });
  4035. SMARTLIST_FOREACH(routerlist->old_routers, signed_descriptor_t *, sd,
  4036. {
  4037. download_status_reset(&sd->ei_dl_status);
  4038. });
  4039. }
  4040. /** Any changes in a router descriptor's publication time larger than this are
  4041. * automatically non-cosmetic. */
  4042. #define ROUTER_MAX_COSMETIC_TIME_DIFFERENCE (2*60*60)
  4043. /** We allow uptime to vary from how much it ought to be by this much. */
  4044. #define ROUTER_ALLOW_UPTIME_DRIFT (6*60*60)
  4045. /** Return true iff the only differences between r1 and r2 are such that
  4046. * would not cause a recent (post 0.1.1.6) dirserver to republish.
  4047. */
  4048. int
  4049. router_differences_are_cosmetic(const routerinfo_t *r1, const routerinfo_t *r2)
  4050. {
  4051. time_t r1pub, r2pub;
  4052. long time_difference;
  4053. tor_assert(r1 && r2);
  4054. /* r1 should be the one that was published first. */
  4055. if (r1->cache_info.published_on > r2->cache_info.published_on) {
  4056. const routerinfo_t *ri_tmp = r2;
  4057. r2 = r1;
  4058. r1 = ri_tmp;
  4059. }
  4060. /* If any key fields differ, they're different. */
  4061. if (strcasecmp(r1->address, r2->address) ||
  4062. strcasecmp(r1->nickname, r2->nickname) ||
  4063. r1->or_port != r2->or_port ||
  4064. !tor_addr_eq(&r1->ipv6_addr, &r2->ipv6_addr) ||
  4065. r1->ipv6_orport != r2->ipv6_orport ||
  4066. r1->dir_port != r2->dir_port ||
  4067. r1->purpose != r2->purpose ||
  4068. !crypto_pk_eq_keys(r1->onion_pkey, r2->onion_pkey) ||
  4069. !crypto_pk_eq_keys(r1->identity_pkey, r2->identity_pkey) ||
  4070. strcasecmp(r1->platform, r2->platform) ||
  4071. (r1->contact_info && !r2->contact_info) || /* contact_info is optional */
  4072. (!r1->contact_info && r2->contact_info) ||
  4073. (r1->contact_info && r2->contact_info &&
  4074. strcasecmp(r1->contact_info, r2->contact_info)) ||
  4075. r1->is_hibernating != r2->is_hibernating ||
  4076. cmp_addr_policies(r1->exit_policy, r2->exit_policy))
  4077. return 0;
  4078. if ((r1->declared_family == NULL) != (r2->declared_family == NULL))
  4079. return 0;
  4080. if (r1->declared_family && r2->declared_family) {
  4081. int i, n;
  4082. if (smartlist_len(r1->declared_family)!=smartlist_len(r2->declared_family))
  4083. return 0;
  4084. n = smartlist_len(r1->declared_family);
  4085. for (i=0; i < n; ++i) {
  4086. if (strcasecmp(smartlist_get(r1->declared_family, i),
  4087. smartlist_get(r2->declared_family, i)))
  4088. return 0;
  4089. }
  4090. }
  4091. /* Did bandwidth change a lot? */
  4092. if ((r1->bandwidthcapacity < r2->bandwidthcapacity/2) ||
  4093. (r2->bandwidthcapacity < r1->bandwidthcapacity/2))
  4094. return 0;
  4095. /* Did the bandwidthrate or bandwidthburst change? */
  4096. if ((r1->bandwidthrate != r2->bandwidthrate) ||
  4097. (r1->bandwidthburst != r2->bandwidthburst))
  4098. return 0;
  4099. /* Did more than 12 hours pass? */
  4100. if (r1->cache_info.published_on + ROUTER_MAX_COSMETIC_TIME_DIFFERENCE
  4101. < r2->cache_info.published_on)
  4102. return 0;
  4103. /* Did uptime fail to increase by approximately the amount we would think,
  4104. * give or take some slop? */
  4105. r1pub = r1->cache_info.published_on;
  4106. r2pub = r2->cache_info.published_on;
  4107. time_difference = labs(r2->uptime - (r1->uptime + (r2pub - r1pub)));
  4108. if (time_difference > ROUTER_ALLOW_UPTIME_DRIFT &&
  4109. time_difference > r1->uptime * .05 &&
  4110. time_difference > r2->uptime * .05)
  4111. return 0;
  4112. /* Otherwise, the difference is cosmetic. */
  4113. return 1;
  4114. }
  4115. /** Check whether <b>ri</b> (a.k.a. sd) is a router compatible with the
  4116. * extrainfo document
  4117. * <b>ei</b>. If no router is compatible with <b>ei</b>, <b>ei</b> should be
  4118. * dropped. Return 0 for "compatible", return 1 for "reject, and inform
  4119. * whoever uploaded <b>ei</b>, and return -1 for "reject silently.". If
  4120. * <b>msg</b> is present, set *<b>msg</b> to a description of the
  4121. * incompatibility (if any).
  4122. **/
  4123. int
  4124. routerinfo_incompatible_with_extrainfo(const routerinfo_t *ri,
  4125. extrainfo_t *ei,
  4126. signed_descriptor_t *sd,
  4127. const char **msg)
  4128. {
  4129. int digest_matches, r=1;
  4130. tor_assert(ri);
  4131. tor_assert(ei);
  4132. if (!sd)
  4133. sd = (signed_descriptor_t*)&ri->cache_info;
  4134. if (ei->bad_sig) {
  4135. if (msg) *msg = "Extrainfo signature was bad, or signed with wrong key.";
  4136. return 1;
  4137. }
  4138. digest_matches = tor_memeq(ei->cache_info.signed_descriptor_digest,
  4139. sd->extra_info_digest, DIGEST_LEN);
  4140. /* The identity must match exactly to have been generated at the same time
  4141. * by the same router. */
  4142. if (tor_memneq(ri->cache_info.identity_digest,
  4143. ei->cache_info.identity_digest,
  4144. DIGEST_LEN)) {
  4145. if (msg) *msg = "Extrainfo nickname or identity did not match routerinfo";
  4146. goto err; /* different servers */
  4147. }
  4148. if (ei->pending_sig) {
  4149. char signed_digest[128];
  4150. if (crypto_pk_public_checksig(ri->identity_pkey,
  4151. signed_digest, sizeof(signed_digest),
  4152. ei->pending_sig, ei->pending_sig_len) != DIGEST_LEN ||
  4153. tor_memneq(signed_digest, ei->cache_info.signed_descriptor_digest,
  4154. DIGEST_LEN)) {
  4155. ei->bad_sig = 1;
  4156. tor_free(ei->pending_sig);
  4157. if (msg) *msg = "Extrainfo signature bad, or signed with wrong key";
  4158. goto err; /* Bad signature, or no match. */
  4159. }
  4160. ei->cache_info.send_unencrypted = ri->cache_info.send_unencrypted;
  4161. tor_free(ei->pending_sig);
  4162. }
  4163. if (ei->cache_info.published_on < sd->published_on) {
  4164. if (msg) *msg = "Extrainfo published time did not match routerdesc";
  4165. goto err;
  4166. } else if (ei->cache_info.published_on > sd->published_on) {
  4167. if (msg) *msg = "Extrainfo published time did not match routerdesc";
  4168. r = -1;
  4169. goto err;
  4170. }
  4171. if (!digest_matches) {
  4172. if (msg) *msg = "Extrainfo digest did not match value from routerdesc";
  4173. goto err; /* Digest doesn't match declared value. */
  4174. }
  4175. return 0;
  4176. err:
  4177. if (digest_matches) {
  4178. /* This signature was okay, and the digest was right: This is indeed the
  4179. * corresponding extrainfo. But insanely, it doesn't match the routerinfo
  4180. * that lists it. Don't try to fetch this one again. */
  4181. sd->extrainfo_is_bogus = 1;
  4182. }
  4183. return r;
  4184. }
  4185. /** Assert that the internal representation of <b>rl</b> is
  4186. * self-consistent. */
  4187. void
  4188. routerlist_assert_ok(const routerlist_t *rl)
  4189. {
  4190. routerinfo_t *r2;
  4191. signed_descriptor_t *sd2;
  4192. if (!rl)
  4193. return;
  4194. SMARTLIST_FOREACH_BEGIN(rl->routers, routerinfo_t *, r) {
  4195. r2 = rimap_get(rl->identity_map, r->cache_info.identity_digest);
  4196. tor_assert(r == r2);
  4197. sd2 = sdmap_get(rl->desc_digest_map,
  4198. r->cache_info.signed_descriptor_digest);
  4199. tor_assert(&(r->cache_info) == sd2);
  4200. tor_assert(r->cache_info.routerlist_index == r_sl_idx);
  4201. /* XXXX
  4202. *
  4203. * Hoo boy. We need to fix this one, and the fix is a bit tricky, so
  4204. * commenting this out is just a band-aid.
  4205. *
  4206. * The problem is that, although well-behaved router descriptors
  4207. * should never have the same value for their extra_info_digest, it's
  4208. * possible for ill-behaved routers to claim whatever they like there.
  4209. *
  4210. * The real answer is to trash desc_by_eid_map and instead have
  4211. * something that indicates for a given extra-info digest we want,
  4212. * what its download status is. We'll do that as a part of routerlist
  4213. * refactoring once consensus directories are in. For now,
  4214. * this rep violation is probably harmless: an adversary can make us
  4215. * reset our retry count for an extrainfo, but that's not the end
  4216. * of the world. Changing the representation in 0.2.0.x would just
  4217. * destabilize the codebase.
  4218. if (!tor_digest_is_zero(r->cache_info.extra_info_digest)) {
  4219. signed_descriptor_t *sd3 =
  4220. sdmap_get(rl->desc_by_eid_map, r->cache_info.extra_info_digest);
  4221. tor_assert(sd3 == &(r->cache_info));
  4222. }
  4223. */
  4224. } SMARTLIST_FOREACH_END(r);
  4225. SMARTLIST_FOREACH_BEGIN(rl->old_routers, signed_descriptor_t *, sd) {
  4226. r2 = rimap_get(rl->identity_map, sd->identity_digest);
  4227. tor_assert(sd != &(r2->cache_info));
  4228. sd2 = sdmap_get(rl->desc_digest_map, sd->signed_descriptor_digest);
  4229. tor_assert(sd == sd2);
  4230. tor_assert(sd->routerlist_index == sd_sl_idx);
  4231. /* XXXX see above.
  4232. if (!tor_digest_is_zero(sd->extra_info_digest)) {
  4233. signed_descriptor_t *sd3 =
  4234. sdmap_get(rl->desc_by_eid_map, sd->extra_info_digest);
  4235. tor_assert(sd3 == sd);
  4236. }
  4237. */
  4238. } SMARTLIST_FOREACH_END(sd);
  4239. RIMAP_FOREACH(rl->identity_map, d, r) {
  4240. tor_assert(tor_memeq(r->cache_info.identity_digest, d, DIGEST_LEN));
  4241. } DIGESTMAP_FOREACH_END;
  4242. SDMAP_FOREACH(rl->desc_digest_map, d, sd) {
  4243. tor_assert(tor_memeq(sd->signed_descriptor_digest, d, DIGEST_LEN));
  4244. } DIGESTMAP_FOREACH_END;
  4245. SDMAP_FOREACH(rl->desc_by_eid_map, d, sd) {
  4246. tor_assert(!tor_digest_is_zero(d));
  4247. tor_assert(sd);
  4248. tor_assert(tor_memeq(sd->extra_info_digest, d, DIGEST_LEN));
  4249. } DIGESTMAP_FOREACH_END;
  4250. EIMAP_FOREACH(rl->extra_info_map, d, ei) {
  4251. signed_descriptor_t *sd;
  4252. tor_assert(tor_memeq(ei->cache_info.signed_descriptor_digest,
  4253. d, DIGEST_LEN));
  4254. sd = sdmap_get(rl->desc_by_eid_map,
  4255. ei->cache_info.signed_descriptor_digest);
  4256. // tor_assert(sd); // XXXX see above
  4257. if (sd) {
  4258. tor_assert(tor_memeq(ei->cache_info.signed_descriptor_digest,
  4259. sd->extra_info_digest, DIGEST_LEN));
  4260. }
  4261. } DIGESTMAP_FOREACH_END;
  4262. }
  4263. /** Allocate and return a new string representing the contact info
  4264. * and platform string for <b>router</b>,
  4265. * surrounded by quotes and using standard C escapes.
  4266. *
  4267. * THIS FUNCTION IS NOT REENTRANT. Don't call it from outside the main
  4268. * thread. Also, each call invalidates the last-returned value, so don't
  4269. * try log_warn(LD_GENERAL, "%s %s", esc_router_info(a), esc_router_info(b));
  4270. *
  4271. * If <b>router</b> is NULL, it just frees its internal memory and returns.
  4272. */
  4273. const char *
  4274. esc_router_info(const routerinfo_t *router)
  4275. {
  4276. static char *info=NULL;
  4277. char *esc_contact, *esc_platform;
  4278. tor_free(info);
  4279. if (!router)
  4280. return NULL; /* we're exiting; just free the memory we use */
  4281. esc_contact = esc_for_log(router->contact_info);
  4282. esc_platform = esc_for_log(router->platform);
  4283. tor_asprintf(&info, "Contact %s, Platform %s", esc_contact, esc_platform);
  4284. tor_free(esc_contact);
  4285. tor_free(esc_platform);
  4286. return info;
  4287. }
  4288. /** Helper for sorting: compare two routerinfos by their identity
  4289. * digest. */
  4290. static int
  4291. compare_routerinfo_by_id_digest_(const void **a, const void **b)
  4292. {
  4293. routerinfo_t *first = *(routerinfo_t **)a, *second = *(routerinfo_t **)b;
  4294. return fast_memcmp(first->cache_info.identity_digest,
  4295. second->cache_info.identity_digest,
  4296. DIGEST_LEN);
  4297. }
  4298. /** Sort a list of routerinfo_t in ascending order of identity digest. */
  4299. void
  4300. routers_sort_by_identity(smartlist_t *routers)
  4301. {
  4302. smartlist_sort(routers, compare_routerinfo_by_id_digest_);
  4303. }
  4304. /** Called when we change a node set, or when we reload the geoip list:
  4305. * recompute all country info in all configuration node sets and in the
  4306. * routerlist. */
  4307. void
  4308. refresh_all_country_info(void)
  4309. {
  4310. const or_options_t *options = get_options();
  4311. if (options->EntryNodes)
  4312. routerset_refresh_countries(options->EntryNodes);
  4313. if (options->ExitNodes)
  4314. routerset_refresh_countries(options->ExitNodes);
  4315. if (options->ExcludeNodes)
  4316. routerset_refresh_countries(options->ExcludeNodes);
  4317. if (options->ExcludeExitNodes)
  4318. routerset_refresh_countries(options->ExcludeExitNodes);
  4319. if (options->ExcludeExitNodesUnion_)
  4320. routerset_refresh_countries(options->ExcludeExitNodesUnion_);
  4321. nodelist_refresh_countries();
  4322. }
  4323. /** Determine the routers that are responsible for <b>id</b> (binary) and
  4324. * add pointers to those routers' routerstatus_t to <b>responsible_dirs</b>.
  4325. * Return -1 if we're returning an empty smartlist, else return 0.
  4326. */
  4327. int
  4328. hid_serv_get_responsible_directories(smartlist_t *responsible_dirs,
  4329. const char *id)
  4330. {
  4331. int start, found, n_added = 0, i;
  4332. networkstatus_t *c = networkstatus_get_latest_consensus();
  4333. if (!c || !smartlist_len(c->routerstatus_list)) {
  4334. log_warn(LD_REND, "We don't have a consensus, so we can't perform v2 "
  4335. "rendezvous operations.");
  4336. return -1;
  4337. }
  4338. tor_assert(id);
  4339. start = networkstatus_vote_find_entry_idx(c, id, &found);
  4340. if (start == smartlist_len(c->routerstatus_list)) start = 0;
  4341. i = start;
  4342. do {
  4343. routerstatus_t *r = smartlist_get(c->routerstatus_list, i);
  4344. if (r->is_hs_dir) {
  4345. smartlist_add(responsible_dirs, r);
  4346. if (++n_added == REND_NUMBER_OF_CONSECUTIVE_REPLICAS)
  4347. return 0;
  4348. }
  4349. if (++i == smartlist_len(c->routerstatus_list))
  4350. i = 0;
  4351. } while (i != start);
  4352. /* Even though we don't have the desired number of hidden service
  4353. * directories, be happy if we got any. */
  4354. return smartlist_len(responsible_dirs) ? 0 : -1;
  4355. }
  4356. /** Return true if this node is currently acting as hidden service
  4357. * directory, false otherwise. */
  4358. int
  4359. hid_serv_acting_as_directory(void)
  4360. {
  4361. const routerinfo_t *me = router_get_my_routerinfo();
  4362. if (!me)
  4363. return 0;
  4364. if (!get_options()->HidServDirectoryV2) {
  4365. log_info(LD_REND, "We are not acting as hidden service directory, "
  4366. "because we have not been configured as such.");
  4367. return 0;
  4368. }
  4369. return 1;
  4370. }
  4371. /** Return true if this node is responsible for storing the descriptor ID
  4372. * in <b>query</b> and false otherwise. */
  4373. int
  4374. hid_serv_responsible_for_desc_id(const char *query)
  4375. {
  4376. const routerinfo_t *me;
  4377. routerstatus_t *last_rs;
  4378. const char *my_id, *last_id;
  4379. int result;
  4380. smartlist_t *responsible;
  4381. if (!hid_serv_acting_as_directory())
  4382. return 0;
  4383. if (!(me = router_get_my_routerinfo()))
  4384. return 0; /* This is redundant, but let's be paranoid. */
  4385. my_id = me->cache_info.identity_digest;
  4386. responsible = smartlist_new();
  4387. if (hid_serv_get_responsible_directories(responsible, query) < 0) {
  4388. smartlist_free(responsible);
  4389. return 0;
  4390. }
  4391. last_rs = smartlist_get(responsible, smartlist_len(responsible)-1);
  4392. last_id = last_rs->identity_digest;
  4393. result = rend_id_is_in_interval(my_id, query, last_id);
  4394. smartlist_free(responsible);
  4395. return result;
  4396. }