routerlist.c 169 KB

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