routerlist.c 171 KB

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