routerlist.c 151 KB

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