dirserv.c 34 KB

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