routerlist.c 154 KB

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