routerlist.c 152 KB

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