routerlist.c 152 KB

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