routerlist.c 146 KB

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