dirserv.c 50 KB

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