dirserv.c 53 KB

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