dirserv.c 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246
  1. /* Copyright 2001-2004 Roger Dingledine.
  2. * Copyright 2004-2007 Roger Dingledine, Nick Mathewson. */
  3. /* See LICENSE for licensing information */
  4. /* $Id$ */
  5. const char dirserv_c_id[] =
  6. "$Id$";
  7. #include "or.h"
  8. /**
  9. * \file dirserv.c
  10. * \brief Directory server core implementation. Manages directory
  11. * contents and generates directories.
  12. **/
  13. /** How far in the future do we allow a router to get? (seconds) */
  14. #define ROUTER_ALLOW_SKEW (60*60*12)
  15. /** How many seconds do we wait before regenerating the directory? */
  16. #define DIR_REGEN_SLACK_TIME 30
  17. /** If we're a cache, keep this many networkstatuses around from non-trusted
  18. * directory authorities. */
  19. #define MAX_UNTRUSTED_NETWORKSTATUSES 16
  20. /** If a v1 directory is older than this, discard it. */
  21. #define MAX_V1_DIRECTORY_AGE (30*24*60*60)
  22. /** If a v1 running-routers is older than this, discard it. */
  23. #define MAX_V1_RR_AGE (7*24*60*60)
  24. /** Do we need to regenerate the directory when someone asks for it? */
  25. static int the_directory_is_dirty = 1;
  26. static int runningrouters_is_dirty = 1;
  27. static int the_v2_networkstatus_is_dirty = 1;
  28. static void directory_remove_invalid(void);
  29. static cached_dir_t *dirserv_regenerate_directory(void);
  30. static char *format_versions_list(config_line_t *ln);
  31. /* Should be static; exposed for testing */
  32. struct authdir_config_t;
  33. int add_fingerprint_to_dir(const char *nickname, const char *fp,
  34. struct authdir_config_t *list);
  35. static uint32_t dirserv_router_get_status(const routerinfo_t *router,
  36. const char **msg);
  37. static uint32_t
  38. dirserv_get_status_impl(const char *fp, const char *nickname,
  39. const char *address,
  40. uint32_t addr, uint16_t or_port,
  41. const char *platform, const char *contact,
  42. const char **msg, int should_log);
  43. static int dirserv_thinks_router_is_reachable(routerinfo_t *router,
  44. time_t now);
  45. static void clear_cached_dir(cached_dir_t *d);
  46. /************** Fingerprint handling code ************/
  47. #define FP_NAMED 1 /**< Listed in fingerprint file. */
  48. #define FP_INVALID 2 /**< Believed invalid. */
  49. #define FP_REJECT 4 /**< We will not publish this router. */
  50. #define FP_BADEXIT 8 /**< We'll tell clients not to use this as an exit. */
  51. /** Encapsulate a nickname and an FP_* status; target of status_by_digest
  52. * map. */
  53. typedef struct router_status_t {
  54. char nickname[MAX_NICKNAME_LEN+1];
  55. uint32_t status;
  56. } router_status_t;
  57. /** List of nickname-\>identity fingerprint mappings for all the routers
  58. * that we name. Used to prevent router impersonation. */
  59. typedef struct authdir_config_t {
  60. strmap_t *fp_by_name; /**< Map from lc nickname to fingerprint. */
  61. digestmap_t *status_by_digest; /**< Map from digest to router_status_t. */
  62. } authdir_config_t;
  63. /** Should be static; exposed for testing. */
  64. authdir_config_t *fingerprint_list = NULL;
  65. /** Allocate and return a new, empty, authdir_config_t. */
  66. static authdir_config_t *
  67. authdir_config_new(void)
  68. {
  69. authdir_config_t *list = tor_malloc_zero(sizeof(authdir_config_t));
  70. list->fp_by_name = strmap_new();
  71. list->status_by_digest = digestmap_new();
  72. return list;
  73. }
  74. /** Add the fingerprint <b>fp</b> for the nickname <b>nickname</b> to
  75. * the smartlist of fingerprint_entry_t's <b>list</b>. Return 0 if it's
  76. * new, or 1 if we replaced the old value.
  77. */
  78. int /* Should be static; exposed for testing */
  79. add_fingerprint_to_dir(const char *nickname, const char *fp,
  80. authdir_config_t *list)
  81. {
  82. char *fingerprint;
  83. char d[DIGEST_LEN];
  84. router_status_t *status;
  85. tor_assert(nickname);
  86. tor_assert(fp);
  87. tor_assert(list);
  88. fingerprint = tor_strdup(fp);
  89. tor_strstrip(fingerprint, " ");
  90. if (base16_decode(d, DIGEST_LEN, fingerprint, strlen(fingerprint))) {
  91. log_warn(LD_DIRSERV, "Couldn't decode fingerprint \"%s\"",
  92. escaped(fp));
  93. tor_free(fingerprint);
  94. return 0;
  95. }
  96. if (!strcasecmp(nickname, UNNAMED_ROUTER_NICKNAME)) {
  97. log_warn(LD_DIRSERV, "Tried to add a mapping for reserved nickname %s",
  98. UNNAMED_ROUTER_NICKNAME);
  99. tor_free(fingerprint);
  100. return 0;
  101. }
  102. status = digestmap_get(list->status_by_digest, d);
  103. if (!status) {
  104. status = tor_malloc_zero(sizeof(router_status_t));
  105. digestmap_set(list->status_by_digest, d, status);
  106. }
  107. if (nickname[0] != '!') {
  108. char *old_fp = strmap_get_lc(list->fp_by_name, nickname);
  109. if (old_fp && !strcasecmp(fingerprint, old_fp)) {
  110. tor_free(fingerprint);
  111. } else {
  112. tor_free(old_fp);
  113. strmap_set_lc(list->fp_by_name, nickname, fingerprint);
  114. }
  115. status->status |= FP_NAMED;
  116. strlcpy(status->nickname, nickname, sizeof(status->nickname));
  117. } else {
  118. tor_free(fingerprint);
  119. if (!strcasecmp(nickname, "!reject")) {
  120. status->status |= FP_REJECT;
  121. } else if (!strcasecmp(nickname, "!invalid")) {
  122. status->status |= FP_INVALID;
  123. } else if (!strcasecmp(nickname, "!badexit")) {
  124. status->status |= FP_BADEXIT;
  125. }
  126. }
  127. return 0;
  128. }
  129. /** Add the nickname and fingerprint for this OR to the
  130. * global list of recognized identity key fingerprints. */
  131. int
  132. dirserv_add_own_fingerprint(const char *nickname, crypto_pk_env_t *pk)
  133. {
  134. char fp[FINGERPRINT_LEN+1];
  135. if (crypto_pk_get_fingerprint(pk, fp, 0)<0) {
  136. log_err(LD_BUG, "Error computing fingerprint");
  137. return -1;
  138. }
  139. if (!fingerprint_list)
  140. fingerprint_list = authdir_config_new();
  141. add_fingerprint_to_dir(nickname, fp, fingerprint_list);
  142. return 0;
  143. }
  144. /** Load the nickname-\>fingerprint mappings stored in the approved-routers
  145. * file. The file format is line-based, with each non-blank holding one
  146. * nickname, some space, and a fingerprint for that nickname. On success,
  147. * replace the current fingerprint list with the new list and return 0. On
  148. * failure, leave the current fingerprint list untouched, and
  149. * return -1. */
  150. int
  151. dirserv_load_fingerprint_file(void)
  152. {
  153. char fname[512];
  154. char *cf;
  155. char *nickname, *fingerprint;
  156. authdir_config_t *fingerprint_list_new;
  157. int result;
  158. config_line_t *front=NULL, *list;
  159. or_options_t *options = get_options();
  160. tor_snprintf(fname, sizeof(fname),
  161. "%s/approved-routers", options->DataDirectory);
  162. log_info(LD_GENERAL,
  163. "Reloading approved fingerprints from \"%s\"...", fname);
  164. cf = read_file_to_str(fname, 0, NULL);
  165. if (!cf) {
  166. if (options->NamingAuthoritativeDir) {
  167. log_warn(LD_FS, "Cannot open fingerprint file '%s'. Failing.", fname);
  168. return -1;
  169. } else {
  170. log_info(LD_FS, "Cannot open fingerprint file '%s'. Returning.", fname);
  171. return 0;
  172. }
  173. }
  174. result = config_get_lines(cf, &front);
  175. tor_free(cf);
  176. if (result < 0) {
  177. log_warn(LD_CONFIG, "Error reading from fingerprint file");
  178. return -1;
  179. }
  180. fingerprint_list_new = authdir_config_new();
  181. for (list=front; list; list=list->next) {
  182. nickname = list->key; fingerprint = list->value;
  183. if (strlen(nickname) > MAX_NICKNAME_LEN) {
  184. log_notice(LD_CONFIG,
  185. "Nickname '%s' too long in fingerprint file. Skipping.",
  186. nickname);
  187. continue;
  188. }
  189. if (!is_legal_nickname(nickname) &&
  190. strcasecmp(nickname, "!reject") &&
  191. strcasecmp(nickname, "!invalid") &&
  192. strcasecmp(nickname, "!badexit")) {
  193. log_notice(LD_CONFIG,
  194. "Invalid nickname '%s' in fingerprint file. Skipping.",
  195. nickname);
  196. continue;
  197. }
  198. if (strlen(fingerprint) != FINGERPRINT_LEN ||
  199. !crypto_pk_check_fingerprint_syntax(fingerprint)) {
  200. log_notice(LD_CONFIG,
  201. "Invalid fingerprint (nickname '%s', "
  202. "fingerprint %s). Skipping.",
  203. nickname, fingerprint);
  204. continue;
  205. }
  206. if (0==strcasecmp(nickname, DEFAULT_CLIENT_NICKNAME)) {
  207. /* If you approved an OR called "client", then clients who use
  208. * the default nickname could all be rejected. That's no good. */
  209. log_notice(LD_CONFIG,
  210. "Authorizing a nickname '%s' would break "
  211. "many clients; skipping.",
  212. DEFAULT_CLIENT_NICKNAME);
  213. continue;
  214. }
  215. if (0==strcasecmp(nickname, DEFAULT_CLIENT_NICKNAME)) {
  216. /* If you approved an OR called "client", then clients who use
  217. * the default nickname could all be rejected. That's no good. */
  218. log_notice(LD_CONFIG,
  219. "Authorizing a nickname '%s' would break "
  220. "many clients; skipping.",
  221. DEFAULT_CLIENT_NICKNAME);
  222. continue;
  223. }
  224. if (0==strcasecmp(nickname, UNNAMED_ROUTER_NICKNAME)) {
  225. /* If you approved an OR called "unnamed", then clients will be
  226. * confused. */
  227. log_notice(LD_CONFIG,
  228. "Authorizing a nickname '%s' is not allowed; skipping.",
  229. UNNAMED_ROUTER_NICKNAME);
  230. continue;
  231. }
  232. if (add_fingerprint_to_dir(nickname, fingerprint, fingerprint_list_new)
  233. != 0)
  234. log_notice(LD_CONFIG, "Duplicate nickname '%s'.", nickname);
  235. }
  236. config_free_lines(front);
  237. dirserv_free_fingerprint_list();
  238. fingerprint_list = fingerprint_list_new;
  239. /* Delete any routers whose fingerprints we no longer recognize */
  240. directory_remove_invalid();
  241. return 0;
  242. }
  243. /** Check whether <b>router</b> has a nickname/identity key combination that
  244. * we recognize from the fingerprint list, or an IP we automatically act on
  245. * according to our configuration. Return the appropriate router status.
  246. *
  247. * If the status is 'FP_REJECT' and <b>msg</b> is provided, set
  248. * *<b>msg</b> to an explanation of why. */
  249. static uint32_t
  250. dirserv_router_get_status(const routerinfo_t *router, const char **msg)
  251. {
  252. char d[DIGEST_LEN];
  253. if (crypto_pk_get_digest(router->identity_pkey, d)) {
  254. log_warn(LD_BUG,"Error computing fingerprint");
  255. if (msg)
  256. *msg = "Bug: Error computing fingerprint";
  257. return FP_REJECT;
  258. }
  259. return dirserv_get_status_impl(d, router->nickname,
  260. router->address,
  261. router->addr, router->or_port,
  262. router->platform, router->contact_info,
  263. msg, 1);
  264. }
  265. /** Return true if there is no point in downloading the router described by
  266. * <b>rs</b> because this directory would reject it. */
  267. int
  268. dirserv_would_reject_router(routerstatus_t *rs)
  269. {
  270. uint32_t res;
  271. res = dirserv_get_status_impl(rs->identity_digest, rs->nickname,
  272. "", /* address is only used in logs */
  273. rs->addr, rs->or_port,
  274. NULL, NULL,
  275. NULL, 0);
  276. return (res & FP_REJECT) != 0;
  277. }
  278. /** Helper: As dirserv_get_router_status, but takes the router fingerprint
  279. * (hex, no spaces), nickname, address (used for logging only), IP address, OR
  280. * port, platform (logging only) and contact info (logging only) as arguments.
  281. *
  282. * If should_log is false, do not log messages. (There's not much point in
  283. * logging that we're rejecting servers we'll not download.)
  284. */
  285. static uint32_t
  286. dirserv_get_status_impl(const char *id_digest, const char *nickname,
  287. const char *address,
  288. uint32_t addr, uint16_t or_port,
  289. const char *platform, const char *contact,
  290. const char **msg, int should_log)
  291. {
  292. char fp[HEX_DIGEST_LEN+1];
  293. int reject_unlisted = get_options()->AuthDirRejectUnlisted;
  294. uint32_t result = 0;
  295. router_status_t *status_by_digest;
  296. char *fp_by_name;
  297. if (!fingerprint_list)
  298. fingerprint_list = authdir_config_new();
  299. base16_encode(fp, sizeof(fp), id_digest, DIGEST_LEN);
  300. if (should_log)
  301. log_debug(LD_DIRSERV, "%d fingerprints, %d digests known.",
  302. strmap_size(fingerprint_list->fp_by_name),
  303. digestmap_size(fingerprint_list->status_by_digest));
  304. if ((fp_by_name =
  305. strmap_get_lc(fingerprint_list->fp_by_name, nickname))) {
  306. if (!strcasecmp(fp, fp_by_name)) {
  307. result |= FP_NAMED;
  308. if (should_log)
  309. log_debug(LD_DIRSERV,"Good fingerprint for '%s'",nickname);
  310. } else {
  311. if (should_log) {
  312. char *esc_contact = esc_for_log(contact);
  313. log_warn(LD_DIRSERV,
  314. "Mismatched fingerprint for '%s': expected '%s' got '%s'. "
  315. "ContactInfo '%s', platform '%s'.)",
  316. nickname, fp_by_name, fp,
  317. esc_contact,
  318. platform ? escaped(platform) : "");
  319. tor_free(esc_contact);
  320. }
  321. if (msg)
  322. *msg = "Rejected: There is already a named server with this nickname "
  323. "and a different fingerprint.";
  324. return FP_REJECT; /* Wrong fingerprint. */
  325. }
  326. }
  327. status_by_digest = digestmap_get(fingerprint_list->status_by_digest,
  328. id_digest);
  329. if (status_by_digest)
  330. result |= (status_by_digest->status & ~FP_NAMED);
  331. if (result & FP_REJECT) {
  332. if (msg)
  333. *msg = "Fingerprint is marked rejected";
  334. return FP_REJECT;
  335. } else if (result & FP_INVALID) {
  336. if (msg)
  337. *msg = "Fingerprint is marked invalid";
  338. }
  339. if (authdir_policy_badexit_address(addr, or_port)) {
  340. if (should_log)
  341. log_info(LD_DIRSERV, "Marking '%s' as bad exit because of address '%s'",
  342. nickname, address);
  343. result |= FP_BADEXIT;
  344. }
  345. if (!(result & FP_NAMED)) {
  346. if (!authdir_policy_permits_address(addr, or_port)) {
  347. if (should_log)
  348. log_info(LD_DIRSERV, "Rejecting '%s' because of address '%s'",
  349. nickname, address);
  350. if (msg)
  351. *msg = "Authdir is rejecting routers in this range.";
  352. return FP_REJECT;
  353. }
  354. if (!authdir_policy_valid_address(addr, or_port)) {
  355. if (should_log)
  356. log_info(LD_DIRSERV, "Not marking '%s' valid because of address '%s'",
  357. nickname, address);
  358. result |= FP_INVALID;
  359. }
  360. if (reject_unlisted) {
  361. if (msg)
  362. *msg = "Authdir rejects unknown routers.";
  363. return FP_REJECT;
  364. }
  365. /* 0.1.0.2-rc was the first version that did enough self-testing that
  366. * we're willing to take its word about whether it's running. */
  367. if (platform && !tor_version_as_new_as(platform,"0.1.0.2-rc"))
  368. result |= FP_INVALID;
  369. }
  370. return result;
  371. }
  372. /** If we are an authoritative dirserver, and the list of approved
  373. * servers contains one whose identity key digest is <b>digest</b>,
  374. * return that router's nickname. Otherwise return NULL. */
  375. const char *
  376. dirserv_get_nickname_by_digest(const char *digest)
  377. {
  378. router_status_t *status;
  379. if (!fingerprint_list)
  380. return NULL;
  381. tor_assert(digest);
  382. status = digestmap_get(fingerprint_list->status_by_digest, digest);
  383. return status ? status->nickname : NULL;
  384. }
  385. /** Clear the current fingerprint list. */
  386. void
  387. dirserv_free_fingerprint_list(void)
  388. {
  389. if (!fingerprint_list)
  390. return;
  391. strmap_free(fingerprint_list->fp_by_name, _tor_free);
  392. digestmap_free(fingerprint_list->status_by_digest, _tor_free);
  393. tor_free(fingerprint_list);
  394. }
  395. /*
  396. * Descriptor list
  397. */
  398. /** Return -1 if <b>ri</b> has a private or otherwise bad address,
  399. * unless we're configured to not care. Return 0 if all ok. */
  400. static int
  401. dirserv_router_has_valid_address(routerinfo_t *ri)
  402. {
  403. struct in_addr iaddr;
  404. if (get_options()->DirAllowPrivateAddresses)
  405. return 0; /* whatever it is, we're fine with it */
  406. if (!tor_inet_aton(ri->address, &iaddr)) {
  407. log_info(LD_DIRSERV,"Router '%s' published non-IP address '%s'. Refusing.",
  408. ri->nickname, ri->address);
  409. return -1;
  410. }
  411. if (is_internal_IP(ntohl(iaddr.s_addr), 0)) {
  412. log_info(LD_DIRSERV,
  413. "Router '%s' published internal IP address '%s'. Refusing.",
  414. ri->nickname, ri->address);
  415. return -1; /* it's a private IP, we should reject it */
  416. }
  417. return 0;
  418. }
  419. /** Check whether we, as a directory server, want to accept <b>ri</b>. If so,
  420. * set its is_valid,named,running fields and return 0. Otherwise, return -1.
  421. *
  422. * If the router is rejected, set *<b>msg</b> to an explanation of why.
  423. *
  424. * If <b>complain</b> then explain at log-level 'notice' why we refused
  425. * a descriptor; else explain at log-level 'info'.
  426. */
  427. int
  428. authdir_wants_to_reject_router(routerinfo_t *ri, const char **msg,
  429. int complain)
  430. {
  431. /* Okay. Now check whether the fingerprint is recognized. */
  432. uint32_t status = dirserv_router_get_status(ri, msg);
  433. time_t now;
  434. int severity = complain ? LOG_NOTICE : LOG_INFO;
  435. tor_assert(msg);
  436. if (status & FP_REJECT)
  437. return -1; /* msg is already set. */
  438. /* Is there too much clock skew? */
  439. now = time(NULL);
  440. if (ri->cache_info.published_on > now+ROUTER_ALLOW_SKEW) {
  441. log_fn(severity, LD_DIRSERV, "Publication time for nickname '%s' is too "
  442. "far (%d minutes) in the future; possible clock skew. Not adding "
  443. "(%s)",
  444. ri->nickname, (int)((ri->cache_info.published_on-now)/60),
  445. esc_router_info(ri));
  446. *msg = "Rejected: Your clock is set too far in the future, or your "
  447. "timezone is not correct.";
  448. return -1;
  449. }
  450. if (ri->cache_info.published_on < now-ROUTER_MAX_AGE_TO_PUBLISH) {
  451. log_fn(severity, LD_DIRSERV,
  452. "Publication time for router with nickname '%s' is too far "
  453. "(%d minutes) in the past. Not adding (%s)",
  454. ri->nickname, (int)((now-ri->cache_info.published_on)/60),
  455. esc_router_info(ri));
  456. *msg = "Rejected: Server is expired, or your clock is too far in the past,"
  457. " or your timezone is not correct.";
  458. return -1;
  459. }
  460. if (dirserv_router_has_valid_address(ri) < 0) {
  461. log_fn(severity, LD_DIRSERV,
  462. "Router with nickname '%s' has invalid address '%s'. "
  463. "Not adding (%s).",
  464. ri->nickname, ri->address,
  465. esc_router_info(ri));
  466. *msg = "Rejected: Address is not an IP, or IP is a private address.";
  467. return -1;
  468. }
  469. /* Okay, looks like we're willing to accept this one. */
  470. ri->is_named = (status & FP_NAMED) ? 1 : 0;
  471. ri->is_valid = (status & FP_INVALID) ? 0 : 1;
  472. ri->is_bad_exit = (status & FP_BADEXIT) ? 1 : 0;
  473. return 0;
  474. }
  475. /** Parse the server descriptor at <b>desc</b> and maybe insert it into
  476. * the list of server descriptors. Set *<b>msg</b> to a message that
  477. * should be passed back to the origin of this descriptor.
  478. *
  479. * Return 2 if descriptor is well-formed and accepted;
  480. * 1 if well-formed and accepted but origin should hear *msg;
  481. * 0 if well-formed but redundant with one we already have;
  482. * -1 if it looks vaguely like a router descriptor but rejected;
  483. * -2 if we can't find a router descriptor in <b>desc</b>.
  484. */
  485. int
  486. dirserv_add_descriptor(const char *desc, const char **msg)
  487. {
  488. int r;
  489. routerinfo_t *ri = NULL, *ri_old = NULL;
  490. tor_assert(msg);
  491. *msg = NULL;
  492. /* Check: is the descriptor syntactically valid? */
  493. ri = router_parse_entry_from_string(desc, NULL, 1);
  494. if (!ri) {
  495. log_warn(LD_DIRSERV, "Couldn't parse uploaded server descriptor");
  496. *msg = "Rejected: Couldn't parse server descriptor.";
  497. return -2;
  498. }
  499. /* Check whether this descriptor is semantically identical to the last one
  500. * from this server. (We do this here and not in router_add_to_routerlist
  501. * because we want to be able to accept the newest router descriptor that
  502. * another authority has, so we all converge on the same one.) */
  503. ri_old = router_get_by_digest(ri->cache_info.identity_digest);
  504. if (ri_old && ri_old->cache_info.published_on < ri->cache_info.published_on
  505. && router_differences_are_cosmetic(ri_old, ri)
  506. && !router_is_me(ri)) {
  507. log_info(LD_DIRSERV,
  508. "Not replacing descriptor from '%s'; differences are cosmetic.",
  509. ri->nickname);
  510. *msg = "Not replacing router descriptor; no information has changed since "
  511. "the last one with this identity.";
  512. routerinfo_free(ri);
  513. control_event_or_authdir_new_descriptor("DROPPED", desc, *msg);
  514. return 0;
  515. }
  516. if ((r = router_add_to_routerlist(ri, msg, 0, 0))<0) {
  517. if (r < -1) /* unless the routerinfo was fine, just out-of-date */
  518. control_event_or_authdir_new_descriptor("REJECTED", desc, *msg);
  519. return r == -1 ? 0 : -1;
  520. } else {
  521. smartlist_t *changed;
  522. control_event_or_authdir_new_descriptor("ACCEPTED", desc, *msg);
  523. changed = smartlist_create();
  524. smartlist_add(changed, ri);
  525. control_event_descriptors_changed(changed);
  526. smartlist_free(changed);
  527. if (!*msg) {
  528. *msg = ri->is_valid ? "Descriptor for valid server accepted" :
  529. "Descriptor for invalid server accepted";
  530. }
  531. return r == 0 ? 2 : 1;
  532. }
  533. }
  534. /** Remove all descriptors whose nicknames or fingerprints no longer
  535. * are allowed by our fingerprint list. (Descriptors that used to be
  536. * good can become bad when we reload the fingerprint list.)
  537. */
  538. static void
  539. directory_remove_invalid(void)
  540. {
  541. int i;
  542. int changed = 0;
  543. routerlist_t *rl = router_get_routerlist();
  544. for (i = 0; i < smartlist_len(rl->routers); ++i) {
  545. const char *msg;
  546. routerinfo_t *ent = smartlist_get(rl->routers, i);
  547. uint32_t r = dirserv_router_get_status(ent, &msg);
  548. if (r & FP_REJECT) {
  549. log_info(LD_DIRSERV, "Router '%s' is now rejected: %s",
  550. ent->nickname, msg?msg:"");
  551. routerlist_remove(rl, ent, i--, 0);
  552. changed = 1;
  553. }
  554. if (bool_neq((r & FP_NAMED), ent->is_named)) {
  555. log_info(LD_DIRSERV,
  556. "Router '%s' is now %snamed.", ent->nickname,
  557. (r&FP_NAMED)?"":"un");
  558. ent->is_named = (r&FP_NAMED)?1:0;
  559. changed = 1;
  560. }
  561. if (bool_neq((r & FP_INVALID), !ent->is_valid)) {
  562. log_info(LD_DIRSERV, "Router '%s' is now %svalid.", ent->nickname,
  563. (r&FP_INVALID) ? "in" : "");
  564. ent->is_valid = (r&FP_INVALID)?0:1;
  565. changed = 1;
  566. }
  567. if (bool_neq((r & FP_BADEXIT), ent->is_bad_exit)) {
  568. log_info(LD_DIRSERV, "Router '%s' is now a %s exit", ent->nickname,
  569. (r & FP_BADEXIT) ? "bad" : "good");
  570. ent->is_bad_exit = (r&FP_BADEXIT) ? 1: 0;
  571. changed = 1;
  572. }
  573. }
  574. if (changed)
  575. directory_set_dirty();
  576. }
  577. /** Write a list of unregistered descriptors into a newly allocated
  578. * string and return it. Used by dirserv operators to keep track of
  579. * fast nodes that haven't registered.
  580. */
  581. int
  582. getinfo_helper_dirserv_unregistered(control_connection_t *control_conn,
  583. const char *question, char **answer_out)
  584. {
  585. smartlist_t *answerlist;
  586. char buf[1024];
  587. char *answer;
  588. int min_bw = atoi(question);
  589. routerlist_t *rl = router_get_routerlist();
  590. (void) control_conn;
  591. if (strcmpstart(question, "unregistered-servers-"))
  592. return 0;
  593. question += strlen("unregistered-servers-");
  594. answerlist = smartlist_create();
  595. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ent, {
  596. uint32_t r = dirserv_router_get_status(ent, NULL);
  597. if (router_get_advertised_bandwidth(ent) >= (size_t)min_bw &&
  598. !(r & FP_NAMED)) {
  599. /* then log this one */
  600. tor_snprintf(buf, sizeof(buf),
  601. "%s: BW %d on '%s'.",
  602. ent->nickname, router_get_advertised_bandwidth(ent),
  603. ent->platform ? ent->platform : "");
  604. smartlist_add(answerlist, tor_strdup(buf));
  605. }
  606. });
  607. answer = smartlist_join_strings(answerlist, "\r\n", 0, NULL);
  608. SMARTLIST_FOREACH(answerlist, char *, cp, tor_free(cp));
  609. smartlist_free(answerlist);
  610. *answer_out = answer;
  611. return 0;
  612. }
  613. /** Mark the directory as <b>dirty</b> -- when we're next asked for a
  614. * directory, we will rebuild it instead of reusing the most recently
  615. * generated one.
  616. */
  617. void
  618. directory_set_dirty(void)
  619. {
  620. time_t now = time(NULL);
  621. if (!the_directory_is_dirty)
  622. the_directory_is_dirty = now;
  623. if (!runningrouters_is_dirty)
  624. runningrouters_is_dirty = now;
  625. if (!the_v2_networkstatus_is_dirty)
  626. the_v2_networkstatus_is_dirty = now;
  627. }
  628. /**
  629. * Allocate and return a description of the status of the server <b>desc</b>,
  630. * for use in a router-status line. The server is listed
  631. * as running iff <b>is_live</b> is true.
  632. */
  633. static char *
  634. list_single_server_status(routerinfo_t *desc, int is_live)
  635. {
  636. char buf[MAX_NICKNAME_LEN+HEX_DIGEST_LEN+4]; /* !nickname=$hexdigest\0 */
  637. char *cp;
  638. tor_assert(desc);
  639. cp = buf;
  640. if (!is_live) {
  641. *cp++ = '!';
  642. }
  643. if (desc->is_valid) {
  644. strlcpy(cp, desc->nickname, sizeof(buf)-(cp-buf));
  645. cp += strlen(cp);
  646. *cp++ = '=';
  647. }
  648. *cp++ = '$';
  649. base16_encode(cp, HEX_DIGEST_LEN+1, desc->cache_info.identity_digest,
  650. DIGEST_LEN);
  651. return tor_strdup(buf);
  652. }
  653. /** Each server needs to have passed a reachability test no more
  654. * than this number of seconds ago, or he is listed as down in
  655. * the directory. */
  656. #define REACHABLE_TIMEOUT (45*60)
  657. /** Treat a router as alive if
  658. * - It's me, and I'm not hibernating.
  659. * or - We've found it reachable recently. */
  660. static int
  661. dirserv_thinks_router_is_reachable(routerinfo_t *router, time_t now)
  662. {
  663. if (router_is_me(router) && !we_are_hibernating())
  664. return 1;
  665. return get_options()->AssumeReachable ||
  666. now < router->last_reachable + REACHABLE_TIMEOUT;
  667. }
  668. /** Return 1 if we're confident that there's a problem with
  669. * <b>router</b>'s reachability and its operator should be notified.
  670. */
  671. int
  672. dirserv_thinks_router_is_blatantly_unreachable(routerinfo_t *router,
  673. time_t now)
  674. {
  675. if (router->is_hibernating)
  676. return 0;
  677. if (now >= router->last_reachable + 5*REACHABLE_TIMEOUT &&
  678. router->testing_since &&
  679. now >= router->testing_since + 5*REACHABLE_TIMEOUT)
  680. return 1;
  681. return 0;
  682. }
  683. /** Based on the routerinfo_ts in <b>routers</b>, allocate the
  684. * contents of a router-status line, and store it in
  685. * *<b>router_status_out</b>. Return 0 on success, -1 on failure.
  686. *
  687. * If for_controller is true, include the routers with very old descriptors.
  688. * If for_controller is &gt;1, use the verbose nickname format.
  689. */
  690. int
  691. list_server_status(smartlist_t *routers, char **router_status_out,
  692. int for_controller)
  693. {
  694. /* List of entries in a router-status style: An optional !, then an optional
  695. * equals-suffixed nickname, then a dollar-prefixed hexdigest. */
  696. smartlist_t *rs_entries;
  697. time_t now = time(NULL);
  698. time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
  699. int authdir_mode = get_options()->AuthoritativeDir;
  700. tor_assert(router_status_out);
  701. rs_entries = smartlist_create();
  702. SMARTLIST_FOREACH(routers, routerinfo_t *, ri,
  703. {
  704. if (authdir_mode) {
  705. /* Update router status in routerinfo_t. */
  706. ri->is_running = dirserv_thinks_router_is_reachable(ri, now);
  707. }
  708. if (for_controller == 1 || ri->cache_info.published_on >= cutoff)
  709. smartlist_add(rs_entries, list_single_server_status(ri, ri->is_running));
  710. else if (for_controller > 2) {
  711. char name_buf[MAX_VERBOSE_NICKNAME_LEN+2];
  712. char *cp = name_buf;
  713. if (!ri->is_running)
  714. *cp++ = '!';
  715. router_get_verbose_nickname(cp, ri);
  716. smartlist_add(rs_entries, tor_strdup(name_buf));
  717. }
  718. });
  719. *router_status_out = smartlist_join_strings(rs_entries, " ", 0, NULL);
  720. SMARTLIST_FOREACH(rs_entries, char *, cp, tor_free(cp));
  721. smartlist_free(rs_entries);
  722. return 0;
  723. }
  724. /** Given a (possibly empty) list of config_line_t, each line of which contains
  725. * a list of comma-separated version numbers surrounded by optional space,
  726. * allocate and return a new string containing the version numbers, in order,
  727. * separated by commas. Used to generate Recommended(Client|Server)?Versions
  728. */
  729. static char *
  730. format_versions_list(config_line_t *ln)
  731. {
  732. smartlist_t *versions;
  733. char *result;
  734. versions = smartlist_create();
  735. for ( ; ln; ln = ln->next) {
  736. smartlist_split_string(versions, ln->value, ",",
  737. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  738. }
  739. sort_version_list(versions, 1);
  740. result = smartlist_join_strings(versions,",",0,NULL);
  741. SMARTLIST_FOREACH(versions,char *,s,tor_free(s));
  742. smartlist_free(versions);
  743. return result;
  744. }
  745. /** Return 1 if <b>ri</b>'s descriptor is "active" -- running, valid,
  746. * not hibernating, and not too old. Else return 0.
  747. */
  748. static int
  749. router_is_active(routerinfo_t *ri, time_t now)
  750. {
  751. time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
  752. if (ri->cache_info.published_on < cutoff)
  753. return 0;
  754. if (!ri->is_running || !ri->is_valid || ri->is_hibernating)
  755. return 0;
  756. return 1;
  757. }
  758. /** Generate a new v1 directory and write it into a newly allocated string.
  759. * Point *<b>dir_out</b> to the allocated string. Sign the
  760. * directory with <b>private_key</b>. Return 0 on success, -1 on
  761. * failure. If <b>complete</b> is set, give us all the descriptors;
  762. * otherwise leave out non-running and non-valid ones.
  763. */
  764. int
  765. dirserv_dump_directory_to_string(char **dir_out,
  766. crypto_pk_env_t *private_key, int complete)
  767. {
  768. char *cp;
  769. char *router_status;
  770. char *identity_pkey; /* Identity key, DER64-encoded. */
  771. char *recommended_versions;
  772. char digest[DIGEST_LEN];
  773. char published[ISO_TIME_LEN+1];
  774. char *buf = NULL;
  775. size_t buf_len;
  776. size_t identity_pkey_len;
  777. routerlist_t *rl = router_get_routerlist();
  778. time_t now = time(NULL);
  779. tor_assert(dir_out);
  780. *dir_out = NULL;
  781. if (list_server_status(rl->routers, &router_status, 0))
  782. return -1;
  783. if (crypto_pk_write_public_key_to_string(private_key,&identity_pkey,
  784. &identity_pkey_len)<0) {
  785. log_warn(LD_BUG,"write identity_pkey to string failed!");
  786. return -1;
  787. }
  788. recommended_versions =
  789. format_versions_list(get_options()->RecommendedVersions);
  790. format_iso_time(published, now);
  791. buf_len = 2048+strlen(recommended_versions)+
  792. strlen(router_status);
  793. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri,
  794. if (complete || router_is_active(ri, now))
  795. buf_len += ri->cache_info.signed_descriptor_len+1);
  796. buf = tor_malloc(buf_len);
  797. /* We'll be comparing against buf_len throughout the rest of the
  798. function, though strictly speaking we shouldn't be able to exceed
  799. it. This is C, after all, so we may as well check for buffer
  800. overruns.*/
  801. tor_snprintf(buf, buf_len,
  802. "signed-directory\n"
  803. "published %s\n"
  804. "recommended-software %s\n"
  805. "router-status %s\n"
  806. "dir-signing-key\n%s\n",
  807. published, recommended_versions, router_status,
  808. identity_pkey);
  809. tor_free(recommended_versions);
  810. tor_free(router_status);
  811. tor_free(identity_pkey);
  812. cp = buf + strlen(buf);
  813. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri,
  814. {
  815. size_t len = ri->cache_info.signed_descriptor_len;
  816. const char *body;
  817. if (!complete && !router_is_active(ri, now))
  818. continue;
  819. if (cp+len+1 >= buf+buf_len)
  820. goto truncated;
  821. body = signed_descriptor_get_body(&ri->cache_info);
  822. memcpy(cp, body, len);
  823. cp += len;
  824. *cp++ = '\n'; /* add an extra newline in case somebody was depending on
  825. * it. */
  826. });
  827. *cp = '\0';
  828. /* These multiple strlcat calls are inefficient, but dwarfed by the RSA
  829. signature. */
  830. if (strlcat(buf, "directory-signature ", buf_len) >= buf_len)
  831. goto truncated;
  832. if (strlcat(buf, get_options()->Nickname, buf_len) >= buf_len)
  833. goto truncated;
  834. if (strlcat(buf, "\n", buf_len) >= buf_len)
  835. goto truncated;
  836. if (router_get_dir_hash(buf,digest)) {
  837. log_warn(LD_BUG,"couldn't compute digest");
  838. tor_free(buf);
  839. return -1;
  840. }
  841. note_crypto_pk_op(SIGN_DIR);
  842. if (router_append_dirobj_signature(buf,buf_len,digest,private_key)<0) {
  843. tor_free(buf);
  844. return -1;
  845. }
  846. *dir_out = buf;
  847. return 0;
  848. truncated:
  849. log_warn(LD_BUG,"tried to exceed string length.");
  850. tor_free(buf);
  851. return -1;
  852. }
  853. /** Most recently generated encoded signed v1 directory. (auth dirservers
  854. * only.)*/
  855. static cached_dir_t *the_directory = NULL;
  856. /* Used only by non-auth dirservers: The v1 directory and runningrouters we'll
  857. * serve when requested. */
  858. static cached_dir_t *cached_directory = NULL;
  859. static cached_dir_t cached_runningrouters = { NULL, NULL, 0, 0, 0, -1 };
  860. /** Used for other dirservers' v2 network statuses. Map from hexdigest to
  861. * cached_dir_t. */
  862. static digestmap_t *cached_v2_networkstatus = NULL;
  863. /** Possibly replace the contents of <b>d</b> with the value of
  864. * <b>directory</b> published on <b>when</b>, unless <b>when</b> is older than
  865. * the last value, or too far in the future.
  866. *
  867. * Does not copy <b>directory</b>; frees it if it isn't used.
  868. */
  869. static void
  870. set_cached_dir(cached_dir_t *d, char *directory, time_t when)
  871. {
  872. time_t now = time(NULL);
  873. if (when<=d->published) {
  874. log_info(LD_DIRSERV, "Ignoring old directory; not caching.");
  875. tor_free(directory);
  876. } else if (when>=now+ROUTER_MAX_AGE_TO_PUBLISH) {
  877. log_info(LD_DIRSERV, "Ignoring future directory; not caching.");
  878. tor_free(directory);
  879. } else {
  880. /* if (when>d->published && when<now+ROUTER_MAX_AGE) */
  881. log_debug(LD_DIRSERV, "Caching directory.");
  882. tor_free(d->dir);
  883. d->dir = directory;
  884. d->dir_len = strlen(directory);
  885. tor_free(d->dir_z);
  886. if (tor_gzip_compress(&(d->dir_z), &(d->dir_z_len), d->dir, d->dir_len,
  887. ZLIB_METHOD)) {
  888. log_warn(LD_BUG,"Error compressing cached directory");
  889. }
  890. d->published = when;
  891. }
  892. }
  893. /** Decrement the reference count on <b>d</b>, and free it if it no longer has
  894. * any references. */
  895. void
  896. cached_dir_decref(cached_dir_t *d)
  897. {
  898. if (!d || --d->refcnt > 0)
  899. return;
  900. clear_cached_dir(d);
  901. tor_free(d);
  902. }
  903. /** Allocate and return a new cached_dir_t containing the string <b>s</b>,
  904. * published at <b>published</b>. */
  905. static cached_dir_t *
  906. new_cached_dir(char *s, time_t published)
  907. {
  908. cached_dir_t *d = tor_malloc_zero(sizeof(cached_dir_t));
  909. d->refcnt = 1;
  910. d->dir = s;
  911. d->dir_len = strlen(s);
  912. d->published = published;
  913. if (tor_gzip_compress(&(d->dir_z), &(d->dir_z_len), d->dir, d->dir_len,
  914. ZLIB_METHOD)) {
  915. log_warn(LD_BUG, "Error compressing directory");
  916. }
  917. return d;
  918. }
  919. /** Remove all storage held in <b>d</b>, but do not free <b>d</b> itself. */
  920. static void
  921. clear_cached_dir(cached_dir_t *d)
  922. {
  923. tor_free(d->dir);
  924. tor_free(d->dir_z);
  925. memset(d, 0, sizeof(cached_dir_t));
  926. }
  927. /** Free all storage held by the cached_dir_t in <b>d</b>. */
  928. static void
  929. _free_cached_dir(void *_d)
  930. {
  931. cached_dir_t *d = (cached_dir_t *)_d;
  932. cached_dir_decref(d);
  933. }
  934. /** If we have no cached directory, or it is older than <b>published</b>,
  935. * then replace it with <b>directory</b>, published at <b>published</b>.
  936. *
  937. * If <b>published</b> is too old, do nothing.
  938. *
  939. * If <b>is_running_routers</b>, this is really a running_routers document
  940. * rather than a v1 directory.
  941. */
  942. void
  943. dirserv_set_cached_directory(const char *directory, time_t published,
  944. int is_running_routers)
  945. {
  946. time_t now = time(NULL);
  947. if (is_running_routers) {
  948. if (published >= now - MAX_V1_RR_AGE)
  949. set_cached_dir(&cached_runningrouters, tor_strdup(directory), published);
  950. } else {
  951. if (published >= now - MAX_V1_DIRECTORY_AGE) {
  952. cached_dir_decref(cached_directory);
  953. cached_directory = new_cached_dir(tor_strdup(directory), published);
  954. }
  955. }
  956. }
  957. /** We've just received a v2 network-status for an authoritative directory
  958. * with identity digest <b>identity</b> published at
  959. * <b>published</b>. Store it so we can serve it to others. If
  960. * <b>directory</b> is NULL, remove the entry with the given fingerprint from
  961. * the cache.
  962. */
  963. void
  964. dirserv_set_cached_networkstatus_v2(const char *networkstatus,
  965. const char *identity,
  966. time_t published)
  967. {
  968. cached_dir_t *d, *old_d;
  969. smartlist_t *trusted_dirs;
  970. if (!cached_v2_networkstatus)
  971. cached_v2_networkstatus = digestmap_new();
  972. old_d = digestmap_get(cached_v2_networkstatus, identity);
  973. if (!old_d && !networkstatus)
  974. return;
  975. if (networkstatus) {
  976. if (!old_d || published > old_d->published) {
  977. d = new_cached_dir(tor_strdup(networkstatus), published);
  978. digestmap_set(cached_v2_networkstatus, identity, d);
  979. if (old_d)
  980. cached_dir_decref(old_d);
  981. }
  982. } else {
  983. if (old_d) {
  984. digestmap_remove(cached_v2_networkstatus, identity);
  985. cached_dir_decref(old_d);
  986. }
  987. }
  988. /* Now purge old entries. */
  989. trusted_dirs = router_get_trusted_dir_servers();
  990. if (digestmap_size(cached_v2_networkstatus) >
  991. smartlist_len(trusted_dirs) + MAX_UNTRUSTED_NETWORKSTATUSES) {
  992. /* We need to remove the oldest untrusted networkstatus. */
  993. const char *oldest = NULL;
  994. time_t oldest_published = TIME_MAX;
  995. digestmap_iter_t *iter;
  996. for (iter = digestmap_iter_init(cached_v2_networkstatus);
  997. !digestmap_iter_done(iter);
  998. iter = digestmap_iter_next(cached_v2_networkstatus, iter)) {
  999. const char *ident;
  1000. void *val;
  1001. digestmap_iter_get(iter, &ident, &val);
  1002. d = val;
  1003. if (d->published < oldest_published &&
  1004. !router_digest_is_trusted_dir(ident)) {
  1005. oldest = ident;
  1006. oldest_published = d->published;
  1007. }
  1008. }
  1009. tor_assert(oldest);
  1010. d = digestmap_remove(cached_v2_networkstatus, oldest);
  1011. if (d)
  1012. cached_dir_decref(d);
  1013. }
  1014. }
  1015. /** Remove any networkstatus from the directory cache that was published
  1016. * before <b>cutoff</b>. */
  1017. void
  1018. dirserv_clear_old_networkstatuses(time_t cutoff)
  1019. {
  1020. digestmap_iter_t *iter;
  1021. if (!cached_v2_networkstatus)
  1022. return;
  1023. for (iter = digestmap_iter_init(cached_v2_networkstatus);
  1024. !digestmap_iter_done(iter); ) {
  1025. const char *ident;
  1026. void *val;
  1027. cached_dir_t *dir;
  1028. digestmap_iter_get(iter, &ident, &val);
  1029. dir = val;
  1030. if (dir->published < cutoff) {
  1031. char *fname;
  1032. iter = digestmap_iter_next_rmv(cached_v2_networkstatus, iter);
  1033. fname = networkstatus_get_cache_filename(ident);
  1034. if (file_status(fname) == FN_FILE) {
  1035. log_info(LD_DIR, "Removing too-old untrusted networkstatus in %s",
  1036. fname);
  1037. unlink(fname);
  1038. }
  1039. tor_free(fname);
  1040. cached_dir_decref(dir);
  1041. } else {
  1042. iter = digestmap_iter_next(cached_v2_networkstatus, iter);
  1043. }
  1044. }
  1045. }
  1046. /** Remove any v1 info from the directory cache that was published
  1047. * too long ago. */
  1048. void
  1049. dirserv_clear_old_v1_info(time_t now)
  1050. {
  1051. if (cached_directory &&
  1052. cached_directory->published < (now - MAX_V1_DIRECTORY_AGE)) {
  1053. cached_dir_decref(cached_directory);
  1054. cached_directory = NULL;
  1055. }
  1056. if (cached_runningrouters.published < (now - MAX_V1_RR_AGE)) {
  1057. clear_cached_dir(&cached_runningrouters);
  1058. }
  1059. }
  1060. /** Helper: If we're an authority for the right directory version (the
  1061. * directory version is determined by <b>is_v1_object</b>), try to regenerate
  1062. * auth_src as appropriate and return it, falling back to cache_src on
  1063. * failure. If we're a cache, return cache_src.
  1064. */
  1065. static cached_dir_t *
  1066. dirserv_pick_cached_dir_obj(cached_dir_t *cache_src,
  1067. cached_dir_t *auth_src,
  1068. time_t dirty, cached_dir_t *(*regenerate)(void),
  1069. const char *name,
  1070. int is_v1_object)
  1071. {
  1072. int authority = get_options()->AuthoritativeDir &&
  1073. (!is_v1_object || get_options()->V1AuthoritativeDir);
  1074. if (!authority) {
  1075. return cache_src;
  1076. } else {
  1077. /* We're authoritative. */
  1078. if (regenerate != NULL) {
  1079. if (dirty && dirty + DIR_REGEN_SLACK_TIME < time(NULL)) {
  1080. if (!(auth_src = regenerate())) {
  1081. log_err(LD_BUG, "Couldn't generate %s?", name);
  1082. exit(1);
  1083. }
  1084. } else {
  1085. log_info(LD_DIRSERV, "The %s is still clean; reusing.", name);
  1086. }
  1087. }
  1088. return auth_src ? auth_src : cache_src;
  1089. }
  1090. }
  1091. /** Helper: If we're authoritative and <b>auth_src</b> is set, use
  1092. * <b>auth_src</b>, otherwise use <b>cache_src</b>. If we're using
  1093. * <b>auth_src</b> and it's been <b>dirty</b> for at least
  1094. * DIR_REGEN_SLACK_TIME seconds, call <b>regenerate</b>() to make a fresh one.
  1095. * Yields the compressed version of the directory object if <b>compress</b> is
  1096. * set; otherwise return the uncompressed version. (In either case, sets
  1097. * *<b>out</b> and returns the size of the buffer in *<b>out</b>.)
  1098. *
  1099. * Use <b>is_v1_object</b> to help determine whether we're authoritative for
  1100. * this kind of object.
  1101. **/
  1102. static size_t
  1103. dirserv_get_obj(const char **out,
  1104. int compress,
  1105. cached_dir_t *cache_src,
  1106. cached_dir_t *auth_src,
  1107. time_t dirty, cached_dir_t *(*regenerate)(void),
  1108. const char *name,
  1109. int is_v1_object)
  1110. {
  1111. cached_dir_t *d = dirserv_pick_cached_dir_obj(
  1112. cache_src, auth_src,
  1113. dirty, regenerate, name, is_v1_object);
  1114. if (!d)
  1115. return 0;
  1116. *out = compress ? d->dir_z : d->dir;
  1117. if (*out) {
  1118. return compress ? d->dir_z_len : d->dir_len;
  1119. } else {
  1120. /* not yet available. */
  1121. return 0;
  1122. }
  1123. }
  1124. /** Return the most recently generated encoded signed directory, generating a
  1125. * new one as necessary. If not an authoritative directory may return NULL if
  1126. * no directory is yet cached. */
  1127. cached_dir_t *
  1128. dirserv_get_directory(void)
  1129. {
  1130. return dirserv_pick_cached_dir_obj(cached_directory, the_directory,
  1131. the_directory_is_dirty,
  1132. dirserv_regenerate_directory,
  1133. "server directory", 1);
  1134. }
  1135. /**
  1136. * Generate a fresh v1 directory (authdirservers only); set the_directory
  1137. * and return a pointer to the new value.
  1138. */
  1139. static cached_dir_t *
  1140. dirserv_regenerate_directory(void)
  1141. {
  1142. char *new_directory=NULL;
  1143. if (dirserv_dump_directory_to_string(&new_directory,
  1144. get_identity_key(), 0)) {
  1145. log_warn(LD_BUG, "Error creating directory.");
  1146. tor_free(new_directory);
  1147. return NULL;
  1148. }
  1149. cached_dir_decref(the_directory);
  1150. the_directory = new_cached_dir(new_directory, time(NULL));
  1151. log_info(LD_DIRSERV,"New directory (size %d) has been built.",
  1152. (int)the_directory->dir_len);
  1153. log_debug(LD_DIRSERV,"New directory (size %d):\n%s",
  1154. (int)the_directory->dir_len, the_directory->dir);
  1155. the_directory_is_dirty = 0;
  1156. /* Save the directory to disk so we re-load it quickly on startup.
  1157. */
  1158. dirserv_set_cached_directory(the_directory->dir, time(NULL), 0);
  1159. return the_directory;
  1160. }
  1161. /** For authoritative directories: the current (v1) network status. */
  1162. static cached_dir_t the_runningrouters = { NULL, NULL, 0, 0, 0, -1 };
  1163. /** Replace the current running-routers list with a newly generated one. */
  1164. static cached_dir_t *
  1165. generate_runningrouters(void)
  1166. {
  1167. char *s=NULL;
  1168. char *router_status=NULL;
  1169. char digest[DIGEST_LEN];
  1170. char published[ISO_TIME_LEN+1];
  1171. size_t len;
  1172. crypto_pk_env_t *private_key = get_identity_key();
  1173. char *identity_pkey; /* Identity key, DER64-encoded. */
  1174. size_t identity_pkey_len;
  1175. routerlist_t *rl = router_get_routerlist();
  1176. if (list_server_status(rl->routers, &router_status, 0)) {
  1177. goto err;
  1178. }
  1179. if (crypto_pk_write_public_key_to_string(private_key,&identity_pkey,
  1180. &identity_pkey_len)<0) {
  1181. log_warn(LD_BUG,"write identity_pkey to string failed!");
  1182. goto err;
  1183. }
  1184. format_iso_time(published, time(NULL));
  1185. len = 2048+strlen(router_status);
  1186. s = tor_malloc_zero(len);
  1187. tor_snprintf(s, len,
  1188. "network-status\n"
  1189. "published %s\n"
  1190. "router-status %s\n"
  1191. "dir-signing-key\n%s"
  1192. "directory-signature %s\n",
  1193. published, router_status, identity_pkey,
  1194. get_options()->Nickname);
  1195. tor_free(router_status);
  1196. tor_free(identity_pkey);
  1197. if (router_get_runningrouters_hash(s,digest)) {
  1198. log_warn(LD_BUG,"couldn't compute digest");
  1199. goto err;
  1200. }
  1201. note_crypto_pk_op(SIGN_DIR);
  1202. if (router_append_dirobj_signature(s, len, digest, private_key)<0)
  1203. goto err;
  1204. set_cached_dir(&the_runningrouters, s, time(NULL));
  1205. runningrouters_is_dirty = 0;
  1206. return &the_runningrouters;
  1207. err:
  1208. tor_free(s);
  1209. tor_free(router_status);
  1210. return NULL;
  1211. }
  1212. /** Set *<b>rr</b> to the most recently generated encoded signed
  1213. * running-routers list, generating a new one as necessary. Return the
  1214. * size of the directory on success, and 0 on failure. */
  1215. size_t
  1216. dirserv_get_runningrouters(const char **rr, int compress)
  1217. {
  1218. return dirserv_get_obj(rr, compress,
  1219. &cached_runningrouters, &the_runningrouters,
  1220. runningrouters_is_dirty,
  1221. generate_runningrouters,
  1222. "v1 network status list", 1);
  1223. }
  1224. /** For authoritative directories: the current (v2) network status. */
  1225. static cached_dir_t *the_v2_networkstatus = NULL;
  1226. /** Return true iff our opinion of the routers has been stale for long
  1227. * enough that we should generate a new network status doc. */
  1228. static int
  1229. should_generate_v2_networkstatus(void)
  1230. {
  1231. return get_options()->AuthoritativeDir &&
  1232. the_v2_networkstatus_is_dirty &&
  1233. the_v2_networkstatus_is_dirty + DIR_REGEN_SLACK_TIME < time(NULL);
  1234. }
  1235. /** If a router's uptime is at least this value, then it is always
  1236. * considered stable, regardless of the rest of the network. This
  1237. * way we resist attacks where an attacker doubles the size of the
  1238. * network using allegedly high-uptime nodes, displacing all the
  1239. * current guards. */
  1240. #define UPTIME_TO_GUARANTEE_STABLE (3600*24*30)
  1241. /* Thresholds for server performance: set by
  1242. * dirserv_compute_performance_thresholds, and used by
  1243. * generate_v2_networkstatus */
  1244. static uint32_t stable_uptime = 0; /* start at a safe value */
  1245. static uint32_t fast_bandwidth = 0;
  1246. static uint32_t guard_bandwidth_including_exits = 0;
  1247. static uint32_t guard_bandwidth_excluding_exits = 0;
  1248. static uint64_t total_bandwidth = 0;
  1249. static uint64_t total_exit_bandwidth = 0;
  1250. /** Helper: estimate the uptime of a router given its stated uptime and the
  1251. * amount of time since it last stated its stated uptime. */
  1252. static INLINE int
  1253. real_uptime(routerinfo_t *router, time_t now)
  1254. {
  1255. if (now < router->cache_info.published_on)
  1256. return router->uptime;
  1257. else
  1258. return router->uptime + (now - router->cache_info.published_on);
  1259. }
  1260. /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
  1261. * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
  1262. * If <b>need_capacity</b> is non-zero, we require a minimum advertised
  1263. * bandwidth.
  1264. */
  1265. static int
  1266. dirserv_thinks_router_is_unreliable(time_t now,
  1267. routerinfo_t *router,
  1268. int need_uptime, int need_capacity)
  1269. {
  1270. if (need_uptime) {
  1271. int uptime = real_uptime(router, now);
  1272. if ((unsigned)uptime < stable_uptime &&
  1273. (unsigned)uptime < UPTIME_TO_GUARANTEE_STABLE)
  1274. return 1;
  1275. }
  1276. if (need_capacity &&
  1277. router_get_advertised_bandwidth(router) < fast_bandwidth)
  1278. return 1;
  1279. return 0;
  1280. }
  1281. /** Helper: returns a tristate based on comparing **(uint32_t**)<b>a</b>
  1282. * to **(uint32_t**)<b>b</b>. */
  1283. static int
  1284. _compare_uint32(const void **a, const void **b)
  1285. {
  1286. uint32_t first = **(uint32_t **)a, second = **(uint32_t **)b;
  1287. if (first < second) return -1;
  1288. if (first > second) return 1;
  1289. return 0;
  1290. }
  1291. /** Look through the routerlist, and assign the median uptime of running valid
  1292. * servers to stable_uptime, and the relative bandwidth capacities to
  1293. * fast_bandwidth and guard_bandwidth. Set total_bandwidth to the total
  1294. * capacity of all running valid servers and total_exit_bandwidth to the
  1295. * capacity of all running valid exits. Set the is_exit flag of each router
  1296. * appropriately. */
  1297. static void
  1298. dirserv_compute_performance_thresholds(routerlist_t *rl)
  1299. {
  1300. smartlist_t *uptimes, *bandwidths, *bandwidths_excluding_exits;
  1301. time_t now = time(NULL);
  1302. /* initialize these all here, in case there are no routers */
  1303. stable_uptime = 0;
  1304. fast_bandwidth = 0;
  1305. guard_bandwidth_including_exits = 0;
  1306. guard_bandwidth_excluding_exits = 0;
  1307. total_bandwidth = 0;
  1308. total_exit_bandwidth = 0;
  1309. uptimes = smartlist_create();
  1310. bandwidths = smartlist_create();
  1311. bandwidths_excluding_exits = smartlist_create();
  1312. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
  1313. if (router_is_active(ri, now)) {
  1314. uint32_t *up = tor_malloc(sizeof(uint32_t));
  1315. uint32_t *bw = tor_malloc(sizeof(uint32_t));
  1316. ri->is_exit = exit_policy_is_general_exit(ri->exit_policy);
  1317. *up = (uint32_t) real_uptime(ri, now);
  1318. smartlist_add(uptimes, up);
  1319. *bw = router_get_advertised_bandwidth(ri);
  1320. total_bandwidth += *bw;
  1321. if (ri->is_exit && !ri->is_bad_exit) {
  1322. total_exit_bandwidth += *bw;
  1323. } else {
  1324. uint32_t *bw_not_exit = tor_malloc(sizeof(uint32_t));
  1325. *bw_not_exit = *bw;
  1326. smartlist_add(bandwidths_excluding_exits, bw_not_exit);
  1327. }
  1328. smartlist_add(bandwidths, bw);
  1329. }
  1330. });
  1331. smartlist_sort(uptimes, _compare_uint32);
  1332. smartlist_sort(bandwidths, _compare_uint32);
  1333. smartlist_sort(bandwidths_excluding_exits, _compare_uint32);
  1334. if (smartlist_len(uptimes))
  1335. stable_uptime = *(uint32_t*)smartlist_get(uptimes,
  1336. smartlist_len(uptimes)/2);
  1337. if (smartlist_len(bandwidths)) {
  1338. fast_bandwidth = *(uint32_t*)smartlist_get(bandwidths,
  1339. smartlist_len(bandwidths)/8);
  1340. if (fast_bandwidth < ROUTER_REQUIRED_MIN_BANDWIDTH)
  1341. fast_bandwidth = *(uint32_t*)smartlist_get(bandwidths,
  1342. smartlist_len(bandwidths)/4);
  1343. guard_bandwidth_including_exits =
  1344. *(uint32_t*)smartlist_get(bandwidths, smartlist_len(bandwidths)/2);
  1345. }
  1346. if (smartlist_len(bandwidths_excluding_exits)) {
  1347. guard_bandwidth_excluding_exits =
  1348. *(uint32_t*)smartlist_get(bandwidths_excluding_exits,
  1349. smartlist_len(bandwidths_excluding_exits)/2);
  1350. }
  1351. log(LOG_INFO, LD_DIRSERV,
  1352. "Cutoffs: %lus uptime, %lu b/s fast, %lu or %lu b/s guard.",
  1353. (unsigned long)stable_uptime,
  1354. (unsigned long)fast_bandwidth,
  1355. (unsigned long)guard_bandwidth_including_exits,
  1356. (unsigned long)guard_bandwidth_excluding_exits);
  1357. SMARTLIST_FOREACH(uptimes, uint32_t *, up, tor_free(up));
  1358. SMARTLIST_FOREACH(bandwidths, uint32_t *, bw, tor_free(bw));
  1359. SMARTLIST_FOREACH(bandwidths_excluding_exits, uint32_t *, bw, tor_free(bw));
  1360. smartlist_free(uptimes);
  1361. smartlist_free(bandwidths);
  1362. smartlist_free(bandwidths_excluding_exits);
  1363. }
  1364. /** For authoritative directories only: replace the contents of
  1365. * <b>the_v2_networkstatus</b> with a newly generated network status
  1366. * object. */
  1367. static cached_dir_t *
  1368. generate_v2_networkstatus(void)
  1369. {
  1370. /** Longest status flag name that we generate. */
  1371. #define LONGEST_STATUS_FLAG_NAME_LEN 9
  1372. /** Maximum number of status flags we'll apply to one router. */
  1373. #define N_STATUS_FLAGS 10
  1374. /** Amount of space to allocate for each entry. (r line and s line.) */
  1375. #define RS_ENTRY_LEN \
  1376. ( /* first line */ \
  1377. MAX_NICKNAME_LEN+BASE64_DIGEST_LEN*2+ISO_TIME_LEN+INET_NTOA_BUF_LEN+ \
  1378. 5*2 /* ports */ + 10 /* punctuation */ + \
  1379. /* second line */ \
  1380. (LONGEST_STATUS_FLAG_NAME_LEN+1)*N_STATUS_FLAGS + 2)
  1381. cached_dir_t *r = NULL;
  1382. size_t len, identity_pkey_len;
  1383. char *status = NULL, *client_versions = NULL, *server_versions = NULL,
  1384. *identity_pkey = NULL, *hostname = NULL;
  1385. char *outp, *endp;
  1386. or_options_t *options = get_options();
  1387. char fingerprint[FINGERPRINT_LEN+1];
  1388. char ipaddr[INET_NTOA_BUF_LEN];
  1389. char published[ISO_TIME_LEN+1];
  1390. char digest[DIGEST_LEN];
  1391. struct in_addr in;
  1392. uint32_t addr;
  1393. crypto_pk_env_t *private_key = get_identity_key();
  1394. routerlist_t *rl = router_get_routerlist();
  1395. time_t now = time(NULL);
  1396. time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
  1397. int naming = options->NamingAuthoritativeDir;
  1398. int versioning = options->VersioningAuthoritativeDir;
  1399. int listbadexits = options->AuthDirListBadExits;
  1400. int exits_can_be_guards;
  1401. const char *contact;
  1402. if (resolve_my_address(LOG_WARN, options, &addr, &hostname)<0) {
  1403. log_warn(LD_NET, "Couldn't resolve my hostname");
  1404. goto done;
  1405. }
  1406. in.s_addr = htonl(addr);
  1407. tor_inet_ntoa(&in, ipaddr, sizeof(ipaddr));
  1408. format_iso_time(published, time(NULL));
  1409. client_versions = format_versions_list(options->RecommendedClientVersions);
  1410. server_versions = format_versions_list(options->RecommendedServerVersions);
  1411. if (crypto_pk_write_public_key_to_string(private_key, &identity_pkey,
  1412. &identity_pkey_len)<0) {
  1413. log_warn(LD_BUG,"Writing public key to string failed.");
  1414. goto done;
  1415. }
  1416. if (crypto_pk_get_fingerprint(private_key, fingerprint, 0)<0) {
  1417. log_err(LD_BUG, "Error computing fingerprint");
  1418. goto done;
  1419. }
  1420. contact = get_options()->ContactInfo;
  1421. if (!contact)
  1422. contact = "(none)";
  1423. len = 2048+strlen(client_versions)+strlen(server_versions);
  1424. len += identity_pkey_len*2;
  1425. len += (RS_ENTRY_LEN)*smartlist_len(rl->routers);
  1426. status = tor_malloc(len);
  1427. tor_snprintf(status, len,
  1428. "network-status-version 2\n"
  1429. "dir-source %s %s %d\n"
  1430. "fingerprint %s\n"
  1431. "contact %s\n"
  1432. "published %s\n"
  1433. "dir-options%s%s%s\n"
  1434. "%s%s" /* client versions %s */
  1435. "%s%s%s" /* \nserver versions %s \n */
  1436. "dir-signing-key\n%s\n",
  1437. hostname, ipaddr, (int)options->DirPort,
  1438. fingerprint,
  1439. contact,
  1440. published,
  1441. naming ? " Names" : "",
  1442. listbadexits ? " BadExits" : "",
  1443. versioning ? " Versions" : "",
  1444. versioning ? "client-versions " : "",
  1445. versioning ? client_versions : "",
  1446. versioning ? "\nserver-versions " : "",
  1447. versioning ? server_versions : "",
  1448. versioning ? "\n" : "",
  1449. identity_pkey);
  1450. outp = status + strlen(status);
  1451. endp = status + len;
  1452. /* precompute this part, since we need it to decide what "stable"
  1453. * means. */
  1454. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
  1455. ri->is_running = dirserv_thinks_router_is_reachable(ri, now);
  1456. });
  1457. dirserv_compute_performance_thresholds(rl);
  1458. /* XXXX We should take steps to keep this from oscillating if
  1459. * total_exit_bandwidth is close to total_bandwidth/3. */
  1460. exits_can_be_guards = total_exit_bandwidth >= (total_bandwidth / 3);
  1461. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
  1462. if (ri->cache_info.published_on >= cutoff) {
  1463. /* Already set by compute_performance_thresholds. */
  1464. int f_exit = ri->is_exit;
  1465. /* These versions dump connections with idle live circuits
  1466. sometimes. D'oh!*/
  1467. int unstable_version =
  1468. tor_version_as_new_as(ri->platform,"0.1.1.10-alpha") &&
  1469. !tor_version_as_new_as(ri->platform,"0.1.1.16-rc-cvs");
  1470. int f_stable = ri->is_stable =
  1471. router_is_active(ri, now) &&
  1472. !dirserv_thinks_router_is_unreliable(now, ri, 1, 0) &&
  1473. !unstable_version;
  1474. int f_fast = ri->is_fast =
  1475. router_is_active(ri, now) &&
  1476. !dirserv_thinks_router_is_unreliable(now, ri, 0, 1);
  1477. int f_running = ri->is_running; /* computed above */
  1478. int f_authority = router_digest_is_trusted_dir(
  1479. ri->cache_info.identity_digest);
  1480. int f_named = naming && ri->is_named;
  1481. int f_valid = ri->is_valid;
  1482. int f_guard = f_fast && f_stable &&
  1483. (!f_exit || exits_can_be_guards) &&
  1484. router_get_advertised_bandwidth(ri) >=
  1485. (exits_can_be_guards ? guard_bandwidth_including_exits :
  1486. guard_bandwidth_excluding_exits);
  1487. int f_bad_exit = listbadexits && ri->is_bad_exit;
  1488. /* 0.1.1.9-alpha is the first version to support fetch by descriptor
  1489. * hash. */
  1490. int f_v2_dir = ri->dir_port &&
  1491. tor_version_as_new_as(ri->platform,"0.1.1.9-alpha");
  1492. char identity64[BASE64_DIGEST_LEN+1];
  1493. char digest64[BASE64_DIGEST_LEN+1];
  1494. if (!strcasecmp(ri->nickname, UNNAMED_ROUTER_NICKNAME))
  1495. f_named = 0;
  1496. format_iso_time(published, ri->cache_info.published_on);
  1497. digest_to_base64(identity64, ri->cache_info.identity_digest);
  1498. digest_to_base64(digest64, ri->cache_info.signed_descriptor_digest);
  1499. in.s_addr = htonl(ri->addr);
  1500. tor_inet_ntoa(&in, ipaddr, sizeof(ipaddr));
  1501. if (tor_snprintf(outp, endp-outp,
  1502. "r %s %s %s %s %s %d %d\n"
  1503. "s%s%s%s%s%s%s%s%s%s%s\n",
  1504. ri->nickname,
  1505. identity64,
  1506. digest64,
  1507. published,
  1508. ipaddr,
  1509. ri->or_port,
  1510. ri->dir_port,
  1511. f_authority?" Authority":"",
  1512. f_bad_exit?" BadExit":"",
  1513. f_exit?" Exit":"",
  1514. f_fast?" Fast":"",
  1515. f_guard?" Guard":"",
  1516. f_named?" Named":"",
  1517. f_stable?" Stable":"",
  1518. f_running?" Running":"",
  1519. f_valid?" Valid":"",
  1520. f_v2_dir?" V2Dir":"")<0) {
  1521. log_warn(LD_BUG, "Unable to print router status.");
  1522. goto done;
  1523. }
  1524. outp += strlen(outp);
  1525. if (ri->platform && !strcmpstart(ri->platform, "Tor ")) {
  1526. const char *eos = find_whitespace(ri->platform+4);
  1527. if (eos) {
  1528. char *platform = tor_strndup(ri->platform, eos-(ri->platform));
  1529. if (tor_snprintf(outp, endp-outp,
  1530. "opt v %s\n", platform)<0) {
  1531. log_warn(LD_BUG, "Unable to print router version.");
  1532. goto done;
  1533. }
  1534. tor_free(platform);
  1535. outp += strlen(outp);
  1536. }
  1537. }
  1538. }
  1539. });
  1540. if (tor_snprintf(outp, endp-outp, "directory-signature %s\n",
  1541. get_options()->Nickname)<0) {
  1542. log_warn(LD_BUG, "Unable to write signature line.");
  1543. goto done;
  1544. }
  1545. if (router_get_networkstatus_v2_hash(status, digest)<0) {
  1546. log_warn(LD_BUG, "Unable to hash network status");
  1547. goto done;
  1548. }
  1549. note_crypto_pk_op(SIGN_DIR);
  1550. if (router_append_dirobj_signature(outp,endp-outp,digest,private_key)<0) {
  1551. log_warn(LD_BUG, "Unable to sign router status.");
  1552. goto done;
  1553. }
  1554. if (the_v2_networkstatus)
  1555. cached_dir_decref(the_v2_networkstatus);
  1556. the_v2_networkstatus = new_cached_dir(status, time(NULL));
  1557. status = NULL; /* So it doesn't get double-freed. */
  1558. the_v2_networkstatus_is_dirty = 0;
  1559. router_set_networkstatus(the_v2_networkstatus->dir,
  1560. time(NULL), NS_GENERATED, NULL);
  1561. r = the_v2_networkstatus;
  1562. done:
  1563. tor_free(client_versions);
  1564. tor_free(server_versions);
  1565. tor_free(status);
  1566. tor_free(hostname);
  1567. tor_free(identity_pkey);
  1568. return r;
  1569. }
  1570. /** Given the portion of a networkstatus request URL after "tor/status/" in
  1571. * <b>key</b>, append to <b>result</b> the digests of the identity keys of the
  1572. * networkstatus objects that the client has requested. */
  1573. void
  1574. dirserv_get_networkstatus_v2_fingerprints(smartlist_t *result,
  1575. const char *key)
  1576. {
  1577. tor_assert(result);
  1578. if (!cached_v2_networkstatus)
  1579. cached_v2_networkstatus = digestmap_new();
  1580. if (should_generate_v2_networkstatus())
  1581. generate_v2_networkstatus();
  1582. if (!strcmp(key,"authority")) {
  1583. if (get_options()->AuthoritativeDir) {
  1584. routerinfo_t *me = router_get_my_routerinfo();
  1585. if (me)
  1586. smartlist_add(result,
  1587. tor_memdup(me->cache_info.identity_digest, DIGEST_LEN));
  1588. }
  1589. } else if (!strcmp(key, "all")) {
  1590. if (digestmap_size(cached_v2_networkstatus)) {
  1591. digestmap_iter_t *iter;
  1592. iter = digestmap_iter_init(cached_v2_networkstatus);
  1593. while (!digestmap_iter_done(iter)) {
  1594. const char *ident;
  1595. void *val;
  1596. digestmap_iter_get(iter, &ident, &val);
  1597. smartlist_add(result, tor_memdup(ident, DIGEST_LEN));
  1598. iter = digestmap_iter_next(cached_v2_networkstatus, iter);
  1599. }
  1600. } else {
  1601. SMARTLIST_FOREACH(router_get_trusted_dir_servers(),
  1602. trusted_dir_server_t *, ds,
  1603. smartlist_add(result, tor_memdup(ds->digest, DIGEST_LEN)));
  1604. }
  1605. smartlist_sort_digests(result);
  1606. if (smartlist_len(result) == 0)
  1607. log_warn(LD_DIRSERV,
  1608. "Client requested 'all' network status objects; we have none.");
  1609. } else if (!strcmpstart(key, "fp/")) {
  1610. dir_split_resource_into_fingerprints(key+3, result, NULL, 1, 1);
  1611. }
  1612. }
  1613. /** Look for a network status object as specified by <b>key</b>, which should
  1614. * be either "authority" (to find a network status generated by us), a hex
  1615. * identity digest (to find a network status generated by given directory), or
  1616. * "all" (to return all the v2 network status objects we have).
  1617. */
  1618. void
  1619. dirserv_get_networkstatus_v2(smartlist_t *result,
  1620. const char *key)
  1621. {
  1622. cached_dir_t *cached;
  1623. smartlist_t *fingerprints = smartlist_create();
  1624. tor_assert(result);
  1625. if (!cached_v2_networkstatus)
  1626. cached_v2_networkstatus = digestmap_new();
  1627. dirserv_get_networkstatus_v2_fingerprints(fingerprints, key);
  1628. SMARTLIST_FOREACH(fingerprints, const char *, fp,
  1629. {
  1630. if (router_digest_is_me(fp) && should_generate_v2_networkstatus())
  1631. generate_v2_networkstatus();
  1632. cached = digestmap_get(cached_v2_networkstatus, fp);
  1633. if (cached) {
  1634. smartlist_add(result, cached);
  1635. } else {
  1636. char hexbuf[HEX_DIGEST_LEN+1];
  1637. base16_encode(hexbuf, sizeof(hexbuf), fp, DIGEST_LEN);
  1638. log_info(LD_DIRSERV, "Don't know about any network status with "
  1639. "fingerprint '%s'", hexbuf);
  1640. }
  1641. });
  1642. SMARTLIST_FOREACH(fingerprints, char *, cp, tor_free(cp));
  1643. smartlist_free(fingerprints);
  1644. }
  1645. /** As dirserv_get_routerdescs(), but instead of getting signed_descriptor_t
  1646. * pointers, adds copies of digests to fps_out. For a /tor/server/d/ request,
  1647. * adds descriptor digests; for other requests, adds identity digests.
  1648. */
  1649. int
  1650. dirserv_get_routerdesc_fingerprints(smartlist_t *fps_out, const char *key,
  1651. const char **msg)
  1652. {
  1653. *msg = NULL;
  1654. if (!strcmp(key, "/tor/server/all")) {
  1655. routerlist_t *rl = router_get_routerlist();
  1656. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  1657. smartlist_add(fps_out,
  1658. tor_memdup(r->cache_info.identity_digest, DIGEST_LEN)));
  1659. } else if (!strcmp(key, "/tor/server/authority")) {
  1660. routerinfo_t *ri = router_get_my_routerinfo();
  1661. if (ri)
  1662. smartlist_add(fps_out,
  1663. tor_memdup(ri->cache_info.identity_digest, DIGEST_LEN));
  1664. } else if (!strcmpstart(key, "/tor/server/d/")) {
  1665. key += strlen("/tor/server/d/");
  1666. dir_split_resource_into_fingerprints(key, fps_out, NULL, 1, 1);
  1667. } else if (!strcmpstart(key, "/tor/server/fp/")) {
  1668. key += strlen("/tor/server/fp/");
  1669. dir_split_resource_into_fingerprints(key, fps_out, NULL, 1, 1);
  1670. } else {
  1671. *msg = "Key not recognized";
  1672. return -1;
  1673. }
  1674. if (!smartlist_len(fps_out)) {
  1675. *msg = "Servers unavailable";
  1676. return -1;
  1677. }
  1678. return 0;
  1679. }
  1680. /** Add a signed_descriptor_t to <b>descs_out</b> for each router matching
  1681. * <b>key</b>. The key should be either
  1682. * - "/tor/server/authority" for our own routerinfo;
  1683. * - "/tor/server/all" for all the routerinfos we have, concatenated;
  1684. * - "/tor/server/fp/FP" where FP is a plus-separated sequence of
  1685. * hex identity digests; or
  1686. * - "/tor/server/d/D" where D is a plus-separated sequence
  1687. * of server descriptor digests, in hex.
  1688. *
  1689. * Return 0 if we found some matching descriptors, or -1 if we do not
  1690. * have any descriptors, no matching descriptors, or if we did not
  1691. * recognize the key (URL).
  1692. * If -1 is returned *<b>msg</b> will be set to an appropriate error
  1693. * message.
  1694. *
  1695. * (Despite its name, this function is also called from the controller, which
  1696. * exposes a similar means to fetch descriptors.)
  1697. */
  1698. int
  1699. dirserv_get_routerdescs(smartlist_t *descs_out, const char *key,
  1700. const char **msg)
  1701. {
  1702. *msg = NULL;
  1703. if (!strcmp(key, "/tor/server/all")) {
  1704. routerlist_t *rl = router_get_routerlist();
  1705. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  1706. smartlist_add(descs_out, &(r->cache_info)));
  1707. } else if (!strcmp(key, "/tor/server/authority")) {
  1708. routerinfo_t *ri = router_get_my_routerinfo();
  1709. if (ri)
  1710. smartlist_add(descs_out, &(ri->cache_info));
  1711. } else if (!strcmpstart(key, "/tor/server/d/")) {
  1712. smartlist_t *digests = smartlist_create();
  1713. key += strlen("/tor/server/d/");
  1714. dir_split_resource_into_fingerprints(key, digests, NULL, 1, 1);
  1715. SMARTLIST_FOREACH(digests, const char *, d,
  1716. {
  1717. signed_descriptor_t *sd = router_get_by_descriptor_digest(d);
  1718. if (sd)
  1719. smartlist_add(descs_out,sd);
  1720. });
  1721. SMARTLIST_FOREACH(digests, char *, d, tor_free(d));
  1722. smartlist_free(digests);
  1723. } else if (!strcmpstart(key, "/tor/server/fp/")) {
  1724. smartlist_t *digests = smartlist_create();
  1725. time_t cutoff = time(NULL) - ROUTER_MAX_AGE_TO_PUBLISH;
  1726. key += strlen("/tor/server/fp/");
  1727. dir_split_resource_into_fingerprints(key, digests, NULL, 1, 1);
  1728. SMARTLIST_FOREACH(digests, const char *, d,
  1729. {
  1730. if (router_digest_is_me(d)) {
  1731. smartlist_add(descs_out, &(router_get_my_routerinfo()->cache_info));
  1732. } else {
  1733. routerinfo_t *ri = router_get_by_digest(d);
  1734. /* Don't actually serve a descriptor that everyone will think is
  1735. * expired. This is an (ugly) workaround to keep buggy 0.1.1.10
  1736. * Tors from downloading descriptors that they will throw away.
  1737. */
  1738. if (ri && ri->cache_info.published_on > cutoff)
  1739. smartlist_add(descs_out, &(ri->cache_info));
  1740. }
  1741. });
  1742. SMARTLIST_FOREACH(digests, char *, d, tor_free(d));
  1743. smartlist_free(digests);
  1744. } else {
  1745. *msg = "Key not recognized";
  1746. return -1;
  1747. }
  1748. if (!smartlist_len(descs_out)) {
  1749. *msg = "Servers unavailable";
  1750. return -1;
  1751. }
  1752. return 0;
  1753. }
  1754. /** Called when a TLS handshake has completed successfully with a
  1755. * router listening at <b>address</b>:<b>or_port</b>, and has yielded
  1756. * a certificate with digest <b>digest_rcvd</b>.
  1757. *
  1758. * Also, if as_advertised is 1, then inform the reachability checker
  1759. * that we could get to this guy.
  1760. */
  1761. void
  1762. dirserv_orconn_tls_done(const char *address,
  1763. uint16_t or_port,
  1764. const char *digest_rcvd,
  1765. int as_advertised)
  1766. {
  1767. routerlist_t *rl = router_get_routerlist();
  1768. tor_assert(address);
  1769. tor_assert(digest_rcvd);
  1770. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
  1771. if (!strcasecmp(address, ri->address) && or_port == ri->or_port &&
  1772. as_advertised &&
  1773. !memcmp(ri->cache_info.identity_digest, digest_rcvd, DIGEST_LEN)) {
  1774. /* correct digest. mark this router reachable! */
  1775. log_info(LD_DIRSERV, "Found router %s to be reachable. Yay.",
  1776. ri->nickname);
  1777. ri->last_reachable = time(NULL);
  1778. ri->num_unreachable_notifications = 0;
  1779. }
  1780. });
  1781. /* FFFF Maybe we should reinstate the code that dumps routers with the same
  1782. * addr/port but with nonmatching keys, but instead of dumping, we should
  1783. * skip testing. */
  1784. }
  1785. /** Auth dir server only: if <b>try_all</b> is 1, launch connections to
  1786. * all known routers; else we want to load balance such that we only
  1787. * try a few connections per call.
  1788. *
  1789. * The load balancing is such that if we get called once every ten
  1790. * seconds, we will cycle through all the tests in 1280 seconds (a
  1791. * bit over 20 minutes).
  1792. */
  1793. void
  1794. dirserv_test_reachability(int try_all)
  1795. {
  1796. time_t now = time(NULL);
  1797. /* XXX decide what to do here; see or-talk thread "purging old router
  1798. * information, revocation." -NM
  1799. * We can't afford to mess with this in 0.1.2.x. The reason is that
  1800. * if we stop doing reachability tests on some of routerlist, then
  1801. * we'll for-sure think they're down, which may have unexpected
  1802. * effects in other parts of the code. It doesn't hurt much to do
  1803. * the testing, and directory authorities are easy to upgrade. Let's
  1804. * wait til 0.2.0. -RD */
  1805. // time_t cutoff = now - ROUTER_MAX_AGE_TO_PUBLISH;
  1806. routerlist_t *rl = router_get_routerlist();
  1807. static char ctr = 0;
  1808. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, router, {
  1809. const char *id_digest = router->cache_info.identity_digest;
  1810. if (router_is_me(router))
  1811. continue;
  1812. // if (router->cache_info.published_on > cutoff)
  1813. // continue;
  1814. if (try_all || (((uint8_t)id_digest[0]) % 128) == ctr) {
  1815. log_debug(LD_OR,"Testing reachability of %s at %s:%u.",
  1816. router->nickname, router->address, router->or_port);
  1817. /* Remember when we started trying to determine reachability */
  1818. if (!router->testing_since)
  1819. router->testing_since = now;
  1820. connection_or_connect(router->addr, router->or_port,
  1821. id_digest);
  1822. }
  1823. });
  1824. if (!try_all) /* increment ctr */
  1825. ctr = (ctr + 1) % 128;
  1826. }
  1827. /** Return an approximate estimate of the number of bytes that will
  1828. * be needed to transmit the server descriptors (if is_serverdescs --
  1829. * they can be either d/ or fp/ queries) or networkstatus objects (if
  1830. * !is_serverdescs) listed in <b>fps</b>. If <b>compressed</b> is set,
  1831. * we guess how large the data will be after compression.
  1832. *
  1833. * The return value is an estimate; it might be larger or smaller.
  1834. **/
  1835. size_t
  1836. dirserv_estimate_data_size(smartlist_t *fps, int is_serverdescs,
  1837. int compressed)
  1838. {
  1839. size_t result;
  1840. tor_assert(fps);
  1841. if (is_serverdescs) {
  1842. int n = smartlist_len(fps);
  1843. routerinfo_t *me = router_get_my_routerinfo();
  1844. result = (me?me->cache_info.signed_descriptor_len:2048) * n;
  1845. if (compressed)
  1846. result /= 2; /* observed compressability is between 35 and 55%. */
  1847. } else {
  1848. result = 0;
  1849. SMARTLIST_FOREACH(fps, const char *, d, {
  1850. cached_dir_t *dir = digestmap_get(cached_v2_networkstatus, d);
  1851. if (dir)
  1852. result += compressed ? dir->dir_z_len : dir->dir_len;
  1853. });
  1854. }
  1855. return result;
  1856. }
  1857. /** When we're spooling data onto our outbuf, add more whenever we dip
  1858. * below this threshold. */
  1859. #define DIRSERV_BUFFER_MIN 16384
  1860. /** Spooling helper: called when we have no more data to spool to <b>conn</b>.
  1861. * Flushes any remaining data to be (un)compressed, and changes the spool
  1862. * source to NONE. Returns 0 on success, negative on failure. */
  1863. static int
  1864. connection_dirserv_finish_spooling(dir_connection_t *conn)
  1865. {
  1866. if (conn->zlib_state) {
  1867. connection_write_to_buf_zlib("", 0, conn, 1);
  1868. tor_zlib_free(conn->zlib_state);
  1869. conn->zlib_state = NULL;
  1870. }
  1871. conn->dir_spool_src = DIR_SPOOL_NONE;
  1872. return 0;
  1873. }
  1874. /** Spooling helper: called when we're sending a bunch of server descriptors,
  1875. * and the outbuf has become too empty. Pulls some entries from
  1876. * fingerprint_stack, and writes the corresponding servers onto outbuf. If we
  1877. * run out of entries, flushes the zlib state and sets the spool source to
  1878. * NONE. Returns 0 on success, negative on failure.
  1879. */
  1880. static int
  1881. connection_dirserv_add_servers_to_outbuf(dir_connection_t *conn)
  1882. {
  1883. int by_fp = conn->dir_spool_src == DIR_SPOOL_SERVER_BY_FP;
  1884. while (smartlist_len(conn->fingerprint_stack) &&
  1885. buf_datalen(conn->_base.outbuf) < DIRSERV_BUFFER_MIN) {
  1886. const char *body;
  1887. char *fp = smartlist_pop_last(conn->fingerprint_stack);
  1888. signed_descriptor_t *sd = NULL;
  1889. if (by_fp) {
  1890. if (router_digest_is_me(fp)) {
  1891. sd = &(router_get_my_routerinfo()->cache_info);
  1892. } else {
  1893. routerinfo_t *ri = router_get_by_digest(fp);
  1894. if (ri &&
  1895. ri->cache_info.published_on > time(NULL)-ROUTER_MAX_AGE_TO_PUBLISH)
  1896. sd = &ri->cache_info;
  1897. }
  1898. } else
  1899. sd = router_get_by_descriptor_digest(fp);
  1900. tor_free(fp);
  1901. if (!sd)
  1902. continue;
  1903. body = signed_descriptor_get_body(sd);
  1904. if (conn->zlib_state) {
  1905. int last = ! smartlist_len(conn->fingerprint_stack);
  1906. connection_write_to_buf_zlib(body, sd->signed_descriptor_len, conn,
  1907. last);
  1908. if (last) {
  1909. tor_zlib_free(conn->zlib_state);
  1910. conn->zlib_state = NULL;
  1911. }
  1912. } else {
  1913. connection_write_to_buf(body,
  1914. sd->signed_descriptor_len,
  1915. TO_CONN(conn));
  1916. }
  1917. }
  1918. if (!smartlist_len(conn->fingerprint_stack)) {
  1919. /* We just wrote the last one; finish up. */
  1920. conn->dir_spool_src = DIR_SPOOL_NONE;
  1921. smartlist_free(conn->fingerprint_stack);
  1922. conn->fingerprint_stack = NULL;
  1923. }
  1924. return 0;
  1925. }
  1926. /** Spooling helper: Called when we're sending a directory or networkstatus,
  1927. * and the outbuf has become too empty. Pulls some bytes from
  1928. * <b>conn</b>-\>cached_dir-\>dir_z, uncompresses them if appropriate, and
  1929. * puts them on the outbuf. If we run out of entries, flushes the zlib state
  1930. * and sets the spool source to NONE. Returns 0 on success, negative on
  1931. * failure. */
  1932. static int
  1933. connection_dirserv_add_dir_bytes_to_outbuf(dir_connection_t *conn)
  1934. {
  1935. ssize_t bytes;
  1936. int64_t remaining;
  1937. bytes = DIRSERV_BUFFER_MIN - buf_datalen(conn->_base.outbuf);
  1938. tor_assert(bytes > 0);
  1939. tor_assert(conn->cached_dir);
  1940. if (bytes < 8192)
  1941. bytes = 8192;
  1942. remaining = conn->cached_dir->dir_z_len - conn->cached_dir_offset;
  1943. if (bytes > remaining)
  1944. bytes = (ssize_t) remaining;
  1945. if (conn->zlib_state) {
  1946. connection_write_to_buf_zlib(
  1947. conn->cached_dir->dir_z + conn->cached_dir_offset,
  1948. bytes, conn, bytes == remaining);
  1949. } else {
  1950. connection_write_to_buf(conn->cached_dir->dir_z + conn->cached_dir_offset,
  1951. bytes, TO_CONN(conn));
  1952. }
  1953. conn->cached_dir_offset += bytes;
  1954. if (conn->cached_dir_offset == (int)conn->cached_dir->dir_z_len) {
  1955. /* We just wrote the last one; finish up. */
  1956. connection_dirserv_finish_spooling(conn);
  1957. cached_dir_decref(conn->cached_dir);
  1958. conn->cached_dir = NULL;
  1959. }
  1960. return 0;
  1961. }
  1962. /** Spooling helper: Called when we're spooling networkstatus objects on
  1963. * <b>conn</b>, and the outbuf has become too empty. If the current
  1964. * networkstatus object (in <b>conn</b>-\>cached_dir) has more data, pull data
  1965. * from there. Otherwise, pop the next fingerprint from fingerprint_stack,
  1966. * and start spooling the next networkstatus. If we run out of entries,
  1967. * flushes the zlib state and sets the spool source to NONE. Returns 0 on
  1968. * success, negative on failure. */
  1969. static int
  1970. connection_dirserv_add_networkstatus_bytes_to_outbuf(dir_connection_t *conn)
  1971. {
  1972. while (buf_datalen(conn->_base.outbuf) < DIRSERV_BUFFER_MIN) {
  1973. if (conn->cached_dir) {
  1974. int uncompressing = (conn->zlib_state != NULL);
  1975. int r = connection_dirserv_add_dir_bytes_to_outbuf(conn);
  1976. if (conn->dir_spool_src == DIR_SPOOL_NONE) {
  1977. /* add_dir_bytes thinks we're done with the cached_dir. But we
  1978. * may have more cached_dirs! */
  1979. conn->dir_spool_src = DIR_SPOOL_NETWORKSTATUS;
  1980. /* This bit is tricky. If we were uncompressing the last
  1981. * networkstatus, we may need to make a new zlib object to
  1982. * uncompress the next one. */
  1983. if (uncompressing && ! conn->zlib_state &&
  1984. conn->fingerprint_stack &&
  1985. smartlist_len(conn->fingerprint_stack)) {
  1986. conn->zlib_state = tor_zlib_new(0, ZLIB_METHOD);
  1987. }
  1988. }
  1989. if (r) return r;
  1990. } else if (conn->fingerprint_stack &&
  1991. smartlist_len(conn->fingerprint_stack)) {
  1992. /* Add another networkstatus; start serving it. */
  1993. char *fp = smartlist_pop_last(conn->fingerprint_stack);
  1994. cached_dir_t *d;
  1995. if (router_digest_is_me(fp))
  1996. d = the_v2_networkstatus;
  1997. else
  1998. d = digestmap_get(cached_v2_networkstatus, fp);
  1999. tor_free(fp);
  2000. if (d) {
  2001. ++d->refcnt;
  2002. conn->cached_dir = d;
  2003. conn->cached_dir_offset = 0;
  2004. }
  2005. } else {
  2006. connection_dirserv_finish_spooling(conn);
  2007. if (conn->fingerprint_stack)
  2008. smartlist_free(conn->fingerprint_stack);
  2009. conn->fingerprint_stack = NULL;
  2010. return 0;
  2011. }
  2012. }
  2013. return 0;
  2014. }
  2015. /** Called whenever we have flushed some directory data in state
  2016. * SERVER_WRITING. */
  2017. int
  2018. connection_dirserv_flushed_some(dir_connection_t *conn)
  2019. {
  2020. tor_assert(conn->_base.state == DIR_CONN_STATE_SERVER_WRITING);
  2021. if (buf_datalen(conn->_base.outbuf) >= DIRSERV_BUFFER_MIN)
  2022. return 0;
  2023. switch (conn->dir_spool_src) {
  2024. case DIR_SPOOL_SERVER_BY_DIGEST:
  2025. case DIR_SPOOL_SERVER_BY_FP:
  2026. return connection_dirserv_add_servers_to_outbuf(conn);
  2027. case DIR_SPOOL_CACHED_DIR:
  2028. return connection_dirserv_add_dir_bytes_to_outbuf(conn);
  2029. case DIR_SPOOL_NETWORKSTATUS:
  2030. return connection_dirserv_add_networkstatus_bytes_to_outbuf(conn);
  2031. case DIR_SPOOL_NONE:
  2032. default:
  2033. return 0;
  2034. }
  2035. }
  2036. /** Release all storage used by the directory server. */
  2037. void
  2038. dirserv_free_all(void)
  2039. {
  2040. dirserv_free_fingerprint_list();
  2041. cached_dir_decref(the_directory);
  2042. clear_cached_dir(&the_runningrouters);
  2043. cached_dir_decref(the_v2_networkstatus);
  2044. cached_dir_decref(cached_directory);
  2045. clear_cached_dir(&cached_runningrouters);
  2046. if (cached_v2_networkstatus) {
  2047. digestmap_free(cached_v2_networkstatus, _free_cached_dir);
  2048. cached_v2_networkstatus = NULL;
  2049. }
  2050. }