dirserv.c 56 KB

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