routerlist.c 153 KB

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