dirserv.c 110 KB

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