routerlist.c 153 KB

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