dirserv.c 68 KB

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