routerlist.c 145 KB

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