routerlist.c 153 KB

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