dirserv.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  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.
  10. **/
  11. /** How far in the future do we allow a router to get? (seconds) */
  12. #define ROUTER_ALLOW_SKEW (30*60)
  13. /** How many seconds do we wait before regenerating the directory? */
  14. #define DIR_REGEN_SLACK_TIME 10
  15. /** Do we need to regenerate the directory when someone asks for it? */
  16. static int the_directory_is_dirty = 1;
  17. static int runningrouters_is_dirty = 1;
  18. static void directory_remove_unrecognized(void);
  19. static int dirserv_regenerate_directory(void);
  20. /* Should be static; exposed for testing */
  21. void add_fingerprint_to_dir(const char *nickname, const char *fp);
  22. /************** Fingerprint handling code ************/
  23. typedef struct fingerprint_entry_t {
  24. char *nickname;
  25. char *fingerprint; /**< Stored as HEX_DIGEST_LEN characters, followed by a NUL */
  26. } fingerprint_entry_t;
  27. /** List of nickname-\>identity fingerprint mappings for all the routers
  28. * that we recognize. Used to prevent Sybil attacks. */
  29. static smartlist_t *fingerprint_list = NULL;
  30. /** Add the fingerprint <b>fp</b> for the nickname <b>nickname</b> to
  31. * the global list of recognized identity key fingerprints.
  32. */
  33. void /* Should be static; exposed for testing */
  34. add_fingerprint_to_dir(const char *nickname, const char *fp)
  35. {
  36. int i;
  37. fingerprint_entry_t *ent;
  38. if (!fingerprint_list)
  39. fingerprint_list = smartlist_create();
  40. for (i = 0; i < smartlist_len(fingerprint_list); ++i) {
  41. ent = smartlist_get(fingerprint_list, i);
  42. if (!strcasecmp(ent->nickname,nickname)) {
  43. tor_free(ent->fingerprint);
  44. ent->fingerprint = tor_strdup(fp);
  45. return;
  46. }
  47. }
  48. ent = tor_malloc(sizeof(fingerprint_entry_t));
  49. ent->nickname = tor_strdup(nickname);
  50. ent->fingerprint = tor_strdup(fp);
  51. tor_strstrip(ent->fingerprint, " ");
  52. smartlist_add(fingerprint_list, ent);
  53. }
  54. /** Add the nickname and fingerprint for this OR to the recognized list.
  55. */
  56. int
  57. dirserv_add_own_fingerprint(const char *nickname, crypto_pk_env_t *pk)
  58. {
  59. char fp[FINGERPRINT_LEN+1];
  60. if (crypto_pk_get_fingerprint(pk, fp, 0)<0) {
  61. log_fn(LOG_ERR, "Error computing fingerprint");
  62. return -1;
  63. }
  64. add_fingerprint_to_dir(nickname, fp);
  65. return 0;
  66. }
  67. /** Parse the nickname-\>fingerprint mappings stored in the file named
  68. * <b>fname</b>. The file format is line-based, with each non-blank
  69. * holding one nickname, some space, and a fingerprint for that
  70. * nickname. On success, replace the current fingerprint list with
  71. * the contents of <b>fname</b> and return 0. On failure, leave the
  72. * current fingerprint list untouched, and return -1. */
  73. int
  74. dirserv_parse_fingerprint_file(const char *fname)
  75. {
  76. char *cf;
  77. char *nickname, *fingerprint;
  78. smartlist_t *fingerprint_list_new;
  79. int i, result;
  80. fingerprint_entry_t *ent;
  81. struct config_line_t *front=NULL, *list;
  82. cf = read_file_to_str(fname, 0);
  83. if (!cf) {
  84. log_fn(LOG_WARN, "Cannot open fingerprint file %s", fname);
  85. return -1;
  86. }
  87. result = config_get_lines(cf, &front);
  88. tor_free(cf);
  89. if (result < 0) {
  90. log_fn(LOG_WARN, "Error reading from fingerprint file");
  91. return -1;
  92. }
  93. fingerprint_list_new = smartlist_create();
  94. for (list=front; list; list=list->next) {
  95. nickname = list->key; fingerprint = list->value;
  96. if (strlen(nickname) > MAX_NICKNAME_LEN) {
  97. log(LOG_NOTICE, "Nickname '%s' too long in fingerprint file. Skipping.", nickname);
  98. continue;
  99. }
  100. if (strlen(fingerprint) != FINGERPRINT_LEN ||
  101. !crypto_pk_check_fingerprint_syntax(fingerprint)) {
  102. log_fn(LOG_NOTICE, "Invalid fingerprint (nickname '%s', fingerprint %s). Skipping.",
  103. nickname, fingerprint);
  104. continue;
  105. }
  106. if (0==strcasecmp(nickname, DEFAULT_CLIENT_NICKNAME)) {
  107. /* If you approved an OR called "client", then clients who use
  108. * the default nickname could all be rejected. That's no good. */
  109. log(LOG_NOTICE,
  110. "Authorizing a nickname '%s' would break many clients; skipping.",
  111. DEFAULT_CLIENT_NICKNAME);
  112. continue;
  113. }
  114. for (i = 0; i < smartlist_len(fingerprint_list_new); ++i) {
  115. ent = smartlist_get(fingerprint_list_new, i);
  116. if (0==strcasecmp(ent->nickname, nickname)) {
  117. log(LOG_NOTICE, "Duplicate nickname '%s'. Skipping.",nickname);
  118. break; /* out of the for. the 'if' below means skip to the next line. */
  119. }
  120. }
  121. if (i == smartlist_len(fingerprint_list_new)) { /* not a duplicate */
  122. ent = tor_malloc(sizeof(fingerprint_entry_t));
  123. ent->nickname = tor_strdup(nickname);
  124. ent->fingerprint = tor_strdup(fingerprint);
  125. tor_strstrip(ent->fingerprint, " ");
  126. smartlist_add(fingerprint_list_new, ent);
  127. }
  128. }
  129. config_free_lines(front);
  130. dirserv_free_fingerprint_list();
  131. fingerprint_list = fingerprint_list_new;
  132. /* Delete any routers whose fingerprints we no longer recognize */
  133. directory_remove_unrecognized();
  134. return 0;
  135. }
  136. /** Check whether <b>router</b> has a nickname/identity key combination that
  137. * we recognize from the fingerprint list. Return 1 if router's
  138. * identity and nickname match, -1 if we recognize the nickname but
  139. * the identity key is wrong, and 0 if the nickname is not known. */
  140. int
  141. dirserv_router_fingerprint_is_known(const routerinfo_t *router)
  142. {
  143. int i, found=0;
  144. fingerprint_entry_t *ent =NULL;
  145. char fp[FINGERPRINT_LEN+1];
  146. if (!fingerprint_list)
  147. fingerprint_list = smartlist_create();
  148. log_fn(LOG_DEBUG, "%d fingerprints known.", smartlist_len(fingerprint_list));
  149. for (i=0;i<smartlist_len(fingerprint_list);++i) {
  150. ent = smartlist_get(fingerprint_list, i);
  151. log_fn(LOG_DEBUG,"%s vs %s", router->nickname, ent->nickname);
  152. if (!strcasecmp(router->nickname,ent->nickname)) {
  153. found = 1;
  154. break;
  155. }
  156. }
  157. if (!found) { /* No such server known */
  158. log_fn(LOG_INFO,"no fingerprint found for '%s'",router->nickname);
  159. return 0;
  160. }
  161. if (crypto_pk_get_fingerprint(router->identity_pkey, fp, 0)) {
  162. log_fn(LOG_WARN,"error computing fingerprint");
  163. return -1;
  164. }
  165. if (0==strcasecmp(ent->fingerprint, fp)) {
  166. log_fn(LOG_DEBUG,"good fingerprint for '%s'",router->nickname);
  167. return 1; /* Right fingerprint. */
  168. } else {
  169. log_fn(LOG_WARN,"mismatched fingerprint for '%s'",router->nickname);
  170. return -1; /* Wrong fingerprint. */
  171. }
  172. }
  173. /** If we are an authoritative dirserver, and the list of approved
  174. * servers contains one whose identity key digest is <b>digest</b>,
  175. * return that router's nickname. Otherwise return NULL. */
  176. const char *dirserv_get_nickname_by_digest(const char *digest)
  177. {
  178. char hexdigest[HEX_DIGEST_LEN+1];
  179. if (!fingerprint_list)
  180. return NULL;
  181. tor_assert(digest);
  182. base16_encode(hexdigest, HEX_DIGEST_LEN+1, digest, DIGEST_LEN);
  183. SMARTLIST_FOREACH(fingerprint_list, fingerprint_entry_t*, ent,
  184. { if (!strcasecmp(hexdigest, ent->fingerprint))
  185. return ent->nickname; } );
  186. return NULL;
  187. }
  188. #if 0
  189. /** Return true iff any router named <b>nickname</b> with <b>digest</b>
  190. * is in the verified fingerprint list. */
  191. static int
  192. router_nickname_is_approved(const char *nickname, const char *digest)
  193. {
  194. const char *n;
  195. n = dirserv_get_nickname_by_digest(digest);
  196. if (n && !strcasecmp(n,nickname))
  197. return 1;
  198. else
  199. return 0;
  200. }
  201. #endif
  202. /** Clear the current fingerprint list. */
  203. void
  204. dirserv_free_fingerprint_list()
  205. {
  206. int i;
  207. fingerprint_entry_t *ent;
  208. if (!fingerprint_list)
  209. return;
  210. for (i = 0; i < smartlist_len(fingerprint_list); ++i) {
  211. ent = smartlist_get(fingerprint_list, i);
  212. tor_free(ent->nickname);
  213. tor_free(ent->fingerprint);
  214. tor_free(ent);
  215. }
  216. smartlist_free(fingerprint_list);
  217. fingerprint_list = NULL;
  218. }
  219. /*
  220. * Descriptor list
  221. */
  222. /** List of routerinfo_t for all server descriptors that this dirserv
  223. * is holding.
  224. * XXXX This should eventually get coalesced into routerlist.c
  225. */
  226. static smartlist_t *descriptor_list = NULL;
  227. /** Release all storage that the dirserv is holding for server
  228. * descriptors. */
  229. void
  230. dirserv_free_descriptors()
  231. {
  232. if (!descriptor_list)
  233. return;
  234. SMARTLIST_FOREACH(descriptor_list, routerinfo_t *, ri,
  235. routerinfo_free(ri));
  236. smartlist_clear(descriptor_list);
  237. }
  238. /** Return -1 if <b>ri</b> has a private or otherwise bad address,
  239. * unless we're configured to not care. Return 0 if all ok. */
  240. static int
  241. dirserv_router_has_valid_address(routerinfo_t *ri)
  242. {
  243. struct in_addr iaddr;
  244. if (get_options()->DirAllowPrivateAddresses)
  245. return 0; /* whatever it is, we're fine with it */
  246. if (!tor_inet_aton(ri->address, &iaddr)) {
  247. log_fn(LOG_INFO,"Router '%s' published non-IP address '%s'. Refusing.",
  248. ri->nickname, ri->address);
  249. return -1;
  250. }
  251. if (is_internal_IP(ntohl(iaddr.s_addr))) {
  252. log_fn(LOG_INFO,"Router '%s' published internal IP address '%s'. Refusing.",
  253. ri->nickname, ri->address);
  254. return -1; /* it's a private IP, we should reject it */
  255. }
  256. return 0;
  257. }
  258. /** Parse the server descriptor at *desc and maybe insert it into the
  259. * list of server descriptors, and (if the descriptor is well-formed)
  260. * advance *desc immediately past the descriptor's end. Set msg to a
  261. * message that should be passed back to the origin of this descriptor, or
  262. * to NULL.
  263. *
  264. * Return 1 if descriptor is well-formed and accepted;
  265. * 0 if well-formed and server is unapproved but accepted;
  266. * -1 if well-formed but rejected;
  267. * -2 if not well-formed.
  268. */
  269. int
  270. dirserv_add_descriptor(const char **desc, const char **msg)
  271. {
  272. routerinfo_t *ri = NULL, *ri_old=NULL;
  273. int i, r, found=-1;
  274. char *start, *end;
  275. char *desc_tmp = NULL;
  276. size_t desc_len;
  277. time_t now;
  278. int verified=1; /* whether we knew its fingerprint already */
  279. tor_assert(msg);
  280. *msg = NULL;
  281. if (!descriptor_list)
  282. descriptor_list = smartlist_create();
  283. start = strstr(*desc, "router ");
  284. if (!start) {
  285. log_fn(LOG_WARN, "no 'router' line found. This is not a descriptor.");
  286. return -2;
  287. }
  288. if ((end = strstr(start+6, "\nrouter "))) {
  289. ++end; /* Include NL. */
  290. } else if ((end = strstr(start+6, "\ndirectory-signature"))) {
  291. ++end;
  292. } else {
  293. end = start+strlen(start);
  294. }
  295. desc_len = end-start;
  296. desc_tmp = tor_strndup(start, desc_len); /* Is this strndup still needed???*/
  297. /* Check: is the descriptor syntactically valid? */
  298. ri = router_parse_entry_from_string(desc_tmp, NULL);
  299. tor_free(desc_tmp);
  300. if (!ri) {
  301. log(LOG_WARN, "Couldn't parse descriptor");
  302. *msg = "Rejected: Couldn't parse server descriptor.";
  303. return -1;
  304. }
  305. /* Okay. Now check whether the fingerprint is recognized. */
  306. r = dirserv_router_fingerprint_is_known(ri);
  307. if (r==-1) {
  308. log_fn(LOG_WARN, "Known nickname '%s', wrong fingerprint. Not adding.", ri->nickname);
  309. *msg = "Rejected: There is already a verified server with this nickname and a different fingerprint.";
  310. routerinfo_free(ri);
  311. *desc = end;
  312. return -1;
  313. }
  314. if (r==0) {
  315. char fp[FINGERPRINT_LEN+1];
  316. log_fn(LOG_INFO, "Unknown nickname '%s' (%s:%d). Will try to add.",
  317. ri->nickname, ri->address, ri->or_port);
  318. if (crypto_pk_get_fingerprint(ri->identity_pkey, fp, 1) < 0) {
  319. log_fn(LOG_WARN, "Error computing fingerprint for '%s'", ri->nickname);
  320. } else {
  321. log_fn(LOG_INFO, "Fingerprint line: %s %s", ri->nickname, fp);
  322. }
  323. verified = 0;
  324. }
  325. /* Is there too much clock skew? */
  326. now = time(NULL);
  327. if (ri->published_on > now+ROUTER_ALLOW_SKEW) {
  328. log_fn(LOG_NOTICE, "Publication time for nickname '%s' is too far in the future; possible clock skew. Not adding.", ri->nickname);
  329. *msg = "Rejected: Your clock is set too far in the future, or your timezone is not correct.";
  330. routerinfo_free(ri);
  331. *desc = end;
  332. return -1;
  333. }
  334. if (ri->published_on < now-ROUTER_MAX_AGE) {
  335. log_fn(LOG_NOTICE, "Publication time for router with nickname '%s' is too far in the past. Not adding.", ri->nickname);
  336. *msg = "Rejected: Server is expired, or your clock is too far in the past, or your timezone is not correct.";
  337. routerinfo_free(ri);
  338. *desc = end;
  339. return -1;
  340. }
  341. if (dirserv_router_has_valid_address(ri) < 0) {
  342. log_fn(LOG_NOTICE, "Router with nickname '%s' has invalid address '%s'. Not adding.", ri->nickname, ri->address);
  343. *msg = "Rejected: Address is not an IP, or IP is a private address.";
  344. routerinfo_free(ri);
  345. *desc = end;
  346. return -1;
  347. }
  348. /* Do we already have an entry for this router? */
  349. for (i = 0; i < smartlist_len(descriptor_list); ++i) {
  350. ri_old = smartlist_get(descriptor_list, i);
  351. if (!strcasecmp(ri->nickname, ri_old->nickname)) {
  352. found = i;
  353. break;
  354. }
  355. }
  356. if (found >= 0) {
  357. /* if so, decide whether to update it. */
  358. if (ri_old->published_on >= ri->published_on) {
  359. /* We already have a newer or equal-time descriptor */
  360. log_fn(LOG_INFO,"We already have a new enough desc for nickname '%s'. Not adding.",ri->nickname);
  361. *msg = "We already have a newer descriptor.";
  362. /* This isn't really an error; return success. */
  363. routerinfo_free(ri);
  364. *desc = end;
  365. return verified;
  366. }
  367. /* We don't alrady have a newer one; we'll update this one. */
  368. log_fn(LOG_INFO,"Dirserv updating desc for nickname '%s'",ri->nickname);
  369. *msg = verified?"Verified server updated":"Unverified server updated. (Have you sent us your key fingerprint?)";
  370. routerinfo_free(ri_old);
  371. smartlist_del_keeporder(descriptor_list, found);
  372. } else {
  373. /* Add at the end. */
  374. log_fn(LOG_INFO,"Dirserv adding desc for nickname '%s'",ri->nickname);
  375. *msg = verified?"Verified server added":"Unverified server added. (Have you sent us your key fingerprint?)";
  376. }
  377. ri->is_verified = verified;
  378. smartlist_add(descriptor_list, ri);
  379. *desc = end;
  380. directory_set_dirty();
  381. return verified;
  382. }
  383. /** Remove all descriptors whose nicknames or fingerprints we don't
  384. * recognize. (Descriptors that used to be good can become
  385. * unrecognized when we reload the fingerprint list.)
  386. */
  387. static void
  388. directory_remove_unrecognized(void)
  389. {
  390. int i;
  391. routerinfo_t *ent;
  392. if (!descriptor_list)
  393. descriptor_list = smartlist_create();
  394. for (i = 0; i < smartlist_len(descriptor_list); ++i) {
  395. ent = smartlist_get(descriptor_list, i);
  396. if (dirserv_router_fingerprint_is_known(ent)<=0) {
  397. log(LOG_INFO, "Router '%s' is no longer recognized",
  398. ent->nickname);
  399. routerinfo_free(ent);
  400. smartlist_del(descriptor_list, i--);
  401. }
  402. }
  403. }
  404. /** Mark the directory as <b>dirty</b> -- when we're next asked for a
  405. * directory, we will rebuild it instead of reusing the most recently
  406. * generated one.
  407. */
  408. void
  409. directory_set_dirty()
  410. {
  411. time_t now = time(NULL);
  412. if (!the_directory_is_dirty)
  413. the_directory_is_dirty = now;
  414. if (!runningrouters_is_dirty)
  415. runningrouters_is_dirty = now;
  416. }
  417. /** Load all descriptors from a directory stored in the string
  418. * <b>dir</b>.
  419. */
  420. int
  421. dirserv_load_from_directory_string(const char *dir)
  422. {
  423. const char *cp = dir, *m;
  424. while (1) {
  425. cp = strstr(cp, "\nrouter ");
  426. if (!cp) break;
  427. ++cp;
  428. if (dirserv_add_descriptor(&cp,&m) < -1) {
  429. /* only fail if parsing failed; keep going if simply rejected */
  430. return -1;
  431. }
  432. --cp; /*Back up to newline.*/
  433. }
  434. return 0;
  435. }
  436. /**
  437. * Allocate and return a description of the status of the server <b>desc</b>,
  438. * for use in a running-routers line (if <b>rr_format</b> is true), or in a
  439. * router-status line (if <b>rr_format</b> is false. The server is listed
  440. * as running iff <b>is_live</b> is true.
  441. */
  442. static char *
  443. list_single_server_status(routerinfo_t *desc, int is_live,
  444. int rr_format)
  445. {
  446. char buf[MAX_NICKNAME_LEN+HEX_DIGEST_LEN+4]; /* !nickname=$hexdigest\0 */
  447. char *cp;
  448. tor_assert(desc);
  449. cp = buf;
  450. if (!is_live) {
  451. *cp++ = '!';
  452. }
  453. if (desc->is_verified) {
  454. strlcpy(cp, desc->nickname, sizeof(buf)-(cp-buf));
  455. cp += strlen(cp);
  456. if (!rr_format)
  457. *cp++ = '=';
  458. }
  459. if (!desc->is_verified || !rr_format) {
  460. *cp++ = '$';
  461. base16_encode(cp, HEX_DIGEST_LEN+1, desc->identity_digest,
  462. DIGEST_LEN);
  463. }
  464. return tor_strdup(buf);
  465. }
  466. /** Based on the routerinfo_ts in <b>routers</b>, allocate the
  467. * contents of a running-routers line and a router-status line, and
  468. * store them in *<b>running_routers_out</b> and
  469. * *<b>router_status_out</b> respectively. If either is NULL, skip
  470. * it. Return 0 on success, -1 on failure.
  471. */
  472. int
  473. list_server_status(smartlist_t *routers, char **running_routers_out, char **router_status_out)
  474. {
  475. /* List of entries in running-routers style: An optional !, then either
  476. * a nickname or a dollar-prefixed hexdigest. */
  477. smartlist_t *rr_entries;
  478. /* List of entries in a router-status style: An optional !, then an optional
  479. * equals-suffixed nickname, then a dollar-prefixed hexdigest. */
  480. smartlist_t *rs_entries;
  481. /* XXXX Really, we should merge descriptor_list into routerlist. But
  482. * this is potentially tricky, since the semantics of the two lists
  483. * are not quite the same. In any case, it's not for the 0.1.0.x
  484. * series.
  485. */
  486. int authdir_mode = get_options()->AuthoritativeDir;
  487. tor_assert(running_routers_out || router_status_out);
  488. rr_entries = smartlist_create();
  489. rs_entries = smartlist_create();
  490. SMARTLIST_FOREACH(routers, routerinfo_t *, ri,
  491. {
  492. int is_live;
  493. connection_t *conn;
  494. conn = connection_get_by_identity_digest(
  495. ri->identity_digest, CONN_TYPE_OR);
  496. if (authdir_mode) {
  497. /* Treat a router as alive if
  498. * - It's me, and I'm not hibernating.
  499. * or - we're connected to it. */
  500. is_live = (router_is_me(ri) && !we_are_hibernating()) ||
  501. (conn && conn->state == OR_CONN_STATE_OPEN);
  502. } else {
  503. is_live = ri->is_running;
  504. }
  505. smartlist_add(rr_entries, list_single_server_status(ri, is_live, 1));
  506. smartlist_add(rs_entries, list_single_server_status(ri, is_live, 0));
  507. });
  508. if (running_routers_out)
  509. *running_routers_out = smartlist_join_strings(rr_entries, " ", 0,NULL);
  510. if (router_status_out)
  511. *router_status_out = smartlist_join_strings(rs_entries, " ", 0,NULL);
  512. SMARTLIST_FOREACH(rr_entries, char *, cp, tor_free(cp));
  513. SMARTLIST_FOREACH(rs_entries, char *, cp, tor_free(cp));
  514. smartlist_free(rr_entries);
  515. smartlist_free(rs_entries);
  516. return 0;
  517. }
  518. /** Remove any descriptors from the directory that are more than <b>age</b>
  519. * seconds old.
  520. */
  521. void
  522. dirserv_remove_old_servers(int age)
  523. {
  524. int i;
  525. time_t cutoff;
  526. routerinfo_t *ent;
  527. if (!descriptor_list)
  528. descriptor_list = smartlist_create();
  529. cutoff = time(NULL) - age;
  530. for (i = 0; i < smartlist_len(descriptor_list); ++i) {
  531. ent = smartlist_get(descriptor_list, i);
  532. if (ent->published_on <= cutoff) {
  533. /* descriptor_list[i] is too old. Remove it. */
  534. routerinfo_free(ent);
  535. smartlist_del(descriptor_list, i--);
  536. directory_set_dirty();
  537. }
  538. }
  539. }
  540. /** Generate a new directory and write it into a newly allocated string.
  541. * Point *<b>dir_out</b> to the allocated string. Sign the
  542. * directory with <b>private_key</b>. Return 0 on success, -1 on
  543. * failure.
  544. */
  545. int
  546. dirserv_dump_directory_to_string(char **dir_out,
  547. crypto_pk_env_t *private_key)
  548. {
  549. char *cp;
  550. char *running_routers, *router_status;
  551. char *identity_pkey; /* Identity key, DER64-encoded. */
  552. char *recommended_versions;
  553. char digest[20];
  554. char signature[128];
  555. char published[33];
  556. time_t published_on;
  557. char *buf = NULL;
  558. size_t buf_len;
  559. int i;
  560. tor_assert(dir_out);
  561. *dir_out = NULL;
  562. if (!descriptor_list)
  563. descriptor_list = smartlist_create();
  564. if (list_server_status(descriptor_list, &running_routers, &router_status))
  565. return -1;
  566. /* ASN.1-encode the public key. This is a temporary measure; once
  567. * everyone is running 0.0.9pre3 or later, we can shift to using a
  568. * PEM-encoded key instead.
  569. */
  570. #if 1
  571. if (crypto_pk_DER64_encode_public_key(private_key, &identity_pkey)<0) {
  572. log_fn(LOG_WARN,"write identity_pkey to string failed!");
  573. return -1;
  574. }
  575. #else
  576. {
  577. int l;
  578. if (crypto_pk_write_public_key_to_string(private_key,&identity_pkey,&l)<0) {
  579. log_fn(LOG_WARN,"write identity_pkey to string failed!");
  580. return -1;
  581. }
  582. }
  583. #endif
  584. {
  585. smartlist_t *versions;
  586. struct config_line_t *ln;
  587. versions = smartlist_create();
  588. for (ln = get_options()->RecommendedVersions; ln; ln = ln->next) {
  589. smartlist_split_string(versions, ln->value, ",",
  590. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  591. }
  592. recommended_versions = smartlist_join_strings(versions,",",0,NULL);
  593. SMARTLIST_FOREACH(versions,char *,s,tor_free(s));
  594. smartlist_free(versions);
  595. }
  596. dirserv_remove_old_servers(ROUTER_MAX_AGE);
  597. published_on = time(NULL);
  598. format_iso_time(published, published_on);
  599. buf_len = 2048+strlen(recommended_versions)+strlen(running_routers)+
  600. strlen(router_status);
  601. SMARTLIST_FOREACH(descriptor_list, routerinfo_t *, ri,
  602. buf_len += strlen(ri->signed_descriptor));
  603. buf = tor_malloc(buf_len);
  604. /* We'll be comparing against buf_len throughout the rest of the
  605. function, though strictly speaking we shouldn't be able to exceed
  606. it. This is C, after all, so we may as well check for buffer
  607. overruns.*/
  608. tor_snprintf(buf, buf_len,
  609. "signed-directory\n"
  610. "published %s\n"
  611. "recommended-software %s\n"
  612. "running-routers %s\n"
  613. "opt router-status %s\n"
  614. "opt dir-signing-key %s\n\n",
  615. published, recommended_versions, running_routers, router_status,
  616. identity_pkey);
  617. tor_free(recommended_versions);
  618. tor_free(running_routers);
  619. tor_free(router_status);
  620. tor_free(identity_pkey);
  621. i = strlen(buf);
  622. cp = buf+i;
  623. SMARTLIST_FOREACH(descriptor_list, routerinfo_t *, ri,
  624. if (strlcat(buf, ri->signed_descriptor, buf_len) >= buf_len)
  625. goto truncated);
  626. /* These multiple strlcat calls are inefficient, but dwarfed by the RSA
  627. signature.
  628. */
  629. if (strlcat(buf, "directory-signature ", buf_len) >= buf_len)
  630. goto truncated;
  631. if (strlcat(buf, get_options()->Nickname, buf_len) >= buf_len)
  632. goto truncated;
  633. if (strlcat(buf, "\n", buf_len) >= buf_len)
  634. goto truncated;
  635. if (router_get_dir_hash(buf,digest)) {
  636. log_fn(LOG_WARN,"couldn't compute digest");
  637. tor_free(buf);
  638. return -1;
  639. }
  640. if (crypto_pk_private_sign(private_key, signature, digest, 20) < 0) {
  641. log_fn(LOG_WARN,"couldn't sign digest");
  642. tor_free(buf);
  643. return -1;
  644. }
  645. log(LOG_DEBUG,"generated directory digest begins with %s",hex_str(digest,4));
  646. if (strlcat(cp, "-----BEGIN SIGNATURE-----\n", buf_len) >= buf_len)
  647. goto truncated;
  648. i = strlen(buf);
  649. cp = buf+i;
  650. if (base64_encode(cp, buf_len-i, signature, 128) < 0) {
  651. log_fn(LOG_WARN,"couldn't base64-encode signature");
  652. tor_free(buf);
  653. return -1;
  654. }
  655. if (strlcat(buf, "-----END SIGNATURE-----\n", buf_len) >= buf_len)
  656. goto truncated;
  657. *dir_out = buf;
  658. return 0;
  659. truncated:
  660. log_fn(LOG_WARN,"tried to exceed string length.");
  661. tor_free(buf);
  662. return -1;
  663. }
  664. /** Most recently generated encoded signed directory. */
  665. static char *the_directory = NULL;
  666. static size_t the_directory_len = 0;
  667. static char *the_directory_z = NULL;
  668. static size_t the_directory_z_len = 0;
  669. typedef struct cached_dir_t {
  670. char *dir;
  671. char *dir_z;
  672. size_t dir_len;
  673. size_t dir_z_len;
  674. time_t published;
  675. } cached_dir_t;
  676. /* used only by non-auth dirservers */
  677. static cached_dir_t cached_directory = { NULL, NULL, 0, 0, 0 };
  678. static cached_dir_t cached_runningrouters = { NULL, NULL, 0, 0, 0 };
  679. /** If we have no cached directory, or it is older than <b>when</b>, then
  680. * replace it with <b>directory</b>, published at <b>when</b>.
  681. */
  682. void dirserv_set_cached_directory(const char *directory, time_t when,
  683. int is_running_routers)
  684. {
  685. time_t now;
  686. cached_dir_t *d;
  687. now = time(NULL);
  688. d = is_running_routers ? &cached_runningrouters : &cached_directory;
  689. if (when<=d->published) {
  690. log_fn(LOG_INFO, "Ignoring old directory; not caching.");
  691. } else if (when>=now+ROUTER_MAX_AGE) {
  692. log_fn(LOG_INFO, "Ignoring future directory; not caching.");
  693. } else {
  694. /* if (when>d->published && when<now+ROUTER_MAX_AGE) */
  695. log_fn(LOG_DEBUG, "Caching directory.");
  696. tor_free(d->dir);
  697. d->dir = tor_strdup(directory);
  698. d->dir_len = strlen(directory);
  699. tor_free(d->dir_z);
  700. if (tor_gzip_compress(&(d->dir_z), &(d->dir_z_len), d->dir, d->dir_len,
  701. ZLIB_METHOD)) {
  702. log_fn(LOG_WARN,"Error compressing cached directory");
  703. }
  704. d->published = when;
  705. if (!is_running_routers) {
  706. char filename[512];
  707. tor_snprintf(filename,sizeof(filename),"%s/cached-directory", get_options()->DataDirectory);
  708. if (write_str_to_file(filename,cached_directory.dir,0) < 0) {
  709. log_fn(LOG_NOTICE, "Couldn't write cached directory to disk. Ignoring.");
  710. }
  711. }
  712. }
  713. }
  714. /** Set *<b>directory</b> to the most recently generated encoded signed
  715. * directory, generating a new one as necessary. If not an authoritative
  716. * directory may return 0 if no directory is yet cached.*/
  717. size_t dirserv_get_directory(const char **directory, int compress)
  718. {
  719. if (!get_options()->AuthoritativeDir) {
  720. cached_dir_t *d = &cached_directory;
  721. *directory = compress ? d->dir_z : d->dir;
  722. if (*directory) {
  723. return compress ? d->dir_z_len : d->dir_len;
  724. } else {
  725. /* no directory yet retrieved */
  726. return 0;
  727. }
  728. }
  729. if (the_directory_is_dirty &&
  730. the_directory_is_dirty + DIR_REGEN_SLACK_TIME < time(NULL)) {
  731. if (dirserv_regenerate_directory())
  732. return 0;
  733. } else {
  734. log(LOG_INFO,"Directory still clean, reusing.");
  735. }
  736. *directory = compress ? the_directory_z : the_directory;
  737. return compress ? the_directory_z_len : the_directory_len;
  738. }
  739. /**
  740. * Generate a fresh directory (authdirservers only.)
  741. */
  742. static int dirserv_regenerate_directory(void)
  743. {
  744. char *new_directory=NULL;
  745. if (dirserv_dump_directory_to_string(&new_directory,
  746. get_identity_key())) {
  747. log(LOG_WARN, "Error creating directory.");
  748. tor_free(new_directory);
  749. return -1;
  750. }
  751. tor_free(the_directory);
  752. the_directory = new_directory;
  753. the_directory_len = strlen(the_directory);
  754. log_fn(LOG_INFO,"New directory (size %d):\n%s",(int)the_directory_len,
  755. the_directory);
  756. tor_free(the_directory_z);
  757. if (tor_gzip_compress(&the_directory_z, &the_directory_z_len,
  758. the_directory, the_directory_len,
  759. ZLIB_METHOD)) {
  760. log_fn(LOG_WARN, "Error gzipping directory.");
  761. return -1;
  762. }
  763. /* Now read the directory we just made in order to update our own
  764. * router lists. This does more signature checking than is strictly
  765. * necessary, but safe is better than sorry. */
  766. new_directory = tor_strdup(the_directory);
  767. /* use a new copy of the dir, since get_dir_from_string scribbles on it */
  768. if (router_load_routerlist_from_directory(new_directory,
  769. get_identity_key(), 1, 0)) {
  770. log_fn(LOG_ERR, "We just generated a directory we can't parse. Dying.");
  771. tor_cleanup();
  772. exit(0);
  773. }
  774. tor_free(new_directory);
  775. the_directory_is_dirty = 0;
  776. /* Save the directory to disk so we re-load it quickly on startup.
  777. */
  778. dirserv_set_cached_directory(the_directory, time(NULL), 0);
  779. return 0;
  780. }
  781. static char *the_runningrouters=NULL;
  782. static size_t the_runningrouters_len=0;
  783. static char *the_runningrouters_z=NULL;
  784. static size_t the_runningrouters_z_len=0;
  785. /** Replace the current running-routers list with a newly generated one. */
  786. static int generate_runningrouters(crypto_pk_env_t *private_key)
  787. {
  788. char *s=NULL, *cp;
  789. char *router_status=NULL;
  790. char digest[DIGEST_LEN];
  791. char signature[PK_BYTES];
  792. int i;
  793. char published[33];
  794. size_t len;
  795. time_t published_on;
  796. char *identity_pkey; /* Identity key, DER64-encoded. */
  797. if (!descriptor_list)
  798. descriptor_list = smartlist_create();
  799. if (list_server_status(descriptor_list, NULL, &router_status)) {
  800. goto err;
  801. }
  802. /* ASN.1-encode the public key. This is a temporary measure; once
  803. * everyone is running 0.0.9pre3 or later, we can shift to using a
  804. * PEM-encoded key instead.
  805. */
  806. #if 1
  807. if (crypto_pk_DER64_encode_public_key(private_key, &identity_pkey)<0) {
  808. log_fn(LOG_WARN,"write identity_pkey to string failed!");
  809. goto err;
  810. }
  811. #else
  812. {
  813. int l;
  814. if (crypto_pk_write_public_key_to_string(private_key,&identity_pkey,&l)<0) {
  815. log_fn(LOG_WARN,"write identity_pkey to string failed!");
  816. goto err;
  817. }
  818. }
  819. #endif
  820. published_on = time(NULL);
  821. format_iso_time(published, published_on);
  822. len = 2048+strlen(router_status);
  823. s = tor_malloc_zero(len);
  824. tor_snprintf(s, len, "network-status\n"
  825. "published %s\n"
  826. "router-status %s\n"
  827. "opt dir-signing-key %s\n"
  828. "directory-signature %s\n"
  829. "-----BEGIN SIGNATURE-----\n",
  830. published, router_status, identity_pkey, get_options()->Nickname);
  831. tor_free(router_status);
  832. tor_free(identity_pkey);
  833. if (router_get_runningrouters_hash(s,digest)) {
  834. log_fn(LOG_WARN,"couldn't compute digest");
  835. goto err;
  836. }
  837. if (crypto_pk_private_sign(private_key, signature, digest, 20) < 0) {
  838. log_fn(LOG_WARN,"couldn't sign digest");
  839. goto err;
  840. }
  841. i = strlen(s);
  842. cp = s+i;
  843. if (base64_encode(cp, len-i, signature, 128) < 0) {
  844. log_fn(LOG_WARN,"couldn't base64-encode signature");
  845. goto err;
  846. }
  847. if (strlcat(s, "-----END SIGNATURE-----\n", len) >= len) {
  848. goto err;
  849. }
  850. tor_free(the_runningrouters);
  851. the_runningrouters = s;
  852. the_runningrouters_len = strlen(s);
  853. tor_free(the_runningrouters_z);
  854. if (tor_gzip_compress(&the_runningrouters_z, &the_runningrouters_z_len,
  855. the_runningrouters, the_runningrouters_len,
  856. ZLIB_METHOD)) {
  857. log_fn(LOG_WARN, "Error gzipping runningrouters");
  858. return -1;
  859. }
  860. runningrouters_is_dirty = 0;
  861. /* We don't cache running-routers to disk, so there's no point in
  862. * authdirservers caching it. */
  863. /* dirserv_set_cached_directory(the_runningrouters, time(NULL), 1); */
  864. return 0;
  865. err:
  866. tor_free(s);
  867. tor_free(router_status);
  868. return -1;
  869. }
  870. /** Set *<b>rr</b> to the most recently generated encoded signed
  871. * running-routers list, generating a new one as necessary. Return the
  872. * size of the directory on success, and 0 on failure. */
  873. size_t dirserv_get_runningrouters(const char **rr, int compress)
  874. {
  875. if (!get_options()->AuthoritativeDir) {
  876. cached_dir_t *d = &cached_runningrouters;
  877. *rr = compress ? d->dir_z : d->dir;
  878. if (*rr) {
  879. return compress ? d->dir_z_len : d->dir_len;
  880. } else {
  881. /* no directory yet retrieved */
  882. return 0;
  883. }
  884. }
  885. if (runningrouters_is_dirty &&
  886. runningrouters_is_dirty + DIR_REGEN_SLACK_TIME < time(NULL)) {
  887. if (generate_runningrouters(get_identity_key())) {
  888. log_fn(LOG_ERR, "Couldn't generate running-routers list?");
  889. return 0;
  890. }
  891. }
  892. *rr = compress ? the_runningrouters_z : the_runningrouters;
  893. return compress ? the_runningrouters_z_len : the_runningrouters_len;
  894. }
  895. void
  896. dirserv_free_all(void)
  897. {
  898. if (fingerprint_list) {
  899. SMARTLIST_FOREACH(fingerprint_list, fingerprint_entry_t*, fp,
  900. { tor_free(fp->nickname);
  901. tor_free(fp->fingerprint);
  902. tor_free(fp); });
  903. smartlist_free(fingerprint_list);
  904. fingerprint_list = NULL;
  905. }
  906. if (descriptor_list) {
  907. SMARTLIST_FOREACH(descriptor_list, routerinfo_t *, ri,
  908. routerinfo_free(ri));
  909. smartlist_free(descriptor_list);
  910. descriptor_list = NULL;
  911. }
  912. tor_free(the_directory);
  913. tor_free(the_directory_z);
  914. the_directory_len = 0;
  915. the_directory_z_len = 0;
  916. tor_free(the_runningrouters);
  917. tor_free(the_runningrouters_z);
  918. the_runningrouters_len = 0;
  919. the_runningrouters_z_len = 0;
  920. tor_free(cached_directory.dir);
  921. tor_free(cached_directory.dir_z);
  922. tor_free(cached_runningrouters.dir);
  923. tor_free(cached_runningrouters.dir_z);
  924. memset(&cached_directory, 0, sizeof(cached_directory));
  925. memset(&cached_runningrouters, 0, sizeof(cached_runningrouters));
  926. }