dirserv.c 57 KB

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