dirserv.c 128 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743
  1. /* Copyright (c) 2001-2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2013, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. #define DIRSERV_PRIVATE
  6. #include "or.h"
  7. #include "buffers.h"
  8. #include "config.h"
  9. #include "confparse.h"
  10. #include "channel.h"
  11. #include "channeltls.h"
  12. #include "command.h"
  13. #include "connection.h"
  14. #include "connection_or.h"
  15. #include "control.h"
  16. #include "directory.h"
  17. #include "dirserv.h"
  18. #include "dirvote.h"
  19. #include "hibernate.h"
  20. #include "microdesc.h"
  21. #include "networkstatus.h"
  22. #include "nodelist.h"
  23. #include "policies.h"
  24. #include "rephist.h"
  25. #include "router.h"
  26. #include "routerlist.h"
  27. #include "routerparse.h"
  28. #include "routerset.h"
  29. /**
  30. * \file dirserv.c
  31. * \brief Directory server core implementation. Manages directory
  32. * contents and generates directories.
  33. */
  34. /** How far in the future do we allow a router to get? (seconds) */
  35. #define ROUTER_ALLOW_SKEW (60*60*12)
  36. /** How many seconds do we wait before regenerating the directory? */
  37. #define DIR_REGEN_SLACK_TIME 30
  38. /** If we're a cache, keep this many networkstatuses around from non-trusted
  39. * directory authorities. */
  40. #define MAX_UNTRUSTED_NETWORKSTATUSES 16
  41. /** If a v1 directory is older than this, discard it. */
  42. #define MAX_V1_DIRECTORY_AGE (30*24*60*60)
  43. /** If a v1 running-routers is older than this, discard it. */
  44. #define MAX_V1_RR_AGE (7*24*60*60)
  45. extern time_t time_of_process_start; /* from main.c */
  46. extern long stats_n_seconds_working; /* from main.c */
  47. /** Do we need to regenerate the v1 directory when someone asks for it? */
  48. static time_t the_directory_is_dirty = 1;
  49. /** Do we need to regenerate the v1 runningrouters document when somebody
  50. * asks for it? */
  51. static time_t runningrouters_is_dirty = 1;
  52. /** Most recently generated encoded signed v1 directory. (v1 auth dirservers
  53. * only.) */
  54. static cached_dir_t *the_directory = NULL;
  55. /** For authoritative directories: the current (v1) network status. */
  56. static cached_dir_t the_runningrouters;
  57. /** Total number of routers with measured bandwidth; this is set by
  58. * dirserv_count_measured_bws() before the loop in
  59. * dirserv_generate_networkstatus_vote_obj() and checked by
  60. * dirserv_get_credible_bandwidth() and
  61. * dirserv_compute_performance_thresholds() */
  62. static int routers_with_measured_bw = 0;
  63. static void directory_remove_invalid(void);
  64. static cached_dir_t *dirserv_regenerate_directory(void);
  65. static char *format_versions_list(config_line_t *ln);
  66. struct authdir_config_t;
  67. static int add_fingerprint_to_dir(const char *nickname, const char *fp,
  68. struct authdir_config_t *list);
  69. static uint32_t
  70. dirserv_get_status_impl(const char *fp, const char *nickname,
  71. uint32_t addr, uint16_t or_port,
  72. const char *platform, const char *contact,
  73. const char **msg, int should_log);
  74. static void clear_cached_dir(cached_dir_t *d);
  75. static const signed_descriptor_t *get_signed_descriptor_by_fp(
  76. const char *fp,
  77. int extrainfo,
  78. time_t publish_cutoff);
  79. static was_router_added_t dirserv_add_extrainfo(extrainfo_t *ei,
  80. const char **msg);
  81. static uint32_t dirserv_get_bandwidth_for_router_kb(const routerinfo_t *ri);
  82. static uint32_t dirserv_get_credible_bandwidth_kb(const routerinfo_t *ri);
  83. /************** Fingerprint handling code ************/
  84. #define FP_NAMED 1 /**< Listed in fingerprint file. */
  85. #define FP_INVALID 2 /**< Believed invalid. */
  86. #define FP_REJECT 4 /**< We will not publish this router. */
  87. #define FP_BADDIR 8 /**< We'll tell clients to avoid using this as a dir. */
  88. #define FP_BADEXIT 16 /**< We'll tell clients not to use this as an exit. */
  89. #define FP_UNNAMED 32 /**< Another router has this name in fingerprint file. */
  90. /** Encapsulate a nickname and an FP_* status; target of status_by_digest
  91. * map. */
  92. typedef struct router_status_t {
  93. char nickname[MAX_NICKNAME_LEN+1];
  94. uint32_t status;
  95. } router_status_t;
  96. /** List of nickname-\>identity fingerprint mappings for all the routers
  97. * that we name. Used to prevent router impersonation. */
  98. typedef struct authdir_config_t {
  99. strmap_t *fp_by_name; /**< Map from lc nickname to fingerprint. */
  100. digestmap_t *status_by_digest; /**< Map from digest to router_status_t. */
  101. } authdir_config_t;
  102. /** Should be static; exposed for testing. */
  103. static authdir_config_t *fingerprint_list = NULL;
  104. /** Allocate and return a new, empty, authdir_config_t. */
  105. static authdir_config_t *
  106. authdir_config_new(void)
  107. {
  108. authdir_config_t *list = tor_malloc_zero(sizeof(authdir_config_t));
  109. list->fp_by_name = strmap_new();
  110. list->status_by_digest = digestmap_new();
  111. return list;
  112. }
  113. /** Add the fingerprint <b>fp</b> for <b>nickname</b> to
  114. * the smartlist of fingerprint_entry_t's <b>list</b>. Return 0 if it's
  115. * new, or 1 if we replaced the old value.
  116. */
  117. /* static */ int
  118. add_fingerprint_to_dir(const char *nickname, const char *fp,
  119. authdir_config_t *list)
  120. {
  121. char *fingerprint;
  122. char d[DIGEST_LEN];
  123. router_status_t *status;
  124. tor_assert(nickname);
  125. tor_assert(fp);
  126. tor_assert(list);
  127. fingerprint = tor_strdup(fp);
  128. tor_strstrip(fingerprint, " ");
  129. if (base16_decode(d, DIGEST_LEN, fingerprint, strlen(fingerprint))) {
  130. log_warn(LD_DIRSERV, "Couldn't decode fingerprint \"%s\"",
  131. escaped(fp));
  132. tor_free(fingerprint);
  133. return 0;
  134. }
  135. if (!strcasecmp(nickname, UNNAMED_ROUTER_NICKNAME)) {
  136. log_warn(LD_DIRSERV, "Tried to add a mapping for reserved nickname %s",
  137. UNNAMED_ROUTER_NICKNAME);
  138. tor_free(fingerprint);
  139. return 0;
  140. }
  141. status = digestmap_get(list->status_by_digest, d);
  142. if (!status) {
  143. status = tor_malloc_zero(sizeof(router_status_t));
  144. digestmap_set(list->status_by_digest, d, status);
  145. }
  146. if (nickname[0] != '!') {
  147. char *old_fp = strmap_get_lc(list->fp_by_name, nickname);
  148. if (old_fp && !strcasecmp(fingerprint, old_fp)) {
  149. tor_free(fingerprint);
  150. } else {
  151. tor_free(old_fp);
  152. strmap_set_lc(list->fp_by_name, nickname, fingerprint);
  153. }
  154. status->status |= FP_NAMED;
  155. strlcpy(status->nickname, nickname, sizeof(status->nickname));
  156. } else {
  157. tor_free(fingerprint);
  158. if (!strcasecmp(nickname, "!reject")) {
  159. status->status |= FP_REJECT;
  160. } else if (!strcasecmp(nickname, "!invalid")) {
  161. status->status |= FP_INVALID;
  162. } else if (!strcasecmp(nickname, "!baddir")) {
  163. status->status |= FP_BADDIR;
  164. } else if (!strcasecmp(nickname, "!badexit")) {
  165. status->status |= FP_BADEXIT;
  166. }
  167. }
  168. return 0;
  169. }
  170. /** Add the nickname and fingerprint for this OR to the
  171. * global list of recognized identity key fingerprints. */
  172. int
  173. dirserv_add_own_fingerprint(const char *nickname, crypto_pk_t *pk)
  174. {
  175. char fp[FINGERPRINT_LEN+1];
  176. if (crypto_pk_get_fingerprint(pk, fp, 0)<0) {
  177. log_err(LD_BUG, "Error computing fingerprint");
  178. return -1;
  179. }
  180. if (!fingerprint_list)
  181. fingerprint_list = authdir_config_new();
  182. add_fingerprint_to_dir(nickname, fp, fingerprint_list);
  183. return 0;
  184. }
  185. /** Load the nickname-\>fingerprint mappings stored in the approved-routers
  186. * file. The file format is line-based, with each non-blank holding one
  187. * nickname, some space, and a fingerprint for that nickname. On success,
  188. * replace the current fingerprint list with the new list and return 0. On
  189. * failure, leave the current fingerprint list untouched, and return -1. */
  190. int
  191. dirserv_load_fingerprint_file(void)
  192. {
  193. char *fname;
  194. char *cf;
  195. char *nickname, *fingerprint;
  196. authdir_config_t *fingerprint_list_new;
  197. int result;
  198. config_line_t *front=NULL, *list;
  199. const or_options_t *options = get_options();
  200. fname = get_datadir_fname("approved-routers");
  201. log_info(LD_GENERAL,
  202. "Reloading approved fingerprints from \"%s\"...", fname);
  203. cf = read_file_to_str(fname, RFTS_IGNORE_MISSING, NULL);
  204. if (!cf) {
  205. if (options->NamingAuthoritativeDir) {
  206. log_warn(LD_FS, "Cannot open fingerprint file '%s'. Failing.", fname);
  207. tor_free(fname);
  208. return -1;
  209. } else {
  210. log_info(LD_FS, "Cannot open fingerprint file '%s'. That's ok.", fname);
  211. tor_free(fname);
  212. return 0;
  213. }
  214. }
  215. tor_free(fname);
  216. result = config_get_lines(cf, &front, 0);
  217. tor_free(cf);
  218. if (result < 0) {
  219. log_warn(LD_CONFIG, "Error reading from fingerprint file");
  220. return -1;
  221. }
  222. fingerprint_list_new = authdir_config_new();
  223. for (list=front; list; list=list->next) {
  224. char digest_tmp[DIGEST_LEN];
  225. nickname = list->key; fingerprint = list->value;
  226. if (strlen(nickname) > MAX_NICKNAME_LEN) {
  227. log_notice(LD_CONFIG,
  228. "Nickname '%s' too long in fingerprint file. Skipping.",
  229. nickname);
  230. continue;
  231. }
  232. if (!is_legal_nickname(nickname) &&
  233. strcasecmp(nickname, "!reject") &&
  234. strcasecmp(nickname, "!invalid") &&
  235. strcasecmp(nickname, "!badexit")) {
  236. log_notice(LD_CONFIG,
  237. "Invalid nickname '%s' in fingerprint file. Skipping.",
  238. nickname);
  239. continue;
  240. }
  241. tor_strstrip(fingerprint, " "); /* remove spaces */
  242. if (strlen(fingerprint) != HEX_DIGEST_LEN ||
  243. base16_decode(digest_tmp, sizeof(digest_tmp),
  244. fingerprint, HEX_DIGEST_LEN) < 0) {
  245. log_notice(LD_CONFIG,
  246. "Invalid fingerprint (nickname '%s', "
  247. "fingerprint %s). Skipping.",
  248. nickname, fingerprint);
  249. continue;
  250. }
  251. if (0==strcasecmp(nickname, DEFAULT_CLIENT_NICKNAME)) {
  252. /* If you approved an OR called "client", then clients who use
  253. * the default nickname could all be rejected. That's no good. */
  254. log_notice(LD_CONFIG,
  255. "Authorizing nickname '%s' would break "
  256. "many clients; skipping.",
  257. DEFAULT_CLIENT_NICKNAME);
  258. continue;
  259. }
  260. if (0==strcasecmp(nickname, UNNAMED_ROUTER_NICKNAME)) {
  261. /* If you approved an OR called "unnamed", then clients will be
  262. * confused. */
  263. log_notice(LD_CONFIG,
  264. "Authorizing nickname '%s' is not allowed; skipping.",
  265. UNNAMED_ROUTER_NICKNAME);
  266. continue;
  267. }
  268. if (add_fingerprint_to_dir(nickname, fingerprint, fingerprint_list_new)
  269. != 0)
  270. log_notice(LD_CONFIG, "Duplicate nickname '%s'.", nickname);
  271. }
  272. config_free_lines(front);
  273. dirserv_free_fingerprint_list();
  274. fingerprint_list = fingerprint_list_new;
  275. /* Delete any routers whose fingerprints we no longer recognize */
  276. directory_remove_invalid();
  277. return 0;
  278. }
  279. /** Check whether <b>router</b> has a nickname/identity key combination that
  280. * we recognize from the fingerprint list, or an IP we automatically act on
  281. * according to our configuration. Return the appropriate router status.
  282. *
  283. * If the status is 'FP_REJECT' and <b>msg</b> is provided, set
  284. * *<b>msg</b> to an explanation of why. */
  285. uint32_t
  286. dirserv_router_get_status(const routerinfo_t *router, const char **msg)
  287. {
  288. char d[DIGEST_LEN];
  289. if (crypto_pk_get_digest(router->identity_pkey, d)) {
  290. log_warn(LD_BUG,"Error computing fingerprint");
  291. if (msg)
  292. *msg = "Bug: Error computing fingerprint";
  293. return FP_REJECT;
  294. }
  295. return dirserv_get_status_impl(d, router->nickname,
  296. router->addr, router->or_port,
  297. router->platform, router->contact_info,
  298. msg, 1);
  299. }
  300. /** Return true if there is no point in downloading the router described by
  301. * <b>rs</b> because this directory would reject it. */
  302. int
  303. dirserv_would_reject_router(const routerstatus_t *rs)
  304. {
  305. uint32_t res;
  306. res = dirserv_get_status_impl(rs->identity_digest, rs->nickname,
  307. rs->addr, rs->or_port,
  308. NULL, NULL,
  309. NULL, 0);
  310. return (res & FP_REJECT) != 0;
  311. }
  312. /** Helper: Based only on the ID/Nickname combination,
  313. * return FP_UNNAMED (unnamed), FP_NAMED (named), or 0 (neither).
  314. */
  315. static uint32_t
  316. dirserv_get_name_status(const char *id_digest, const char *nickname)
  317. {
  318. char fp[HEX_DIGEST_LEN+1];
  319. char *fp_by_name;
  320. base16_encode(fp, sizeof(fp), id_digest, DIGEST_LEN);
  321. if ((fp_by_name =
  322. strmap_get_lc(fingerprint_list->fp_by_name, nickname))) {
  323. if (!strcasecmp(fp, fp_by_name)) {
  324. return FP_NAMED;
  325. } else {
  326. return FP_UNNAMED; /* Wrong fingerprint. */
  327. }
  328. }
  329. return 0;
  330. }
  331. /** Helper: As dirserv_router_get_status, but takes the router fingerprint
  332. * (hex, no spaces), nickname, address (used for logging only), IP address, OR
  333. * port, platform (logging only) and contact info (logging only) as arguments.
  334. *
  335. * If should_log is false, do not log messages. (There's not much point in
  336. * logging that we're rejecting servers we'll not download.)
  337. */
  338. static uint32_t
  339. dirserv_get_status_impl(const char *id_digest, const char *nickname,
  340. uint32_t addr, uint16_t or_port,
  341. const char *platform, const char *contact,
  342. const char **msg, int should_log)
  343. {
  344. int reject_unlisted = get_options()->AuthDirRejectUnlisted;
  345. uint32_t result;
  346. router_status_t *status_by_digest;
  347. if (!fingerprint_list)
  348. fingerprint_list = authdir_config_new();
  349. if (should_log)
  350. log_debug(LD_DIRSERV, "%d fingerprints, %d digests known.",
  351. strmap_size(fingerprint_list->fp_by_name),
  352. digestmap_size(fingerprint_list->status_by_digest));
  353. /* Versions before Tor 0.2.2.35 have known security issues that
  354. * make them unsuitable for the current network. */
  355. if (platform && !tor_version_as_new_as(platform,"0.2.2.35")) {
  356. if (msg)
  357. *msg = "Tor version is insecure or unsupported. Please upgrade!";
  358. return FP_REJECT;
  359. } else if (platform && tor_version_as_new_as(platform,"0.2.3.0-alpha")) {
  360. /* Versions from 0.2.3-alpha...0.2.3.9-alpha have known security
  361. * issues that make them unusable for the current network */
  362. if (!tor_version_as_new_as(platform, "0.2.3.10-alpha")) {
  363. if (msg)
  364. *msg = "Tor version is insecure or unsupported. Please upgrade!";
  365. return FP_REJECT;
  366. }
  367. }
  368. result = dirserv_get_name_status(id_digest, nickname);
  369. if (result & FP_NAMED) {
  370. if (should_log)
  371. log_debug(LD_DIRSERV,"Good fingerprint for '%s'",nickname);
  372. }
  373. if (result & FP_UNNAMED) {
  374. if (should_log) {
  375. char *esc_contact = esc_for_log(contact);
  376. log_info(LD_DIRSERV,
  377. "Mismatched fingerprint for '%s'. "
  378. "ContactInfo '%s', platform '%s'.)",
  379. nickname,
  380. esc_contact,
  381. platform ? escaped(platform) : "");
  382. tor_free(esc_contact);
  383. }
  384. if (msg)
  385. *msg = "Rejected: There is already a named server with this nickname "
  386. "and a different fingerprint.";
  387. }
  388. status_by_digest = digestmap_get(fingerprint_list->status_by_digest,
  389. id_digest);
  390. if (status_by_digest)
  391. result |= (status_by_digest->status & ~FP_NAMED);
  392. if (result & FP_REJECT) {
  393. if (msg)
  394. *msg = "Fingerprint is marked rejected";
  395. return FP_REJECT;
  396. } else if (result & FP_INVALID) {
  397. if (msg)
  398. *msg = "Fingerprint is marked invalid";
  399. }
  400. if (authdir_policy_baddir_address(addr, or_port)) {
  401. if (should_log)
  402. log_info(LD_DIRSERV,
  403. "Marking '%s' as bad directory because of address '%s'",
  404. nickname, fmt_addr32(addr));
  405. result |= FP_BADDIR;
  406. }
  407. if (authdir_policy_badexit_address(addr, or_port)) {
  408. if (should_log)
  409. log_info(LD_DIRSERV, "Marking '%s' as bad exit because of address '%s'",
  410. nickname, fmt_addr32(addr));
  411. result |= FP_BADEXIT;
  412. }
  413. if (!(result & FP_NAMED)) {
  414. if (!authdir_policy_permits_address(addr, or_port)) {
  415. if (should_log)
  416. log_info(LD_DIRSERV, "Rejecting '%s' because of address '%s'",
  417. nickname, fmt_addr32(addr));
  418. if (msg)
  419. *msg = "Authdir is rejecting routers in this range.";
  420. return FP_REJECT;
  421. }
  422. if (!authdir_policy_valid_address(addr, or_port)) {
  423. if (should_log)
  424. log_info(LD_DIRSERV, "Not marking '%s' valid because of address '%s'",
  425. nickname, fmt_addr32(addr));
  426. result |= FP_INVALID;
  427. }
  428. if (reject_unlisted) {
  429. if (msg)
  430. *msg = "Authdir rejects unknown routers.";
  431. return FP_REJECT;
  432. }
  433. }
  434. return result;
  435. }
  436. /** If we are an authoritative dirserver, and the list of approved
  437. * servers contains one whose identity key digest is <b>digest</b>,
  438. * return that router's nickname. Otherwise return NULL. */
  439. const char *
  440. dirserv_get_nickname_by_digest(const char *digest)
  441. {
  442. router_status_t *status;
  443. if (!fingerprint_list)
  444. return NULL;
  445. tor_assert(digest);
  446. status = digestmap_get(fingerprint_list->status_by_digest, digest);
  447. return status ? status->nickname : NULL;
  448. }
  449. /** Clear the current fingerprint list. */
  450. void
  451. dirserv_free_fingerprint_list(void)
  452. {
  453. if (!fingerprint_list)
  454. return;
  455. strmap_free(fingerprint_list->fp_by_name, tor_free_);
  456. digestmap_free(fingerprint_list->status_by_digest, tor_free_);
  457. tor_free(fingerprint_list);
  458. }
  459. /*
  460. * Descriptor list
  461. */
  462. /** Return -1 if <b>ri</b> has a private or otherwise bad address,
  463. * unless we're configured to not care. Return 0 if all ok. */
  464. static int
  465. dirserv_router_has_valid_address(routerinfo_t *ri)
  466. {
  467. if (get_options()->DirAllowPrivateAddresses)
  468. return 0; /* whatever it is, we're fine with it */
  469. if (is_internal_IP(ri->addr, 0)) {
  470. log_info(LD_DIRSERV,
  471. "Router %s published internal IP address. Refusing.",
  472. router_describe(ri));
  473. return -1; /* it's a private IP, we should reject it */
  474. }
  475. return 0;
  476. }
  477. /** Check whether we, as a directory server, want to accept <b>ri</b>. If so,
  478. * set its is_valid,named,running fields and return 0. Otherwise, return -1.
  479. *
  480. * If the router is rejected, set *<b>msg</b> to an explanation of why.
  481. *
  482. * If <b>complain</b> then explain at log-level 'notice' why we refused
  483. * a descriptor; else explain at log-level 'info'.
  484. */
  485. int
  486. authdir_wants_to_reject_router(routerinfo_t *ri, const char **msg,
  487. int complain, int *valid_out)
  488. {
  489. /* Okay. Now check whether the fingerprint is recognized. */
  490. uint32_t status = dirserv_router_get_status(ri, msg);
  491. time_t now;
  492. int severity = (complain && ri->contact_info) ? LOG_NOTICE : LOG_INFO;
  493. tor_assert(msg);
  494. if (status & FP_REJECT)
  495. return -1; /* msg is already set. */
  496. /* Is there too much clock skew? */
  497. now = time(NULL);
  498. if (ri->cache_info.published_on > now+ROUTER_ALLOW_SKEW) {
  499. log_fn(severity, LD_DIRSERV, "Publication time for %s is too "
  500. "far (%d minutes) in the future; possible clock skew. Not adding "
  501. "(%s)",
  502. router_describe(ri),
  503. (int)((ri->cache_info.published_on-now)/60),
  504. esc_router_info(ri));
  505. *msg = "Rejected: Your clock is set too far in the future, or your "
  506. "timezone is not correct.";
  507. return -1;
  508. }
  509. if (ri->cache_info.published_on < now-ROUTER_MAX_AGE_TO_PUBLISH) {
  510. log_fn(severity, LD_DIRSERV,
  511. "Publication time for %s is too far "
  512. "(%d minutes) in the past. Not adding (%s)",
  513. router_describe(ri),
  514. (int)((now-ri->cache_info.published_on)/60),
  515. esc_router_info(ri));
  516. *msg = "Rejected: Server is expired, or your clock is too far in the past,"
  517. " or your timezone is not correct.";
  518. return -1;
  519. }
  520. if (dirserv_router_has_valid_address(ri) < 0) {
  521. log_fn(severity, LD_DIRSERV,
  522. "Router %s has invalid address. Not adding (%s).",
  523. router_describe(ri),
  524. esc_router_info(ri));
  525. *msg = "Rejected: Address is a private address.";
  526. return -1;
  527. }
  528. *valid_out = ! (status & FP_INVALID);
  529. return 0;
  530. }
  531. /** Update the relevant flags of <b>node</b> based on our opinion as a
  532. * directory authority in <b>authstatus</b>, as returned by
  533. * dirserv_router_get_status or equivalent. */
  534. void
  535. dirserv_set_node_flags_from_authoritative_status(node_t *node,
  536. uint32_t authstatus)
  537. {
  538. node->is_valid = (authstatus & FP_INVALID) ? 0 : 1;
  539. node->is_bad_directory = (authstatus & FP_BADDIR) ? 1 : 0;
  540. node->is_bad_exit = (authstatus & FP_BADEXIT) ? 1 : 0;
  541. }
  542. /** True iff <b>a</b> is more severe than <b>b</b>. */
  543. static int
  544. WRA_MORE_SEVERE(was_router_added_t a, was_router_added_t b)
  545. {
  546. return a < b;
  547. }
  548. /** As for dirserv_add_descriptor(), but accepts multiple documents, and
  549. * returns the most severe error that occurred for any one of them. */
  550. was_router_added_t
  551. dirserv_add_multiple_descriptors(const char *desc, uint8_t purpose,
  552. const char *source,
  553. const char **msg)
  554. {
  555. was_router_added_t r, r_tmp;
  556. const char *msg_out;
  557. smartlist_t *list;
  558. const char *s;
  559. int n_parsed = 0;
  560. time_t now = time(NULL);
  561. char annotation_buf[ROUTER_ANNOTATION_BUF_LEN];
  562. char time_buf[ISO_TIME_LEN+1];
  563. int general = purpose == ROUTER_PURPOSE_GENERAL;
  564. tor_assert(msg);
  565. r=ROUTER_ADDED_SUCCESSFULLY; /*Least severe return value. */
  566. format_iso_time(time_buf, now);
  567. if (tor_snprintf(annotation_buf, sizeof(annotation_buf),
  568. "@uploaded-at %s\n"
  569. "@source %s\n"
  570. "%s%s%s", time_buf, escaped(source),
  571. !general ? "@purpose " : "",
  572. !general ? router_purpose_to_string(purpose) : "",
  573. !general ? "\n" : "")<0) {
  574. *msg = "Couldn't format annotations";
  575. return -1;
  576. }
  577. s = desc;
  578. list = smartlist_new();
  579. if (!router_parse_list_from_string(&s, NULL, list, SAVED_NOWHERE, 0, 0,
  580. annotation_buf)) {
  581. SMARTLIST_FOREACH(list, routerinfo_t *, ri, {
  582. msg_out = NULL;
  583. tor_assert(ri->purpose == purpose);
  584. r_tmp = dirserv_add_descriptor(ri, &msg_out, source);
  585. if (WRA_MORE_SEVERE(r_tmp, r)) {
  586. r = r_tmp;
  587. *msg = msg_out;
  588. }
  589. });
  590. }
  591. n_parsed += smartlist_len(list);
  592. smartlist_clear(list);
  593. s = desc;
  594. if (!router_parse_list_from_string(&s, NULL, list, SAVED_NOWHERE, 1, 0,
  595. NULL)) {
  596. SMARTLIST_FOREACH(list, extrainfo_t *, ei, {
  597. msg_out = NULL;
  598. r_tmp = dirserv_add_extrainfo(ei, &msg_out);
  599. if (WRA_MORE_SEVERE(r_tmp, r)) {
  600. r = r_tmp;
  601. *msg = msg_out;
  602. }
  603. });
  604. }
  605. n_parsed += smartlist_len(list);
  606. smartlist_free(list);
  607. if (! *msg) {
  608. if (!n_parsed) {
  609. *msg = "No descriptors found in your POST.";
  610. if (WRA_WAS_ADDED(r))
  611. r = ROUTER_WAS_NOT_NEW;
  612. } else {
  613. *msg = "(no message)";
  614. }
  615. }
  616. return r;
  617. }
  618. /** Examine the parsed server descriptor in <b>ri</b> and maybe insert it into
  619. * the list of server descriptors. Set *<b>msg</b> to a message that should be
  620. * passed back to the origin of this descriptor, or NULL if there is no such
  621. * message. Use <b>source</b> to produce better log messages.
  622. *
  623. * Return the status of the operation
  624. *
  625. * This function is only called when fresh descriptors are posted, not when
  626. * we re-load the cache.
  627. */
  628. was_router_added_t
  629. dirserv_add_descriptor(routerinfo_t *ri, const char **msg, const char *source)
  630. {
  631. was_router_added_t r;
  632. routerinfo_t *ri_old;
  633. char *desc, *nickname;
  634. size_t desclen = 0;
  635. *msg = NULL;
  636. /* If it's too big, refuse it now. Otherwise we'll cache it all over the
  637. * network and it'll clog everything up. */
  638. if (ri->cache_info.signed_descriptor_len > MAX_DESCRIPTOR_UPLOAD_SIZE) {
  639. log_notice(LD_DIR, "Somebody attempted to publish a router descriptor '%s'"
  640. " (source: %s) with size %d. Either this is an attack, or the "
  641. "MAX_DESCRIPTOR_UPLOAD_SIZE (%d) constant is too low.",
  642. ri->nickname, source, (int)ri->cache_info.signed_descriptor_len,
  643. MAX_DESCRIPTOR_UPLOAD_SIZE);
  644. *msg = "Router descriptor was too large.";
  645. control_event_or_authdir_new_descriptor("REJECTED",
  646. ri->cache_info.signed_descriptor_body,
  647. ri->cache_info.signed_descriptor_len, *msg);
  648. routerinfo_free(ri);
  649. return ROUTER_AUTHDIR_REJECTS;
  650. }
  651. /* Check whether this descriptor is semantically identical to the last one
  652. * from this server. (We do this here and not in router_add_to_routerlist
  653. * because we want to be able to accept the newest router descriptor that
  654. * another authority has, so we all converge on the same one.) */
  655. ri_old = router_get_mutable_by_digest(ri->cache_info.identity_digest);
  656. if (ri_old && ri_old->cache_info.published_on < ri->cache_info.published_on
  657. && router_differences_are_cosmetic(ri_old, ri)
  658. && !router_is_me(ri)) {
  659. log_info(LD_DIRSERV,
  660. "Not replacing descriptor from %s (source: %s); "
  661. "differences are cosmetic.",
  662. router_describe(ri), source);
  663. *msg = "Not replacing router descriptor; no information has changed since "
  664. "the last one with this identity.";
  665. control_event_or_authdir_new_descriptor("DROPPED",
  666. ri->cache_info.signed_descriptor_body,
  667. ri->cache_info.signed_descriptor_len, *msg);
  668. routerinfo_free(ri);
  669. return ROUTER_WAS_NOT_NEW;
  670. }
  671. /* Make a copy of desc, since router_add_to_routerlist might free
  672. * ri and its associated signed_descriptor_t. */
  673. desclen = ri->cache_info.signed_descriptor_len;
  674. desc = tor_strndup(ri->cache_info.signed_descriptor_body, desclen);
  675. nickname = tor_strdup(ri->nickname);
  676. /* Tell if we're about to need to launch a test if we add this. */
  677. ri->needs_retest_if_added =
  678. dirserv_should_launch_reachability_test(ri, ri_old);
  679. r = router_add_to_routerlist(ri, msg, 0, 0);
  680. if (!WRA_WAS_ADDED(r)) {
  681. /* unless the routerinfo was fine, just out-of-date */
  682. if (WRA_WAS_REJECTED(r))
  683. control_event_or_authdir_new_descriptor("REJECTED", desc, desclen, *msg);
  684. log_info(LD_DIRSERV,
  685. "Did not add descriptor from '%s' (source: %s): %s.",
  686. nickname, source, *msg ? *msg : "(no message)");
  687. } else {
  688. smartlist_t *changed;
  689. control_event_or_authdir_new_descriptor("ACCEPTED", desc, desclen, *msg);
  690. changed = smartlist_new();
  691. smartlist_add(changed, ri);
  692. routerlist_descriptors_added(changed, 0);
  693. smartlist_free(changed);
  694. if (!*msg) {
  695. *msg = "Descriptor accepted";
  696. }
  697. log_info(LD_DIRSERV,
  698. "Added descriptor from '%s' (source: %s): %s.",
  699. nickname, source, *msg);
  700. }
  701. tor_free(desc);
  702. tor_free(nickname);
  703. return r;
  704. }
  705. /** As dirserv_add_descriptor, but for an extrainfo_t <b>ei</b>. */
  706. static was_router_added_t
  707. dirserv_add_extrainfo(extrainfo_t *ei, const char **msg)
  708. {
  709. const routerinfo_t *ri;
  710. int r;
  711. tor_assert(msg);
  712. *msg = NULL;
  713. ri = router_get_by_id_digest(ei->cache_info.identity_digest);
  714. if (!ri) {
  715. *msg = "No corresponding router descriptor for extra-info descriptor";
  716. extrainfo_free(ei);
  717. return ROUTER_BAD_EI;
  718. }
  719. /* If it's too big, refuse it now. Otherwise we'll cache it all over the
  720. * network and it'll clog everything up. */
  721. if (ei->cache_info.signed_descriptor_len > MAX_EXTRAINFO_UPLOAD_SIZE) {
  722. log_notice(LD_DIR, "Somebody attempted to publish an extrainfo "
  723. "with size %d. Either this is an attack, or the "
  724. "MAX_EXTRAINFO_UPLOAD_SIZE (%d) constant is too low.",
  725. (int)ei->cache_info.signed_descriptor_len,
  726. MAX_EXTRAINFO_UPLOAD_SIZE);
  727. *msg = "Extrainfo document was too large";
  728. extrainfo_free(ei);
  729. return ROUTER_BAD_EI;
  730. }
  731. if ((r = routerinfo_incompatible_with_extrainfo(ri, ei, NULL, msg))) {
  732. extrainfo_free(ei);
  733. return r < 0 ? ROUTER_WAS_NOT_NEW : ROUTER_BAD_EI;
  734. }
  735. router_add_extrainfo_to_routerlist(ei, msg, 0, 0);
  736. return ROUTER_ADDED_SUCCESSFULLY;
  737. }
  738. /** Remove all descriptors whose nicknames or fingerprints no longer
  739. * are allowed by our fingerprint list. (Descriptors that used to be
  740. * good can become bad when we reload the fingerprint list.)
  741. */
  742. static void
  743. directory_remove_invalid(void)
  744. {
  745. int changed = 0;
  746. routerlist_t *rl = router_get_routerlist();
  747. smartlist_t *nodes = smartlist_new();
  748. smartlist_add_all(nodes, nodelist_get_list());
  749. SMARTLIST_FOREACH_BEGIN(nodes, node_t *, node) {
  750. const char *msg;
  751. routerinfo_t *ent = node->ri;
  752. char description[NODE_DESC_BUF_LEN];
  753. uint32_t r;
  754. if (!ent)
  755. continue;
  756. r = dirserv_router_get_status(ent, &msg);
  757. router_get_description(description, ent);
  758. if (r & FP_REJECT) {
  759. log_info(LD_DIRSERV, "Router %s is now rejected: %s",
  760. description, msg?msg:"");
  761. routerlist_remove(rl, ent, 0, time(NULL));
  762. changed = 1;
  763. continue;
  764. }
  765. #if 0
  766. if (bool_neq((r & FP_NAMED), ent->auth_says_is_named)) {
  767. log_info(LD_DIRSERV,
  768. "Router %s is now %snamed.", description,
  769. (r&FP_NAMED)?"":"un");
  770. ent->is_named = (r&FP_NAMED)?1:0;
  771. changed = 1;
  772. }
  773. if (bool_neq((r & FP_UNNAMED), ent->auth_says_is_unnamed)) {
  774. log_info(LD_DIRSERV,
  775. "Router '%s' is now %snamed. (FP_UNNAMED)", description,
  776. (r&FP_NAMED)?"":"un");
  777. ent->is_named = (r&FP_NUNAMED)?0:1;
  778. changed = 1;
  779. }
  780. #endif
  781. if (bool_neq((r & FP_INVALID), !node->is_valid)) {
  782. log_info(LD_DIRSERV, "Router '%s' is now %svalid.", description,
  783. (r&FP_INVALID) ? "in" : "");
  784. node->is_valid = (r&FP_INVALID)?0:1;
  785. changed = 1;
  786. }
  787. if (bool_neq((r & FP_BADDIR), node->is_bad_directory)) {
  788. log_info(LD_DIRSERV, "Router '%s' is now a %s directory", description,
  789. (r & FP_BADDIR) ? "bad" : "good");
  790. node->is_bad_directory = (r&FP_BADDIR) ? 1: 0;
  791. changed = 1;
  792. }
  793. if (bool_neq((r & FP_BADEXIT), node->is_bad_exit)) {
  794. log_info(LD_DIRSERV, "Router '%s' is now a %s exit", description,
  795. (r & FP_BADEXIT) ? "bad" : "good");
  796. node->is_bad_exit = (r&FP_BADEXIT) ? 1: 0;
  797. changed = 1;
  798. }
  799. } SMARTLIST_FOREACH_END(node);
  800. if (changed)
  801. directory_set_dirty();
  802. routerlist_assert_ok(rl);
  803. smartlist_free(nodes);
  804. }
  805. /** Mark the directory as <b>dirty</b> -- when we're next asked for a
  806. * directory, we will rebuild it instead of reusing the most recently
  807. * generated one.
  808. */
  809. void
  810. directory_set_dirty(void)
  811. {
  812. time_t now = time(NULL);
  813. int set_v1_dirty=0;
  814. /* Regenerate stubs only every 8 hours.
  815. * XXXX It would be nice to generate less often, but these are just
  816. * stubs: it doesn't matter. */
  817. #define STUB_REGENERATE_INTERVAL (8*60*60)
  818. if (!the_directory || !the_runningrouters.dir)
  819. set_v1_dirty = 1;
  820. else if (the_directory->published < now - STUB_REGENERATE_INTERVAL ||
  821. the_runningrouters.published < now - STUB_REGENERATE_INTERVAL)
  822. set_v1_dirty = 1;
  823. if (set_v1_dirty) {
  824. if (!the_directory_is_dirty)
  825. the_directory_is_dirty = now;
  826. if (!runningrouters_is_dirty)
  827. runningrouters_is_dirty = now;
  828. }
  829. }
  830. /**
  831. * Allocate and return a description of the status of the server <b>desc</b>,
  832. * for use in a v1-style router-status line. The server is listed
  833. * as running iff <b>is_live</b> is true.
  834. */
  835. static char *
  836. list_single_server_status(const routerinfo_t *desc, int is_live)
  837. {
  838. char buf[MAX_NICKNAME_LEN+HEX_DIGEST_LEN+4]; /* !nickname=$hexdigest\0 */
  839. char *cp;
  840. const node_t *node;
  841. tor_assert(desc);
  842. cp = buf;
  843. if (!is_live) {
  844. *cp++ = '!';
  845. }
  846. node = node_get_by_id(desc->cache_info.identity_digest);
  847. if (node && node->is_valid) {
  848. strlcpy(cp, desc->nickname, sizeof(buf)-(cp-buf));
  849. cp += strlen(cp);
  850. *cp++ = '=';
  851. }
  852. *cp++ = '$';
  853. base16_encode(cp, HEX_DIGEST_LEN+1, desc->cache_info.identity_digest,
  854. DIGEST_LEN);
  855. return tor_strdup(buf);
  856. }
  857. /* DOCDOC running_long_enough_to_decide_unreachable */
  858. static INLINE int
  859. running_long_enough_to_decide_unreachable(void)
  860. {
  861. return time_of_process_start
  862. + get_options()->TestingAuthDirTimeToLearnReachability < approx_time();
  863. }
  864. /** Each server needs to have passed a reachability test no more
  865. * than this number of seconds ago, or he is listed as down in
  866. * the directory. */
  867. #define REACHABLE_TIMEOUT (45*60)
  868. /** If we tested a router and found it reachable _at least this long_ after it
  869. * declared itself hibernating, it is probably done hibernating and we just
  870. * missed a descriptor from it. */
  871. #define HIBERNATION_PUBLICATION_SKEW (60*60)
  872. /** Treat a router as alive if
  873. * - It's me, and I'm not hibernating.
  874. * or - We've found it reachable recently. */
  875. void
  876. dirserv_set_router_is_running(routerinfo_t *router, time_t now)
  877. {
  878. /*XXXX024 This function is a mess. Separate out the part that calculates
  879. whether it's reachable and the part that tells rephist that the router was
  880. unreachable.
  881. */
  882. int answer;
  883. const or_options_t *options = get_options();
  884. node_t *node = node_get_mutable_by_id(router->cache_info.identity_digest);
  885. tor_assert(node);
  886. if (router_is_me(router)) {
  887. /* We always know if we are down ourselves. */
  888. answer = ! we_are_hibernating();
  889. } else if (router->is_hibernating &&
  890. (router->cache_info.published_on +
  891. HIBERNATION_PUBLICATION_SKEW) > node->last_reachable) {
  892. /* A hibernating router is down unless we (somehow) had contact with it
  893. * since it declared itself to be hibernating. */
  894. answer = 0;
  895. } else if (options->AssumeReachable) {
  896. /* If AssumeReachable, everybody is up unless they say they are down! */
  897. answer = 1;
  898. } else {
  899. /* Otherwise, a router counts as up if we found all announced OR
  900. ports reachable in the last REACHABLE_TIMEOUT seconds.
  901. XXX prop186 For now there's always one IPv4 and at most one
  902. IPv6 OR port.
  903. If we're not on IPv6, don't consider reachability of potential
  904. IPv6 OR port since that'd kill all dual stack relays until a
  905. majority of the dir auths have IPv6 connectivity. */
  906. answer = (now < node->last_reachable + REACHABLE_TIMEOUT &&
  907. (options->AuthDirHasIPv6Connectivity != 1 ||
  908. tor_addr_is_null(&router->ipv6_addr) ||
  909. now < node->last_reachable6 + REACHABLE_TIMEOUT));
  910. }
  911. if (!answer && running_long_enough_to_decide_unreachable()) {
  912. /* Not considered reachable. tell rephist about that.
  913. Because we launch a reachability test for each router every
  914. REACHABILITY_TEST_CYCLE_PERIOD seconds, then the router has probably
  915. been down since at least that time after we last successfully reached
  916. it.
  917. XXX ipv6
  918. */
  919. time_t when = now;
  920. if (node->last_reachable &&
  921. node->last_reachable + REACHABILITY_TEST_CYCLE_PERIOD < now)
  922. when = node->last_reachable + REACHABILITY_TEST_CYCLE_PERIOD;
  923. rep_hist_note_router_unreachable(router->cache_info.identity_digest, when);
  924. }
  925. node->is_running = answer;
  926. }
  927. /** Based on the routerinfo_ts in <b>routers</b>, allocate the
  928. * contents of a v1-style router-status line, and store it in
  929. * *<b>router_status_out</b>. Return 0 on success, -1 on failure.
  930. *
  931. * If for_controller is true, include the routers with very old descriptors.
  932. */
  933. int
  934. list_server_status_v1(smartlist_t *routers, char **router_status_out,
  935. int for_controller)
  936. {
  937. /* List of entries in a router-status style: An optional !, then an optional
  938. * equals-suffixed nickname, then a dollar-prefixed hexdigest. */
  939. smartlist_t *rs_entries;
  940. time_t now = time(NULL);
  941. time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
  942. const or_options_t *options = get_options();
  943. /* We include v2 dir auths here too, because they need to answer
  944. * controllers. Eventually we'll deprecate this whole function;
  945. * see also networkstatus_getinfo_by_purpose(). */
  946. int authdir = authdir_mode_publishes_statuses(options);
  947. tor_assert(router_status_out);
  948. rs_entries = smartlist_new();
  949. SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
  950. const node_t *node = node_get_by_id(ri->cache_info.identity_digest);
  951. tor_assert(node);
  952. if (authdir) {
  953. /* Update router status in routerinfo_t. */
  954. dirserv_set_router_is_running(ri, now);
  955. }
  956. if (for_controller) {
  957. char name_buf[MAX_VERBOSE_NICKNAME_LEN+2];
  958. char *cp = name_buf;
  959. if (!node->is_running)
  960. *cp++ = '!';
  961. router_get_verbose_nickname(cp, ri);
  962. smartlist_add(rs_entries, tor_strdup(name_buf));
  963. } else if (ri->cache_info.published_on >= cutoff) {
  964. smartlist_add(rs_entries, list_single_server_status(ri,
  965. node->is_running));
  966. }
  967. } SMARTLIST_FOREACH_END(ri);
  968. *router_status_out = smartlist_join_strings(rs_entries, " ", 0, NULL);
  969. SMARTLIST_FOREACH(rs_entries, char *, cp, tor_free(cp));
  970. smartlist_free(rs_entries);
  971. return 0;
  972. }
  973. /** Given a (possibly empty) list of config_line_t, each line of which contains
  974. * a list of comma-separated version numbers surrounded by optional space,
  975. * allocate and return a new string containing the version numbers, in order,
  976. * separated by commas. Used to generate Recommended(Client|Server)?Versions
  977. */
  978. static char *
  979. format_versions_list(config_line_t *ln)
  980. {
  981. smartlist_t *versions;
  982. char *result;
  983. versions = smartlist_new();
  984. for ( ; ln; ln = ln->next) {
  985. smartlist_split_string(versions, ln->value, ",",
  986. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  987. }
  988. sort_version_list(versions, 1);
  989. result = smartlist_join_strings(versions,",",0,NULL);
  990. SMARTLIST_FOREACH(versions,char *,s,tor_free(s));
  991. smartlist_free(versions);
  992. return result;
  993. }
  994. /** Return 1 if <b>ri</b>'s descriptor is "active" -- running, valid,
  995. * not hibernating, and not too old. Else return 0.
  996. */
  997. static int
  998. router_is_active(const routerinfo_t *ri, const node_t *node, time_t now)
  999. {
  1000. time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
  1001. if (ri->cache_info.published_on < cutoff)
  1002. return 0;
  1003. if (!node->is_running || !node->is_valid || ri->is_hibernating)
  1004. return 0;
  1005. return 1;
  1006. }
  1007. /** Generate a new v1 directory and write it into a newly allocated string.
  1008. * Point *<b>dir_out</b> to the allocated string. Sign the
  1009. * directory with <b>private_key</b>. Return 0 on success, -1 on
  1010. * failure. If <b>complete</b> is set, give us all the descriptors;
  1011. * otherwise leave out non-running and non-valid ones.
  1012. */
  1013. int
  1014. dirserv_dump_directory_to_string(char **dir_out,
  1015. crypto_pk_t *private_key)
  1016. {
  1017. /* XXXX 024 Get rid of this function if we can confirm that nobody's
  1018. * fetching these any longer */
  1019. char *cp;
  1020. char *identity_pkey; /* Identity key, DER64-encoded. */
  1021. char *recommended_versions;
  1022. char digest[DIGEST_LEN];
  1023. char published[ISO_TIME_LEN+1];
  1024. char *buf = NULL;
  1025. size_t buf_len;
  1026. size_t identity_pkey_len;
  1027. time_t now = time(NULL);
  1028. tor_assert(dir_out);
  1029. *dir_out = NULL;
  1030. if (crypto_pk_write_public_key_to_string(private_key,&identity_pkey,
  1031. &identity_pkey_len)<0) {
  1032. log_warn(LD_BUG,"write identity_pkey to string failed!");
  1033. return -1;
  1034. }
  1035. recommended_versions =
  1036. format_versions_list(get_options()->RecommendedVersions);
  1037. format_iso_time(published, now);
  1038. buf_len = 2048+strlen(recommended_versions);
  1039. buf = tor_malloc(buf_len);
  1040. /* We'll be comparing against buf_len throughout the rest of the
  1041. function, though strictly speaking we shouldn't be able to exceed
  1042. it. This is C, after all, so we may as well check for buffer
  1043. overruns.*/
  1044. tor_snprintf(buf, buf_len,
  1045. "signed-directory\n"
  1046. "published %s\n"
  1047. "recommended-software %s\n"
  1048. "router-status %s\n"
  1049. "dir-signing-key\n%s\n",
  1050. published, recommended_versions, "",
  1051. identity_pkey);
  1052. tor_free(recommended_versions);
  1053. tor_free(identity_pkey);
  1054. cp = buf + strlen(buf);
  1055. *cp = '\0';
  1056. /* These multiple strlcat calls are inefficient, but dwarfed by the RSA
  1057. signature. */
  1058. if (strlcat(buf, "directory-signature ", buf_len) >= buf_len)
  1059. goto truncated;
  1060. if (strlcat(buf, get_options()->Nickname, buf_len) >= buf_len)
  1061. goto truncated;
  1062. if (strlcat(buf, "\n", buf_len) >= buf_len)
  1063. goto truncated;
  1064. if (router_get_dir_hash(buf,digest)) {
  1065. log_warn(LD_BUG,"couldn't compute digest");
  1066. tor_free(buf);
  1067. return -1;
  1068. }
  1069. note_crypto_pk_op(SIGN_DIR);
  1070. if (router_append_dirobj_signature(buf,buf_len,digest,DIGEST_LEN,
  1071. private_key)<0) {
  1072. tor_free(buf);
  1073. return -1;
  1074. }
  1075. *dir_out = buf;
  1076. return 0;
  1077. truncated:
  1078. log_warn(LD_BUG,"tried to exceed string length.");
  1079. tor_free(buf);
  1080. return -1;
  1081. }
  1082. /********************************************************************/
  1083. /* A set of functions to answer questions about how we'd like to behave
  1084. * as a directory mirror/client. */
  1085. /** Return 1 if we fetch our directory material directly from the
  1086. * authorities, rather than from a mirror. */
  1087. int
  1088. directory_fetches_from_authorities(const or_options_t *options)
  1089. {
  1090. const routerinfo_t *me;
  1091. uint32_t addr;
  1092. int refuseunknown;
  1093. if (options->FetchDirInfoEarly)
  1094. return 1;
  1095. if (options->BridgeRelay == 1)
  1096. return 0;
  1097. if (server_mode(options) && router_pick_published_address(options, &addr)<0)
  1098. return 1; /* we don't know our IP address; ask an authority. */
  1099. refuseunknown = ! router_my_exit_policy_is_reject_star() &&
  1100. should_refuse_unknown_exits(options);
  1101. if (!options->DirPort_set && !refuseunknown)
  1102. return 0;
  1103. if (!server_mode(options) || !advertised_server_mode())
  1104. return 0;
  1105. me = router_get_my_routerinfo();
  1106. if (!me || (!me->dir_port && !refuseunknown))
  1107. return 0; /* if dirport not advertised, return 0 too */
  1108. return 1;
  1109. }
  1110. /** Return 1 if we should fetch new networkstatuses, descriptors, etc
  1111. * on the "mirror" schedule rather than the "client" schedule.
  1112. */
  1113. int
  1114. directory_fetches_dir_info_early(const or_options_t *options)
  1115. {
  1116. return directory_fetches_from_authorities(options);
  1117. }
  1118. /** Return 1 if we should fetch new networkstatuses, descriptors, etc
  1119. * on a very passive schedule -- waiting long enough for ordinary clients
  1120. * to probably have the info we want. These would include bridge users,
  1121. * and maybe others in the future e.g. if a Tor client uses another Tor
  1122. * client as a directory guard.
  1123. */
  1124. int
  1125. directory_fetches_dir_info_later(const or_options_t *options)
  1126. {
  1127. return options->UseBridges != 0;
  1128. }
  1129. /** Return true iff we want to fetch and keep certificates for authorities
  1130. * that we don't acknowledge as aurthorities ourself.
  1131. */
  1132. int
  1133. directory_caches_unknown_auth_certs(const or_options_t *options)
  1134. {
  1135. return options->DirPort_set || options->BridgeRelay;
  1136. }
  1137. /** Return 1 if we want to keep descriptors, networkstatuses, etc around
  1138. * and we're willing to serve them to others. Else return 0.
  1139. */
  1140. int
  1141. directory_caches_dir_info(const or_options_t *options)
  1142. {
  1143. if (options->BridgeRelay || options->DirPort_set)
  1144. return 1;
  1145. if (!server_mode(options) || !advertised_server_mode())
  1146. return 0;
  1147. /* We need an up-to-date view of network info if we're going to try to
  1148. * block exit attempts from unknown relays. */
  1149. return ! router_my_exit_policy_is_reject_star() &&
  1150. should_refuse_unknown_exits(options);
  1151. }
  1152. /** Return 1 if we want to allow remote people to ask us directory
  1153. * requests via the "begin_dir" interface, which doesn't require
  1154. * having any separate port open. */
  1155. int
  1156. directory_permits_begindir_requests(const or_options_t *options)
  1157. {
  1158. return options->BridgeRelay != 0 || options->DirPort_set;
  1159. }
  1160. /** Return 1 if we have no need to fetch new descriptors. This generally
  1161. * happens when we're not a dir cache and we haven't built any circuits
  1162. * lately.
  1163. */
  1164. int
  1165. directory_too_idle_to_fetch_descriptors(const or_options_t *options,
  1166. time_t now)
  1167. {
  1168. return !directory_caches_dir_info(options) &&
  1169. !options->FetchUselessDescriptors &&
  1170. rep_hist_circbuilding_dormant(now);
  1171. }
  1172. /********************************************************************/
  1173. /* Used only by non-v1-auth dirservers: The v1 directory and
  1174. * runningrouters we'll serve when requested. */
  1175. /** The v1 directory we'll serve (as a cache or as an authority) if
  1176. * requested. */
  1177. static cached_dir_t *cached_directory = NULL;
  1178. /** The v1 runningrouters document we'll serve (as a cache or as an authority)
  1179. * if requested. */
  1180. static cached_dir_t cached_runningrouters;
  1181. /** Map from flavor name to the cached_dir_t for the v3 consensuses that we're
  1182. * currently serving. */
  1183. static strmap_t *cached_consensuses = NULL;
  1184. /** Possibly replace the contents of <b>d</b> with the value of
  1185. * <b>directory</b> published on <b>when</b>, unless <b>when</b> is older than
  1186. * the last value, or too far in the future.
  1187. *
  1188. * Does not copy <b>directory</b>; frees it if it isn't used.
  1189. */
  1190. static void
  1191. set_cached_dir(cached_dir_t *d, char *directory, time_t when)
  1192. {
  1193. time_t now = time(NULL);
  1194. if (when<=d->published) {
  1195. log_info(LD_DIRSERV, "Ignoring old directory; not caching.");
  1196. tor_free(directory);
  1197. } else if (when>=now+ROUTER_MAX_AGE_TO_PUBLISH) {
  1198. log_info(LD_DIRSERV, "Ignoring future directory; not caching.");
  1199. tor_free(directory);
  1200. } else {
  1201. /* if (when>d->published && when<now+ROUTER_MAX_AGE) */
  1202. log_debug(LD_DIRSERV, "Caching directory.");
  1203. tor_free(d->dir);
  1204. d->dir = directory;
  1205. d->dir_len = strlen(directory);
  1206. tor_free(d->dir_z);
  1207. if (tor_gzip_compress(&(d->dir_z), &(d->dir_z_len), d->dir, d->dir_len,
  1208. ZLIB_METHOD)) {
  1209. log_warn(LD_BUG,"Error compressing cached directory");
  1210. }
  1211. d->published = when;
  1212. }
  1213. }
  1214. /** Decrement the reference count on <b>d</b>, and free it if it no longer has
  1215. * any references. */
  1216. void
  1217. cached_dir_decref(cached_dir_t *d)
  1218. {
  1219. if (!d || --d->refcnt > 0)
  1220. return;
  1221. clear_cached_dir(d);
  1222. tor_free(d);
  1223. }
  1224. /** Allocate and return a new cached_dir_t containing the string <b>s</b>,
  1225. * published at <b>published</b>. */
  1226. cached_dir_t *
  1227. new_cached_dir(char *s, time_t published)
  1228. {
  1229. cached_dir_t *d = tor_malloc_zero(sizeof(cached_dir_t));
  1230. d->refcnt = 1;
  1231. d->dir = s;
  1232. d->dir_len = strlen(s);
  1233. d->published = published;
  1234. if (tor_gzip_compress(&(d->dir_z), &(d->dir_z_len), d->dir, d->dir_len,
  1235. ZLIB_METHOD)) {
  1236. log_warn(LD_BUG, "Error compressing directory");
  1237. }
  1238. return d;
  1239. }
  1240. /** Remove all storage held in <b>d</b>, but do not free <b>d</b> itself. */
  1241. static void
  1242. clear_cached_dir(cached_dir_t *d)
  1243. {
  1244. tor_free(d->dir);
  1245. tor_free(d->dir_z);
  1246. memset(d, 0, sizeof(cached_dir_t));
  1247. }
  1248. /** Free all storage held by the cached_dir_t in <b>d</b>. */
  1249. static void
  1250. free_cached_dir_(void *_d)
  1251. {
  1252. cached_dir_t *d;
  1253. if (!_d)
  1254. return;
  1255. d = (cached_dir_t *)_d;
  1256. cached_dir_decref(d);
  1257. }
  1258. /** If we have no cached v1 directory, or it is older than <b>published</b>,
  1259. * then replace it with <b>directory</b>, published at <b>published</b>.
  1260. *
  1261. * If <b>published</b> is too old, do nothing.
  1262. *
  1263. * If <b>is_running_routers</b>, this is really a v1 running_routers
  1264. * document rather than a v1 directory.
  1265. */
  1266. static void
  1267. dirserv_set_cached_directory(const char *directory, time_t published)
  1268. {
  1269. cached_dir_decref(cached_directory);
  1270. cached_directory = new_cached_dir(tor_strdup(directory), published);
  1271. }
  1272. /** Replace the v3 consensus networkstatus of type <b>flavor_name</b> that
  1273. * we're serving with <b>networkstatus</b>, published at <b>published</b>. No
  1274. * validation is performed. */
  1275. void
  1276. dirserv_set_cached_consensus_networkstatus(const char *networkstatus,
  1277. const char *flavor_name,
  1278. const digests_t *digests,
  1279. time_t published)
  1280. {
  1281. cached_dir_t *new_networkstatus;
  1282. cached_dir_t *old_networkstatus;
  1283. if (!cached_consensuses)
  1284. cached_consensuses = strmap_new();
  1285. new_networkstatus = new_cached_dir(tor_strdup(networkstatus), published);
  1286. memcpy(&new_networkstatus->digests, digests, sizeof(digests_t));
  1287. old_networkstatus = strmap_set(cached_consensuses, flavor_name,
  1288. new_networkstatus);
  1289. if (old_networkstatus)
  1290. cached_dir_decref(old_networkstatus);
  1291. }
  1292. /** Helper: If we're an authority for the right directory version (v1)
  1293. * (based on <b>auth_type</b>), try to regenerate
  1294. * auth_src as appropriate and return it, falling back to cache_src on
  1295. * failure. If we're a cache, simply return cache_src.
  1296. */
  1297. static cached_dir_t *
  1298. dirserv_pick_cached_dir_obj(cached_dir_t *cache_src,
  1299. cached_dir_t *auth_src,
  1300. time_t dirty, cached_dir_t *(*regenerate)(void),
  1301. const char *name,
  1302. dirinfo_type_t auth_type)
  1303. {
  1304. const or_options_t *options = get_options();
  1305. int authority = (auth_type == V1_DIRINFO && authdir_mode_v1(options));
  1306. if (!authority || authdir_mode_bridge(options)) {
  1307. return cache_src;
  1308. } else {
  1309. /* We're authoritative. */
  1310. if (regenerate != NULL) {
  1311. if (dirty && dirty + DIR_REGEN_SLACK_TIME < time(NULL)) {
  1312. if (!(auth_src = regenerate())) {
  1313. log_err(LD_BUG, "Couldn't generate %s?", name);
  1314. exit(1);
  1315. }
  1316. } else {
  1317. log_info(LD_DIRSERV, "The %s is still clean; reusing.", name);
  1318. }
  1319. }
  1320. return auth_src ? auth_src : cache_src;
  1321. }
  1322. }
  1323. /** Return the most recently generated encoded signed v1 directory,
  1324. * generating a new one as necessary. If not a v1 authoritative directory
  1325. * may return NULL if no directory is yet cached. */
  1326. cached_dir_t *
  1327. dirserv_get_directory(void)
  1328. {
  1329. return dirserv_pick_cached_dir_obj(cached_directory, the_directory,
  1330. the_directory_is_dirty,
  1331. dirserv_regenerate_directory,
  1332. "v1 server directory", V1_DIRINFO);
  1333. }
  1334. /** Only called by v1 auth dirservers.
  1335. * Generate a fresh v1 directory; set the_directory and return a pointer
  1336. * to the new value.
  1337. */
  1338. static cached_dir_t *
  1339. dirserv_regenerate_directory(void)
  1340. {
  1341. /* XXXX 024 Get rid of this function if we can confirm that nobody's
  1342. * fetching these any longer */
  1343. char *new_directory=NULL;
  1344. if (dirserv_dump_directory_to_string(&new_directory,
  1345. get_server_identity_key())) {
  1346. log_warn(LD_BUG, "Error creating directory.");
  1347. tor_free(new_directory);
  1348. return NULL;
  1349. }
  1350. cached_dir_decref(the_directory);
  1351. the_directory = new_cached_dir(new_directory, time(NULL));
  1352. log_info(LD_DIRSERV,"New directory (size %d) has been built.",
  1353. (int)the_directory->dir_len);
  1354. log_debug(LD_DIRSERV,"New directory (size %d):\n%s",
  1355. (int)the_directory->dir_len, the_directory->dir);
  1356. the_directory_is_dirty = 0;
  1357. /* Save the directory to disk so we re-load it quickly on startup.
  1358. */
  1359. dirserv_set_cached_directory(the_directory->dir, time(NULL));
  1360. return the_directory;
  1361. }
  1362. /** Only called by v1 auth dirservers.
  1363. * Replace the current running-routers list with a newly generated one. */
  1364. static cached_dir_t *
  1365. generate_runningrouters(void)
  1366. {
  1367. char *s=NULL;
  1368. char digest[DIGEST_LEN];
  1369. char published[ISO_TIME_LEN+1];
  1370. size_t len;
  1371. crypto_pk_t *private_key = get_server_identity_key();
  1372. char *identity_pkey; /* Identity key, DER64-encoded. */
  1373. size_t identity_pkey_len;
  1374. if (crypto_pk_write_public_key_to_string(private_key,&identity_pkey,
  1375. &identity_pkey_len)<0) {
  1376. log_warn(LD_BUG,"write identity_pkey to string failed!");
  1377. goto err;
  1378. }
  1379. format_iso_time(published, time(NULL));
  1380. len = 2048;
  1381. s = tor_malloc_zero(len);
  1382. tor_snprintf(s, len,
  1383. "network-status\n"
  1384. "published %s\n"
  1385. "router-status %s\n"
  1386. "dir-signing-key\n%s"
  1387. "directory-signature %s\n",
  1388. published, "", identity_pkey,
  1389. get_options()->Nickname);
  1390. tor_free(identity_pkey);
  1391. if (router_get_runningrouters_hash(s,digest)) {
  1392. log_warn(LD_BUG,"couldn't compute digest");
  1393. goto err;
  1394. }
  1395. note_crypto_pk_op(SIGN_DIR);
  1396. if (router_append_dirobj_signature(s, len, digest, DIGEST_LEN,
  1397. private_key)<0)
  1398. goto err;
  1399. set_cached_dir(&the_runningrouters, s, time(NULL));
  1400. runningrouters_is_dirty = 0;
  1401. return &the_runningrouters;
  1402. err:
  1403. tor_free(s);
  1404. return NULL;
  1405. }
  1406. /** Set *<b>rr</b> to the most recently generated encoded signed
  1407. * running-routers list, generating a new one as necessary. Return the
  1408. * size of the directory on success, and 0 on failure. */
  1409. cached_dir_t *
  1410. dirserv_get_runningrouters(void)
  1411. {
  1412. return dirserv_pick_cached_dir_obj(
  1413. &cached_runningrouters, &the_runningrouters,
  1414. runningrouters_is_dirty,
  1415. generate_runningrouters,
  1416. "v1 network status list", V1_DIRINFO);
  1417. }
  1418. /** Return the latest downloaded consensus networkstatus in encoded, signed,
  1419. * optionally compressed format, suitable for sending to clients. */
  1420. cached_dir_t *
  1421. dirserv_get_consensus(const char *flavor_name)
  1422. {
  1423. if (!cached_consensuses)
  1424. return NULL;
  1425. return strmap_get(cached_consensuses, flavor_name);
  1426. }
  1427. /** If a router's uptime is at least this value, then it is always
  1428. * considered stable, regardless of the rest of the network. This
  1429. * way we resist attacks where an attacker doubles the size of the
  1430. * network using allegedly high-uptime nodes, displacing all the
  1431. * current guards. */
  1432. #define UPTIME_TO_GUARANTEE_STABLE (3600*24*30)
  1433. /** If a router's MTBF is at least this value, then it is always stable.
  1434. * See above. (Corresponds to about 7 days for current decay rates.) */
  1435. #define MTBF_TO_GUARANTEE_STABLE (60*60*24*5)
  1436. /** Similarly, every node with at least this much weighted time known can be
  1437. * considered familiar enough to be a guard. Corresponds to about 20 days for
  1438. * current decay rates.
  1439. */
  1440. #define TIME_KNOWN_TO_GUARANTEE_FAMILIAR (8*24*60*60)
  1441. /** Similarly, every node with sufficient WFU is around enough to be a guard.
  1442. */
  1443. #define WFU_TO_GUARANTEE_GUARD (0.98)
  1444. /* Thresholds for server performance: set by
  1445. * dirserv_compute_performance_thresholds, and used by
  1446. * generate_v2_networkstatus */
  1447. /** Any router with an uptime of at least this value is stable. */
  1448. static uint32_t stable_uptime = 0; /* start at a safe value */
  1449. /** Any router with an mtbf of at least this value is stable. */
  1450. static double stable_mtbf = 0.0;
  1451. /** If true, we have measured enough mtbf info to look at stable_mtbf rather
  1452. * than stable_uptime. */
  1453. static int enough_mtbf_info = 0;
  1454. /** Any router with a weighted fractional uptime of at least this much might
  1455. * be good as a guard. */
  1456. static double guard_wfu = 0.0;
  1457. /** Don't call a router a guard unless we've known about it for at least this
  1458. * many seconds. */
  1459. static long guard_tk = 0;
  1460. /** Any router with a bandwidth at least this high is "Fast" */
  1461. static uint32_t fast_bandwidth_kb = 0;
  1462. /** If exits can be guards, then all guards must have a bandwidth this
  1463. * high. */
  1464. static uint32_t guard_bandwidth_including_exits_kb = 0;
  1465. /** If exits can't be guards, then all guards must have a bandwidth this
  1466. * high. */
  1467. static uint32_t guard_bandwidth_excluding_exits_kb = 0;
  1468. /** Helper: estimate the uptime of a router given its stated uptime and the
  1469. * amount of time since it last stated its stated uptime. */
  1470. static INLINE long
  1471. real_uptime(const routerinfo_t *router, time_t now)
  1472. {
  1473. if (now < router->cache_info.published_on)
  1474. return router->uptime;
  1475. else
  1476. return router->uptime + (now - router->cache_info.published_on);
  1477. }
  1478. /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
  1479. * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
  1480. * If <b>need_capacity</b> is non-zero, we require a minimum advertised
  1481. * bandwidth.
  1482. */
  1483. static int
  1484. dirserv_thinks_router_is_unreliable(time_t now,
  1485. routerinfo_t *router,
  1486. int need_uptime, int need_capacity)
  1487. {
  1488. if (need_uptime) {
  1489. if (!enough_mtbf_info) {
  1490. /* XXX024 Once most authorities are on v3, we should change the rule from
  1491. * "use uptime if we don't have mtbf data" to "don't advertise Stable on
  1492. * v3 if we don't have enough mtbf data." Or maybe not, since if we ever
  1493. * hit a point where we need to reset a lot of authorities at once,
  1494. * none of them would be in a position to declare Stable.
  1495. */
  1496. long uptime = real_uptime(router, now);
  1497. if ((unsigned)uptime < stable_uptime &&
  1498. (unsigned)uptime < UPTIME_TO_GUARANTEE_STABLE)
  1499. return 1;
  1500. } else {
  1501. double mtbf =
  1502. rep_hist_get_stability(router->cache_info.identity_digest, now);
  1503. if (mtbf < stable_mtbf &&
  1504. mtbf < MTBF_TO_GUARANTEE_STABLE)
  1505. return 1;
  1506. }
  1507. }
  1508. if (need_capacity) {
  1509. uint32_t bw_kb = dirserv_get_credible_bandwidth_kb(router);
  1510. if (bw_kb < fast_bandwidth_kb)
  1511. return 1;
  1512. }
  1513. return 0;
  1514. }
  1515. /** Return true iff <b>router</b> should be assigned the "HSDir" flag.
  1516. * Right now this means it advertises support for it, it has a high
  1517. * uptime, it has a DirPort open, and it's currently considered Running.
  1518. *
  1519. * This function needs to be called after router-\>is_running has
  1520. * been set.
  1521. */
  1522. static int
  1523. dirserv_thinks_router_is_hs_dir(const routerinfo_t *router,
  1524. const node_t *node, time_t now)
  1525. {
  1526. long uptime;
  1527. /* If we haven't been running for at least
  1528. * get_options()->MinUptimeHidServDirectoryV2 seconds, we can't
  1529. * have accurate data telling us a relay has been up for at least
  1530. * that long. We also want to allow a bit of slack: Reachability
  1531. * tests aren't instant. If we haven't been running long enough,
  1532. * trust the relay. */
  1533. if (stats_n_seconds_working >
  1534. get_options()->MinUptimeHidServDirectoryV2 * 1.1)
  1535. uptime = MIN(rep_hist_get_uptime(router->cache_info.identity_digest, now),
  1536. real_uptime(router, now));
  1537. else
  1538. uptime = real_uptime(router, now);
  1539. /* XXX We shouldn't need to check dir_port, but we do because of
  1540. * bug 1693. In the future, once relays set wants_to_be_hs_dir
  1541. * correctly, we can revert to only checking dir_port if router's
  1542. * version is too old. */
  1543. /* XXX Unfortunately, we need to keep checking dir_port until all
  1544. * *clients* suffering from bug 2722 are obsolete. The first version
  1545. * to fix the bug was 0.2.2.25-alpha. */
  1546. return (router->wants_to_be_hs_dir && router->dir_port &&
  1547. uptime >= get_options()->MinUptimeHidServDirectoryV2 &&
  1548. node->is_running);
  1549. }
  1550. /** Don't consider routers with less bandwidth than this when computing
  1551. * thresholds. */
  1552. #define ABSOLUTE_MIN_BW_VALUE_TO_CONSIDER_KB 4
  1553. /** Helper for dirserv_compute_performance_thresholds(): Decide whether to
  1554. * include a router in our calculations, and return true iff we should; the
  1555. * require_mbw parameter is passed in by
  1556. * dirserv_compute_performance_thresholds() and controls whether we ever
  1557. * count routers with only advertised bandwidths */
  1558. static int
  1559. router_counts_toward_thresholds(const node_t *node, time_t now,
  1560. const digestmap_t *omit_as_sybil,
  1561. int require_mbw)
  1562. {
  1563. /* Have measured bw? */
  1564. int have_mbw =
  1565. dirserv_has_measured_bw(node->identity);
  1566. uint64_t min_bw_kb = ABSOLUTE_MIN_BW_VALUE_TO_CONSIDER_KB;
  1567. const or_options_t *options = get_options();
  1568. if (options->TestingTorNetwork) {
  1569. min_bw_kb = (int64_t)options->TestingMinExitFlagThreshold / 1000;
  1570. }
  1571. return node->ri && router_is_active(node->ri, node, now) &&
  1572. !digestmap_get(omit_as_sybil, node->identity) &&
  1573. (dirserv_get_credible_bandwidth_kb(node->ri) >= min_bw_kb) &&
  1574. (have_mbw || !require_mbw);
  1575. }
  1576. /** Look through the routerlist, the Mean Time Between Failure history, and
  1577. * the Weighted Fractional Uptime history, and use them to set thresholds for
  1578. * the Stable, Fast, and Guard flags. Update the fields stable_uptime,
  1579. * stable_mtbf, enough_mtbf_info, guard_wfu, guard_tk, fast_bandwidth,
  1580. * guard_bandwidth_including_exits, and guard_bandwidth_excluding_exits.
  1581. *
  1582. * Also, set the is_exit flag of each router appropriately. */
  1583. static void
  1584. dirserv_compute_performance_thresholds(routerlist_t *rl,
  1585. digestmap_t *omit_as_sybil)
  1586. {
  1587. int n_active, n_active_nonexit, n_familiar;
  1588. uint32_t *uptimes, *bandwidths_kb, *bandwidths_excluding_exits_kb;
  1589. long *tks;
  1590. double *mtbfs, *wfus;
  1591. time_t now = time(NULL);
  1592. const or_options_t *options = get_options();
  1593. /* Require mbw? */
  1594. int require_mbw =
  1595. (routers_with_measured_bw >
  1596. options->MinMeasuredBWsForAuthToIgnoreAdvertised) ? 1 : 0;
  1597. /* initialize these all here, in case there are no routers */
  1598. stable_uptime = 0;
  1599. stable_mtbf = 0;
  1600. fast_bandwidth_kb = 0;
  1601. guard_bandwidth_including_exits_kb = 0;
  1602. guard_bandwidth_excluding_exits_kb = 0;
  1603. guard_tk = 0;
  1604. guard_wfu = 0;
  1605. /* Initialize arrays that will hold values for each router. We'll
  1606. * sort them and use that to compute thresholds. */
  1607. n_active = n_active_nonexit = 0;
  1608. /* Uptime for every active router. */
  1609. uptimes = tor_malloc(sizeof(uint32_t)*smartlist_len(rl->routers));
  1610. /* Bandwidth for every active router. */
  1611. bandwidths_kb = tor_malloc(sizeof(uint32_t)*smartlist_len(rl->routers));
  1612. /* Bandwidth for every active non-exit router. */
  1613. bandwidths_excluding_exits_kb =
  1614. tor_malloc(sizeof(uint32_t)*smartlist_len(rl->routers));
  1615. /* Weighted mean time between failure for each active router. */
  1616. mtbfs = tor_malloc(sizeof(double)*smartlist_len(rl->routers));
  1617. /* Time-known for each active router. */
  1618. tks = tor_malloc(sizeof(long)*smartlist_len(rl->routers));
  1619. /* Weighted fractional uptime for each active router. */
  1620. wfus = tor_malloc(sizeof(double)*smartlist_len(rl->routers));
  1621. nodelist_assert_ok();
  1622. /* Now, fill in the arrays. */
  1623. SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), node_t *, node) {
  1624. if (options->BridgeAuthoritativeDir &&
  1625. node->ri &&
  1626. node->ri->purpose != ROUTER_PURPOSE_BRIDGE)
  1627. continue;
  1628. if (router_counts_toward_thresholds(node, now, omit_as_sybil,
  1629. require_mbw)) {
  1630. routerinfo_t *ri = node->ri;
  1631. const char *id = node->identity;
  1632. uint32_t bw_kb;
  1633. node->is_exit = (!router_exit_policy_rejects_all(ri) &&
  1634. exit_policy_is_general_exit(ri->exit_policy));
  1635. uptimes[n_active] = (uint32_t)real_uptime(ri, now);
  1636. mtbfs[n_active] = rep_hist_get_stability(id, now);
  1637. tks [n_active] = rep_hist_get_weighted_time_known(id, now);
  1638. bandwidths_kb[n_active] = bw_kb = dirserv_get_credible_bandwidth_kb(ri);
  1639. if (!node->is_exit || node->is_bad_exit) {
  1640. bandwidths_excluding_exits_kb[n_active_nonexit] = bw_kb;
  1641. ++n_active_nonexit;
  1642. }
  1643. ++n_active;
  1644. }
  1645. } SMARTLIST_FOREACH_END(node);
  1646. /* Now, compute thresholds. */
  1647. if (n_active) {
  1648. /* The median uptime is stable. */
  1649. stable_uptime = median_uint32(uptimes, n_active);
  1650. /* The median mtbf is stable, if we have enough mtbf info */
  1651. stable_mtbf = median_double(mtbfs, n_active);
  1652. /* The 12.5th percentile bandwidth is fast. */
  1653. fast_bandwidth_kb = find_nth_uint32(bandwidths_kb, n_active, n_active/8);
  1654. /* (Now bandwidths is sorted.) */
  1655. if (fast_bandwidth_kb < ROUTER_REQUIRED_MIN_BANDWIDTH/(2 * 1000))
  1656. fast_bandwidth_kb = bandwidths_kb[n_active/4];
  1657. guard_bandwidth_including_exits_kb = bandwidths_kb[(n_active-1)/2];
  1658. guard_tk = find_nth_long(tks, n_active, n_active/8);
  1659. }
  1660. if (guard_tk > TIME_KNOWN_TO_GUARANTEE_FAMILIAR)
  1661. guard_tk = TIME_KNOWN_TO_GUARANTEE_FAMILIAR;
  1662. {
  1663. /* We can vote on a parameter for the minimum and maximum. */
  1664. #define ABSOLUTE_MIN_VALUE_FOR_FAST_FLAG 4
  1665. int32_t min_fast_kb, max_fast_kb, min_fast, max_fast;
  1666. min_fast = networkstatus_get_param(NULL, "FastFlagMinThreshold",
  1667. ABSOLUTE_MIN_VALUE_FOR_FAST_FLAG,
  1668. ABSOLUTE_MIN_VALUE_FOR_FAST_FLAG,
  1669. INT32_MAX);
  1670. if (options->TestingTorNetwork) {
  1671. min_fast = (int32_t)options->TestingMinFastFlagThreshold;
  1672. }
  1673. max_fast = networkstatus_get_param(NULL, "FastFlagMaxThreshold",
  1674. INT32_MAX, min_fast, INT32_MAX);
  1675. min_fast_kb = min_fast / 1000;
  1676. max_fast_kb = max_fast / 1000;
  1677. if (fast_bandwidth_kb < (uint32_t)min_fast_kb)
  1678. fast_bandwidth_kb = min_fast_kb;
  1679. if (fast_bandwidth_kb > (uint32_t)max_fast_kb)
  1680. fast_bandwidth_kb = max_fast_kb;
  1681. }
  1682. /* Protect sufficiently fast nodes from being pushed out of the set
  1683. * of Fast nodes. */
  1684. if (options->AuthDirFastGuarantee &&
  1685. fast_bandwidth_kb > options->AuthDirFastGuarantee/1000)
  1686. fast_bandwidth_kb = (uint32_t)options->AuthDirFastGuarantee/1000;
  1687. /* Now that we have a time-known that 7/8 routers are known longer than,
  1688. * fill wfus with the wfu of every such "familiar" router. */
  1689. n_familiar = 0;
  1690. SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), node_t *, node) {
  1691. if (router_counts_toward_thresholds(node, now,
  1692. omit_as_sybil, require_mbw)) {
  1693. routerinfo_t *ri = node->ri;
  1694. const char *id = ri->cache_info.identity_digest;
  1695. long tk = rep_hist_get_weighted_time_known(id, now);
  1696. if (tk < guard_tk)
  1697. continue;
  1698. wfus[n_familiar++] = rep_hist_get_weighted_fractional_uptime(id, now);
  1699. }
  1700. } SMARTLIST_FOREACH_END(node);
  1701. if (n_familiar)
  1702. guard_wfu = median_double(wfus, n_familiar);
  1703. if (guard_wfu > WFU_TO_GUARANTEE_GUARD)
  1704. guard_wfu = WFU_TO_GUARANTEE_GUARD;
  1705. enough_mtbf_info = rep_hist_have_measured_enough_stability();
  1706. if (n_active_nonexit) {
  1707. guard_bandwidth_excluding_exits_kb =
  1708. median_uint32(bandwidths_excluding_exits_kb, n_active_nonexit);
  1709. }
  1710. log_info(LD_DIRSERV,
  1711. "Cutoffs: For Stable, %lu sec uptime, %lu sec MTBF. "
  1712. "For Fast: %lu kilobytes/sec. "
  1713. "For Guard: WFU %.03f%%, time-known %lu sec, "
  1714. "and bandwidth %lu or %lu kilobytes/sec. "
  1715. "We%s have enough stability data.",
  1716. (unsigned long)stable_uptime,
  1717. (unsigned long)stable_mtbf,
  1718. (unsigned long)fast_bandwidth_kb,
  1719. guard_wfu*100,
  1720. (unsigned long)guard_tk,
  1721. (unsigned long)guard_bandwidth_including_exits_kb,
  1722. (unsigned long)guard_bandwidth_excluding_exits_kb,
  1723. enough_mtbf_info ? "" : " don't ");
  1724. tor_free(uptimes);
  1725. tor_free(mtbfs);
  1726. tor_free(bandwidths_kb);
  1727. tor_free(bandwidths_excluding_exits_kb);
  1728. tor_free(tks);
  1729. tor_free(wfus);
  1730. }
  1731. /* Use dirserv_compute_performance_thresholds() to compute the thresholds
  1732. * for the status flags, specifically for bridges.
  1733. *
  1734. * This is only called by a Bridge Authority from
  1735. * networkstatus_getinfo_by_purpose().
  1736. */
  1737. void
  1738. dirserv_compute_bridge_flag_thresholds(routerlist_t *rl)
  1739. {
  1740. digestmap_t *omit_as_sybil = digestmap_new();
  1741. dirserv_compute_performance_thresholds(rl, omit_as_sybil);
  1742. digestmap_free(omit_as_sybil, NULL);
  1743. }
  1744. /** Measured bandwidth cache entry */
  1745. typedef struct mbw_cache_entry_s {
  1746. long mbw_kb;
  1747. time_t as_of;
  1748. } mbw_cache_entry_t;
  1749. /** Measured bandwidth cache - keys are identity_digests, values are
  1750. * mbw_cache_entry_t *. */
  1751. static digestmap_t *mbw_cache = NULL;
  1752. /** Store a measured bandwidth cache entry when reading the measured
  1753. * bandwidths file. */
  1754. STATIC void
  1755. dirserv_cache_measured_bw(const measured_bw_line_t *parsed_line,
  1756. time_t as_of)
  1757. {
  1758. mbw_cache_entry_t *e = NULL;
  1759. tor_assert(parsed_line);
  1760. /* Allocate a cache if we need */
  1761. if (!mbw_cache) mbw_cache = digestmap_new();
  1762. /* Check if we have an existing entry */
  1763. e = digestmap_get(mbw_cache, parsed_line->node_id);
  1764. /* If we do, we can re-use it */
  1765. if (e) {
  1766. /* Check that we really are newer, and update */
  1767. if (as_of > e->as_of) {
  1768. e->mbw_kb = parsed_line->bw_kb;
  1769. e->as_of = as_of;
  1770. }
  1771. } else {
  1772. /* We'll have to insert a new entry */
  1773. e = tor_malloc(sizeof(*e));
  1774. e->mbw_kb = parsed_line->bw_kb;
  1775. e->as_of = as_of;
  1776. digestmap_set(mbw_cache, parsed_line->node_id, e);
  1777. }
  1778. }
  1779. /** Clear and free the measured bandwidth cache */
  1780. STATIC void
  1781. dirserv_clear_measured_bw_cache(void)
  1782. {
  1783. if (mbw_cache) {
  1784. /* Free the map and all entries */
  1785. digestmap_free(mbw_cache, tor_free_);
  1786. mbw_cache = NULL;
  1787. }
  1788. }
  1789. /** Scan the measured bandwidth cache and remove expired entries */
  1790. STATIC void
  1791. dirserv_expire_measured_bw_cache(time_t now)
  1792. {
  1793. if (mbw_cache) {
  1794. /* Iterate through the cache and check each entry */
  1795. DIGESTMAP_FOREACH_MODIFY(mbw_cache, k, mbw_cache_entry_t *, e) {
  1796. if (now > e->as_of + MAX_MEASUREMENT_AGE) {
  1797. tor_free(e);
  1798. MAP_DEL_CURRENT(k);
  1799. }
  1800. } DIGESTMAP_FOREACH_END;
  1801. /* Check if we cleared the whole thing and free if so */
  1802. if (digestmap_size(mbw_cache) == 0) {
  1803. digestmap_free(mbw_cache, tor_free_);
  1804. mbw_cache = 0;
  1805. }
  1806. }
  1807. }
  1808. /** Get the current size of the measured bandwidth cache */
  1809. STATIC int
  1810. dirserv_get_measured_bw_cache_size(void)
  1811. {
  1812. if (mbw_cache) return digestmap_size(mbw_cache);
  1813. else return 0;
  1814. }
  1815. /** Query the cache by identity digest, return value indicates whether
  1816. * we found it. The bw_out and as_of_out pointers receive the cached
  1817. * bandwidth value and the time it was cached if not NULL. */
  1818. STATIC int
  1819. dirserv_query_measured_bw_cache_kb(const char *node_id, long *bw_kb_out,
  1820. time_t *as_of_out)
  1821. {
  1822. mbw_cache_entry_t *v = NULL;
  1823. int rv = 0;
  1824. if (mbw_cache && node_id) {
  1825. v = digestmap_get(mbw_cache, node_id);
  1826. if (v) {
  1827. /* Found something */
  1828. rv = 1;
  1829. if (bw_kb_out) *bw_kb_out = v->mbw_kb;
  1830. if (as_of_out) *as_of_out = v->as_of;
  1831. }
  1832. }
  1833. return rv;
  1834. }
  1835. /** Predicate wrapper for dirserv_query_measured_bw_cache() */
  1836. STATIC int
  1837. dirserv_has_measured_bw(const char *node_id)
  1838. {
  1839. return dirserv_query_measured_bw_cache_kb(node_id, NULL, NULL);
  1840. }
  1841. /** Get the best estimate of a router's bandwidth for dirauth purposes,
  1842. * preferring measured to advertised values if available. */
  1843. static uint32_t
  1844. dirserv_get_bandwidth_for_router_kb(const routerinfo_t *ri)
  1845. {
  1846. uint32_t bw_kb = 0;
  1847. /*
  1848. * Yeah, measured bandwidths in measured_bw_line_t are (implicitly
  1849. * signed) longs and the ones router_get_advertised_bandwidth() returns
  1850. * are uint32_t.
  1851. */
  1852. long mbw_kb = 0;
  1853. if (ri) {
  1854. /*
  1855. * * First try to see if we have a measured bandwidth; don't bother with
  1856. * as_of_out here, on the theory that a stale measured bandwidth is still
  1857. * better to trust than an advertised one.
  1858. */
  1859. if (dirserv_query_measured_bw_cache_kb(ri->cache_info.identity_digest,
  1860. &mbw_kb, NULL)) {
  1861. /* Got one! */
  1862. bw_kb = (uint32_t)mbw_kb;
  1863. } else {
  1864. /* If not, fall back to advertised */
  1865. bw_kb = router_get_advertised_bandwidth(ri) / 1000;
  1866. }
  1867. }
  1868. return bw_kb;
  1869. }
  1870. /** Look through the routerlist, and using the measured bandwidth cache count
  1871. * how many measured bandwidths we know. This is used to decide whether we
  1872. * ever trust advertised bandwidths for purposes of assigning flags. */
  1873. static void
  1874. dirserv_count_measured_bws(routerlist_t *rl)
  1875. {
  1876. /* Initialize this first */
  1877. routers_with_measured_bw = 0;
  1878. tor_assert(rl);
  1879. tor_assert(rl->routers);
  1880. /* Iterate over the routerlist and count measured bandwidths */
  1881. SMARTLIST_FOREACH_BEGIN(rl->routers, routerinfo_t *, ri) {
  1882. /* Check if we know a measured bandwidth for this one */
  1883. if (dirserv_has_measured_bw(ri->cache_info.identity_digest)) {
  1884. ++routers_with_measured_bw;
  1885. }
  1886. } SMARTLIST_FOREACH_END(ri);
  1887. }
  1888. /** Return the bandwidth we believe for assigning flags; prefer measured
  1889. * over advertised, and if we have above a threshold quantity of measured
  1890. * bandwidths, we don't want to ever give flags to unmeasured routers, so
  1891. * return 0. */
  1892. static uint32_t
  1893. dirserv_get_credible_bandwidth_kb(const routerinfo_t *ri)
  1894. {
  1895. int threshold;
  1896. uint32_t bw_kb = 0;
  1897. long mbw_kb;
  1898. tor_assert(ri);
  1899. /* Check if we have a measured bandwidth, and check the threshold if not */
  1900. if (!(dirserv_query_measured_bw_cache_kb(ri->cache_info.identity_digest,
  1901. &mbw_kb, NULL))) {
  1902. threshold = get_options()->MinMeasuredBWsForAuthToIgnoreAdvertised;
  1903. if (routers_with_measured_bw > threshold) {
  1904. /* Return zero for unmeasured bandwidth if we are above threshold */
  1905. bw_kb = 0;
  1906. } else {
  1907. /* Return an advertised bandwidth otherwise */
  1908. bw_kb = router_get_advertised_bandwidth_capped(ri) / 1000;
  1909. }
  1910. } else {
  1911. /* We have the measured bandwidth in mbw */
  1912. bw_kb = (uint32_t)mbw_kb;
  1913. }
  1914. return bw_kb;
  1915. }
  1916. /** Give a statement of our current performance thresholds for inclusion
  1917. * in a vote document. */
  1918. char *
  1919. dirserv_get_flag_thresholds_line(void)
  1920. {
  1921. char *result=NULL;
  1922. const int measured_threshold =
  1923. get_options()->MinMeasuredBWsForAuthToIgnoreAdvertised;
  1924. const int enough_measured_bw = routers_with_measured_bw > measured_threshold;
  1925. tor_asprintf(&result,
  1926. "stable-uptime=%lu stable-mtbf=%lu "
  1927. "fast-speed=%lu "
  1928. "guard-wfu=%.03f%% guard-tk=%lu "
  1929. "guard-bw-inc-exits=%lu guard-bw-exc-exits=%lu "
  1930. "enough-mtbf=%d ignoring-advertised-bws=%d",
  1931. (unsigned long)stable_uptime,
  1932. (unsigned long)stable_mtbf,
  1933. (unsigned long)fast_bandwidth_kb*1000,
  1934. guard_wfu*100,
  1935. (unsigned long)guard_tk,
  1936. (unsigned long)guard_bandwidth_including_exits_kb*1000,
  1937. (unsigned long)guard_bandwidth_excluding_exits_kb*1000,
  1938. enough_mtbf_info ? 1 : 0,
  1939. enough_measured_bw ? 1 : 0);
  1940. return result;
  1941. }
  1942. /** Given a platform string as in a routerinfo_t (possibly null), return a
  1943. * newly allocated version string for a networkstatus document, or NULL if the
  1944. * platform doesn't give a Tor version. */
  1945. static char *
  1946. version_from_platform(const char *platform)
  1947. {
  1948. if (platform && !strcmpstart(platform, "Tor ")) {
  1949. const char *eos = find_whitespace(platform+4);
  1950. if (eos && !strcmpstart(eos, " (r")) {
  1951. /* XXXX Unify this logic with the other version extraction
  1952. * logic in routerparse.c. */
  1953. eos = find_whitespace(eos+1);
  1954. }
  1955. if (eos) {
  1956. return tor_strndup(platform, eos-platform);
  1957. }
  1958. }
  1959. return NULL;
  1960. }
  1961. /** Helper: write the router-status information in <b>rs</b> into a newly
  1962. * allocated character buffer. Use the same format as in network-status
  1963. * documents. If <b>version</b> is non-NULL, add a "v" line for the platform.
  1964. * Return 0 on success, -1 on failure.
  1965. *
  1966. * The format argument has one of the following values:
  1967. * NS_V2 - Output an entry suitable for a V2 NS opinion document
  1968. * NS_V3_CONSENSUS - Output the first portion of a V3 NS consensus entry
  1969. * NS_V3_CONSENSUS_MICRODESC - Output the first portion of a V3 microdesc
  1970. * consensus entry.
  1971. * NS_V3_VOTE - Output a complete V3 NS vote. If <b>vrs</b> is present,
  1972. * it contains additional information for the vote.
  1973. * NS_CONTROL_PORT - Output a NS document for the control port
  1974. */
  1975. char *
  1976. routerstatus_format_entry(const routerstatus_t *rs, const char *version,
  1977. routerstatus_format_type_t format,
  1978. const vote_routerstatus_t *vrs)
  1979. {
  1980. char *summary;
  1981. char *result = NULL;
  1982. char published[ISO_TIME_LEN+1];
  1983. char identity64[BASE64_DIGEST_LEN+1];
  1984. char digest64[BASE64_DIGEST_LEN+1];
  1985. smartlist_t *chunks = NULL;
  1986. format_iso_time(published, rs->published_on);
  1987. digest_to_base64(identity64, rs->identity_digest);
  1988. digest_to_base64(digest64, rs->descriptor_digest);
  1989. chunks = smartlist_new();
  1990. smartlist_add_asprintf(chunks,
  1991. "r %s %s %s%s%s %s %d %d\n",
  1992. rs->nickname,
  1993. identity64,
  1994. (format==NS_V3_CONSENSUS_MICRODESC)?"":digest64,
  1995. (format==NS_V3_CONSENSUS_MICRODESC)?"":" ",
  1996. published,
  1997. fmt_addr32(rs->addr),
  1998. (int)rs->or_port,
  1999. (int)rs->dir_port);
  2000. /* TODO: Maybe we want to pass in what we need to build the rest of
  2001. * this here, instead of in the caller. Then we could use the
  2002. * networkstatus_type_t values, with an additional control port value
  2003. * added -MP */
  2004. /* V3 microdesc consensuses don't have "a" lines. */
  2005. if (format == NS_V3_CONSENSUS_MICRODESC)
  2006. goto done;
  2007. /* Possible "a" line. At most one for now. */
  2008. if (!tor_addr_is_null(&rs->ipv6_addr)) {
  2009. smartlist_add_asprintf(chunks, "a %s\n",
  2010. fmt_addrport(&rs->ipv6_addr, rs->ipv6_orport));
  2011. }
  2012. if (format == NS_V3_CONSENSUS)
  2013. goto done;
  2014. smartlist_add_asprintf(chunks,
  2015. "s%s%s%s%s%s%s%s%s%s%s%s%s%s\n",
  2016. /* These must stay in alphabetical order. */
  2017. rs->is_authority?" Authority":"",
  2018. rs->is_bad_directory?" BadDirectory":"",
  2019. rs->is_bad_exit?" BadExit":"",
  2020. rs->is_exit?" Exit":"",
  2021. rs->is_fast?" Fast":"",
  2022. rs->is_possible_guard?" Guard":"",
  2023. rs->is_hs_dir?" HSDir":"",
  2024. rs->is_named?" Named":"",
  2025. rs->is_flagged_running?" Running":"",
  2026. rs->is_stable?" Stable":"",
  2027. rs->is_unnamed?" Unnamed":"",
  2028. (rs->dir_port!=0)?" V2Dir":"",
  2029. rs->is_valid?" Valid":"");
  2030. /* length of "opt v \n" */
  2031. #define V_LINE_OVERHEAD 7
  2032. if (version && strlen(version) < MAX_V_LINE_LEN - V_LINE_OVERHEAD) {
  2033. smartlist_add_asprintf(chunks, "v %s\n", version);
  2034. }
  2035. if (format != NS_V2) {
  2036. const routerinfo_t* desc = router_get_by_id_digest(rs->identity_digest);
  2037. uint32_t bw_kb;
  2038. if (format != NS_CONTROL_PORT) {
  2039. /* Blow up more or less nicely if we didn't get anything or not the
  2040. * thing we expected.
  2041. */
  2042. if (!desc) {
  2043. char id[HEX_DIGEST_LEN+1];
  2044. char dd[HEX_DIGEST_LEN+1];
  2045. base16_encode(id, sizeof(id), rs->identity_digest, DIGEST_LEN);
  2046. base16_encode(dd, sizeof(dd), rs->descriptor_digest, DIGEST_LEN);
  2047. log_warn(LD_BUG, "Cannot get any descriptor for %s "
  2048. "(wanted descriptor %s).",
  2049. id, dd);
  2050. goto err;
  2051. }
  2052. /* This assert could fire for the control port, because
  2053. * it can request NS documents before all descriptors
  2054. * have been fetched. Therefore, we only do this test when
  2055. * format != NS_CONTROL_PORT. */
  2056. if (tor_memneq(desc->cache_info.signed_descriptor_digest,
  2057. rs->descriptor_digest,
  2058. DIGEST_LEN)) {
  2059. char rl_d[HEX_DIGEST_LEN+1];
  2060. char rs_d[HEX_DIGEST_LEN+1];
  2061. char id[HEX_DIGEST_LEN+1];
  2062. base16_encode(rl_d, sizeof(rl_d),
  2063. desc->cache_info.signed_descriptor_digest, DIGEST_LEN);
  2064. base16_encode(rs_d, sizeof(rs_d), rs->descriptor_digest, DIGEST_LEN);
  2065. base16_encode(id, sizeof(id), rs->identity_digest, DIGEST_LEN);
  2066. log_err(LD_BUG, "descriptor digest in routerlist does not match "
  2067. "the one in routerstatus: %s vs %s "
  2068. "(router %s)\n",
  2069. rl_d, rs_d, id);
  2070. tor_assert(tor_memeq(desc->cache_info.signed_descriptor_digest,
  2071. rs->descriptor_digest,
  2072. DIGEST_LEN));
  2073. }
  2074. }
  2075. if (format == NS_CONTROL_PORT && rs->has_bandwidth) {
  2076. bw_kb = rs->bandwidth_kb;
  2077. } else {
  2078. tor_assert(desc);
  2079. bw_kb = router_get_advertised_bandwidth_capped(desc) / 1000;
  2080. }
  2081. smartlist_add_asprintf(chunks,
  2082. "w Bandwidth=%d", bw_kb);
  2083. if (format == NS_V3_VOTE && vrs && vrs->has_measured_bw) {
  2084. smartlist_add_asprintf(chunks,
  2085. " Measured=%d", vrs->measured_bw_kb);
  2086. }
  2087. smartlist_add(chunks, tor_strdup("\n"));
  2088. if (desc) {
  2089. summary = policy_summarize(desc->exit_policy, AF_INET);
  2090. smartlist_add_asprintf(chunks, "p %s\n", summary);
  2091. tor_free(summary);
  2092. }
  2093. }
  2094. done:
  2095. result = smartlist_join_strings(chunks, "", 0, NULL);
  2096. err:
  2097. if (chunks) {
  2098. SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
  2099. smartlist_free(chunks);
  2100. }
  2101. return result;
  2102. }
  2103. /** Helper for sorting: compares two routerinfos first by address, and then by
  2104. * descending order of "usefulness". (An authority is more useful than a
  2105. * non-authority; a running router is more useful than a non-running router;
  2106. * and a router with more bandwidth is more useful than one with less.)
  2107. **/
  2108. static int
  2109. compare_routerinfo_by_ip_and_bw_(const void **a, const void **b)
  2110. {
  2111. routerinfo_t *first = *(routerinfo_t **)a, *second = *(routerinfo_t **)b;
  2112. int first_is_auth, second_is_auth;
  2113. uint32_t bw_kb_first, bw_kb_second;
  2114. const node_t *node_first, *node_second;
  2115. int first_is_running, second_is_running;
  2116. /* we return -1 if first should appear before second... that is,
  2117. * if first is a better router. */
  2118. if (first->addr < second->addr)
  2119. return -1;
  2120. else if (first->addr > second->addr)
  2121. return 1;
  2122. /* Potentially, this next bit could cause k n lg n memeq calls. But in
  2123. * reality, we will almost never get here, since addresses will usually be
  2124. * different. */
  2125. first_is_auth =
  2126. router_digest_is_trusted_dir(first->cache_info.identity_digest);
  2127. second_is_auth =
  2128. router_digest_is_trusted_dir(second->cache_info.identity_digest);
  2129. if (first_is_auth && !second_is_auth)
  2130. return -1;
  2131. else if (!first_is_auth && second_is_auth)
  2132. return 1;
  2133. node_first = node_get_by_id(first->cache_info.identity_digest);
  2134. node_second = node_get_by_id(second->cache_info.identity_digest);
  2135. first_is_running = node_first && node_first->is_running;
  2136. second_is_running = node_second && node_second->is_running;
  2137. if (first_is_running && !second_is_running)
  2138. return -1;
  2139. else if (!first_is_running && second_is_running)
  2140. return 1;
  2141. bw_kb_first = dirserv_get_bandwidth_for_router_kb(first);
  2142. bw_kb_second = dirserv_get_bandwidth_for_router_kb(second);
  2143. if (bw_kb_first > bw_kb_second)
  2144. return -1;
  2145. else if (bw_kb_first < bw_kb_second)
  2146. return 1;
  2147. /* They're equal! Compare by identity digest, so there's a
  2148. * deterministic order and we avoid flapping. */
  2149. return fast_memcmp(first->cache_info.identity_digest,
  2150. second->cache_info.identity_digest,
  2151. DIGEST_LEN);
  2152. }
  2153. /** Given a list of routerinfo_t in <b>routers</b>, return a new digestmap_t
  2154. * whose keys are the identity digests of those routers that we're going to
  2155. * exclude for Sybil-like appearance. */
  2156. static digestmap_t *
  2157. get_possible_sybil_list(const smartlist_t *routers)
  2158. {
  2159. const or_options_t *options = get_options();
  2160. digestmap_t *omit_as_sybil;
  2161. smartlist_t *routers_by_ip = smartlist_new();
  2162. uint32_t last_addr;
  2163. int addr_count;
  2164. /* Allow at most this number of Tor servers on a single IP address, ... */
  2165. int max_with_same_addr = options->AuthDirMaxServersPerAddr;
  2166. /* ... unless it's a directory authority, in which case allow more. */
  2167. int max_with_same_addr_on_authority = options->AuthDirMaxServersPerAuthAddr;
  2168. if (max_with_same_addr <= 0)
  2169. max_with_same_addr = INT_MAX;
  2170. if (max_with_same_addr_on_authority <= 0)
  2171. max_with_same_addr_on_authority = INT_MAX;
  2172. smartlist_add_all(routers_by_ip, routers);
  2173. smartlist_sort(routers_by_ip, compare_routerinfo_by_ip_and_bw_);
  2174. omit_as_sybil = digestmap_new();
  2175. last_addr = 0;
  2176. addr_count = 0;
  2177. SMARTLIST_FOREACH_BEGIN(routers_by_ip, routerinfo_t *, ri) {
  2178. if (last_addr != ri->addr) {
  2179. last_addr = ri->addr;
  2180. addr_count = 1;
  2181. } else if (++addr_count > max_with_same_addr) {
  2182. if (!router_addr_is_trusted_dir(ri->addr) ||
  2183. addr_count > max_with_same_addr_on_authority)
  2184. digestmap_set(omit_as_sybil, ri->cache_info.identity_digest, ri);
  2185. }
  2186. } SMARTLIST_FOREACH_END(ri);
  2187. smartlist_free(routers_by_ip);
  2188. return omit_as_sybil;
  2189. }
  2190. /** Return non-zero iff a relay running the Tor version specified in
  2191. * <b>platform</b> is suitable for use as a potential entry guard. */
  2192. static int
  2193. is_router_version_good_for_possible_guard(const char *platform)
  2194. {
  2195. static int parsed_versions_initialized = 0;
  2196. static tor_version_t first_good_0_2_1_guard_version;
  2197. static tor_version_t first_good_0_2_2_guard_version;
  2198. static tor_version_t first_good_later_guard_version;
  2199. tor_version_t router_version;
  2200. /* XXX024 This block should be extracted into its own function. */
  2201. /* XXXX Begin code copied from tor_version_as_new_as (in routerparse.c) */
  2202. {
  2203. char *s, *s2, *start;
  2204. char tmp[128];
  2205. tor_assert(platform);
  2206. /* nonstandard Tor; be safe and say yes */
  2207. if (strcmpstart(platform,"Tor "))
  2208. return 1;
  2209. start = (char *)eat_whitespace(platform+3);
  2210. if (!*start) return 0;
  2211. s = (char *)find_whitespace(start); /* also finds '\0', which is fine */
  2212. s2 = (char*)eat_whitespace(s);
  2213. if (!strcmpstart(s2, "(r") || !strcmpstart(s2, "(git-"))
  2214. s = (char*)find_whitespace(s2);
  2215. if ((size_t)(s-start+1) >= sizeof(tmp)) /* too big, no */
  2216. return 0;
  2217. strlcpy(tmp, start, s-start+1);
  2218. if (tor_version_parse(tmp, &router_version)<0) {
  2219. log_info(LD_DIR,"Router version '%s' unparseable.",tmp);
  2220. return 1; /* be safe and say yes */
  2221. }
  2222. }
  2223. /* XXXX End code copied from tor_version_as_new_as (in routerparse.c) */
  2224. if (!parsed_versions_initialized) {
  2225. /* CVE-2011-2769 was fixed on the relay side in Tor versions
  2226. * 0.2.1.31, 0.2.2.34, and 0.2.3.6-alpha. */
  2227. tor_assert(tor_version_parse("0.2.1.31",
  2228. &first_good_0_2_1_guard_version)>=0);
  2229. tor_assert(tor_version_parse("0.2.2.34",
  2230. &first_good_0_2_2_guard_version)>=0);
  2231. tor_assert(tor_version_parse("0.2.3.6-alpha",
  2232. &first_good_later_guard_version)>=0);
  2233. /* Don't parse these constant version strings once for every relay
  2234. * for every vote. */
  2235. parsed_versions_initialized = 1;
  2236. }
  2237. return ((tor_version_same_series(&first_good_0_2_1_guard_version,
  2238. &router_version) &&
  2239. tor_version_compare(&first_good_0_2_1_guard_version,
  2240. &router_version) <= 0) ||
  2241. (tor_version_same_series(&first_good_0_2_2_guard_version,
  2242. &router_version) &&
  2243. tor_version_compare(&first_good_0_2_2_guard_version,
  2244. &router_version) <= 0) ||
  2245. (tor_version_compare(&first_good_later_guard_version,
  2246. &router_version) <= 0));
  2247. }
  2248. /** Extract status information from <b>ri</b> and from other authority
  2249. * functions and store it in <b>rs</b>>. If <b>naming</b>, consider setting
  2250. * the named flag in <b>rs</b>.
  2251. *
  2252. * We assume that ri-\>is_running has already been set, e.g. by
  2253. * dirserv_set_router_is_running(ri, now);
  2254. */
  2255. void
  2256. set_routerstatus_from_routerinfo(routerstatus_t *rs,
  2257. node_t *node,
  2258. routerinfo_t *ri,
  2259. time_t now,
  2260. int naming, int listbadexits,
  2261. int listbaddirs, int vote_on_hsdirs)
  2262. {
  2263. const or_options_t *options = get_options();
  2264. uint32_t routerbw_kb = dirserv_get_credible_bandwidth_kb(ri);
  2265. memset(rs, 0, sizeof(routerstatus_t));
  2266. rs->is_authority =
  2267. router_digest_is_trusted_dir(ri->cache_info.identity_digest);
  2268. /* Already set by compute_performance_thresholds. */
  2269. rs->is_exit = node->is_exit;
  2270. rs->is_stable = node->is_stable =
  2271. router_is_active(ri, node, now) &&
  2272. !dirserv_thinks_router_is_unreliable(now, ri, 1, 0);
  2273. rs->is_fast = node->is_fast =
  2274. router_is_active(ri, node, now) &&
  2275. !dirserv_thinks_router_is_unreliable(now, ri, 0, 1);
  2276. rs->is_flagged_running = node->is_running; /* computed above */
  2277. if (naming) {
  2278. uint32_t name_status = dirserv_get_name_status(
  2279. node->identity, ri->nickname);
  2280. rs->is_named = (naming && (name_status & FP_NAMED)) ? 1 : 0;
  2281. rs->is_unnamed = (naming && (name_status & FP_UNNAMED)) ? 1 : 0;
  2282. }
  2283. rs->is_valid = node->is_valid;
  2284. if (node->is_fast &&
  2285. ((options->AuthDirGuardBWGuarantee &&
  2286. routerbw_kb >= options->AuthDirGuardBWGuarantee/1000) ||
  2287. routerbw_kb >= MIN(guard_bandwidth_including_exits_kb,
  2288. guard_bandwidth_excluding_exits_kb)) &&
  2289. is_router_version_good_for_possible_guard(ri->platform)) {
  2290. long tk = rep_hist_get_weighted_time_known(
  2291. node->identity, now);
  2292. double wfu = rep_hist_get_weighted_fractional_uptime(
  2293. node->identity, now);
  2294. rs->is_possible_guard = (wfu >= guard_wfu && tk >= guard_tk) ? 1 : 0;
  2295. } else {
  2296. rs->is_possible_guard = 0;
  2297. }
  2298. if (options->TestingTorNetwork &&
  2299. routerset_contains_routerstatus(options->TestingDirAuthVoteGuard,
  2300. rs, 0)) {
  2301. rs->is_possible_guard = 1;
  2302. }
  2303. rs->is_bad_directory = listbaddirs && node->is_bad_directory;
  2304. rs->is_bad_exit = listbadexits && node->is_bad_exit;
  2305. node->is_hs_dir = dirserv_thinks_router_is_hs_dir(ri, node, now);
  2306. rs->is_hs_dir = vote_on_hsdirs && node->is_hs_dir;
  2307. if (!strcasecmp(ri->nickname, UNNAMED_ROUTER_NICKNAME))
  2308. rs->is_named = rs->is_unnamed = 0;
  2309. rs->published_on = ri->cache_info.published_on;
  2310. memcpy(rs->identity_digest, node->identity, DIGEST_LEN);
  2311. memcpy(rs->descriptor_digest, ri->cache_info.signed_descriptor_digest,
  2312. DIGEST_LEN);
  2313. rs->addr = ri->addr;
  2314. strlcpy(rs->nickname, ri->nickname, sizeof(rs->nickname));
  2315. rs->or_port = ri->or_port;
  2316. rs->dir_port = ri->dir_port;
  2317. if (options->AuthDirHasIPv6Connectivity == 1 &&
  2318. !tor_addr_is_null(&ri->ipv6_addr) &&
  2319. node->last_reachable6 >= now - REACHABLE_TIMEOUT) {
  2320. /* We're configured as having IPv6 connectivity. There's an IPv6
  2321. OR port and it's reachable so copy it to the routerstatus. */
  2322. tor_addr_copy(&rs->ipv6_addr, &ri->ipv6_addr);
  2323. rs->ipv6_orport = ri->ipv6_orport;
  2324. }
  2325. }
  2326. /** Routerstatus <b>rs</b> is part of a group of routers that are on
  2327. * too narrow an IP-space. Clear out its flags: we don't want people
  2328. * using it.
  2329. */
  2330. static void
  2331. clear_status_flags_on_sybil(routerstatus_t *rs)
  2332. {
  2333. rs->is_authority = rs->is_exit = rs->is_stable = rs->is_fast =
  2334. rs->is_flagged_running = rs->is_named = rs->is_valid =
  2335. rs->is_hs_dir = rs->is_possible_guard = rs->is_bad_exit =
  2336. rs->is_bad_directory = 0;
  2337. /* FFFF we might want some mechanism to check later on if we
  2338. * missed zeroing any flags: it's easy to add a new flag but
  2339. * forget to add it to this clause. */
  2340. }
  2341. /**
  2342. * Helper function to parse out a line in the measured bandwidth file
  2343. * into a measured_bw_line_t output structure. Returns -1 on failure
  2344. * or 0 on success.
  2345. */
  2346. STATIC int
  2347. measured_bw_line_parse(measured_bw_line_t *out, const char *orig_line)
  2348. {
  2349. char *line = tor_strdup(orig_line);
  2350. char *cp = line;
  2351. int got_bw = 0;
  2352. int got_node_id = 0;
  2353. char *strtok_state; /* lame sauce d'jour */
  2354. cp = tor_strtok_r(cp, " \t", &strtok_state);
  2355. if (!cp) {
  2356. log_warn(LD_DIRSERV, "Invalid line in bandwidth file: %s",
  2357. escaped(orig_line));
  2358. tor_free(line);
  2359. return -1;
  2360. }
  2361. if (orig_line[strlen(orig_line)-1] != '\n') {
  2362. log_warn(LD_DIRSERV, "Incomplete line in bandwidth file: %s",
  2363. escaped(orig_line));
  2364. tor_free(line);
  2365. return -1;
  2366. }
  2367. do {
  2368. if (strcmpstart(cp, "bw=") == 0) {
  2369. int parse_ok = 0;
  2370. char *endptr;
  2371. if (got_bw) {
  2372. log_warn(LD_DIRSERV, "Double bw= in bandwidth file line: %s",
  2373. escaped(orig_line));
  2374. tor_free(line);
  2375. return -1;
  2376. }
  2377. cp+=strlen("bw=");
  2378. out->bw_kb = tor_parse_long(cp, 0, 0, LONG_MAX, &parse_ok, &endptr);
  2379. if (!parse_ok || (*endptr && !TOR_ISSPACE(*endptr))) {
  2380. log_warn(LD_DIRSERV, "Invalid bandwidth in bandwidth file line: %s",
  2381. escaped(orig_line));
  2382. tor_free(line);
  2383. return -1;
  2384. }
  2385. got_bw=1;
  2386. } else if (strcmpstart(cp, "node_id=$") == 0) {
  2387. if (got_node_id) {
  2388. log_warn(LD_DIRSERV, "Double node_id= in bandwidth file line: %s",
  2389. escaped(orig_line));
  2390. tor_free(line);
  2391. return -1;
  2392. }
  2393. cp+=strlen("node_id=$");
  2394. if (strlen(cp) != HEX_DIGEST_LEN ||
  2395. base16_decode(out->node_id, DIGEST_LEN, cp, HEX_DIGEST_LEN)) {
  2396. log_warn(LD_DIRSERV, "Invalid node_id in bandwidth file line: %s",
  2397. escaped(orig_line));
  2398. tor_free(line);
  2399. return -1;
  2400. }
  2401. strlcpy(out->node_hex, cp, sizeof(out->node_hex));
  2402. got_node_id=1;
  2403. }
  2404. } while ((cp = tor_strtok_r(NULL, " \t", &strtok_state)));
  2405. if (got_bw && got_node_id) {
  2406. tor_free(line);
  2407. return 0;
  2408. } else {
  2409. log_warn(LD_DIRSERV, "Incomplete line in bandwidth file: %s",
  2410. escaped(orig_line));
  2411. tor_free(line);
  2412. return -1;
  2413. }
  2414. }
  2415. /**
  2416. * Helper function to apply a parsed measurement line to a list
  2417. * of bandwidth statuses. Returns true if a line is found,
  2418. * false otherwise.
  2419. */
  2420. STATIC int
  2421. measured_bw_line_apply(measured_bw_line_t *parsed_line,
  2422. smartlist_t *routerstatuses)
  2423. {
  2424. vote_routerstatus_t *rs = NULL;
  2425. if (!routerstatuses)
  2426. return 0;
  2427. rs = smartlist_bsearch(routerstatuses, parsed_line->node_id,
  2428. compare_digest_to_vote_routerstatus_entry);
  2429. if (rs) {
  2430. rs->has_measured_bw = 1;
  2431. rs->measured_bw_kb = (uint32_t)parsed_line->bw_kb;
  2432. } else {
  2433. log_info(LD_DIRSERV, "Node ID %s not found in routerstatus list",
  2434. parsed_line->node_hex);
  2435. }
  2436. return rs != NULL;
  2437. }
  2438. /**
  2439. * Read the measured bandwidth file and apply it to the list of
  2440. * vote_routerstatus_t. Returns -1 on error, 0 otherwise.
  2441. */
  2442. int
  2443. dirserv_read_measured_bandwidths(const char *from_file,
  2444. smartlist_t *routerstatuses)
  2445. {
  2446. char line[256];
  2447. FILE *fp = tor_fopen_cloexec(from_file, "r");
  2448. int applied_lines = 0;
  2449. time_t file_time, now;
  2450. int ok;
  2451. if (fp == NULL) {
  2452. log_warn(LD_CONFIG, "Can't open bandwidth file at configured location: %s",
  2453. from_file);
  2454. return -1;
  2455. }
  2456. if (!fgets(line, sizeof(line), fp)
  2457. || !strlen(line) || line[strlen(line)-1] != '\n') {
  2458. log_warn(LD_DIRSERV, "Long or truncated time in bandwidth file: %s",
  2459. escaped(line));
  2460. fclose(fp);
  2461. return -1;
  2462. }
  2463. line[strlen(line)-1] = '\0';
  2464. file_time = tor_parse_ulong(line, 10, 0, ULONG_MAX, &ok, NULL);
  2465. if (!ok) {
  2466. log_warn(LD_DIRSERV, "Non-integer time in bandwidth file: %s",
  2467. escaped(line));
  2468. fclose(fp);
  2469. return -1;
  2470. }
  2471. now = time(NULL);
  2472. if ((now - file_time) > MAX_MEASUREMENT_AGE) {
  2473. log_warn(LD_DIRSERV, "Bandwidth measurement file stale. Age: %u",
  2474. (unsigned)(time(NULL) - file_time));
  2475. fclose(fp);
  2476. return -1;
  2477. }
  2478. if (routerstatuses)
  2479. smartlist_sort(routerstatuses, compare_vote_routerstatus_entries);
  2480. while (!feof(fp)) {
  2481. measured_bw_line_t parsed_line;
  2482. if (fgets(line, sizeof(line), fp) && strlen(line)) {
  2483. if (measured_bw_line_parse(&parsed_line, line) != -1) {
  2484. /* Also cache the line for dirserv_get_bandwidth_for_router() */
  2485. dirserv_cache_measured_bw(&parsed_line, file_time);
  2486. if (measured_bw_line_apply(&parsed_line, routerstatuses) > 0)
  2487. applied_lines++;
  2488. }
  2489. }
  2490. }
  2491. /* Now would be a nice time to clean the cache, too */
  2492. dirserv_expire_measured_bw_cache(now);
  2493. fclose(fp);
  2494. log_info(LD_DIRSERV,
  2495. "Bandwidth measurement file successfully read. "
  2496. "Applied %d measurements.", applied_lines);
  2497. return 0;
  2498. }
  2499. /** Return a new networkstatus_t* containing our current opinion. (For v3
  2500. * authorities) */
  2501. networkstatus_t *
  2502. dirserv_generate_networkstatus_vote_obj(crypto_pk_t *private_key,
  2503. authority_cert_t *cert)
  2504. {
  2505. const or_options_t *options = get_options();
  2506. networkstatus_t *v3_out = NULL;
  2507. uint32_t addr;
  2508. char *hostname = NULL, *client_versions = NULL, *server_versions = NULL;
  2509. const char *contact;
  2510. smartlist_t *routers, *routerstatuses;
  2511. char identity_digest[DIGEST_LEN];
  2512. char signing_key_digest[DIGEST_LEN];
  2513. int naming = options->NamingAuthoritativeDir;
  2514. int listbadexits = options->AuthDirListBadExits;
  2515. int listbaddirs = options->AuthDirListBadDirs;
  2516. int vote_on_hsdirs = options->VoteOnHidServDirectoriesV2;
  2517. routerlist_t *rl = router_get_routerlist();
  2518. time_t now = time(NULL);
  2519. time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
  2520. networkstatus_voter_info_t *voter = NULL;
  2521. vote_timing_t timing;
  2522. digestmap_t *omit_as_sybil = NULL;
  2523. const int vote_on_reachability = running_long_enough_to_decide_unreachable();
  2524. smartlist_t *microdescriptors = NULL;
  2525. tor_assert(private_key);
  2526. tor_assert(cert);
  2527. if (resolve_my_address(LOG_WARN, options, &addr, NULL, &hostname)<0) {
  2528. log_warn(LD_NET, "Couldn't resolve my hostname");
  2529. return NULL;
  2530. }
  2531. if (!hostname || !strchr(hostname, '.')) {
  2532. tor_free(hostname);
  2533. hostname = tor_dup_ip(addr);
  2534. }
  2535. if (crypto_pk_get_digest(private_key, signing_key_digest)<0) {
  2536. log_err(LD_BUG, "Error computing signing key digest");
  2537. return NULL;
  2538. }
  2539. if (crypto_pk_get_digest(cert->identity_key, identity_digest)<0) {
  2540. log_err(LD_BUG, "Error computing identity key digest");
  2541. return NULL;
  2542. }
  2543. if (options->VersioningAuthoritativeDir) {
  2544. client_versions = format_versions_list(options->RecommendedClientVersions);
  2545. server_versions = format_versions_list(options->RecommendedServerVersions);
  2546. }
  2547. contact = get_options()->ContactInfo;
  2548. if (!contact)
  2549. contact = "(none)";
  2550. /*
  2551. * Do this so dirserv_compute_performance_thresholds() and
  2552. * set_routerstatus_from_routerinfo() see up-to-date bandwidth info.
  2553. */
  2554. if (options->V3BandwidthsFile) {
  2555. dirserv_read_measured_bandwidths(options->V3BandwidthsFile, NULL);
  2556. } else {
  2557. /*
  2558. * No bandwidths file; clear the measured bandwidth cache in case we had
  2559. * one last time around.
  2560. */
  2561. if (dirserv_get_measured_bw_cache_size() > 0) {
  2562. dirserv_clear_measured_bw_cache();
  2563. }
  2564. }
  2565. /* precompute this part, since we need it to decide what "stable"
  2566. * means. */
  2567. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
  2568. dirserv_set_router_is_running(ri, now);
  2569. });
  2570. routers = smartlist_new();
  2571. smartlist_add_all(routers, rl->routers);
  2572. routers_sort_by_identity(routers);
  2573. omit_as_sybil = get_possible_sybil_list(routers);
  2574. DIGESTMAP_FOREACH(omit_as_sybil, sybil_id, void *, ignore) {
  2575. (void) ignore;
  2576. rep_hist_make_router_pessimal(sybil_id, now);
  2577. } DIGESTMAP_FOREACH_END;
  2578. /* Count how many have measured bandwidths so we know how to assign flags;
  2579. * this must come before dirserv_compute_performance_thresholds() */
  2580. dirserv_count_measured_bws(rl);
  2581. dirserv_compute_performance_thresholds(rl, omit_as_sybil);
  2582. routerstatuses = smartlist_new();
  2583. microdescriptors = smartlist_new();
  2584. SMARTLIST_FOREACH_BEGIN(routers, routerinfo_t *, ri) {
  2585. if (ri->cache_info.published_on >= cutoff) {
  2586. routerstatus_t *rs;
  2587. vote_routerstatus_t *vrs;
  2588. node_t *node = node_get_mutable_by_id(ri->cache_info.identity_digest);
  2589. if (!node)
  2590. continue;
  2591. vrs = tor_malloc_zero(sizeof(vote_routerstatus_t));
  2592. rs = &vrs->status;
  2593. set_routerstatus_from_routerinfo(rs, node, ri, now,
  2594. naming, listbadexits, listbaddirs,
  2595. vote_on_hsdirs);
  2596. if (digestmap_get(omit_as_sybil, ri->cache_info.identity_digest))
  2597. clear_status_flags_on_sybil(rs);
  2598. if (!vote_on_reachability)
  2599. rs->is_flagged_running = 0;
  2600. vrs->version = version_from_platform(ri->platform);
  2601. vrs->microdesc = dirvote_format_all_microdesc_vote_lines(ri, now,
  2602. microdescriptors);
  2603. smartlist_add(routerstatuses, vrs);
  2604. }
  2605. } SMARTLIST_FOREACH_END(ri);
  2606. {
  2607. smartlist_t *added =
  2608. microdescs_add_list_to_cache(get_microdesc_cache(),
  2609. microdescriptors, SAVED_NOWHERE, 0);
  2610. smartlist_free(added);
  2611. smartlist_free(microdescriptors);
  2612. }
  2613. smartlist_free(routers);
  2614. digestmap_free(omit_as_sybil, NULL);
  2615. /* This pass through applies the measured bw lines to the routerstatuses */
  2616. if (options->V3BandwidthsFile) {
  2617. dirserv_read_measured_bandwidths(options->V3BandwidthsFile,
  2618. routerstatuses);
  2619. } else {
  2620. /*
  2621. * No bandwidths file; clear the measured bandwidth cache in case we had
  2622. * one last time around.
  2623. */
  2624. if (dirserv_get_measured_bw_cache_size() > 0) {
  2625. dirserv_clear_measured_bw_cache();
  2626. }
  2627. }
  2628. v3_out = tor_malloc_zero(sizeof(networkstatus_t));
  2629. v3_out->type = NS_TYPE_VOTE;
  2630. dirvote_get_preferred_voting_intervals(&timing);
  2631. v3_out->published = now;
  2632. {
  2633. char tbuf[ISO_TIME_LEN+1];
  2634. networkstatus_t *current_consensus =
  2635. networkstatus_get_live_consensus(now);
  2636. long last_consensus_interval; /* only used to pick a valid_after */
  2637. if (current_consensus)
  2638. last_consensus_interval = current_consensus->fresh_until -
  2639. current_consensus->valid_after;
  2640. else
  2641. last_consensus_interval = options->TestingV3AuthInitialVotingInterval;
  2642. v3_out->valid_after =
  2643. dirvote_get_start_of_next_interval(now, (int)last_consensus_interval,
  2644. options->TestingV3AuthVotingStartOffset);
  2645. format_iso_time(tbuf, v3_out->valid_after);
  2646. log_notice(LD_DIR,"Choosing valid-after time in vote as %s: "
  2647. "consensus_set=%d, last_interval=%d",
  2648. tbuf, current_consensus?1:0, (int)last_consensus_interval);
  2649. }
  2650. v3_out->fresh_until = v3_out->valid_after + timing.vote_interval;
  2651. v3_out->valid_until = v3_out->valid_after +
  2652. (timing.vote_interval * timing.n_intervals_valid);
  2653. v3_out->vote_seconds = timing.vote_delay;
  2654. v3_out->dist_seconds = timing.dist_delay;
  2655. tor_assert(v3_out->vote_seconds > 0);
  2656. tor_assert(v3_out->dist_seconds > 0);
  2657. tor_assert(timing.n_intervals_valid > 0);
  2658. v3_out->client_versions = client_versions;
  2659. v3_out->server_versions = server_versions;
  2660. v3_out->known_flags = smartlist_new();
  2661. smartlist_split_string(v3_out->known_flags,
  2662. "Authority Exit Fast Guard Stable V2Dir Valid",
  2663. 0, SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  2664. if (vote_on_reachability)
  2665. smartlist_add(v3_out->known_flags, tor_strdup("Running"));
  2666. if (listbaddirs)
  2667. smartlist_add(v3_out->known_flags, tor_strdup("BadDirectory"));
  2668. if (listbadexits)
  2669. smartlist_add(v3_out->known_flags, tor_strdup("BadExit"));
  2670. if (naming) {
  2671. smartlist_add(v3_out->known_flags, tor_strdup("Named"));
  2672. smartlist_add(v3_out->known_flags, tor_strdup("Unnamed"));
  2673. }
  2674. if (vote_on_hsdirs)
  2675. smartlist_add(v3_out->known_flags, tor_strdup("HSDir"));
  2676. smartlist_sort_strings(v3_out->known_flags);
  2677. if (options->ConsensusParams) {
  2678. v3_out->net_params = smartlist_new();
  2679. smartlist_split_string(v3_out->net_params,
  2680. options->ConsensusParams, NULL, 0, 0);
  2681. smartlist_sort_strings(v3_out->net_params);
  2682. }
  2683. voter = tor_malloc_zero(sizeof(networkstatus_voter_info_t));
  2684. voter->nickname = tor_strdup(options->Nickname);
  2685. memcpy(voter->identity_digest, identity_digest, DIGEST_LEN);
  2686. voter->sigs = smartlist_new();
  2687. voter->address = hostname;
  2688. voter->addr = addr;
  2689. voter->dir_port = router_get_advertised_dir_port(options, 0);
  2690. voter->or_port = router_get_advertised_or_port(options);
  2691. voter->contact = tor_strdup(contact);
  2692. if (options->V3AuthUseLegacyKey) {
  2693. authority_cert_t *c = get_my_v3_legacy_cert();
  2694. if (c) {
  2695. if (crypto_pk_get_digest(c->identity_key, voter->legacy_id_digest)) {
  2696. log_warn(LD_BUG, "Unable to compute digest of legacy v3 identity key");
  2697. memset(voter->legacy_id_digest, 0, DIGEST_LEN);
  2698. }
  2699. }
  2700. }
  2701. v3_out->voters = smartlist_new();
  2702. smartlist_add(v3_out->voters, voter);
  2703. v3_out->cert = authority_cert_dup(cert);
  2704. v3_out->routerstatus_list = routerstatuses;
  2705. /* Note: networkstatus_digest is unset; it won't get set until we actually
  2706. * format the vote. */
  2707. return v3_out;
  2708. }
  2709. /** As dirserv_get_routerdescs(), but instead of getting signed_descriptor_t
  2710. * pointers, adds copies of digests to fps_out, and doesn't use the
  2711. * /tor/server/ prefix. For a /d/ request, adds descriptor digests; for other
  2712. * requests, adds identity digests.
  2713. */
  2714. int
  2715. dirserv_get_routerdesc_fingerprints(smartlist_t *fps_out, const char *key,
  2716. const char **msg, int for_unencrypted_conn,
  2717. int is_extrainfo)
  2718. {
  2719. int by_id = 1;
  2720. *msg = NULL;
  2721. if (!strcmp(key, "all")) {
  2722. routerlist_t *rl = router_get_routerlist();
  2723. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  2724. smartlist_add(fps_out,
  2725. tor_memdup(r->cache_info.identity_digest, DIGEST_LEN)));
  2726. /* Treat "all" requests as if they were unencrypted */
  2727. for_unencrypted_conn = 1;
  2728. } else if (!strcmp(key, "authority")) {
  2729. const routerinfo_t *ri = router_get_my_routerinfo();
  2730. if (ri)
  2731. smartlist_add(fps_out,
  2732. tor_memdup(ri->cache_info.identity_digest, DIGEST_LEN));
  2733. } else if (!strcmpstart(key, "d/")) {
  2734. by_id = 0;
  2735. key += strlen("d/");
  2736. dir_split_resource_into_fingerprints(key, fps_out, NULL,
  2737. DSR_HEX|DSR_SORT_UNIQ);
  2738. } else if (!strcmpstart(key, "fp/")) {
  2739. key += strlen("fp/");
  2740. dir_split_resource_into_fingerprints(key, fps_out, NULL,
  2741. DSR_HEX|DSR_SORT_UNIQ);
  2742. } else {
  2743. *msg = "Key not recognized";
  2744. return -1;
  2745. }
  2746. if (for_unencrypted_conn) {
  2747. /* Remove anything that insists it not be sent unencrypted. */
  2748. SMARTLIST_FOREACH_BEGIN(fps_out, char *, cp) {
  2749. const signed_descriptor_t *sd;
  2750. if (by_id)
  2751. sd = get_signed_descriptor_by_fp(cp,is_extrainfo,0);
  2752. else if (is_extrainfo)
  2753. sd = extrainfo_get_by_descriptor_digest(cp);
  2754. else
  2755. sd = router_get_by_descriptor_digest(cp);
  2756. if (sd && !sd->send_unencrypted) {
  2757. tor_free(cp);
  2758. SMARTLIST_DEL_CURRENT(fps_out, cp);
  2759. }
  2760. } SMARTLIST_FOREACH_END(cp);
  2761. }
  2762. if (!smartlist_len(fps_out)) {
  2763. *msg = "Servers unavailable";
  2764. return -1;
  2765. }
  2766. return 0;
  2767. }
  2768. /** Add a signed_descriptor_t to <b>descs_out</b> for each router matching
  2769. * <b>key</b>. The key should be either
  2770. * - "/tor/server/authority" for our own routerinfo;
  2771. * - "/tor/server/all" for all the routerinfos we have, concatenated;
  2772. * - "/tor/server/fp/FP" where FP is a plus-separated sequence of
  2773. * hex identity digests; or
  2774. * - "/tor/server/d/D" where D is a plus-separated sequence
  2775. * of server descriptor digests, in hex.
  2776. *
  2777. * Return 0 if we found some matching descriptors, or -1 if we do not
  2778. * have any descriptors, no matching descriptors, or if we did not
  2779. * recognize the key (URL).
  2780. * If -1 is returned *<b>msg</b> will be set to an appropriate error
  2781. * message.
  2782. *
  2783. * XXXX rename this function. It's only called from the controller.
  2784. * XXXX in fact, refactor this function, merging as much as possible.
  2785. */
  2786. int
  2787. dirserv_get_routerdescs(smartlist_t *descs_out, const char *key,
  2788. const char **msg)
  2789. {
  2790. *msg = NULL;
  2791. if (!strcmp(key, "/tor/server/all")) {
  2792. routerlist_t *rl = router_get_routerlist();
  2793. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  2794. smartlist_add(descs_out, &(r->cache_info)));
  2795. } else if (!strcmp(key, "/tor/server/authority")) {
  2796. const routerinfo_t *ri = router_get_my_routerinfo();
  2797. if (ri)
  2798. smartlist_add(descs_out, (void*) &(ri->cache_info));
  2799. } else if (!strcmpstart(key, "/tor/server/d/")) {
  2800. smartlist_t *digests = smartlist_new();
  2801. key += strlen("/tor/server/d/");
  2802. dir_split_resource_into_fingerprints(key, digests, NULL,
  2803. DSR_HEX|DSR_SORT_UNIQ);
  2804. SMARTLIST_FOREACH(digests, const char *, d,
  2805. {
  2806. signed_descriptor_t *sd = router_get_by_descriptor_digest(d);
  2807. if (sd)
  2808. smartlist_add(descs_out,sd);
  2809. });
  2810. SMARTLIST_FOREACH(digests, char *, d, tor_free(d));
  2811. smartlist_free(digests);
  2812. } else if (!strcmpstart(key, "/tor/server/fp/")) {
  2813. smartlist_t *digests = smartlist_new();
  2814. time_t cutoff = time(NULL) - ROUTER_MAX_AGE_TO_PUBLISH;
  2815. key += strlen("/tor/server/fp/");
  2816. dir_split_resource_into_fingerprints(key, digests, NULL,
  2817. DSR_HEX|DSR_SORT_UNIQ);
  2818. SMARTLIST_FOREACH_BEGIN(digests, const char *, d) {
  2819. if (router_digest_is_me(d)) {
  2820. /* make sure desc_routerinfo exists */
  2821. const routerinfo_t *ri = router_get_my_routerinfo();
  2822. if (ri)
  2823. smartlist_add(descs_out, (void*) &(ri->cache_info));
  2824. } else {
  2825. const routerinfo_t *ri = router_get_by_id_digest(d);
  2826. /* Don't actually serve a descriptor that everyone will think is
  2827. * expired. This is an (ugly) workaround to keep buggy 0.1.1.10
  2828. * Tors from downloading descriptors that they will throw away.
  2829. */
  2830. if (ri && ri->cache_info.published_on > cutoff)
  2831. smartlist_add(descs_out, (void*) &(ri->cache_info));
  2832. }
  2833. } SMARTLIST_FOREACH_END(d);
  2834. SMARTLIST_FOREACH(digests, char *, d, tor_free(d));
  2835. smartlist_free(digests);
  2836. } else {
  2837. *msg = "Key not recognized";
  2838. return -1;
  2839. }
  2840. if (!smartlist_len(descs_out)) {
  2841. *msg = "Servers unavailable";
  2842. return -1;
  2843. }
  2844. return 0;
  2845. }
  2846. /** Called when a TLS handshake has completed successfully with a
  2847. * router listening at <b>address</b>:<b>or_port</b>, and has yielded
  2848. * a certificate with digest <b>digest_rcvd</b>.
  2849. *
  2850. * Inform the reachability checker that we could get to this guy.
  2851. */
  2852. void
  2853. dirserv_orconn_tls_done(const tor_addr_t *addr,
  2854. uint16_t or_port,
  2855. const char *digest_rcvd)
  2856. {
  2857. node_t *node = NULL;
  2858. tor_addr_port_t orport;
  2859. routerinfo_t *ri = NULL;
  2860. time_t now = time(NULL);
  2861. tor_assert(addr);
  2862. tor_assert(digest_rcvd);
  2863. node = node_get_mutable_by_id(digest_rcvd);
  2864. if (node == NULL || node->ri == NULL)
  2865. return;
  2866. ri = node->ri;
  2867. tor_addr_copy(&orport.addr, addr);
  2868. orport.port = or_port;
  2869. if (router_has_orport(ri, &orport)) {
  2870. /* Found the right router. */
  2871. if (!authdir_mode_bridge(get_options()) ||
  2872. ri->purpose == ROUTER_PURPOSE_BRIDGE) {
  2873. char addrstr[TOR_ADDR_BUF_LEN];
  2874. /* This is a bridge or we're not a bridge authorititative --
  2875. mark it as reachable. */
  2876. log_info(LD_DIRSERV, "Found router %s to be reachable at %s:%d. Yay.",
  2877. router_describe(ri),
  2878. tor_addr_to_str(addrstr, addr, sizeof(addrstr), 1),
  2879. ri->or_port);
  2880. if (tor_addr_family(addr) == AF_INET) {
  2881. rep_hist_note_router_reachable(digest_rcvd, addr, or_port, now);
  2882. node->last_reachable = now;
  2883. } else if (tor_addr_family(addr) == AF_INET6) {
  2884. /* No rephist for IPv6. */
  2885. node->last_reachable6 = now;
  2886. }
  2887. }
  2888. }
  2889. }
  2890. /** Called when we, as an authority, receive a new router descriptor either as
  2891. * an upload or a download. Used to decide whether to relaunch reachability
  2892. * testing for the server. */
  2893. int
  2894. dirserv_should_launch_reachability_test(const routerinfo_t *ri,
  2895. const routerinfo_t *ri_old)
  2896. {
  2897. if (!authdir_mode_handles_descs(get_options(), ri->purpose))
  2898. return 0;
  2899. if (!ri_old) {
  2900. /* New router: Launch an immediate reachability test, so we will have an
  2901. * opinion soon in case we're generating a consensus soon */
  2902. return 1;
  2903. }
  2904. if (ri_old->is_hibernating && !ri->is_hibernating) {
  2905. /* It just came out of hibernation; launch a reachability test */
  2906. return 1;
  2907. }
  2908. if (! routers_have_same_or_addrs(ri, ri_old)) {
  2909. /* Address or port changed; launch a reachability test */
  2910. return 1;
  2911. }
  2912. return 0;
  2913. }
  2914. /** Helper function for dirserv_test_reachability(). Start a TLS
  2915. * connection to <b>router</b>, and annotate it with when we started
  2916. * the test. */
  2917. void
  2918. dirserv_single_reachability_test(time_t now, routerinfo_t *router)
  2919. {
  2920. channel_t *chan = NULL;
  2921. node_t *node = NULL;
  2922. tor_addr_t router_addr;
  2923. (void) now;
  2924. tor_assert(router);
  2925. node = node_get_mutable_by_id(router->cache_info.identity_digest);
  2926. tor_assert(node);
  2927. /* IPv4. */
  2928. log_debug(LD_OR,"Testing reachability of %s at %s:%u.",
  2929. router->nickname, fmt_addr32(router->addr), router->or_port);
  2930. tor_addr_from_ipv4h(&router_addr, router->addr);
  2931. chan = channel_tls_connect(&router_addr, router->or_port,
  2932. router->cache_info.identity_digest);
  2933. if (chan) command_setup_channel(chan);
  2934. /* Possible IPv6. */
  2935. if (get_options()->AuthDirHasIPv6Connectivity == 1 &&
  2936. !tor_addr_is_null(&router->ipv6_addr)) {
  2937. char addrstr[TOR_ADDR_BUF_LEN];
  2938. log_debug(LD_OR, "Testing reachability of %s at %s:%u.",
  2939. router->nickname,
  2940. tor_addr_to_str(addrstr, &router->ipv6_addr, sizeof(addrstr), 1),
  2941. router->ipv6_orport);
  2942. chan = channel_tls_connect(&router->ipv6_addr, router->ipv6_orport,
  2943. router->cache_info.identity_digest);
  2944. if (chan) command_setup_channel(chan);
  2945. }
  2946. }
  2947. /** Auth dir server only: load balance such that we only
  2948. * try a few connections per call.
  2949. *
  2950. * The load balancing is such that if we get called once every ten
  2951. * seconds, we will cycle through all the tests in
  2952. * REACHABILITY_TEST_CYCLE_PERIOD seconds (a bit over 20 minutes).
  2953. */
  2954. void
  2955. dirserv_test_reachability(time_t now)
  2956. {
  2957. /* XXX decide what to do here; see or-talk thread "purging old router
  2958. * information, revocation." -NM
  2959. * We can't afford to mess with this in 0.1.2.x. The reason is that
  2960. * if we stop doing reachability tests on some of routerlist, then
  2961. * we'll for-sure think they're down, which may have unexpected
  2962. * effects in other parts of the code. It doesn't hurt much to do
  2963. * the testing, and directory authorities are easy to upgrade. Let's
  2964. * wait til 0.2.0. -RD */
  2965. // time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
  2966. routerlist_t *rl = router_get_routerlist();
  2967. static char ctr = 0;
  2968. int bridge_auth = authdir_mode_bridge(get_options());
  2969. SMARTLIST_FOREACH_BEGIN(rl->routers, routerinfo_t *, router) {
  2970. const char *id_digest = router->cache_info.identity_digest;
  2971. if (router_is_me(router))
  2972. continue;
  2973. if (bridge_auth && router->purpose != ROUTER_PURPOSE_BRIDGE)
  2974. continue; /* bridge authorities only test reachability on bridges */
  2975. // if (router->cache_info.published_on > cutoff)
  2976. // continue;
  2977. if ((((uint8_t)id_digest[0]) % REACHABILITY_MODULO_PER_TEST) == ctr) {
  2978. dirserv_single_reachability_test(now, router);
  2979. }
  2980. } SMARTLIST_FOREACH_END(router);
  2981. ctr = (ctr + 1) % REACHABILITY_MODULO_PER_TEST; /* increment ctr */
  2982. }
  2983. /** Given a fingerprint <b>fp</b> which is either set if we're looking for a
  2984. * v2 status, or zeroes if we're looking for a v3 status, or a NUL-padded
  2985. * flavor name if we want a flavored v3 status, return a pointer to the
  2986. * appropriate cached dir object, or NULL if there isn't one available. */
  2987. static cached_dir_t *
  2988. lookup_cached_dir_by_fp(const char *fp)
  2989. {
  2990. cached_dir_t *d = NULL;
  2991. if (tor_digest_is_zero(fp) && cached_consensuses) {
  2992. d = strmap_get(cached_consensuses, "ns");
  2993. } else if (memchr(fp, '\0', DIGEST_LEN) && cached_consensuses &&
  2994. (d = strmap_get(cached_consensuses, fp))) {
  2995. /* this here interface is a nasty hack XXXX024 */;
  2996. }
  2997. return d;
  2998. }
  2999. /** Remove from <b>fps</b> every networkstatus key where both
  3000. * a) we have a networkstatus document and
  3001. * b) it is not newer than <b>cutoff</b>.
  3002. *
  3003. * Return 1 if any items were present at all; else return 0.
  3004. */
  3005. int
  3006. dirserv_remove_old_statuses(smartlist_t *fps, time_t cutoff)
  3007. {
  3008. int found_any = 0;
  3009. SMARTLIST_FOREACH_BEGIN(fps, char *, digest) {
  3010. cached_dir_t *d = lookup_cached_dir_by_fp(digest);
  3011. if (!d)
  3012. continue;
  3013. found_any = 1;
  3014. if (d->published <= cutoff) {
  3015. tor_free(digest);
  3016. SMARTLIST_DEL_CURRENT(fps, digest);
  3017. }
  3018. } SMARTLIST_FOREACH_END(digest);
  3019. return found_any;
  3020. }
  3021. /** Return the cache-info for identity fingerprint <b>fp</b>, or
  3022. * its extra-info document if <b>extrainfo</b> is true. Return
  3023. * NULL if not found or if the descriptor is older than
  3024. * <b>publish_cutoff</b>. */
  3025. static const signed_descriptor_t *
  3026. get_signed_descriptor_by_fp(const char *fp, int extrainfo,
  3027. time_t publish_cutoff)
  3028. {
  3029. if (router_digest_is_me(fp)) {
  3030. if (extrainfo)
  3031. return &(router_get_my_extrainfo()->cache_info);
  3032. else
  3033. return &(router_get_my_routerinfo()->cache_info);
  3034. } else {
  3035. const routerinfo_t *ri = router_get_by_id_digest(fp);
  3036. if (ri &&
  3037. ri->cache_info.published_on > publish_cutoff) {
  3038. if (extrainfo)
  3039. return extrainfo_get_by_descriptor_digest(
  3040. ri->cache_info.extra_info_digest);
  3041. else
  3042. return &ri->cache_info;
  3043. }
  3044. }
  3045. return NULL;
  3046. }
  3047. /** Return true iff we have any of the documents (extrainfo or routerdesc)
  3048. * specified by the fingerprints in <b>fps</b> and <b>spool_src</b>. Used to
  3049. * decide whether to send a 404. */
  3050. int
  3051. dirserv_have_any_serverdesc(smartlist_t *fps, int spool_src)
  3052. {
  3053. time_t publish_cutoff = time(NULL)-ROUTER_MAX_AGE_TO_PUBLISH;
  3054. SMARTLIST_FOREACH_BEGIN(fps, const char *, fp) {
  3055. switch (spool_src)
  3056. {
  3057. case DIR_SPOOL_EXTRA_BY_DIGEST:
  3058. if (extrainfo_get_by_descriptor_digest(fp)) return 1;
  3059. break;
  3060. case DIR_SPOOL_SERVER_BY_DIGEST:
  3061. if (router_get_by_descriptor_digest(fp)) return 1;
  3062. break;
  3063. case DIR_SPOOL_EXTRA_BY_FP:
  3064. case DIR_SPOOL_SERVER_BY_FP:
  3065. if (get_signed_descriptor_by_fp(fp,
  3066. spool_src == DIR_SPOOL_EXTRA_BY_FP, publish_cutoff))
  3067. return 1;
  3068. break;
  3069. }
  3070. } SMARTLIST_FOREACH_END(fp);
  3071. return 0;
  3072. }
  3073. /** Return true iff any of the 256-bit elements in <b>fps</b> is the digest of
  3074. * a microdescriptor we have. */
  3075. int
  3076. dirserv_have_any_microdesc(const smartlist_t *fps)
  3077. {
  3078. microdesc_cache_t *cache = get_microdesc_cache();
  3079. SMARTLIST_FOREACH(fps, const char *, fp,
  3080. if (microdesc_cache_lookup_by_digest256(cache, fp))
  3081. return 1);
  3082. return 0;
  3083. }
  3084. /** Return an approximate estimate of the number of bytes that will
  3085. * be needed to transmit the server descriptors (if is_serverdescs --
  3086. * they can be either d/ or fp/ queries) or networkstatus objects (if
  3087. * !is_serverdescs) listed in <b>fps</b>. If <b>compressed</b> is set,
  3088. * we guess how large the data will be after compression.
  3089. *
  3090. * The return value is an estimate; it might be larger or smaller.
  3091. **/
  3092. size_t
  3093. dirserv_estimate_data_size(smartlist_t *fps, int is_serverdescs,
  3094. int compressed)
  3095. {
  3096. size_t result;
  3097. tor_assert(fps);
  3098. if (is_serverdescs) {
  3099. int n = smartlist_len(fps);
  3100. const routerinfo_t *me = router_get_my_routerinfo();
  3101. result = (me?me->cache_info.signed_descriptor_len:2048) * n;
  3102. if (compressed)
  3103. result /= 2; /* observed compressibility is between 35 and 55%. */
  3104. } else {
  3105. result = 0;
  3106. SMARTLIST_FOREACH(fps, const char *, digest, {
  3107. cached_dir_t *dir = lookup_cached_dir_by_fp(digest);
  3108. if (dir)
  3109. result += compressed ? dir->dir_z_len : dir->dir_len;
  3110. });
  3111. }
  3112. return result;
  3113. }
  3114. /** Given a list of microdescriptor hashes, guess how many bytes will be
  3115. * needed to transmit them, and return the guess. */
  3116. size_t
  3117. dirserv_estimate_microdesc_size(const smartlist_t *fps, int compressed)
  3118. {
  3119. size_t result = smartlist_len(fps) * microdesc_average_size(NULL);
  3120. if (compressed)
  3121. result /= 2;
  3122. return result;
  3123. }
  3124. /** When we're spooling data onto our outbuf, add more whenever we dip
  3125. * below this threshold. */
  3126. #define DIRSERV_BUFFER_MIN 16384
  3127. /** Spooling helper: called when we have no more data to spool to <b>conn</b>.
  3128. * Flushes any remaining data to be (un)compressed, and changes the spool
  3129. * source to NONE. Returns 0 on success, negative on failure. */
  3130. static int
  3131. connection_dirserv_finish_spooling(dir_connection_t *conn)
  3132. {
  3133. if (conn->zlib_state) {
  3134. connection_write_to_buf_zlib("", 0, conn, 1);
  3135. tor_zlib_free(conn->zlib_state);
  3136. conn->zlib_state = NULL;
  3137. }
  3138. conn->dir_spool_src = DIR_SPOOL_NONE;
  3139. return 0;
  3140. }
  3141. /** Spooling helper: called when we're sending a bunch of server descriptors,
  3142. * and the outbuf has become too empty. Pulls some entries from
  3143. * fingerprint_stack, and writes the corresponding servers onto outbuf. If we
  3144. * run out of entries, flushes the zlib state and sets the spool source to
  3145. * NONE. Returns 0 on success, negative on failure.
  3146. */
  3147. static int
  3148. connection_dirserv_add_servers_to_outbuf(dir_connection_t *conn)
  3149. {
  3150. int by_fp = (conn->dir_spool_src == DIR_SPOOL_SERVER_BY_FP ||
  3151. conn->dir_spool_src == DIR_SPOOL_EXTRA_BY_FP);
  3152. int extra = (conn->dir_spool_src == DIR_SPOOL_EXTRA_BY_FP ||
  3153. conn->dir_spool_src == DIR_SPOOL_EXTRA_BY_DIGEST);
  3154. time_t publish_cutoff = time(NULL)-ROUTER_MAX_AGE_TO_PUBLISH;
  3155. const or_options_t *options = get_options();
  3156. while (smartlist_len(conn->fingerprint_stack) &&
  3157. connection_get_outbuf_len(TO_CONN(conn)) < DIRSERV_BUFFER_MIN) {
  3158. const char *body;
  3159. char *fp = smartlist_pop_last(conn->fingerprint_stack);
  3160. const signed_descriptor_t *sd = NULL;
  3161. if (by_fp) {
  3162. sd = get_signed_descriptor_by_fp(fp, extra, publish_cutoff);
  3163. } else {
  3164. sd = extra ? extrainfo_get_by_descriptor_digest(fp)
  3165. : router_get_by_descriptor_digest(fp);
  3166. }
  3167. tor_free(fp);
  3168. if (!sd)
  3169. continue;
  3170. if (!connection_dir_is_encrypted(conn) && !sd->send_unencrypted) {
  3171. /* we did this check once before (so we could have an accurate size
  3172. * estimate and maybe send a 404 if somebody asked for only bridges on a
  3173. * connection), but we need to do it again in case a previously
  3174. * unknown bridge descriptor has shown up between then and now. */
  3175. continue;
  3176. }
  3177. /** If we are the bridge authority and the descriptor is a bridge
  3178. * descriptor, remember that we served this descriptor for desc stats. */
  3179. if (options->BridgeAuthoritativeDir && by_fp) {
  3180. const routerinfo_t *router =
  3181. router_get_by_id_digest(sd->identity_digest);
  3182. /* router can be NULL here when the bridge auth is asked for its own
  3183. * descriptor. */
  3184. if (router && router->purpose == ROUTER_PURPOSE_BRIDGE)
  3185. rep_hist_note_desc_served(sd->identity_digest);
  3186. }
  3187. body = signed_descriptor_get_body(sd);
  3188. if (conn->zlib_state) {
  3189. /* XXXX024 This 'last' business should actually happen on the last
  3190. * routerinfo, not on the last fingerprint. */
  3191. int last = ! smartlist_len(conn->fingerprint_stack);
  3192. connection_write_to_buf_zlib(body, sd->signed_descriptor_len, conn,
  3193. last);
  3194. if (last) {
  3195. tor_zlib_free(conn->zlib_state);
  3196. conn->zlib_state = NULL;
  3197. }
  3198. } else {
  3199. connection_write_to_buf(body,
  3200. sd->signed_descriptor_len,
  3201. TO_CONN(conn));
  3202. }
  3203. }
  3204. if (!smartlist_len(conn->fingerprint_stack)) {
  3205. /* We just wrote the last one; finish up. */
  3206. conn->dir_spool_src = DIR_SPOOL_NONE;
  3207. smartlist_free(conn->fingerprint_stack);
  3208. conn->fingerprint_stack = NULL;
  3209. }
  3210. return 0;
  3211. }
  3212. /** Spooling helper: called when we're sending a bunch of microdescriptors,
  3213. * and the outbuf has become too empty. Pulls some entries from
  3214. * fingerprint_stack, and writes the corresponding microdescs onto outbuf. If
  3215. * we run out of entries, flushes the zlib state and sets the spool source to
  3216. * NONE. Returns 0 on success, negative on failure.
  3217. */
  3218. static int
  3219. connection_dirserv_add_microdescs_to_outbuf(dir_connection_t *conn)
  3220. {
  3221. microdesc_cache_t *cache = get_microdesc_cache();
  3222. while (smartlist_len(conn->fingerprint_stack) &&
  3223. connection_get_outbuf_len(TO_CONN(conn)) < DIRSERV_BUFFER_MIN) {
  3224. char *fp256 = smartlist_pop_last(conn->fingerprint_stack);
  3225. microdesc_t *md = microdesc_cache_lookup_by_digest256(cache, fp256);
  3226. tor_free(fp256);
  3227. if (!md || !md->body)
  3228. continue;
  3229. if (conn->zlib_state) {
  3230. /* XXXX024 This 'last' business should actually happen on the last
  3231. * routerinfo, not on the last fingerprint. */
  3232. int last = !smartlist_len(conn->fingerprint_stack);
  3233. connection_write_to_buf_zlib(md->body, md->bodylen, conn, last);
  3234. if (last) {
  3235. tor_zlib_free(conn->zlib_state);
  3236. conn->zlib_state = NULL;
  3237. }
  3238. } else {
  3239. connection_write_to_buf(md->body, md->bodylen, TO_CONN(conn));
  3240. }
  3241. }
  3242. if (!smartlist_len(conn->fingerprint_stack)) {
  3243. conn->dir_spool_src = DIR_SPOOL_NONE;
  3244. smartlist_free(conn->fingerprint_stack);
  3245. conn->fingerprint_stack = NULL;
  3246. }
  3247. return 0;
  3248. }
  3249. /** Spooling helper: Called when we're sending a directory or networkstatus,
  3250. * and the outbuf has become too empty. Pulls some bytes from
  3251. * <b>conn</b>-\>cached_dir-\>dir_z, uncompresses them if appropriate, and
  3252. * puts them on the outbuf. If we run out of entries, flushes the zlib state
  3253. * and sets the spool source to NONE. Returns 0 on success, negative on
  3254. * failure. */
  3255. static int
  3256. connection_dirserv_add_dir_bytes_to_outbuf(dir_connection_t *conn)
  3257. {
  3258. ssize_t bytes;
  3259. int64_t remaining;
  3260. bytes = DIRSERV_BUFFER_MIN - connection_get_outbuf_len(TO_CONN(conn));
  3261. tor_assert(bytes > 0);
  3262. tor_assert(conn->cached_dir);
  3263. if (bytes < 8192)
  3264. bytes = 8192;
  3265. remaining = conn->cached_dir->dir_z_len - conn->cached_dir_offset;
  3266. if (bytes > remaining)
  3267. bytes = (ssize_t) remaining;
  3268. if (conn->zlib_state) {
  3269. connection_write_to_buf_zlib(
  3270. conn->cached_dir->dir_z + conn->cached_dir_offset,
  3271. bytes, conn, bytes == remaining);
  3272. } else {
  3273. connection_write_to_buf(conn->cached_dir->dir_z + conn->cached_dir_offset,
  3274. bytes, TO_CONN(conn));
  3275. }
  3276. conn->cached_dir_offset += bytes;
  3277. if (conn->cached_dir_offset == (int)conn->cached_dir->dir_z_len) {
  3278. /* We just wrote the last one; finish up. */
  3279. connection_dirserv_finish_spooling(conn);
  3280. cached_dir_decref(conn->cached_dir);
  3281. conn->cached_dir = NULL;
  3282. }
  3283. return 0;
  3284. }
  3285. /** Spooling helper: Called when we're spooling networkstatus objects on
  3286. * <b>conn</b>, and the outbuf has become too empty. If the current
  3287. * networkstatus object (in <b>conn</b>-\>cached_dir) has more data, pull data
  3288. * from there. Otherwise, pop the next fingerprint from fingerprint_stack,
  3289. * and start spooling the next networkstatus. (A digest of all 0 bytes is
  3290. * treated as a request for the current consensus.) If we run out of entries,
  3291. * flushes the zlib state and sets the spool source to NONE. Returns 0 on
  3292. * success, negative on failure. */
  3293. static int
  3294. connection_dirserv_add_networkstatus_bytes_to_outbuf(dir_connection_t *conn)
  3295. {
  3296. while (connection_get_outbuf_len(TO_CONN(conn)) < DIRSERV_BUFFER_MIN) {
  3297. if (conn->cached_dir) {
  3298. int uncompressing = (conn->zlib_state != NULL);
  3299. int r = connection_dirserv_add_dir_bytes_to_outbuf(conn);
  3300. if (conn->dir_spool_src == DIR_SPOOL_NONE) {
  3301. /* add_dir_bytes thinks we're done with the cached_dir. But we
  3302. * may have more cached_dirs! */
  3303. conn->dir_spool_src = DIR_SPOOL_NETWORKSTATUS;
  3304. /* This bit is tricky. If we were uncompressing the last
  3305. * networkstatus, we may need to make a new zlib object to
  3306. * uncompress the next one. */
  3307. if (uncompressing && ! conn->zlib_state &&
  3308. conn->fingerprint_stack &&
  3309. smartlist_len(conn->fingerprint_stack)) {
  3310. conn->zlib_state = tor_zlib_new(0, ZLIB_METHOD);
  3311. }
  3312. }
  3313. if (r) return r;
  3314. } else if (conn->fingerprint_stack &&
  3315. smartlist_len(conn->fingerprint_stack)) {
  3316. /* Add another networkstatus; start serving it. */
  3317. char *fp = smartlist_pop_last(conn->fingerprint_stack);
  3318. cached_dir_t *d = lookup_cached_dir_by_fp(fp);
  3319. tor_free(fp);
  3320. if (d) {
  3321. ++d->refcnt;
  3322. conn->cached_dir = d;
  3323. conn->cached_dir_offset = 0;
  3324. }
  3325. } else {
  3326. connection_dirserv_finish_spooling(conn);
  3327. smartlist_free(conn->fingerprint_stack);
  3328. conn->fingerprint_stack = NULL;
  3329. return 0;
  3330. }
  3331. }
  3332. return 0;
  3333. }
  3334. /** Called whenever we have flushed some directory data in state
  3335. * SERVER_WRITING. */
  3336. int
  3337. connection_dirserv_flushed_some(dir_connection_t *conn)
  3338. {
  3339. tor_assert(conn->base_.state == DIR_CONN_STATE_SERVER_WRITING);
  3340. if (connection_get_outbuf_len(TO_CONN(conn)) >= DIRSERV_BUFFER_MIN)
  3341. return 0;
  3342. switch (conn->dir_spool_src) {
  3343. case DIR_SPOOL_EXTRA_BY_DIGEST:
  3344. case DIR_SPOOL_EXTRA_BY_FP:
  3345. case DIR_SPOOL_SERVER_BY_DIGEST:
  3346. case DIR_SPOOL_SERVER_BY_FP:
  3347. return connection_dirserv_add_servers_to_outbuf(conn);
  3348. case DIR_SPOOL_MICRODESC:
  3349. return connection_dirserv_add_microdescs_to_outbuf(conn);
  3350. case DIR_SPOOL_CACHED_DIR:
  3351. return connection_dirserv_add_dir_bytes_to_outbuf(conn);
  3352. case DIR_SPOOL_NETWORKSTATUS:
  3353. return connection_dirserv_add_networkstatus_bytes_to_outbuf(conn);
  3354. case DIR_SPOOL_NONE:
  3355. default:
  3356. return 0;
  3357. }
  3358. }
  3359. /** Release all storage used by the directory server. */
  3360. void
  3361. dirserv_free_all(void)
  3362. {
  3363. dirserv_free_fingerprint_list();
  3364. cached_dir_decref(the_directory);
  3365. clear_cached_dir(&the_runningrouters);
  3366. cached_dir_decref(cached_directory);
  3367. clear_cached_dir(&cached_runningrouters);
  3368. strmap_free(cached_consensuses, free_cached_dir_);
  3369. cached_consensuses = NULL;
  3370. dirserv_clear_measured_bw_cache();
  3371. }