dirserv.c 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703
  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) /* 12 hours */
  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. extern long stats_n_seconds_working;
  21. typedef enum {
  22. FP_NAMED, /**< Listed in fingerprint file. */
  23. FP_VALID, /**< Unlisted but believed valid. */
  24. FP_INVALID, /**< Believed invalid. */
  25. FP_REJECT, /**< We will not publish this router. */
  26. } router_status_t;
  27. /** Do we need to regenerate the directory when someone asks for it? */
  28. static int the_directory_is_dirty = 1;
  29. static int runningrouters_is_dirty = 1;
  30. static int the_v2_networkstatus_is_dirty = 1;
  31. static void directory_remove_invalid(void);
  32. static int dirserv_regenerate_directory(void);
  33. static char *format_versions_list(config_line_t *ln);
  34. /* Should be static; exposed for testing */
  35. int add_fingerprint_to_dir(const char *nickname, const char *fp,
  36. smartlist_t *list);
  37. static int router_is_general_exit(routerinfo_t *ri);
  38. static router_status_t dirserv_router_get_status(const routerinfo_t *router,
  39. const char **msg);
  40. static router_status_t
  41. dirserv_get_status_impl(const char *fp, const char *nickname,
  42. const char *address,
  43. uint32_t addr, uint16_t or_port,
  44. const char *platform, const char *contact,
  45. const char **msg, int should_log);
  46. static int dirserv_thinks_router_is_reachable(routerinfo_t *router,
  47. time_t now);
  48. /************** Fingerprint handling code ************/
  49. static addr_policy_t *authdir_reject_policy = NULL;
  50. static addr_policy_t *authdir_invalid_policy = NULL;
  51. /** Parse authdir policy strings from the configuration.
  52. */
  53. void
  54. parse_authdir_policy(void)
  55. {
  56. addr_policy_t *n;
  57. if (authdir_reject_policy) {
  58. addr_policy_free(authdir_reject_policy);
  59. authdir_reject_policy = NULL;
  60. }
  61. config_parse_addr_policy(get_options()->AuthDirReject,
  62. &authdir_reject_policy, ADDR_POLICY_REJECT);
  63. /* ports aren't used. */
  64. for (n=authdir_reject_policy; n; n = n->next) {
  65. n->prt_min = 1;
  66. n->prt_max = 65535;
  67. }
  68. if (authdir_invalid_policy) {
  69. addr_policy_free(authdir_invalid_policy);
  70. authdir_invalid_policy = NULL;
  71. }
  72. config_parse_addr_policy(get_options()->AuthDirInvalid,
  73. &authdir_invalid_policy, ADDR_POLICY_REJECT);
  74. /* ports aren't used. */
  75. for (n=authdir_invalid_policy; n; n = n->next) {
  76. n->prt_min = 1;
  77. n->prt_max = 65535;
  78. }
  79. }
  80. /** A member of fingerprint_list: maps a name to a fingerprint.
  81. **/
  82. typedef struct fingerprint_entry_t {
  83. char *nickname; /**< The name of a router (if this fingerprint is bound to a
  84. * name); the string "!reject" (if this fingerprint should
  85. * always be rejected); or the string "!invalid" (if this
  86. * fingerprint should be accepted but never marked as
  87. * valid. */
  88. char *fingerprint; /**< Stored as HEX_DIGEST_LEN characters, followed by a
  89. * NUL */
  90. } fingerprint_entry_t;
  91. /** List of nickname-\>identity fingerprint mappings for all the routers
  92. * that we name. Used to prevent router impersonation. */
  93. /* Should be static; exposed for testing */
  94. smartlist_t *fingerprint_list = NULL;
  95. /** Add the fingerprint <b>fp</b> for the nickname <b>nickname</b> to
  96. * the smartlist of fingerprint_entry_t's <b>list</b>. Return 0 if it's
  97. * new, or 1 if we replaced the old value.
  98. */
  99. int /* Should be static; exposed for testing */
  100. add_fingerprint_to_dir(const char *nickname, const char *fp, smartlist_t *list)
  101. {
  102. int i;
  103. fingerprint_entry_t *ent;
  104. char *fingerprint;
  105. tor_assert(nickname);
  106. tor_assert(fp);
  107. tor_assert(list);
  108. fingerprint = tor_strdup(fp);
  109. tor_strstrip(fingerprint, " ");
  110. if (nickname[0] != '!') {
  111. for (i = 0; i < smartlist_len(list); ++i) {
  112. ent = smartlist_get(list, i);
  113. if (!strcasecmp(ent->nickname,nickname)) {
  114. tor_free(ent->fingerprint);
  115. ent->fingerprint = fingerprint;
  116. return 1;
  117. }
  118. }
  119. }
  120. ent = tor_malloc(sizeof(fingerprint_entry_t));
  121. ent->nickname = tor_strdup(nickname);
  122. ent->fingerprint = fingerprint;
  123. smartlist_add(list, ent);
  124. return 0;
  125. }
  126. /** Add the nickname and fingerprint for this OR to the
  127. * global list of recognized identity key fingerprints. */
  128. int
  129. dirserv_add_own_fingerprint(const char *nickname, crypto_pk_env_t *pk)
  130. {
  131. char fp[FINGERPRINT_LEN+1];
  132. if (crypto_pk_get_fingerprint(pk, fp, 0)<0) {
  133. err(LD_BUG, "Error computing fingerprint");
  134. return -1;
  135. }
  136. if (!fingerprint_list)
  137. fingerprint_list = smartlist_create();
  138. add_fingerprint_to_dir(nickname, fp, fingerprint_list);
  139. return 0;
  140. }
  141. /** Parse the nickname-\>fingerprint mappings stored in the file named
  142. * <b>fname</b>. The file format is line-based, with each non-blank
  143. * holding one nickname, some space, and a fingerprint for that
  144. * nickname. On success, replace the current fingerprint list with
  145. * the contents of <b>fname</b> and return 0. On failure, leave the
  146. * current fingerprint list untouched, and return -1. */
  147. int
  148. dirserv_parse_fingerprint_file(const char *fname)
  149. {
  150. char *cf;
  151. char *nickname, *fingerprint;
  152. smartlist_t *fingerprint_list_new;
  153. int result;
  154. config_line_t *front=NULL, *list;
  155. cf = read_file_to_str(fname, 0);
  156. if (!cf) {
  157. warn(LD_FS, "Cannot open fingerprint file %s", fname);
  158. return -1;
  159. }
  160. result = config_get_lines(cf, &front);
  161. tor_free(cf);
  162. if (result < 0) {
  163. warn(LD_CONFIG, "Error reading from fingerprint file");
  164. return -1;
  165. }
  166. fingerprint_list_new = smartlist_create();
  167. for (list=front; list; list=list->next) {
  168. nickname = list->key; fingerprint = list->value;
  169. if (strlen(nickname) > MAX_NICKNAME_LEN) {
  170. notice(LD_CONFIG,
  171. "Nickname '%s' too long in fingerprint file. Skipping.", nickname);
  172. continue;
  173. }
  174. if (!is_legal_nickname(nickname) &&
  175. strcasecmp(nickname, "!reject") &&
  176. strcasecmp(nickname, "!invalid")) {
  177. notice(LD_CONFIG,
  178. "Invalid nickname '%s' in fingerprint file. Skipping.", nickname);
  179. continue;
  180. }
  181. if (strlen(fingerprint) != FINGERPRINT_LEN ||
  182. !crypto_pk_check_fingerprint_syntax(fingerprint)) {
  183. notice(LD_CONFIG,
  184. "Invalid fingerprint (nickname '%s', fingerprint %s). Skipping.",
  185. nickname, fingerprint);
  186. continue;
  187. }
  188. if (0==strcasecmp(nickname, DEFAULT_CLIENT_NICKNAME)) {
  189. /* If you approved an OR called "client", then clients who use
  190. * the default nickname could all be rejected. That's no good. */
  191. notice(LD_CONFIG,
  192. "Authorizing a nickname '%s' would break many clients; skipping.",
  193. DEFAULT_CLIENT_NICKNAME);
  194. continue;
  195. }
  196. if (add_fingerprint_to_dir(nickname, fingerprint, fingerprint_list_new)
  197. != 0)
  198. notice(LD_CONFIG, "Duplicate nickname '%s'.", nickname);
  199. }
  200. config_free_lines(front);
  201. dirserv_free_fingerprint_list();
  202. fingerprint_list = fingerprint_list_new;
  203. /* Delete any routers whose fingerprints we no longer recognize */
  204. directory_remove_invalid();
  205. return 0;
  206. }
  207. /** Check whether <b>router</b> has a nickname/identity key combination that
  208. * we recognize from the fingerprint list, or an IP we automatically act on
  209. * according to our configuration. Return the appropriate router status.
  210. *
  211. * If the status is 'FP_REJECT' and <b>msg</b> is provided, set
  212. * *<b>msg</b> to an explanation of why. */
  213. static router_status_t
  214. dirserv_router_get_status(const routerinfo_t *router, const char **msg)
  215. {
  216. char fingerprint[FINGERPRINT_LEN+1];
  217. if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 0)) {
  218. warn(LD_BUG,"Error computing fingerprint");
  219. return -1;
  220. }
  221. return dirserv_get_status_impl(fingerprint, router->nickname,
  222. router->address,
  223. router->addr, router->or_port,
  224. router->platform, router->contact_info,
  225. msg, 1);
  226. }
  227. /** Return true if there is no point in downloading the router described by
  228. * <b>rs</b> because this directory would reject it. */
  229. int
  230. dirserv_would_reject_router(routerstatus_t *rs)
  231. {
  232. char fp[FINGERPRINT_LEN+1];
  233. router_status_t res;
  234. base16_encode(fp, sizeof(fp), rs->identity_digest, DIGEST_LEN);
  235. res = dirserv_get_status_impl(fp, rs->nickname,
  236. "", /* address is only used in logs */
  237. rs->addr, rs->or_port,
  238. NULL, NULL,
  239. NULL, 0);
  240. return (res == FP_REJECT);
  241. }
  242. /** Helper: As dirserv_get_router_status, but takes the router fingerprint
  243. * (hex, no spaces), nickname, address (used for logging only), IP address, OR
  244. * port, platform (logging only) and contact info (logging only) as arguments.
  245. *
  246. * If should_log is false, do not log messages. (There's not much point in
  247. * logging that we're rejecting servers we'll not download.)
  248. */
  249. static router_status_t
  250. dirserv_get_status_impl(const char *fp, const char *nickname,
  251. const char *address,
  252. uint32_t addr, uint16_t or_port,
  253. const char *platform, const char *contact,
  254. const char **msg, int should_log)
  255. {
  256. fingerprint_entry_t *nn_ent = NULL, *fp_ent = NULL;
  257. int reject_unlisted = get_options()->AuthDirRejectUnlisted;
  258. if (!fingerprint_list)
  259. fingerprint_list = smartlist_create();
  260. if (should_log)
  261. debug(LD_DIRSERV, "%d fingerprints known.",
  262. smartlist_len(fingerprint_list));
  263. SMARTLIST_FOREACH(fingerprint_list, fingerprint_entry_t *, ent,
  264. {
  265. if (!strcasecmp(fp,ent->fingerprint))
  266. fp_ent = ent;
  267. if (!strcasecmp(nickname,ent->nickname))
  268. nn_ent = ent;
  269. });
  270. if (fp_ent) {
  271. if (!strcasecmp(fp_ent->nickname, "!reject")) {
  272. if (msg)
  273. *msg = "Fingerprint is marked rejected";
  274. return FP_REJECT;
  275. } else if (!strcasecmp(fp_ent->nickname, "!invalid")) {
  276. if (msg)
  277. *msg = "Fingerprint is marked invalid";
  278. return FP_INVALID;
  279. }
  280. }
  281. if (!nn_ent) { /* No such server known with that nickname */
  282. addr_policy_result_t rej = router_compare_addr_to_addr_policy(
  283. addr, or_port, authdir_reject_policy);
  284. addr_policy_result_t inv = router_compare_addr_to_addr_policy(
  285. addr, or_port, authdir_invalid_policy);
  286. if (rej == ADDR_POLICY_PROBABLY_REJECTED || rej == ADDR_POLICY_REJECTED) {
  287. if (should_log)
  288. info(LD_DIRSERV, "Rejecting '%s' because of address '%s'",
  289. nickname, address);
  290. if (msg)
  291. *msg = "Authdir is rejecting routers in this range.";
  292. return FP_REJECT;
  293. }
  294. if (inv == ADDR_POLICY_PROBABLY_REJECTED || inv == ADDR_POLICY_REJECTED) {
  295. if (should_log)
  296. info(LD_DIRSERV, "Not marking '%s' valid because of address '%s'",
  297. nickname, address);
  298. return FP_INVALID;
  299. }
  300. if (should_log)
  301. debug(LD_DIRSERV,"No fingerprint found for '%s'",nickname);
  302. if (!platform || tor_version_as_new_as(platform,"0.1.0.2-rc"))
  303. return reject_unlisted ? FP_REJECT : FP_VALID;
  304. else
  305. return FP_INVALID;
  306. }
  307. if (0==strcasecmp(nn_ent->fingerprint, fp)) {
  308. if (should_log)
  309. debug(LD_DIRSERV,"Good fingerprint for '%s'",nickname);
  310. return FP_NAMED; /* Right fingerprint. */
  311. } else {
  312. if (should_log)
  313. warn(LD_DIRSERV,
  314. "Mismatched fingerprint for '%s': expected '%s' got '%s'. "
  315. "ContactInfo '%s', platform '%s'.)",
  316. nickname, nn_ent->fingerprint, fp,
  317. contact ? contact : "",
  318. platform ? platform : "");
  319. if (msg)
  320. *msg = "Rejected: There is already a verified server with this nickname "
  321. "and a different fingerprint.";
  322. return FP_REJECT; /* Wrong fingerprint. */
  323. }
  324. }
  325. /** If we are an authoritative dirserver, and the list of approved
  326. * servers contains one whose identity key digest is <b>digest</b>,
  327. * return that router's nickname. Otherwise return NULL. */
  328. const char *
  329. dirserv_get_nickname_by_digest(const char *digest)
  330. {
  331. char hexdigest[HEX_DIGEST_LEN+1];
  332. if (!fingerprint_list)
  333. return NULL;
  334. tor_assert(digest);
  335. base16_encode(hexdigest, HEX_DIGEST_LEN+1, digest, DIGEST_LEN);
  336. SMARTLIST_FOREACH(fingerprint_list, fingerprint_entry_t*, ent,
  337. { if (!strcasecmp(hexdigest, ent->fingerprint))
  338. return ent->nickname; } );
  339. return NULL;
  340. }
  341. /** Clear the current fingerprint list. */
  342. void
  343. dirserv_free_fingerprint_list(void)
  344. {
  345. int i;
  346. fingerprint_entry_t *ent;
  347. if (!fingerprint_list)
  348. return;
  349. for (i = 0; i < smartlist_len(fingerprint_list); ++i) {
  350. ent = smartlist_get(fingerprint_list, i);
  351. tor_free(ent->nickname);
  352. tor_free(ent->fingerprint);
  353. tor_free(ent);
  354. }
  355. smartlist_free(fingerprint_list);
  356. fingerprint_list = NULL;
  357. }
  358. /*
  359. * Descriptor list
  360. */
  361. /** Return -1 if <b>ri</b> has a private or otherwise bad address,
  362. * unless we're configured to not care. Return 0 if all ok. */
  363. static int
  364. dirserv_router_has_valid_address(routerinfo_t *ri)
  365. {
  366. struct in_addr iaddr;
  367. if (get_options()->DirAllowPrivateAddresses)
  368. return 0; /* whatever it is, we're fine with it */
  369. if (!tor_inet_aton(ri->address, &iaddr)) {
  370. info(LD_DIRSERV,"Router '%s' published non-IP address '%s'. Refusing.",
  371. ri->nickname, ri->address);
  372. return -1;
  373. }
  374. if (is_internal_IP(ntohl(iaddr.s_addr), 0)) {
  375. info(LD_DIRSERV,
  376. "Router '%s' published internal IP address '%s'. Refusing.",
  377. ri->nickname, ri->address);
  378. return -1; /* it's a private IP, we should reject it */
  379. }
  380. return 0;
  381. }
  382. /** Check whether we, as a directory server, want to accept <b>ri</b>. If so,
  383. * set its is_valid,named,running fields and return 0. Otherwise, return -1.
  384. *
  385. * If the router is rejected, set *<b>msg</b> to an explanation of why.
  386. *
  387. * If <b>complain</b> then explain at log-level 'notice' why we refused
  388. * a descriptor; else explain at log-level 'info'.
  389. */
  390. int
  391. authdir_wants_to_reject_router(routerinfo_t *ri, const char **msg,
  392. int complain)
  393. {
  394. /* Okay. Now check whether the fingerprint is recognized. */
  395. router_status_t status = dirserv_router_get_status(ri, msg);
  396. time_t now;
  397. int severity = complain ? LOG_NOTICE : LOG_INFO;
  398. tor_assert(msg);
  399. if (status == FP_REJECT)
  400. return -1; /* msg is already set. */
  401. /* Is there too much clock skew? */
  402. now = time(NULL);
  403. if (ri->cache_info.published_on > now+ROUTER_ALLOW_SKEW) {
  404. log_fn(severity, LD_DIRSERV, "Publication time for nickname '%s' is too "
  405. "far (%d minutes) in the future; possible clock skew. Not adding "
  406. "(ContactInfo '%s', platform '%s').",
  407. ri->nickname, (int)((ri->cache_info.published_on-now)/60),
  408. ri->contact_info ? ri->contact_info : "",
  409. ri->platform ? ri->platform : "");
  410. *msg = "Rejected: Your clock is set too far in the future, or your "
  411. "timezone is not correct.";
  412. return -1;
  413. }
  414. if (ri->cache_info.published_on < now-ROUTER_MAX_AGE) {
  415. log_fn(severity, LD_DIRSERV,
  416. "Publication time for router with nickname '%s' is too far "
  417. "(%d minutes) in the past. Not adding (ContactInfo '%s', "
  418. "platform '%s').",
  419. ri->nickname, (int)((now-ri->cache_info.published_on)/60),
  420. ri->contact_info ? ri->contact_info : "",
  421. ri->platform ? ri->platform : "");
  422. *msg = "Rejected: Server is expired, or your clock is too far in the past,"
  423. " or your timezone is not correct.";
  424. return -1;
  425. }
  426. if (dirserv_router_has_valid_address(ri) < 0) {
  427. log_fn(severity, LD_DIRSERV,
  428. "Router with nickname '%s' has invalid address '%s'. "
  429. "Not adding (ContactInfo '%s', platform '%s').",
  430. ri->nickname, ri->address,
  431. ri->contact_info ? ri->contact_info : "",
  432. ri->platform ? ri->platform : "");
  433. *msg = "Rejected: Address is not an IP, or IP is a private address.";
  434. return -1;
  435. }
  436. /* Okay, looks like we're willing to accept this one. */
  437. switch (status) {
  438. case FP_NAMED:
  439. ri->is_named = ri->is_verified = 1;
  440. break;
  441. case FP_VALID:
  442. ri->is_named = 0;
  443. ri->is_verified = 1;
  444. break;
  445. case FP_INVALID:
  446. ri->is_named = ri->is_verified = 0;
  447. break;
  448. default:
  449. tor_assert(0);
  450. }
  451. return 0;
  452. }
  453. /** Parse the server descriptor at <b>desc</b> and maybe insert it into
  454. * the list of server descriptors. Set *<b>msg</b> to a message that
  455. * should be passed back to the origin of this descriptor.
  456. *
  457. * Return 2 if descriptor is well-formed and accepted;
  458. * 1 if well-formed and accepted but origin should hear *msg;
  459. * 0 if well-formed but redundant with one we already have;
  460. * -1 if it looks vaguely like a router descriptor but rejected;
  461. * -2 if we can't find a router descriptor in <b>desc</b>.
  462. */
  463. int
  464. dirserv_add_descriptor(const char *desc, const char **msg)
  465. {
  466. int r;
  467. routerinfo_t *ri = NULL, *ri_old = NULL;
  468. tor_assert(msg);
  469. *msg = NULL;
  470. /* Check: is the descriptor syntactically valid? */
  471. ri = router_parse_entry_from_string(desc, NULL);
  472. if (!ri) {
  473. warn(LD_DIRSERV, "Couldn't parse uploaded server descriptor");
  474. *msg = "Rejected: Couldn't parse server descriptor.";
  475. return -2;
  476. }
  477. /* Check whether this descriptor is semantically identical to the last one
  478. * from this server. (We do this here and not in router_add_to_routerlist
  479. * because we want to be able to accept the newest router descriptor that
  480. * another authority has, so we all converge on the same one.) */
  481. ri_old = router_get_by_digest(ri->cache_info.identity_digest);
  482. if (ri_old && ri_old->cache_info.published_on < ri->cache_info.published_on
  483. && router_differences_are_cosmetic(ri_old, ri)
  484. && !router_is_me(ri)) {
  485. info(LD_DIRSERV,
  486. "Not replacing descriptor from '%s'; differences are cosmetic.",
  487. ri->nickname);
  488. *msg = "Not replacing router descriptor; no information has changed since "
  489. "the last one with this identity.";
  490. routerinfo_free(ri);
  491. control_event_or_authdir_new_descriptor("DROPPED", desc, *msg);
  492. return 0;
  493. }
  494. if ((r = router_add_to_routerlist(ri, msg, 0, 0))<0) {
  495. if (r < -1) /* unless the routerinfo was fine, just out-of-date */
  496. control_event_or_authdir_new_descriptor("REJECTED", desc, *msg);
  497. return r == -1 ? 0 : -1;
  498. } else {
  499. smartlist_t *changed;
  500. control_event_or_authdir_new_descriptor("ACCEPTED", desc, *msg);
  501. changed = smartlist_create();
  502. smartlist_add(changed, ri);
  503. control_event_descriptors_changed(changed);
  504. smartlist_free(changed);
  505. if (!*msg) {
  506. *msg = ri->is_verified ? "Verified server descriptor accepted" :
  507. "Unverified server descriptor accepted";
  508. }
  509. return r == 0 ? 2 : 1;
  510. }
  511. }
  512. /** Remove all descriptors whose nicknames or fingerprints no longer
  513. * are allowed by our fingerprint list. (Descriptors that used to be
  514. * good can become bad when we reload the fingerprint list.)
  515. */
  516. static void
  517. directory_remove_invalid(void)
  518. {
  519. int i;
  520. int changed = 0;
  521. routerlist_t *rl = router_get_routerlist();
  522. for (i = 0; i < smartlist_len(rl->routers); ++i) {
  523. const char *msg;
  524. routerinfo_t *ent = smartlist_get(rl->routers, i);
  525. router_status_t r = dirserv_router_get_status(ent, &msg);
  526. switch (r) {
  527. case FP_REJECT:
  528. info(LD_DIRSERV, "Router '%s' is now rejected: %s",
  529. ent->nickname, msg?msg:"");
  530. routerlist_remove(rl, ent, i--, 0);
  531. changed = 1;
  532. break;
  533. case FP_NAMED:
  534. if (!ent->is_verified || !ent->is_named) {
  535. info(LD_DIRSERV,
  536. "Router '%s' is now verified and named.", ent->nickname);
  537. ent->is_verified = ent->is_named = 1;
  538. changed = 1;
  539. }
  540. break;
  541. case FP_VALID:
  542. if (!ent->is_verified || ent->is_named) {
  543. info(LD_DIRSERV, "Router '%s' is now verified.", ent->nickname);
  544. ent->is_verified = 1;
  545. ent->is_named = 0;
  546. changed = 1;
  547. }
  548. break;
  549. case FP_INVALID:
  550. if (ent->is_verified || ent->is_named) {
  551. info(LD_DIRSERV,
  552. "Router '%s' is no longer verified.", ent->nickname);
  553. ent->is_verified = ent->is_named = 0;
  554. changed = 1;
  555. }
  556. break;
  557. }
  558. }
  559. if (changed)
  560. directory_set_dirty();
  561. }
  562. /** Write a list of unregistered descriptors into a newly allocated
  563. * string and return it. Used by dirserv operators to keep track of
  564. * fast nodes that haven't registered.
  565. */
  566. char *
  567. dirserver_getinfo_unregistered(const char *question)
  568. {
  569. router_status_t r;
  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. r = dirserv_router_get_status(ent, NULL);
  578. if (ent->bandwidthcapacity >= (size_t)min_bw &&
  579. ent->bandwidthrate >= (size_t)min_bw &&
  580. r != FP_NAMED) {
  581. /* then log this one */
  582. tor_snprintf(buf, sizeof(buf),
  583. "%s: BW %d on '%s'.",
  584. ent->nickname, ent->bandwidthcapacity,
  585. ent->platform ? ent->platform : "");
  586. smartlist_add(answerlist, tor_strdup(buf));
  587. }
  588. });
  589. answer = smartlist_join_strings(answerlist, "\r\n", 0, NULL);
  590. SMARTLIST_FOREACH(answerlist, char *, cp, tor_free(cp));
  591. smartlist_free(answerlist);
  592. return answer;
  593. }
  594. /** Mark the directory as <b>dirty</b> -- when we're next asked for a
  595. * directory, we will rebuild it instead of reusing the most recently
  596. * generated one.
  597. */
  598. void
  599. directory_set_dirty(void)
  600. {
  601. time_t now = time(NULL);
  602. if (!the_directory_is_dirty)
  603. the_directory_is_dirty = now;
  604. if (!runningrouters_is_dirty)
  605. runningrouters_is_dirty = now;
  606. if (!the_v2_networkstatus_is_dirty)
  607. the_v2_networkstatus_is_dirty = now;
  608. }
  609. /**
  610. * Allocate and return a description of the status of the server <b>desc</b>,
  611. * for use in a router-status line. The server is listed
  612. * as running iff <b>is_live</b> is true.
  613. */
  614. static char *
  615. list_single_server_status(routerinfo_t *desc, int is_live)
  616. {
  617. char buf[MAX_NICKNAME_LEN+HEX_DIGEST_LEN+4]; /* !nickname=$hexdigest\0 */
  618. char *cp;
  619. tor_assert(desc);
  620. cp = buf;
  621. if (!is_live) {
  622. *cp++ = '!';
  623. }
  624. if (desc->is_verified) {
  625. strlcpy(cp, desc->nickname, sizeof(buf)-(cp-buf));
  626. cp += strlen(cp);
  627. *cp++ = '=';
  628. }
  629. *cp++ = '$';
  630. base16_encode(cp, HEX_DIGEST_LEN+1, desc->cache_info.identity_digest,
  631. DIGEST_LEN);
  632. return tor_strdup(buf);
  633. }
  634. #define REACHABLE_TIMEOUT (90*60) /* ninety minutes */
  635. /* Make sure this is at least 3 times the value of get_dir_fetch_period() */
  636. /** Treat a router as alive if
  637. * - It's me, and I'm not hibernating.
  638. * or - we're connected to it and we've found it reachable recently. */
  639. static int
  640. dirserv_thinks_router_is_reachable(routerinfo_t *router, time_t now)
  641. {
  642. connection_t *conn;
  643. if (router_is_me(router) && !we_are_hibernating())
  644. return 1;
  645. conn = connection_or_get_by_identity_digest(
  646. router->cache_info.identity_digest);
  647. if (conn && conn->state == OR_CONN_STATE_OPEN)
  648. return get_options()->AssumeReachable ||
  649. now < router->last_reachable + REACHABLE_TIMEOUT;
  650. return 0;
  651. }
  652. /** Return 1 if we're confident that there's a problem with
  653. * <b>router</b>'s reachability and its operator should be notified.
  654. */
  655. int
  656. dirserv_thinks_router_is_blatantly_unreachable(routerinfo_t *router,
  657. time_t now)
  658. {
  659. connection_t *conn;
  660. if (router->is_hibernating)
  661. return 0;
  662. conn = connection_or_get_by_identity_digest(
  663. router->cache_info.identity_digest);
  664. if (conn && conn->state == OR_CONN_STATE_OPEN &&
  665. now >= router->last_reachable + 2*REACHABLE_TIMEOUT &&
  666. router->testing_since &&
  667. now >= router->testing_since + 2*REACHABLE_TIMEOUT)
  668. return 1;
  669. return 0;
  670. }
  671. /** Based on the routerinfo_ts in <b>routers</b>, allocate the
  672. * contents of a router-status line, and store it in
  673. * *<b>router_status_out</b>. Return 0 on success, -1 on failure.
  674. */
  675. int
  676. list_server_status(smartlist_t *routers, char **router_status_out)
  677. {
  678. /* List of entries in a router-status style: An optional !, then an optional
  679. * equals-suffixed nickname, then a dollar-prefixed hexdigest. */
  680. smartlist_t *rs_entries;
  681. time_t now = time(NULL);
  682. time_t cutoff = now - ROUTER_MAX_AGE;
  683. int authdir_mode = get_options()->AuthoritativeDir;
  684. tor_assert(router_status_out);
  685. rs_entries = smartlist_create();
  686. SMARTLIST_FOREACH(routers, routerinfo_t *, ri,
  687. {
  688. if (authdir_mode) {
  689. /* Update router status in routerinfo_t. */
  690. ri->is_running = dirserv_thinks_router_is_reachable(ri, now);
  691. }
  692. if (ri->cache_info.published_on >= cutoff)
  693. smartlist_add(rs_entries, list_single_server_status(ri, ri->is_running));
  694. });
  695. *router_status_out = smartlist_join_strings(rs_entries, " ", 0, NULL);
  696. SMARTLIST_FOREACH(rs_entries, char *, cp, tor_free(cp));
  697. smartlist_free(rs_entries);
  698. return 0;
  699. }
  700. /* Given a (possibly empty) list of config_line_t, each line of which contains
  701. * a list of comma-separated version numbers surrounded by optional space,
  702. * allocate and return a new string containing the version numbers, in order,
  703. * separated by commas. Used to generate Recommended(Client|Server)?Versions
  704. */
  705. static char *
  706. format_versions_list(config_line_t *ln)
  707. {
  708. smartlist_t *versions;
  709. char *result;
  710. versions = smartlist_create();
  711. for ( ; ln; ln = ln->next) {
  712. smartlist_split_string(versions, ln->value, ",",
  713. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  714. }
  715. sort_version_list(versions);
  716. result = smartlist_join_strings(versions,",",0,NULL);
  717. SMARTLIST_FOREACH(versions,char *,s,tor_free(s));
  718. smartlist_free(versions);
  719. return result;
  720. }
  721. /** Generate a new directory and write it into a newly allocated string.
  722. * Point *<b>dir_out</b> to the allocated string. Sign the
  723. * directory with <b>private_key</b>. Return 0 on success, -1 on
  724. * failure.
  725. */
  726. int
  727. dirserv_dump_directory_to_string(char **dir_out,
  728. crypto_pk_env_t *private_key)
  729. {
  730. char *cp;
  731. char *router_status;
  732. char *identity_pkey; /* Identity key, DER64-encoded. */
  733. char *recommended_versions;
  734. char digest[DIGEST_LEN];
  735. char published[ISO_TIME_LEN+1];
  736. time_t published_on;
  737. char *buf = NULL;
  738. size_t buf_len;
  739. size_t identity_pkey_len;
  740. routerlist_t *rl = router_get_routerlist();
  741. tor_assert(dir_out);
  742. *dir_out = NULL;
  743. if (list_server_status(rl->routers, &router_status))
  744. return -1;
  745. if (crypto_pk_write_public_key_to_string(private_key,&identity_pkey,
  746. &identity_pkey_len)<0) {
  747. warn(LD_BUG,"write identity_pkey to string failed!");
  748. return -1;
  749. }
  750. recommended_versions =
  751. format_versions_list(get_options()->RecommendedVersions);
  752. published_on = time(NULL);
  753. format_iso_time(published, published_on);
  754. buf_len = 2048+strlen(recommended_versions)+
  755. strlen(router_status);
  756. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri,
  757. buf_len += ri->cache_info.signed_descriptor_len+1);
  758. buf = tor_malloc(buf_len);
  759. /* We'll be comparing against buf_len throughout the rest of the
  760. function, though strictly speaking we shouldn't be able to exceed
  761. it. This is C, after all, so we may as well check for buffer
  762. overruns.*/
  763. tor_snprintf(buf, buf_len,
  764. "signed-directory\n"
  765. "published %s\n"
  766. "recommended-software %s\n"
  767. "router-status %s\n"
  768. "dir-signing-key\n%s\n",
  769. published, recommended_versions, router_status,
  770. identity_pkey);
  771. tor_free(recommended_versions);
  772. tor_free(router_status);
  773. tor_free(identity_pkey);
  774. cp = buf + strlen(buf);
  775. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri,
  776. {
  777. size_t len = ri->cache_info.signed_descriptor_len;
  778. const char *body;
  779. if (cp+len+1 >= buf+buf_len)
  780. goto truncated;
  781. body = signed_descriptor_get_body(&ri->cache_info);
  782. memcpy(cp, body, len);
  783. cp += len;
  784. *cp++ = '\n'; /* add an extra newline in case somebody was depending on
  785. * it. */
  786. });
  787. *cp = '\0';
  788. /* These multiple strlcat calls are inefficient, but dwarfed by the RSA
  789. signature. */
  790. if (strlcat(buf, "directory-signature ", buf_len) >= buf_len)
  791. goto truncated;
  792. if (strlcat(buf, get_options()->Nickname, buf_len) >= buf_len)
  793. goto truncated;
  794. if (strlcat(buf, "\n", buf_len) >= buf_len)
  795. goto truncated;
  796. if (router_get_dir_hash(buf,digest)) {
  797. warn(LD_BUG,"couldn't compute digest");
  798. tor_free(buf);
  799. return -1;
  800. }
  801. if (router_append_dirobj_signature(buf,buf_len,digest,private_key)<0) {
  802. tor_free(buf);
  803. return -1;
  804. }
  805. *dir_out = buf;
  806. return 0;
  807. truncated:
  808. warn(LD_BUG,"tried to exceed string length.");
  809. tor_free(buf);
  810. return -1;
  811. }
  812. /** Most recently generated encoded signed directory. (auth dirservers only.)*/
  813. static cached_dir_t the_directory = { NULL, NULL, 0, 0, 0 };
  814. /* Used only by non-auth dirservers: The directory and runningrouters we'll
  815. * serve when requested. */
  816. static cached_dir_t cached_directory = { NULL, NULL, 0, 0, 0 };
  817. static cached_dir_t cached_runningrouters = { NULL, NULL, 0, 0, 0 };
  818. /* Used for other dirservers' v2 network statuses. Map from hexdigest to
  819. * cached_dir_t. */
  820. static digestmap_t *cached_v2_networkstatus = NULL;
  821. /** Possibly replace the contents of <b>d</b> with the value of
  822. * <b>directory</b> published on <b>when</b>, unless <b>when</b> is older than
  823. * the last value, or too far in the future.
  824. *
  825. * Does not copy <b>directory</b>; free it if it isn't used.
  826. */
  827. static void
  828. set_cached_dir(cached_dir_t *d, char *directory, time_t when)
  829. {
  830. time_t now = time(NULL);
  831. if (when<=d->published) {
  832. info(LD_DIRSERV, "Ignoring old directory; not caching.");
  833. tor_free(directory);
  834. } else if (when>=now+ROUTER_MAX_AGE) {
  835. info(LD_DIRSERV, "Ignoring future directory; not caching.");
  836. tor_free(directory);
  837. } else {
  838. /* if (when>d->published && when<now+ROUTER_MAX_AGE) */
  839. debug(LD_DIRSERV, "Caching directory.");
  840. tor_free(d->dir);
  841. d->dir = directory;
  842. d->dir_len = strlen(directory);
  843. tor_free(d->dir_z);
  844. if (tor_gzip_compress(&(d->dir_z), &(d->dir_z_len), d->dir, d->dir_len,
  845. ZLIB_METHOD)) {
  846. warn(LD_BUG,"Error compressing cached directory");
  847. }
  848. d->published = when;
  849. }
  850. }
  851. /** Remove all storage held in <b>d</b>, but do not free <b>d</b> itself. */
  852. static void
  853. clear_cached_dir(cached_dir_t *d)
  854. {
  855. tor_free(d->dir);
  856. tor_free(d->dir_z);
  857. memset(d, 0, sizeof(cached_dir_t));
  858. }
  859. /** Free all storage held by the cached_dir_t in <b>d</b>. */
  860. static void
  861. free_cached_dir(void *_d)
  862. {
  863. cached_dir_t *d = (cached_dir_t *)_d;
  864. clear_cached_dir(d);
  865. tor_free(d);
  866. }
  867. /** If we have no cached directory, or it is older than <b>when</b>, then
  868. * replace it with <b>directory</b>, published at <b>when</b>.
  869. */
  870. void
  871. dirserv_set_cached_directory(const char *directory, time_t published,
  872. int is_running_routers)
  873. {
  874. cached_dir_t *d;
  875. d = is_running_routers ? &cached_runningrouters : &cached_directory;
  876. set_cached_dir(d, tor_strdup(directory), published);
  877. }
  878. /** We've just received a v2 network-status for an authoritative directory
  879. * with identity digest <b>identity</b> published at
  880. * <b>published</b>. Store it so we can serve it to others. If
  881. * <b>directory</b> is NULL, remove the entry with the given fingerprint from
  882. * the cache.
  883. */
  884. void
  885. dirserv_set_cached_networkstatus_v2(const char *networkstatus,
  886. const char *identity,
  887. time_t published)
  888. {
  889. cached_dir_t *d;
  890. smartlist_t *trusted_dirs;
  891. if (!cached_v2_networkstatus)
  892. cached_v2_networkstatus = digestmap_new();
  893. if (!(d = digestmap_get(cached_v2_networkstatus, identity))) {
  894. if (!networkstatus)
  895. return;
  896. d = tor_malloc_zero(sizeof(cached_dir_t));
  897. digestmap_set(cached_v2_networkstatus, identity, d);
  898. }
  899. tor_assert(d);
  900. if (networkstatus) {
  901. if (published > d->published) {
  902. set_cached_dir(d, tor_strdup(networkstatus), published);
  903. }
  904. } else {
  905. free_cached_dir(d);
  906. digestmap_remove(cached_v2_networkstatus, identity);
  907. }
  908. router_get_trusted_dir_servers(&trusted_dirs);
  909. if (digestmap_size(cached_v2_networkstatus) >
  910. smartlist_len(trusted_dirs) + MAX_UNTRUSTED_NETWORKSTATUSES) {
  911. /* We need to remove the oldest untrusted networkstatus. */
  912. const char *oldest = NULL;
  913. time_t oldest_published = TIME_MAX;
  914. digestmap_iter_t *iter;
  915. for (iter = digestmap_iter_init(cached_v2_networkstatus);
  916. !digestmap_iter_done(iter);
  917. iter = digestmap_iter_next(cached_v2_networkstatus, iter)) {
  918. const char *ident;
  919. void *val;
  920. digestmap_iter_get(iter, &ident, &val);
  921. d = val;
  922. if (d->published < oldest_published &&
  923. !router_get_trusteddirserver_by_digest(ident)) {
  924. oldest = ident;
  925. oldest_published = d->published;
  926. }
  927. }
  928. tor_assert(oldest);
  929. d = digestmap_remove(cached_v2_networkstatus, oldest);
  930. if (d)
  931. free_cached_dir(d);
  932. }
  933. }
  934. /** Helper: If we're an authority for the right directory version (the
  935. * directory version is determined by <b>is_v1_object</b>), try to regenerate
  936. * auth_src as appropriate and return it, falling back to cache_src on
  937. * failure. If we're a cache, return cach_src.
  938. */
  939. static cached_dir_t *
  940. dirserv_pick_cached_dir_obj(cached_dir_t *cache_src,
  941. cached_dir_t *auth_src,
  942. time_t dirty, int (*regenerate)(void),
  943. const char *name,
  944. int is_v1_object)
  945. {
  946. int authority = get_options()->AuthoritativeDir &&
  947. (!is_v1_object || get_options()->V1AuthoritativeDir);
  948. if (!authority) {
  949. return cache_src;
  950. } else {
  951. /* We're authoritative. */
  952. if (regenerate != NULL) {
  953. if (dirty && dirty + DIR_REGEN_SLACK_TIME < time(NULL)) {
  954. if (regenerate()) {
  955. err(LD_BUG, "Couldn't generate %s?", name);
  956. exit(1);
  957. }
  958. } else {
  959. info(LD_DIRSERV, "The %s is still clean; reusing.", name);
  960. }
  961. }
  962. return auth_src ? auth_src : cache_src;
  963. }
  964. }
  965. /** Helper: If we're authoritative and <b>auth_src</b> is set, use
  966. * <b>auth_src</b>, otherwise use <b>cache_src</b>. If we're using
  967. * <b>auth_src</b> and it's been <b>dirty</b> for at least
  968. * DIR_REGEN_SLACK_TIME seconds, call <b>regenerate</b>() to make a fresh one.
  969. * Yields the compressed version of the directory object if <b>compress</b> is
  970. * set; otherwise return the uncompressed version. (In either case, sets
  971. * *<b>out</b> and returns the size of the buffer in *<b>out</b>.)
  972. *
  973. * Use <b>is_v1_object</b> to help determine whether we're authoritative for
  974. * this kind of object.
  975. **/
  976. static size_t
  977. dirserv_get_obj(const char **out, int compress,
  978. cached_dir_t *cache_src,
  979. cached_dir_t *auth_src,
  980. time_t dirty, int (*regenerate)(void),
  981. const char *name,
  982. int is_v1_object)
  983. {
  984. cached_dir_t *d = dirserv_pick_cached_dir_obj(
  985. cache_src, auth_src,
  986. dirty, regenerate, name, is_v1_object);
  987. if (!d)
  988. return 0;
  989. *out = compress ? d->dir_z : d->dir;
  990. if (*out) {
  991. return compress ? d->dir_z_len : d->dir_len;
  992. } else {
  993. /* not yet available. */
  994. return 0;
  995. }
  996. }
  997. /** Set *<b>directory</b> to the most recently generated encoded signed
  998. * directory, generating a new one as necessary. If not an authoritative
  999. * directory may return 0 if no directory is yet cached.*/
  1000. size_t
  1001. dirserv_get_directory(const char **directory, int compress)
  1002. {
  1003. return dirserv_get_obj(directory, compress,
  1004. &cached_directory, &the_directory,
  1005. the_directory_is_dirty,
  1006. dirserv_regenerate_directory,
  1007. "server directory", 1);
  1008. }
  1009. /**
  1010. * Generate a fresh directory (authdirservers only.)
  1011. */
  1012. static int
  1013. dirserv_regenerate_directory(void)
  1014. {
  1015. char *new_directory=NULL;
  1016. if (dirserv_dump_directory_to_string(&new_directory,
  1017. get_identity_key())) {
  1018. warn(LD_BUG, "Error creating directory.");
  1019. tor_free(new_directory);
  1020. return -1;
  1021. }
  1022. set_cached_dir(&the_directory, new_directory, time(NULL));
  1023. info(LD_DIRSERV,"New directory (size %d) has been built.",
  1024. (int)the_directory.dir_len);
  1025. debug(LD_DIRSERV,"New directory (size %d):\n%s",(int)the_directory.dir_len,
  1026. the_directory.dir);
  1027. the_directory_is_dirty = 0;
  1028. /* Save the directory to disk so we re-load it quickly on startup.
  1029. */
  1030. dirserv_set_cached_directory(the_directory.dir, time(NULL), 0);
  1031. return 0;
  1032. }
  1033. /** For authoritative directories: the current (v1) network status */
  1034. static cached_dir_t the_runningrouters = { NULL, NULL, 0, 0, 0 };
  1035. /** Replace the current running-routers list with a newly generated one. */
  1036. static int
  1037. generate_runningrouters(void)
  1038. {
  1039. char *s=NULL;
  1040. char *router_status=NULL;
  1041. char digest[DIGEST_LEN];
  1042. char published[ISO_TIME_LEN+1];
  1043. size_t len;
  1044. crypto_pk_env_t *private_key = get_identity_key();
  1045. char *identity_pkey; /* Identity key, DER64-encoded. */
  1046. size_t identity_pkey_len;
  1047. routerlist_t *rl = router_get_routerlist();
  1048. if (list_server_status(rl->routers, &router_status)) {
  1049. goto err;
  1050. }
  1051. if (crypto_pk_write_public_key_to_string(private_key,&identity_pkey,
  1052. &identity_pkey_len)<0) {
  1053. warn(LD_BUG,"write identity_pkey to string failed!");
  1054. goto err;
  1055. }
  1056. format_iso_time(published, time(NULL));
  1057. len = 2048+strlen(router_status);
  1058. s = tor_malloc_zero(len);
  1059. tor_snprintf(s, len,
  1060. "network-status\n"
  1061. "published %s\n"
  1062. "router-status %s\n"
  1063. "dir-signing-key\n%s"
  1064. "directory-signature %s\n",
  1065. published, router_status, identity_pkey,
  1066. get_options()->Nickname);
  1067. tor_free(router_status);
  1068. tor_free(identity_pkey);
  1069. if (router_get_runningrouters_hash(s,digest)) {
  1070. warn(LD_BUG,"couldn't compute digest");
  1071. goto err;
  1072. }
  1073. if (router_append_dirobj_signature(s, len, digest, private_key)<0)
  1074. goto err;
  1075. set_cached_dir(&the_runningrouters, s, time(NULL));
  1076. runningrouters_is_dirty = 0;
  1077. return 0;
  1078. err:
  1079. tor_free(s);
  1080. tor_free(router_status);
  1081. return -1;
  1082. }
  1083. /** Set *<b>rr</b> to the most recently generated encoded signed
  1084. * running-routers list, generating a new one as necessary. Return the
  1085. * size of the directory on success, and 0 on failure. */
  1086. size_t
  1087. dirserv_get_runningrouters(const char **rr, int compress)
  1088. {
  1089. return dirserv_get_obj(rr, compress,
  1090. &cached_runningrouters, &the_runningrouters,
  1091. runningrouters_is_dirty,
  1092. generate_runningrouters,
  1093. "v1 network status list", 1);
  1094. }
  1095. /** Return true iff <b>ri</b> is "useful as an exit node", meaning
  1096. * it allows exit to at least one /8 address space for at least
  1097. * one of ports 80, 443, and 6667. */
  1098. static int
  1099. router_is_general_exit(routerinfo_t *ri)
  1100. {
  1101. static const int ports[] = { 80, 443, 6667 };
  1102. int n_allowed = 0;
  1103. int i;
  1104. for (i = 0; i < 3; ++i) {
  1105. struct addr_policy_t *policy = ri->exit_policy;
  1106. for ( ; policy; policy = policy->next) {
  1107. if (policy->prt_min > ports[i] || policy->prt_max < ports[i])
  1108. continue; /* Doesn't cover our port. */
  1109. if ((policy->msk & 0x00fffffful) != 0)
  1110. continue; /* Narrower than a /8. */
  1111. if ((policy->addr & 0xff000000ul) == 0x7f000000ul)
  1112. continue; /* 127.x */
  1113. /* We have a match that is at least a /8. */
  1114. if (policy->policy_type == ADDR_POLICY_ACCEPT)
  1115. ++n_allowed;
  1116. break;
  1117. }
  1118. }
  1119. return n_allowed > 0;
  1120. }
  1121. /** For authoritative directories: the current (v2) network status */
  1122. static cached_dir_t the_v2_networkstatus = { NULL, NULL, 0, 0, 0 };
  1123. static int
  1124. should_generate_v2_networkstatus(void)
  1125. {
  1126. return get_options()->AuthoritativeDir &&
  1127. the_v2_networkstatus_is_dirty &&
  1128. the_v2_networkstatus_is_dirty + DIR_REGEN_SLACK_TIME < time(NULL);
  1129. }
  1130. long stable_uptime = 0; /* start at a safe value */
  1131. /** Return 1 if <b>router</b> is not suitable for these parameters, else 0.
  1132. * If <b>need_uptime</b> is non-zero, we require a minimum uptime.
  1133. * If <b>need_capacity</b> is non-zero, we require a minimum advertised
  1134. * bandwidth.
  1135. */
  1136. static int
  1137. dirserv_thinks_router_is_unreliable(routerinfo_t *router,
  1138. int need_uptime, int need_capacity)
  1139. {
  1140. if (need_uptime && router->uptime < stable_uptime)
  1141. return 1;
  1142. if (need_capacity &&
  1143. router->bandwidthcapacity < ROUTER_REQUIRED_MIN_BANDWIDTH)
  1144. return 1;
  1145. return 0;
  1146. }
  1147. static int
  1148. _compare_longs(const void **a, const void **b)
  1149. {
  1150. long first = **(long **)a, second = **(long **)b;
  1151. if (first < second) return -1;
  1152. if (first > second) return 1;
  1153. return 0;
  1154. }
  1155. /** Look through the routerlist, and assign the median uptime
  1156. * of running verified servers to stable_uptime. */
  1157. static void
  1158. dirserv_compute_stable_uptime(routerlist_t *rl)
  1159. {
  1160. smartlist_t *uptimes = smartlist_create();
  1161. long *up;
  1162. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
  1163. if (ri->is_running && ri->is_verified) {
  1164. up = tor_malloc(sizeof(long));
  1165. *up = ri->uptime;
  1166. smartlist_add(uptimes, up);
  1167. }
  1168. });
  1169. smartlist_sort(uptimes, _compare_longs);
  1170. stable_uptime = *(long *)smartlist_get(uptimes,
  1171. smartlist_len(uptimes)/2);
  1172. info(LD_DIRSERV, "Uptime cutoff is %ld seconds.", stable_uptime);
  1173. SMARTLIST_FOREACH(uptimes, long *, up, tor_free(up));
  1174. smartlist_free(uptimes);
  1175. }
  1176. /** For authoritative directories only: replace the contents of
  1177. * <b>the_v2_networkstatus</b> with a newly generated network status
  1178. * object. */
  1179. static int
  1180. generate_v2_networkstatus(void)
  1181. {
  1182. #define LONGEST_STATUS_FLAG_NAME_LEN 7
  1183. #define N_STATUS_FLAGS 6
  1184. #define RS_ENTRY_LEN \
  1185. ( /* first line */ \
  1186. MAX_NICKNAME_LEN+BASE64_DIGEST_LEN*2+ISO_TIME_LEN+INET_NTOA_BUF_LEN+ \
  1187. 5*2 /* ports */ + 10 /* punctuation */ + \
  1188. /* second line */ \
  1189. (LONGEST_STATUS_FLAG_NAME_LEN+1)*N_STATUS_FLAGS + 2)
  1190. int r = -1;
  1191. size_t len, identity_pkey_len;
  1192. char *status = NULL, *client_versions = NULL, *server_versions = NULL,
  1193. *identity_pkey = NULL, *hostname = NULL;
  1194. char *outp, *endp;
  1195. or_options_t *options = get_options();
  1196. char fingerprint[FINGERPRINT_LEN+1];
  1197. char ipaddr[INET_NTOA_BUF_LEN+1];
  1198. char published[ISO_TIME_LEN];
  1199. char digest[DIGEST_LEN];
  1200. struct in_addr in;
  1201. uint32_t addr;
  1202. crypto_pk_env_t *private_key = get_identity_key();
  1203. routerlist_t *rl = router_get_routerlist();
  1204. time_t now = time(NULL);
  1205. time_t cutoff = now - ROUTER_MAX_AGE;
  1206. int naming = options->NamingAuthoritativeDir;
  1207. int versioning = options->VersioningAuthoritativeDir;
  1208. const char *contact;
  1209. if (resolve_my_address(options, &addr, &hostname)<0) {
  1210. warn(LD_NET, "Couldn't resolve my hostname");
  1211. goto done;
  1212. }
  1213. in.s_addr = htonl(addr);
  1214. tor_inet_ntoa(&in, ipaddr, sizeof(ipaddr));
  1215. format_iso_time(published, time(NULL));
  1216. client_versions = format_versions_list(options->RecommendedClientVersions);
  1217. server_versions = format_versions_list(options->RecommendedServerVersions);
  1218. if (crypto_pk_write_public_key_to_string(private_key, &identity_pkey,
  1219. &identity_pkey_len)<0) {
  1220. warn(LD_BUG,"Writing public key to string failed.");
  1221. goto done;
  1222. }
  1223. if (crypto_pk_get_fingerprint(private_key, fingerprint, 0)<0) {
  1224. err(LD_BUG, "Error computing fingerprint");
  1225. goto done;
  1226. }
  1227. contact = get_options()->ContactInfo;
  1228. if (!contact)
  1229. contact = "(none)";
  1230. len = 2048+strlen(client_versions)+strlen(server_versions);
  1231. len += identity_pkey_len*2;
  1232. len += (RS_ENTRY_LEN)*smartlist_len(rl->routers);
  1233. status = tor_malloc(len);
  1234. tor_snprintf(status, len,
  1235. "network-status-version 2\n"
  1236. "dir-source %s %s %d\n"
  1237. "fingerprint %s\n"
  1238. "contact %s\n"
  1239. "published %s\n"
  1240. "dir-options%s%s\n"
  1241. "client-versions %s\n"
  1242. "server-versions %s\n"
  1243. "dir-signing-key\n%s\n",
  1244. hostname, ipaddr, (int)options->DirPort,
  1245. fingerprint,
  1246. contact,
  1247. published,
  1248. naming ? " Names" : "",
  1249. versioning ? " Versions" : "",
  1250. client_versions,
  1251. server_versions,
  1252. identity_pkey);
  1253. outp = status + strlen(status);
  1254. endp = status + len;
  1255. /* precompute this part, since we need it to decide what "stable"
  1256. * means. */
  1257. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
  1258. ri->is_running = dirserv_thinks_router_is_reachable(ri, now);
  1259. });
  1260. dirserv_compute_stable_uptime(rl);
  1261. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, ri, {
  1262. if (ri->cache_info.published_on >= cutoff) {
  1263. int f_exit = router_is_general_exit(ri);
  1264. int f_stable = ri->is_stable =
  1265. !dirserv_thinks_router_is_unreliable(ri, 1, 0);
  1266. int f_fast = ri->is_fast =
  1267. !dirserv_thinks_router_is_unreliable(ri, 0, 1);
  1268. int f_running = ri->is_running; /* computed above */
  1269. int f_authority = router_digest_is_trusted_dir(
  1270. ri->cache_info.identity_digest);
  1271. int f_named = naming && ri->is_named;
  1272. int f_valid = ri->is_verified;
  1273. int f_guard = f_fast && f_stable;
  1274. /* 0.1.1.9-alpha is the first version to support fetch by descriptor
  1275. * hash. */
  1276. int f_v2_dir = ri->dir_port &&
  1277. tor_version_as_new_as(ri->platform,"0.1.1.9-alpha");
  1278. char identity64[BASE64_DIGEST_LEN+1];
  1279. char digest64[BASE64_DIGEST_LEN+1];
  1280. format_iso_time(published, ri->cache_info.published_on);
  1281. digest_to_base64(identity64, ri->cache_info.identity_digest);
  1282. digest_to_base64(digest64, ri->cache_info.signed_descriptor_digest);
  1283. in.s_addr = htonl(ri->addr);
  1284. tor_inet_ntoa(&in, ipaddr, sizeof(ipaddr));
  1285. if (tor_snprintf(outp, endp-outp,
  1286. "r %s %s %s %s %s %d %d\n"
  1287. "s%s%s%s%s%s%s%s%s%s\n",
  1288. ri->nickname,
  1289. identity64,
  1290. digest64,
  1291. published,
  1292. ipaddr,
  1293. ri->or_port,
  1294. ri->dir_port,
  1295. f_authority?" Authority":"",
  1296. f_exit?" Exit":"",
  1297. f_fast?" Fast":"",
  1298. f_guard?" Guard":"",
  1299. f_named?" Named":"",
  1300. f_stable?" Stable":"",
  1301. f_running?" Running":"",
  1302. f_valid?" Valid":"",
  1303. f_v2_dir?" V2Dir":"")<0) {
  1304. warn(LD_BUG, "Unable to print router status.");
  1305. goto done;
  1306. }
  1307. outp += strlen(outp);
  1308. }
  1309. });
  1310. if (tor_snprintf(outp, endp-outp, "directory-signature %s\n",
  1311. get_options()->Nickname)<0) {
  1312. warn(LD_BUG, "Unable to write signature line.");
  1313. goto done;
  1314. }
  1315. if (router_get_networkstatus_v2_hash(status, digest)<0) {
  1316. warn(LD_BUG, "Unable to hash network status");
  1317. goto done;
  1318. }
  1319. if (router_append_dirobj_signature(outp,endp-outp,digest,private_key)<0) {
  1320. warn(LD_BUG, "Unable to sign router status.");
  1321. goto done;
  1322. }
  1323. set_cached_dir(&the_v2_networkstatus, status, time(NULL));
  1324. status = NULL; /* So it doesn't get double-freed. */
  1325. the_v2_networkstatus_is_dirty = 0;
  1326. router_set_networkstatus(the_v2_networkstatus.dir, time(NULL), NS_GENERATED,
  1327. NULL);
  1328. r = 0;
  1329. done:
  1330. tor_free(client_versions);
  1331. tor_free(server_versions);
  1332. tor_free(status);
  1333. tor_free(hostname);
  1334. tor_free(identity_pkey);
  1335. return r;
  1336. }
  1337. /** Look for a network status object as specified by <b>key</b>, which should
  1338. * be either "authority" (to find a network status generated by us), a hex
  1339. * identity digest (to find a network status generated by given directory), or
  1340. * "all" (to return all the v2 network status objects we have, concatenated).
  1341. * If <b>compress</b>, find the version compressed with zlib. Return 0 if
  1342. * nothing was found; otherwise set *<b>directory</b> to the matching network
  1343. * status and return its length.
  1344. */
  1345. int
  1346. dirserv_get_networkstatus_v2(smartlist_t *result,
  1347. const char *key)
  1348. {
  1349. tor_assert(result);
  1350. if (!cached_v2_networkstatus)
  1351. cached_v2_networkstatus = digestmap_new();
  1352. if (!(strcmp(key,"authority"))) {
  1353. if (get_options()->AuthoritativeDir) {
  1354. cached_dir_t *d =
  1355. dirserv_pick_cached_dir_obj(NULL,
  1356. &the_v2_networkstatus,
  1357. the_v2_networkstatus_is_dirty,
  1358. generate_v2_networkstatus,
  1359. "network status list", 0);
  1360. if (d)
  1361. smartlist_add(result, d);
  1362. else
  1363. warn(LD_BUG,"Unable to generate an authoritative network status.");
  1364. }
  1365. } else if (!strcmp(key, "all")) {
  1366. digestmap_iter_t *iter;
  1367. if (should_generate_v2_networkstatus())
  1368. generate_v2_networkstatus();
  1369. iter = digestmap_iter_init(cached_v2_networkstatus);
  1370. while (!digestmap_iter_done(iter)) {
  1371. const char *ident;
  1372. void *val;
  1373. digestmap_iter_get(iter, &ident, &val);
  1374. smartlist_add(result, val);
  1375. iter = digestmap_iter_next(cached_v2_networkstatus, iter);
  1376. }
  1377. if (smartlist_len(result) == 0)
  1378. warn(LD_DIRSERV,
  1379. "Client requested 'all' network status objects; we have none.");
  1380. } else if (!strcmpstart(key, "fp/")) {
  1381. smartlist_t *digests = smartlist_create();
  1382. dir_split_resource_into_fingerprints(key+3, digests, NULL, 1);
  1383. SMARTLIST_FOREACH(digests, char *, cp,
  1384. {
  1385. cached_dir_t *cached;
  1386. if (router_digest_is_me(cp) && should_generate_v2_networkstatus())
  1387. generate_v2_networkstatus();
  1388. cached = digestmap_get(cached_v2_networkstatus, cp);
  1389. if (cached) {
  1390. smartlist_add(result, cached);
  1391. } else {
  1392. char hexbuf[HEX_DIGEST_LEN+1];
  1393. base16_encode(hexbuf, sizeof(hexbuf), cp, DIGEST_LEN);
  1394. info(LD_DIRSERV, "Don't know about any network status with "
  1395. "fingerprint '%s'", hexbuf);
  1396. }
  1397. tor_free(cp);
  1398. });
  1399. smartlist_free(digests);
  1400. }
  1401. return 0;
  1402. }
  1403. /** Add a signed_descriptor_t to <b>descs_out</b> for each router matching
  1404. * <b>key</b>. The key should be either
  1405. * - "/tor/server/authority" for our own routerinfo;
  1406. * - "/tor/server/all" for all the routerinfos we have, concatenated;
  1407. * - "/tor/server/fp/FP" where FP is a plus-separated sequence of
  1408. * hex identity digests; or
  1409. * - "/tor/server/d/D" where D is a plus-separated sequence
  1410. * of server descriptor digests, in hex.
  1411. *
  1412. * Return 0 if we found some matching descriptors, or -1 if we do not
  1413. * have any descriptors, no matching descriptors, or if we did not
  1414. * recognize the key (URL).
  1415. * If -1 is returned *<b>msg</b> will be set to an appropriate error
  1416. * message.
  1417. */
  1418. int
  1419. dirserv_get_routerdescs(smartlist_t *descs_out, const char *key,
  1420. const char **msg)
  1421. {
  1422. *msg = NULL;
  1423. if (!strcmp(key, "/tor/server/all")) {
  1424. routerlist_t *rl = router_get_routerlist();
  1425. SMARTLIST_FOREACH(rl->routers, routerinfo_t *, r,
  1426. smartlist_add(descs_out, &(r->cache_info)));
  1427. } else if (!strcmp(key, "/tor/server/authority")) {
  1428. routerinfo_t *ri = router_get_my_routerinfo();
  1429. if (ri)
  1430. smartlist_add(descs_out, &(ri->cache_info));
  1431. } else if (!strcmpstart(key, "/tor/server/d/")) {
  1432. smartlist_t *digests = smartlist_create();
  1433. key += strlen("/tor/server/d/");
  1434. dir_split_resource_into_fingerprints(key, digests, NULL, 1);
  1435. SMARTLIST_FOREACH(digests, const char *, d,
  1436. {
  1437. signed_descriptor_t *sd = router_get_by_descriptor_digest(d);
  1438. if (sd)
  1439. smartlist_add(descs_out,sd);
  1440. });
  1441. SMARTLIST_FOREACH(digests, char *, d, tor_free(d));
  1442. smartlist_free(digests);
  1443. } else if (!strcmpstart(key, "/tor/server/fp/")) {
  1444. smartlist_t *digests = smartlist_create();
  1445. time_t cutoff = time(NULL) - ROUTER_MAX_AGE;
  1446. key += strlen("/tor/server/fp/");
  1447. dir_split_resource_into_fingerprints(key, digests, NULL, 1);
  1448. SMARTLIST_FOREACH(digests, const char *, d,
  1449. {
  1450. if (router_digest_is_me(d)) {
  1451. smartlist_add(descs_out, &(router_get_my_routerinfo()->cache_info));
  1452. } else {
  1453. routerinfo_t *ri = router_get_by_digest(d);
  1454. /* Don't actually serve a descriptor that everyone will think is
  1455. * expired. This is an (ugly) workaround to keep buggy 0.1.1.10
  1456. * Tors from downloading descriptors that they will throw away.
  1457. */
  1458. if (ri && ri->cache_info.published_on > cutoff)
  1459. smartlist_add(descs_out, &(ri->cache_info));
  1460. }
  1461. });
  1462. SMARTLIST_FOREACH(digests, char *, d, tor_free(d));
  1463. smartlist_free(digests);
  1464. } else {
  1465. *msg = "Key not recognized";
  1466. return -1;
  1467. }
  1468. if (!smartlist_len(descs_out)) {
  1469. *msg = "Servers unavailable";
  1470. return -1;
  1471. }
  1472. return 0;
  1473. }
  1474. /** Called when a TLS handshake has completed successfully with a
  1475. * router listening at <b>address</b>:<b>or_port</b>, and has yielded
  1476. * a certificate with digest <b>digest_rcvd</b> and nickname
  1477. * <b>nickname_rcvd</b>. When this happens, it's clear that any other
  1478. * descriptors for that address/port combination must be unusable:
  1479. * delete them if they are not verified.
  1480. *
  1481. * Also, if as_advertised is 1, then inform the reachability checker
  1482. * that we could get to this guy.
  1483. */
  1484. void
  1485. dirserv_orconn_tls_done(const char *address,
  1486. uint16_t or_port,
  1487. const char *digest_rcvd,
  1488. const char *nickname_rcvd,
  1489. int as_advertised)
  1490. {
  1491. int i;
  1492. routerlist_t *rl = router_get_routerlist();
  1493. tor_assert(address);
  1494. tor_assert(digest_rcvd);
  1495. tor_assert(nickname_rcvd);
  1496. // XXXXNM We should really have a better solution here than dropping
  1497. // XXXXNM whole routers; otherwise, they come back way too easily.
  1498. for (i = 0; i < smartlist_len(rl->routers); ++i) {
  1499. routerinfo_t *ri = smartlist_get(rl->routers, i);
  1500. int drop = 0;
  1501. if (strcasecmp(address, ri->address) || or_port != ri->or_port)
  1502. continue;
  1503. if (!ri->is_verified) {
  1504. /* We have a router at the same address! */
  1505. if (strcasecmp(ri->nickname, nickname_rcvd)) {
  1506. notice(LD_DIRSERV, "Dropping descriptor: nickname '%s' does not match "
  1507. "nickname '%s' in cert from %s:%d",
  1508. ri->nickname, nickname_rcvd, address, or_port);
  1509. drop = 1;
  1510. } else if (memcmp(ri->cache_info.identity_digest, digest_rcvd,
  1511. DIGEST_LEN)) {
  1512. notice(LD_DIRSERV, "Dropping descriptor: identity key does not match "
  1513. "key in cert from %s:%d",
  1514. address, or_port);
  1515. drop = 1;
  1516. }
  1517. }
  1518. if (drop) {
  1519. routerlist_remove(rl, ri, i--, 0);
  1520. directory_set_dirty();
  1521. } else { /* correct nickname and digest. mark this router reachable! */
  1522. info(LD_DIRSERV,"Found router %s to be reachable. Yay.", ri->nickname);
  1523. ri->last_reachable = time(NULL);
  1524. ri->num_unreachable_notifications = 0;
  1525. }
  1526. }
  1527. }
  1528. /** Release all storage used by the directory server. */
  1529. void
  1530. dirserv_free_all(void)
  1531. {
  1532. if (fingerprint_list) {
  1533. SMARTLIST_FOREACH(fingerprint_list, fingerprint_entry_t*, fp,
  1534. { tor_free(fp->nickname);
  1535. tor_free(fp->fingerprint);
  1536. tor_free(fp); });
  1537. smartlist_free(fingerprint_list);
  1538. fingerprint_list = NULL;
  1539. }
  1540. if (authdir_reject_policy)
  1541. addr_policy_free(authdir_reject_policy);
  1542. if (authdir_invalid_policy)
  1543. addr_policy_free(authdir_invalid_policy);
  1544. clear_cached_dir(&the_directory);
  1545. clear_cached_dir(&the_runningrouters);
  1546. clear_cached_dir(&the_v2_networkstatus);
  1547. clear_cached_dir(&cached_directory);
  1548. clear_cached_dir(&cached_runningrouters);
  1549. if (cached_v2_networkstatus) {
  1550. digestmap_free(cached_v2_networkstatus, free_cached_dir);
  1551. cached_v2_networkstatus = NULL;
  1552. }
  1553. }