dirserv.c 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417
  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 int networkstatus_v2_is_dirty = 1;
  21. static void directory_remove_invalid(void);
  22. static int dirserv_regenerate_directory(void);
  23. static char *format_versions_list(config_line_t *ln);
  24. /* Should be static; exposed for testing */
  25. int add_fingerprint_to_dir(const char *nickname, const char *fp, smartlist_t *list);
  26. static int router_is_general_exit(routerinfo_t *ri);
  27. /************** Fingerprint handling code ************/
  28. typedef struct fingerprint_entry_t {
  29. char *nickname;
  30. char *fingerprint; /**< Stored as HEX_DIGEST_LEN characters, followed by a NUL */
  31. } fingerprint_entry_t;
  32. /** List of nickname-\>identity fingerprint mappings for all the routers
  33. * that we recognize. Used to prevent Sybil attacks. */
  34. /* Should be static; exposed for testing */
  35. smartlist_t *fingerprint_list = NULL;
  36. /** Add the fingerprint <b>fp</b> for the nickname <b>nickname</b> to
  37. * the smartlist of fingerprint_entry_t's <b>list</b>. Return 0 if it's
  38. * new, or 1 if we replaced the old value.
  39. */
  40. int /* Should be static; exposed for testing */
  41. add_fingerprint_to_dir(const char *nickname, const char *fp, smartlist_t *list)
  42. {
  43. int i;
  44. fingerprint_entry_t *ent;
  45. char *fingerprint;
  46. tor_assert(nickname);
  47. tor_assert(fp);
  48. tor_assert(list);
  49. fingerprint = tor_strdup(fp);
  50. tor_strstrip(fingerprint, " ");
  51. for (i = 0; i < smartlist_len(list); ++i) {
  52. ent = smartlist_get(list, i);
  53. if (!strcasecmp(ent->nickname,nickname)) {
  54. tor_free(ent->fingerprint);
  55. ent->fingerprint = fingerprint;
  56. return 1;
  57. }
  58. }
  59. ent = tor_malloc(sizeof(fingerprint_entry_t));
  60. ent->nickname = tor_strdup(nickname);
  61. ent->fingerprint = fingerprint;
  62. smartlist_add(list, ent);
  63. return 0;
  64. }
  65. /** Add the nickname and fingerprint for this OR to the
  66. * global list of recognized identity key fingerprints. */
  67. int
  68. dirserv_add_own_fingerprint(const char *nickname, crypto_pk_env_t *pk)
  69. {
  70. char fp[FINGERPRINT_LEN+1];
  71. if (crypto_pk_get_fingerprint(pk, fp, 0)<0) {
  72. log_fn(LOG_ERR, "Error computing fingerprint");
  73. return -1;
  74. }
  75. if (!fingerprint_list)
  76. fingerprint_list = smartlist_create();
  77. add_fingerprint_to_dir(nickname, fp, fingerprint_list);
  78. return 0;
  79. }
  80. /** Parse the nickname-\>fingerprint mappings stored in the file named
  81. * <b>fname</b>. The file format is line-based, with each non-blank
  82. * holding one nickname, some space, and a fingerprint for that
  83. * nickname. On success, replace the current fingerprint list with
  84. * the contents of <b>fname</b> and return 0. On failure, leave the
  85. * current fingerprint list untouched, and return -1. */
  86. int
  87. dirserv_parse_fingerprint_file(const char *fname)
  88. {
  89. char *cf;
  90. char *nickname, *fingerprint;
  91. smartlist_t *fingerprint_list_new;
  92. int result;
  93. config_line_t *front=NULL, *list;
  94. cf = read_file_to_str(fname, 0);
  95. if (!cf) {
  96. log_fn(LOG_WARN, "Cannot open fingerprint file %s", fname);
  97. return -1;
  98. }
  99. result = config_get_lines(cf, &front);
  100. tor_free(cf);
  101. if (result < 0) {
  102. log_fn(LOG_WARN, "Error reading from fingerprint file");
  103. return -1;
  104. }
  105. fingerprint_list_new = smartlist_create();
  106. for (list=front; list; list=list->next) {
  107. nickname = list->key; fingerprint = list->value;
  108. if (strlen(nickname) > MAX_NICKNAME_LEN) {
  109. log(LOG_NOTICE, "Nickname '%s' too long in fingerprint file. Skipping.", nickname);
  110. continue;
  111. }
  112. if (strlen(fingerprint) != FINGERPRINT_LEN ||
  113. !crypto_pk_check_fingerprint_syntax(fingerprint)) {
  114. log_fn(LOG_NOTICE, "Invalid fingerprint (nickname '%s', fingerprint %s). Skipping.",
  115. nickname, fingerprint);
  116. continue;
  117. }
  118. if (0==strcasecmp(nickname, DEFAULT_CLIENT_NICKNAME)) {
  119. /* If you approved an OR called "client", then clients who use
  120. * the default nickname could all be rejected. That's no good. */
  121. log(LOG_NOTICE,
  122. "Authorizing a nickname '%s' would break many clients; skipping.",
  123. DEFAULT_CLIENT_NICKNAME);
  124. continue;
  125. }
  126. if (add_fingerprint_to_dir(nickname, fingerprint, fingerprint_list_new) != 0)
  127. log(LOG_NOTICE, "Duplicate nickname '%s'.", nickname);
  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_invalid();
  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': expected '%s' got '%s'",
  170. router->nickname, ent->fingerprint, fp);
  171. return -1; /* Wrong fingerprint. */
  172. }
  173. }
  174. /** If we are an authoritative dirserver, and the list of approved
  175. * servers contains one whose identity key digest is <b>digest</b>,
  176. * return that router's nickname. Otherwise return NULL. */
  177. const char *
  178. dirserv_get_nickname_by_digest(const char *digest)
  179. {
  180. char hexdigest[HEX_DIGEST_LEN+1];
  181. if (!fingerprint_list)
  182. return NULL;
  183. tor_assert(digest);
  184. base16_encode(hexdigest, HEX_DIGEST_LEN+1, digest, DIGEST_LEN);
  185. SMARTLIST_FOREACH(fingerprint_list, fingerprint_entry_t*, ent,
  186. { if (!strcasecmp(hexdigest, ent->fingerprint))
  187. return ent->nickname; } );
  188. return NULL;
  189. }
  190. /** Clear the current fingerprint list. */
  191. void
  192. dirserv_free_fingerprint_list()
  193. {
  194. int i;
  195. fingerprint_entry_t *ent;
  196. if (!fingerprint_list)
  197. return;
  198. for (i = 0; i < smartlist_len(fingerprint_list); ++i) {
  199. ent = smartlist_get(fingerprint_list, i);
  200. tor_free(ent->nickname);
  201. tor_free(ent->fingerprint);
  202. tor_free(ent);
  203. }
  204. smartlist_free(fingerprint_list);
  205. fingerprint_list = NULL;
  206. }
  207. /*
  208. * Descriptor list
  209. */
  210. /** List of routerinfo_t for all server descriptors that this dirserv
  211. * is holding.
  212. * XXXX This should eventually get coalesced into routerlist.c
  213. */
  214. static smartlist_t *descriptor_list = NULL;
  215. /** Release all storage that the dirserv is holding for server
  216. * descriptors. */
  217. void
  218. dirserv_free_descriptors()
  219. {
  220. if (!descriptor_list)
  221. return;
  222. SMARTLIST_FOREACH(descriptor_list, routerinfo_t *, ri,
  223. routerinfo_free(ri));
  224. smartlist_clear(descriptor_list);
  225. }
  226. /** Return -1 if <b>ri</b> has a private or otherwise bad address,
  227. * unless we're configured to not care. Return 0 if all ok. */
  228. static int
  229. dirserv_router_has_valid_address(routerinfo_t *ri)
  230. {
  231. struct in_addr iaddr;
  232. if (get_options()->DirAllowPrivateAddresses)
  233. return 0; /* whatever it is, we're fine with it */
  234. if (!tor_inet_aton(ri->address, &iaddr)) {
  235. log_fn(LOG_INFO,"Router '%s' published non-IP address '%s'. Refusing.",
  236. ri->nickname, ri->address);
  237. return -1;
  238. }
  239. if (is_internal_IP(ntohl(iaddr.s_addr))) {
  240. log_fn(LOG_INFO,"Router '%s' published internal IP address '%s'. Refusing.",
  241. ri->nickname, ri->address);
  242. return -1; /* it's a private IP, we should reject it */
  243. }
  244. return 0;
  245. }
  246. /** Parse the server descriptor at *desc and maybe insert it into the
  247. * list of server descriptors, and (if the descriptor is well-formed)
  248. * advance *desc immediately past the descriptor's end. Set msg to a
  249. * message that should be passed back to the origin of this descriptor, or
  250. * to NULL.
  251. *
  252. * Return 1 if descriptor is well-formed and accepted;
  253. * 0 if well-formed and server is unapproved but accepted;
  254. * -1 if it looks vaguely like a router descriptor but rejected;
  255. * -2 if we can't find a router descriptor in *desc.
  256. */
  257. int
  258. dirserv_add_descriptor(const char **desc, const char **msg)
  259. {
  260. routerinfo_t *ri = NULL, *ri_old=NULL;
  261. int i, r, found=-1;
  262. char *start, *end;
  263. char *desc_tmp = NULL;
  264. size_t desc_len;
  265. time_t now;
  266. int verified=1; /* whether we knew its fingerprint already */
  267. tor_assert(msg);
  268. *msg = NULL;
  269. if (!descriptor_list)
  270. descriptor_list = smartlist_create();
  271. start = strstr(*desc, "router ");
  272. if (!start) {
  273. log_fn(LOG_WARN, "no 'router' line found. This is not a descriptor.");
  274. return -2;
  275. }
  276. if ((end = strstr(start+6, "\nrouter "))) {
  277. ++end; /* Include NL. */
  278. } else if ((end = strstr(start+6, "\ndirectory-signature"))) {
  279. ++end;
  280. } else {
  281. end = start+strlen(start);
  282. }
  283. desc_len = end-start;
  284. desc_tmp = tor_strndup(start, desc_len); /* Is this strndup still needed???*/
  285. /* Check: is the descriptor syntactically valid? */
  286. ri = router_parse_entry_from_string(desc_tmp, NULL);
  287. tor_free(desc_tmp);
  288. if (!ri) {
  289. log(LOG_WARN, "Couldn't parse descriptor");
  290. *msg = "Rejected: Couldn't parse server descriptor.";
  291. return -1;
  292. }
  293. /* Okay. Now check whether the fingerprint is recognized. */
  294. r = dirserv_router_fingerprint_is_known(ri);
  295. if (r==-1) {
  296. log_fn(LOG_WARN, "Known nickname '%s', wrong fingerprint. Not adding (ContactInfo '%s', platform '%s').",
  297. ri->nickname, ri->contact_info ? ri->contact_info : "",
  298. ri->platform ? ri->platform : "");
  299. *msg = "Rejected: There is already a verified server with this nickname and a different fingerprint.";
  300. routerinfo_free(ri);
  301. *desc = end;
  302. return -1;
  303. } else if (r==0) {
  304. char fp[FINGERPRINT_LEN+1];
  305. log_fn(LOG_INFO, "Unknown nickname '%s' (%s:%d). Will try to add.",
  306. ri->nickname, ri->address, ri->or_port);
  307. if (crypto_pk_get_fingerprint(ri->identity_pkey, fp, 1) < 0) {
  308. log_fn(LOG_WARN, "Error computing fingerprint for '%s'", ri->nickname);
  309. } else {
  310. log_fn(LOG_INFO, "Fingerprint line: %s %s", ri->nickname, fp);
  311. }
  312. verified = 0;
  313. }
  314. /* Is there too much clock skew? */
  315. now = time(NULL);
  316. if (ri->published_on > now+ROUTER_ALLOW_SKEW) {
  317. 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').",
  318. ri->nickname, (int)((ri->published_on-now)/60),
  319. ri->contact_info ? ri->contact_info : "",
  320. ri->platform ? ri->platform : "");
  321. *msg = "Rejected: Your clock is set too far in the future, or your timezone is not correct.";
  322. routerinfo_free(ri);
  323. *desc = end;
  324. return -1;
  325. }
  326. if (ri->published_on < now-ROUTER_MAX_AGE) {
  327. 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').",
  328. ri->nickname, (int)((now-ri->published_on)/60),
  329. ri->contact_info ? ri->contact_info : "",
  330. ri->platform ? ri->platform : "");
  331. *msg = "Rejected: Server is expired, or your clock is too far in the past, or your timezone is not correct.";
  332. routerinfo_free(ri);
  333. *desc = end;
  334. return -1;
  335. }
  336. if (dirserv_router_has_valid_address(ri) < 0) {
  337. log_fn(LOG_NOTICE, "Router with nickname '%s' has invalid address '%s'. Not adding (ContactInfo '%s', platform '%s').",
  338. ri->nickname, ri->address,
  339. ri->contact_info ? ri->contact_info : "",
  340. ri->platform ? ri->platform : "");
  341. *msg = "Rejected: Address is not an IP, or IP is a private address.";
  342. routerinfo_free(ri);
  343. *desc = end;
  344. return -1;
  345. }
  346. /* Do we already have an entry for this router? */
  347. for (i = 0; i < smartlist_len(descriptor_list); ++i) {
  348. ri_old = smartlist_get(descriptor_list, i);
  349. if (!memcmp(ri->identity_digest, ri_old->identity_digest, DIGEST_LEN)) {
  350. found = i;
  351. break;
  352. }
  353. }
  354. if (found >= 0) {
  355. char hex_digest[HEX_DIGEST_LEN+1];
  356. base16_encode(hex_digest, HEX_DIGEST_LEN+1, ri->identity_digest,DIGEST_LEN);
  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 server %s (nickname '%s'). Not adding.",hex_digest,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 already have a newer one; we'll update this one. */
  368. log_fn(LOG_INFO,"Dirserv updating desc for server %s (nickname '%s')",hex_digest,ri->nickname);
  369. if (ri->addr == ri_old->addr && ri->or_port == ri_old->or_port) {
  370. ri->last_reachable = ri_old->last_reachable; /* these carry over */
  371. ri->testing_since = ri_old->testing_since;
  372. }
  373. *msg = verified?"Verified server updated":"Unverified server updated. (Have you sent us your key fingerprint?)";
  374. routerinfo_free(ri_old);
  375. smartlist_del_keeporder(descriptor_list, found);
  376. } else {
  377. /* Add at the end. */
  378. log_fn(LOG_INFO,"Dirserv adding desc for nickname '%s'",ri->nickname);
  379. *msg = verified?"Verified server added":"Unverified server added. (Have you sent us your key fingerprint?)";
  380. }
  381. ri->is_verified = verified ||
  382. tor_version_as_new_as(ri->platform,"0.1.0.2-rc");
  383. smartlist_add(descriptor_list, ri);
  384. *desc = end;
  385. directory_set_dirty();
  386. return verified;
  387. }
  388. /** Remove all descriptors whose nicknames or fingerprints no longer
  389. * are allowed by our fingerprint list. (Descriptors that used to be
  390. * good can become bad when we reload the fingerprint list.)
  391. */
  392. static void
  393. directory_remove_invalid(void)
  394. {
  395. int i;
  396. int r;
  397. routerinfo_t *ent;
  398. if (!descriptor_list)
  399. descriptor_list = smartlist_create();
  400. for (i = 0; i < smartlist_len(descriptor_list); ++i) {
  401. ent = smartlist_get(descriptor_list, i);
  402. r = dirserv_router_fingerprint_is_known(ent);
  403. if (r<0) {
  404. log(LOG_INFO, "Router '%s' is now verified with a key; removing old router with same name and different key.",
  405. ent->nickname);
  406. routerinfo_free(ent);
  407. smartlist_del(descriptor_list, i--);
  408. } else if (r>0 && !ent->is_verified) {
  409. log(LOG_INFO, "Router '%s' is now approved.", ent->nickname);
  410. ent->is_verified = 1;
  411. } else if (r==0 && ent->is_verified) {
  412. log(LOG_INFO, "Router '%s' is no longer approved.", ent->nickname);
  413. ent->is_verified = 0;
  414. }
  415. }
  416. }
  417. /** Write a list of unregistered descriptors into a newly allocated
  418. * string and return it. Used by dirserv operators to keep track of
  419. * fast nodes that haven't registered.
  420. */
  421. char *
  422. dirserver_getinfo_unregistered(const char *question)
  423. {
  424. int i, r;
  425. smartlist_t *answerlist;
  426. char buf[1024];
  427. char *answer;
  428. routerinfo_t *ent;
  429. int min_bw = atoi(question);
  430. if (!descriptor_list)
  431. return tor_strdup("");
  432. answerlist = smartlist_create();
  433. for (i = 0; i < smartlist_len(descriptor_list); ++i) {
  434. ent = smartlist_get(descriptor_list, i);
  435. r = dirserv_router_fingerprint_is_known(ent);
  436. if (ent->bandwidthcapacity >= min_bw &&
  437. ent->bandwidthrate >= min_bw &&
  438. r == 0) {
  439. /* then log this one */
  440. tor_snprintf(buf, sizeof(buf),
  441. "%s: BW %d on '%s'.",
  442. ent->nickname, ent->bandwidthcapacity,
  443. ent->platform ? ent->platform : "");
  444. smartlist_add(answerlist, tor_strdup(buf));
  445. }
  446. }
  447. answer = smartlist_join_strings(answerlist, "\r\n", 0, NULL);
  448. SMARTLIST_FOREACH(answerlist, char *, cp, tor_free(cp));
  449. smartlist_free(answerlist);
  450. return answer;
  451. }
  452. /** Mark the directory as <b>dirty</b> -- when we're next asked for a
  453. * directory, we will rebuild it instead of reusing the most recently
  454. * generated one.
  455. */
  456. void
  457. directory_set_dirty()
  458. {
  459. time_t now = time(NULL);
  460. if (!the_directory_is_dirty)
  461. the_directory_is_dirty = now;
  462. if (!runningrouters_is_dirty)
  463. runningrouters_is_dirty = now;
  464. }
  465. /** Load all descriptors from a directory stored in the string
  466. * <b>dir</b>.
  467. */
  468. int
  469. dirserv_load_from_directory_string(const char *dir)
  470. {
  471. const char *cp = dir, *m;
  472. while (1) {
  473. cp = strstr(cp, "\nrouter ");
  474. if (!cp) break;
  475. ++cp;
  476. if (dirserv_add_descriptor(&cp,&m) < -1) {
  477. /* only fail if parsing failed; keep going if simply rejected */
  478. return -1;
  479. }
  480. --cp; /*Back up to newline.*/
  481. }
  482. return 0;
  483. }
  484. /**
  485. * Allocate and return a description of the status of the server <b>desc</b>,
  486. * for use in a router-status line. The server is listed
  487. * as running iff <b>is_live</b> is true.
  488. */
  489. static char *
  490. list_single_server_status(routerinfo_t *desc, int is_live)
  491. {
  492. char buf[MAX_NICKNAME_LEN+HEX_DIGEST_LEN+4]; /* !nickname=$hexdigest\0 */
  493. char *cp;
  494. tor_assert(desc);
  495. cp = buf;
  496. if (!is_live) {
  497. *cp++ = '!';
  498. }
  499. if (desc->is_verified) {
  500. strlcpy(cp, desc->nickname, sizeof(buf)-(cp-buf));
  501. cp += strlen(cp);
  502. *cp++ = '=';
  503. }
  504. *cp++ = '$';
  505. base16_encode(cp, HEX_DIGEST_LEN+1, desc->identity_digest,
  506. DIGEST_LEN);
  507. return tor_strdup(buf);
  508. }
  509. #define REACHABLE_TIMEOUT (60*60) /* an hour */
  510. /* Make sure this is 3 times the value of get_dir_fetch_period() */
  511. /** Based on the routerinfo_ts in <b>routers</b>, allocate the
  512. * contents of a router-status line, and store it in
  513. * *<b>router_status_out</b>. Return 0 on success, -1 on failure.
  514. */
  515. int
  516. list_server_status(smartlist_t *routers, char **router_status_out)
  517. {
  518. /* List of entries in a router-status style: An optional !, then an optional
  519. * equals-suffixed nickname, then a dollar-prefixed hexdigest. */
  520. smartlist_t *rs_entries;
  521. time_t now = time(NULL);
  522. int authdir_mode = get_options()->AuthoritativeDir;
  523. tor_assert(router_status_out);
  524. rs_entries = smartlist_create();
  525. SMARTLIST_FOREACH(routers, routerinfo_t *, ri,
  526. {
  527. int is_live = 0;
  528. connection_t *conn;
  529. conn = connection_get_by_identity_digest(
  530. ri->identity_digest, CONN_TYPE_OR);
  531. if (authdir_mode) {
  532. /* Treat a router as alive if
  533. * - It's me, and I'm not hibernating.
  534. * or - we're connected to it and we've found it reachable recently. */
  535. if (router_is_me(ri) && !we_are_hibernating()) {
  536. is_live = 1;
  537. } else if (conn && conn->state == OR_CONN_STATE_OPEN) {
  538. is_live = get_options()->AssumeReachable ||
  539. now < ri->last_reachable + REACHABLE_TIMEOUT;
  540. }
  541. } else {
  542. is_live = ri->is_running;
  543. }
  544. smartlist_add(rs_entries, list_single_server_status(ri, is_live));
  545. });
  546. *router_status_out = smartlist_join_strings(rs_entries, " ", 0,NULL);
  547. SMARTLIST_FOREACH(rs_entries, char *, cp, tor_free(cp));
  548. smartlist_free(rs_entries);
  549. return 0;
  550. }
  551. /** Log complaints about each server that is connected to us and has
  552. * been found unreachable for the past several testing periods.
  553. */
  554. void
  555. dirserv_log_unreachable_servers(time_t now) {
  556. SMARTLIST_FOREACH(descriptor_list, routerinfo_t *, ri,
  557. {
  558. connection_t *conn;
  559. conn = connection_get_by_identity_digest(
  560. ri->identity_digest, CONN_TYPE_OR);
  561. if (conn && conn->state == OR_CONN_STATE_OPEN &&
  562. now >= ri->last_reachable + 2*REACHABLE_TIMEOUT &&
  563. ri->testing_since &&
  564. now >= ri->testing_since + 2*REACHABLE_TIMEOUT) {
  565. log_fn(LOG_NOTICE,
  566. "Router %s (%s:%d) is connected to us but not reachable by us.",
  567. ri->nickname, ri->address, ri->or_port);
  568. }
  569. });
  570. }
  571. /** Record the fact that we've started trying to determine reachability
  572. * for the router with identity <b>digest</b>.
  573. * (This function can go away when we merge descriptor-list and router-list.)
  574. */
  575. void
  576. dirserv_router_has_begun_reachability_testing(char *digest, time_t now) {
  577. if (!descriptor_list)
  578. return;
  579. SMARTLIST_FOREACH(descriptor_list, routerinfo_t *, ri,
  580. {
  581. if (!memcmp(ri->identity_digest, digest, DIGEST_LEN))
  582. if (!ri->testing_since)
  583. ri->testing_since = now;
  584. });
  585. }
  586. /** Remove any descriptors from the directory that are more than <b>age</b>
  587. * seconds old.
  588. */
  589. void
  590. dirserv_remove_old_servers(int age)
  591. {
  592. int i;
  593. time_t cutoff;
  594. routerinfo_t *ent;
  595. if (!descriptor_list)
  596. descriptor_list = smartlist_create();
  597. cutoff = time(NULL) - age;
  598. for (i = 0; i < smartlist_len(descriptor_list); ++i) {
  599. ent = smartlist_get(descriptor_list, i);
  600. if (ent->published_on <= cutoff) {
  601. /* descriptor_list[i] is too old. Remove it. */
  602. routerinfo_free(ent);
  603. smartlist_del(descriptor_list, i--);
  604. directory_set_dirty();
  605. }
  606. }
  607. }
  608. /* Given a (possibly empty) list of config_line_t, each line of which contains
  609. * a list of comma-separated version numbers surrounded by optional space,
  610. * allocate and return a new string containing the version numbers, in order,
  611. * separated by commas. Used to generate Recommended(Client|Server)?Versions */
  612. static char *
  613. format_versions_list(config_line_t *ln)
  614. {
  615. smartlist_t *versions;
  616. char *result;
  617. versions = smartlist_create();
  618. for ( ; ln; ln = ln->next) {
  619. smartlist_split_string(versions, ln->value, ",",
  620. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  621. }
  622. result = smartlist_join_strings(versions,",",0,NULL);
  623. SMARTLIST_FOREACH(versions,char *,s,tor_free(s));
  624. smartlist_free(versions);
  625. return result;
  626. }
  627. /** Generate a new directory and write it into a newly allocated string.
  628. * Point *<b>dir_out</b> to the allocated string. Sign the
  629. * directory with <b>private_key</b>. Return 0 on success, -1 on
  630. * failure.
  631. */
  632. int
  633. dirserv_dump_directory_to_string(char **dir_out,
  634. crypto_pk_env_t *private_key)
  635. {
  636. char *router_status;
  637. char *identity_pkey; /* Identity key, DER64-encoded. */
  638. char *recommended_versions;
  639. char digest[DIGEST_LEN];
  640. char published[ISO_TIME_LEN+1];
  641. time_t published_on;
  642. char *buf = NULL;
  643. size_t buf_len;
  644. size_t identity_pkey_len;
  645. tor_assert(dir_out);
  646. *dir_out = NULL;
  647. if (!descriptor_list)
  648. descriptor_list = smartlist_create();
  649. if (list_server_status(descriptor_list, &router_status))
  650. return -1;
  651. if (crypto_pk_write_public_key_to_string(private_key,&identity_pkey,
  652. &identity_pkey_len)<0) {
  653. log_fn(LOG_WARN,"write identity_pkey to string failed!");
  654. return -1;
  655. }
  656. recommended_versions = format_versions_list(get_options()->RecommendedVersions);
  657. dirserv_remove_old_servers(ROUTER_MAX_AGE);
  658. published_on = time(NULL);
  659. format_iso_time(published, published_on);
  660. buf_len = 2048+strlen(recommended_versions)+
  661. strlen(router_status);
  662. SMARTLIST_FOREACH(descriptor_list, routerinfo_t *, ri,
  663. buf_len += strlen(ri->signed_descriptor));
  664. buf = tor_malloc(buf_len);
  665. /* We'll be comparing against buf_len throughout the rest of the
  666. function, though strictly speaking we shouldn't be able to exceed
  667. it. This is C, after all, so we may as well check for buffer
  668. overruns.*/
  669. tor_snprintf(buf, buf_len,
  670. "signed-directory\n"
  671. "published %s\n"
  672. "recommended-software %s\n"
  673. "router-status %s\n"
  674. "dir-signing-key\n%s\n",
  675. published, recommended_versions, router_status,
  676. identity_pkey);
  677. tor_free(recommended_versions);
  678. tor_free(router_status);
  679. tor_free(identity_pkey);
  680. SMARTLIST_FOREACH(descriptor_list, routerinfo_t *, ri,
  681. if (strlcat(buf, ri->signed_descriptor, buf_len) >= buf_len)
  682. goto truncated);
  683. /* These multiple strlcat calls are inefficient, but dwarfed by the RSA
  684. signature.
  685. */
  686. if (strlcat(buf, "directory-signature ", buf_len) >= buf_len)
  687. goto truncated;
  688. if (strlcat(buf, get_options()->Nickname, buf_len) >= buf_len)
  689. goto truncated;
  690. if (strlcat(buf, "\n", buf_len) >= buf_len)
  691. goto truncated;
  692. if (router_get_dir_hash(buf,digest)) {
  693. log_fn(LOG_WARN,"couldn't compute digest");
  694. tor_free(buf);
  695. return -1;
  696. }
  697. if (router_append_dirobj_signature(buf,buf_len,digest,private_key)<0) {
  698. tor_free(buf);
  699. return -1;
  700. }
  701. *dir_out = buf;
  702. return 0;
  703. truncated:
  704. log_fn(LOG_WARN,"tried to exceed string length.");
  705. tor_free(buf);
  706. return -1;
  707. }
  708. /** A cached_dir_t represents a cacheable directory object, along with its
  709. * compressed form. */
  710. typedef struct cached_dir_t {
  711. char *dir; /**< Contents of this object */
  712. char *dir_z; /**< Compressed contents of this object. */
  713. size_t dir_len; /**< Length of <b>dir</b> */
  714. size_t dir_z_len; /**< Length of <b>dir_z</b> */
  715. time_t published; /**< When was this object published */
  716. } cached_dir_t;
  717. /** Most recently generated encoded signed directory. (auth dirservers only.)*/
  718. static cached_dir_t the_directory = { NULL, NULL, 0, 0, 0 };
  719. /* Used only by non-auth dirservers: The directory and runningrouters we'll
  720. * serve when requested. */
  721. static cached_dir_t cached_directory = { NULL, NULL, 0, 0, 0 };
  722. static cached_dir_t cached_runningrouters = { NULL, NULL, 0, 0, 0 };
  723. /* Used for other dirservers' v2 network statuses. Map from hexdigest to
  724. * cached_dir_t. */
  725. static strmap_t *cached_v2_networkstatus = NULL;
  726. /** Possibly replace the contents of <b>d</b> with the value of
  727. * <b>directory</b> published on <b>when</b>. (Do nothing if <b>when</b> is
  728. * older than the last value, or too far in the future. */
  729. static void
  730. set_cached_dir(cached_dir_t *d, const char *directory, time_t when)
  731. {
  732. time_t now = time(NULL);
  733. if (when<=d->published) {
  734. log_fn(LOG_INFO, "Ignoring old directory; not caching.");
  735. } else if (when>=now+ROUTER_MAX_AGE) {
  736. log_fn(LOG_INFO, "Ignoring future directory; not caching.");
  737. } else {
  738. /* if (when>d->published && when<now+ROUTER_MAX_AGE) */
  739. log_fn(LOG_DEBUG, "Caching directory.");
  740. tor_free(d->dir);
  741. d->dir = tor_strdup(directory);
  742. d->dir_len = strlen(directory);
  743. tor_free(d->dir_z);
  744. if (tor_gzip_compress(&(d->dir_z), &(d->dir_z_len), d->dir, d->dir_len,
  745. ZLIB_METHOD)) {
  746. log_fn(LOG_WARN,"Error compressing cached directory");
  747. }
  748. d->published = when;
  749. }
  750. }
  751. /** Remove all storage held in <b>d</b>, but do not free <b>d</b> itself. */
  752. static void
  753. clear_cached_dir(cached_dir_t *d)
  754. {
  755. tor_free(d->dir);
  756. tor_free(d->dir_z);
  757. memset(d, 0, sizeof(cached_dir_t));
  758. }
  759. /** Free all storage held by the cached_dir_t in <b>d</b>. */
  760. static void
  761. free_cached_dir(void *_d)
  762. {
  763. cached_dir_t *d = (cached_dir_t *)_d;
  764. clear_cached_dir(d);
  765. tor_free(d);
  766. }
  767. /** If we have no cached directory, or it is older than <b>when</b>, then
  768. * replace it with <b>directory</b>, published at <b>when</b>.
  769. */
  770. void
  771. dirserv_set_cached_directory(const char *directory, time_t published,
  772. int is_running_routers)
  773. {
  774. cached_dir_t *d;
  775. d = is_running_routers ? &cached_runningrouters : &cached_directory;
  776. set_cached_dir(d, directory, published);
  777. if (!is_running_routers) {
  778. char filename[512];
  779. tor_snprintf(filename,sizeof(filename),"%s/cached-directory", get_options()->DataDirectory);
  780. if (write_str_to_file(filename,cached_directory.dir,0) < 0) {
  781. log_fn(LOG_NOTICE, "Couldn't write cached directory to disk. Ignoring.");
  782. }
  783. }
  784. }
  785. /** We've just received a v2 network-status for an authoritative directory
  786. * with fingerprint <b>fp</b> (hex digest, no spaces), published at
  787. * <b>published</b>. Store it so we can serve it to others.
  788. */
  789. void
  790. dirserv_set_cached_networkstatus_v2(const char *directory, const char *fp,
  791. time_t published)
  792. {
  793. cached_dir_t *d;
  794. char fname[512];
  795. if (!cached_v2_networkstatus)
  796. cached_v2_networkstatus = strmap_new();
  797. tor_assert(strlen(fp) == HEX_DIGEST_LEN);
  798. if (!(d = strmap_get(cached_v2_networkstatus, fp))) {
  799. d = tor_malloc_zero(sizeof(cached_dir_t));
  800. strmap_set(cached_v2_networkstatus, fp, d);
  801. }
  802. tor_assert(d);
  803. set_cached_dir(d, directory, published);
  804. if (!d->dir)
  805. return;
  806. tor_snprintf(fname,sizeof(fname), "%s/cached-status/%s",
  807. get_options()->DataDirectory, fp);
  808. if (write_str_to_file(fname, d->dir, 0)<0) {
  809. log_fn(LOG_NOTICE, "Couldn't write cached network status to disk. Ignoring.");
  810. }
  811. }
  812. /** Helper: If we're authoritative and <b>auth_src</b> is set, use
  813. * <b>auth_src</b>, otherwise use <b>cache_src</b>. If we're using
  814. * <b>auth_src</b> and it's been <b>dirty</b> for at least
  815. * DIR_REGEN_SLACK_TIME seconds, call <b>regenerate</b>() to make a fresh one.
  816. * Yields the compressed version of the directory object if <b>compress</b> is
  817. * set; otherwise return the uncompressed version. (In either case, sets
  818. * *<b>out</b> and returns the size of the buffer in *<b>out</b>. */
  819. static size_t
  820. dirserv_get_obj(const char **out, int compress,
  821. cached_dir_t *cache_src,
  822. cached_dir_t *auth_src,
  823. time_t dirty, int (*regenerate)(void),
  824. const char *name)
  825. {
  826. cached_dir_t *d;
  827. if (!get_options()->AuthoritativeDir || !auth_src) {
  828. d = cache_src;
  829. } else {
  830. if (regenerate != NULL) {
  831. if (dirty && dirty + DIR_REGEN_SLACK_TIME < time(NULL)) {
  832. if (regenerate()) {
  833. log_fn(LOG_ERR, "Couldn't generate %s?", name);
  834. exit(1);
  835. }
  836. } else {
  837. log_fn(LOG_INFO, "The %s is still clean; reusing.", name);
  838. }
  839. }
  840. d = auth_src;
  841. }
  842. if (!d)
  843. return 0;
  844. *out = compress ? d->dir_z : d->dir;
  845. if (*out) {
  846. return compress ? d->dir_z_len : d->dir_len;
  847. } else {
  848. /* not yet available. */
  849. return 0;
  850. }
  851. }
  852. /** Set *<b>directory</b> to the most recently generated encoded signed
  853. * directory, generating a new one as necessary. If not an authoritative
  854. * directory may return 0 if no directory is yet cached.*/
  855. size_t
  856. dirserv_get_directory(const char **directory, int compress)
  857. {
  858. return dirserv_get_obj(directory, compress,
  859. &cached_directory, &the_directory,
  860. the_directory_is_dirty,
  861. dirserv_regenerate_directory,
  862. "server directory");
  863. }
  864. /**
  865. * Generate a fresh directory (authdirservers only.)
  866. */
  867. static int
  868. dirserv_regenerate_directory(void)
  869. {
  870. char *new_directory=NULL;
  871. if (dirserv_dump_directory_to_string(&new_directory,
  872. get_identity_key())) {
  873. log(LOG_WARN, "Error creating directory.");
  874. tor_free(new_directory);
  875. return -1;
  876. }
  877. set_cached_dir(&the_directory, new_directory, time(NULL));
  878. log_fn(LOG_INFO,"New directory (size %d):\n%s",(int)the_directory.dir_len,
  879. the_directory.dir);
  880. the_directory_is_dirty = 0;
  881. /* Save the directory to disk so we re-load it quickly on startup.
  882. */
  883. dirserv_set_cached_directory(the_directory.dir, time(NULL), 0);
  884. return 0;
  885. }
  886. /** For authoritative directories: the current (v1) network status */
  887. static cached_dir_t the_runningrouters = { NULL, NULL, 0, 0, 0 };
  888. /** Replace the current running-routers list with a newly generated one. */
  889. static int
  890. generate_runningrouters(void)
  891. {
  892. char *s=NULL;
  893. char *router_status=NULL;
  894. char digest[DIGEST_LEN];
  895. char published[ISO_TIME_LEN+1];
  896. size_t len;
  897. crypto_pk_env_t *private_key = get_identity_key();
  898. char *identity_pkey; /* Identity key, DER64-encoded. */
  899. size_t identity_pkey_len;
  900. if (!descriptor_list)
  901. descriptor_list = smartlist_create();
  902. if (list_server_status(descriptor_list, &router_status)) {
  903. goto err;
  904. }
  905. if (crypto_pk_write_public_key_to_string(private_key,&identity_pkey,
  906. &identity_pkey_len)<0) {
  907. log_fn(LOG_WARN,"write identity_pkey to string failed!");
  908. goto err;
  909. }
  910. format_iso_time(published, time(NULL));
  911. len = 2048+strlen(router_status);
  912. s = tor_malloc_zero(len);
  913. tor_snprintf(s, len,
  914. "network-status\n"
  915. "published %s\n"
  916. "router-status %s\n"
  917. "dir-signing-key\n%s"
  918. "directory-signature %s\n",
  919. published, router_status, identity_pkey, get_options()->Nickname);
  920. tor_free(router_status);
  921. tor_free(identity_pkey);
  922. if (router_get_runningrouters_hash(s,digest)) {
  923. log_fn(LOG_WARN,"couldn't compute digest");
  924. goto err;
  925. }
  926. if (router_append_dirobj_signature(s, len, digest, private_key)<0)
  927. goto err;
  928. set_cached_dir(&the_runningrouters, s, time(NULL));
  929. runningrouters_is_dirty = 0;
  930. /* We don't cache running-routers to disk, so there's no point in
  931. * authdirservers caching it. */
  932. /* dirserv_set_cached_directory(the_runningrouters, time(NULL), 1); */
  933. return 0;
  934. err:
  935. tor_free(s);
  936. tor_free(router_status);
  937. return -1;
  938. }
  939. /** Set *<b>rr</b> to the most recently generated encoded signed
  940. * running-routers list, generating a new one as necessary. Return the
  941. * size of the directory on success, and 0 on failure. */
  942. size_t
  943. dirserv_get_runningrouters(const char **rr, int compress)
  944. {
  945. return dirserv_get_obj(rr, compress,
  946. &cached_runningrouters, &the_runningrouters,
  947. runningrouters_is_dirty,
  948. generate_runningrouters,
  949. "v1 network status list");
  950. }
  951. /** Return true iff <b>ri</b> is "useful as an exit node." */
  952. static int
  953. router_is_general_exit(routerinfo_t *ri)
  954. {
  955. static const int ports[] = { 80, 443, 194 };
  956. int n_allowed = 3;
  957. int i;
  958. for (i = 0; i < 3; ++i) {
  959. struct addr_policy_t *policy = ri->exit_policy;
  960. for ( ; policy; policy = policy->next) {
  961. if (policy->prt_min > ports[i] || policy->prt_max < ports[i])
  962. continue; /* Doesn't cover our port. */
  963. if ((policy->msk & 0x00fffffful) != 0)
  964. continue; /* Wider than /8. */
  965. if ((policy->addr & 0xff000000ul) == 0x7f000000ul)
  966. continue; /* 127.x */
  967. /* We have a match that is wider than /24. */
  968. if (policy->policy_type != ADDR_POLICY_ACCEPT)
  969. --n_allowed;
  970. break;
  971. }
  972. }
  973. return n_allowed > 0;
  974. }
  975. /** For authoritative directories: the current (v2) network status */
  976. static cached_dir_t the_v2_networkstatus = { NULL, NULL, 0, 0, 0 };
  977. /** For authoritative directories only: replace the contents of
  978. * <b>the_v2_networkstatus</b> with a newly generated network status
  979. * object. */
  980. static int
  981. generate_v2_networkstatus(void)
  982. {
  983. #define BASE64_DIGEST_LEN 29
  984. #define LONGEST_STATUS_FLAG_NAME_LEN 7
  985. #define N_STATUS_FLAGS 6
  986. #define RS_ENTRY_LEN \
  987. ( /* first line */ \
  988. MAX_NICKNAME_LEN+BASE64_DIGEST_LEN*2+ISO_TIME_LEN+INET_NTOA_BUF_LEN+ \
  989. 5*2 /* ports */ + 10 /* punctuation */ + \
  990. /* second line */ \
  991. (LONGEST_STATUS_FLAG_NAME_LEN+1)*N_STATUS_FLAGS + 2)
  992. int r = -1;
  993. size_t len, identity_pkey_len;
  994. char *status = NULL, *client_versions = NULL, *server_versions = NULL,
  995. *identity_pkey = NULL, *hostname = NULL;
  996. char *outp, *endp;
  997. or_options_t *options = get_options();
  998. char fingerprint[FINGERPRINT_LEN+1];
  999. char ipaddr[INET_NTOA_BUF_LEN+1];
  1000. char published[ISO_TIME_LEN];
  1001. char digest[DIGEST_LEN];
  1002. struct in_addr in;
  1003. uint32_t addr;
  1004. crypto_pk_env_t *private_key = get_identity_key();
  1005. if (resolve_my_address(options, &addr, &hostname)<0) {
  1006. log_fn(LOG_WARN, "Couldn't resolve my hostname");
  1007. goto done;
  1008. }
  1009. in.s_addr = htonl(addr);
  1010. tor_inet_ntoa(&in, ipaddr, sizeof(ipaddr));
  1011. format_iso_time(published, time(NULL));
  1012. client_versions = format_versions_list(options->RecommendedClientVersions);
  1013. server_versions = format_versions_list(options->RecommendedServerVersions);
  1014. if (crypto_pk_write_public_key_to_string(private_key, &identity_pkey,
  1015. &identity_pkey_len)<0) {
  1016. log_fn(LOG_WARN,"Writing public key to string failed.");
  1017. goto done;
  1018. }
  1019. if (crypto_pk_get_fingerprint(private_key, fingerprint, 0)<0) {
  1020. log_fn(LOG_ERR, "Error computing fingerprint");
  1021. return -1;
  1022. }
  1023. len = 2048+strlen(client_versions)+strlen(server_versions)+identity_pkey_len*2;
  1024. len += (RS_ENTRY_LEN)*smartlist_len(descriptor_list) ;
  1025. status = tor_malloc(len);
  1026. tor_snprintf(status, len,
  1027. "network-status-version 2\n"
  1028. "dir-source %s %s %d\n"
  1029. "dir-fingerprint %s\n"
  1030. "published %s\n"
  1031. "dir-options %s\n"
  1032. "client-versions %s\n"
  1033. "server-versions %s\n"
  1034. "dir-signing-key\n%s\n",
  1035. hostname, ipaddr, (int)options->DirPort,
  1036. fingerprint,
  1037. published,
  1038. "Names",
  1039. client_versions,
  1040. server_versions,
  1041. identity_pkey);
  1042. outp = status + strlen(status);
  1043. endp = status + len;
  1044. SMARTLIST_FOREACH(descriptor_list, routerinfo_t *, ri, {
  1045. int f_exit = router_is_general_exit(ri);
  1046. int f_stable = !router_is_unreliable(ri, 1, 0);
  1047. int f_fast = !router_is_unreliable(ri, 0, 1);
  1048. int f_running;
  1049. int f_named = ri->is_verified;
  1050. int f_valid = f_named;
  1051. char identity64[128];
  1052. char digest64[128];
  1053. if (options->AuthoritativeDir) {
  1054. connection_t *conn = connection_get_by_identity_digest(
  1055. ri->identity_digest, CONN_TYPE_OR);
  1056. f_running = (router_is_me(ri) && !we_are_hibernating()) ||
  1057. (conn && conn->state == OR_CONN_STATE_OPEN);
  1058. } else {
  1059. f_running = ri->is_running;
  1060. }
  1061. format_iso_time(published, ri->published_on);
  1062. if (base64_encode(identity64, sizeof(identity64),
  1063. ri->identity_digest, DIGEST_LEN)<0)
  1064. goto done;
  1065. if (base64_encode(digest64, sizeof(digest64),
  1066. ri->signed_descriptor_digest, DIGEST_LEN)<0)
  1067. goto done;
  1068. identity64[BASE64_DIGEST_LEN] = '\0';
  1069. digest64[BASE64_DIGEST_LEN] = '\0';
  1070. in.s_addr = htonl(ri->addr);
  1071. tor_inet_ntoa(&in, ipaddr, sizeof(ipaddr));
  1072. if (tor_snprintf(outp, endp-outp,
  1073. "r %s %s %s %s %s %d %d\n"
  1074. "s%s%s%s%s%s%s\n",
  1075. ri->nickname,
  1076. identity64,
  1077. digest64,
  1078. published,
  1079. ipaddr,
  1080. ri->or_port,
  1081. ri->dir_port,
  1082. f_exit?" Exit":"",
  1083. f_stable?" Stable":"",
  1084. f_fast?" Fast":"",
  1085. f_running?" Running":"",
  1086. f_named?" Named":"",
  1087. f_valid?" Valid":"")<0) {
  1088. log_fn(LOG_WARN, "Unable to print router status.");
  1089. goto done;
  1090. }
  1091. outp += strlen(outp);
  1092. });
  1093. if (tor_snprintf(outp, endp-outp, "directory-signature %s\n",
  1094. get_options()->Nickname)<0) {
  1095. log_fn(LOG_WARN, "Unable to write signature line.");
  1096. goto done;
  1097. }
  1098. if (router_get_networkstatus_v2_hash(status, digest)<0) {
  1099. log_fn(LOG_WARN, "Unable to hash network status");
  1100. goto done;
  1101. }
  1102. if (router_append_dirobj_signature(outp,endp-outp,digest,private_key)<0)
  1103. goto done;
  1104. set_cached_dir(&the_v2_networkstatus, status, time(NULL));
  1105. dirserv_set_cached_networkstatus_v2(status, fingerprint, time(NULL));
  1106. r = 0;
  1107. done:
  1108. tor_free(client_versions);
  1109. tor_free(server_versions);
  1110. tor_free(status);
  1111. tor_free(hostname);
  1112. tor_free(identity_pkey);
  1113. return r;
  1114. }
  1115. /** Look for a network status object as specified by <b>key</b>, which should
  1116. * be eiher "authority" (to find a network status generated by us), a hex
  1117. * identity digest (to find a network status generated by given directory), or
  1118. * "all" (to return all the v2 network status objects we have, concatenated.
  1119. * If <b>compress</b>, find the version compressed with zlib. Return 0 if
  1120. * nothing was found; otherwise set *<b>directory</b> to the matching network
  1121. * status and return its length.
  1122. */
  1123. size_t
  1124. dirserv_get_networkstatus_v2(const char **directory, const char *key,
  1125. int compress)
  1126. {
  1127. *directory = NULL;
  1128. if (!(strcmp(key,"authority"))) {
  1129. if (get_options()->AuthoritativeDir) {
  1130. return dirserv_get_obj(directory, compress, NULL,
  1131. &the_v2_networkstatus,
  1132. networkstatus_v2_is_dirty,
  1133. generate_v2_networkstatus,
  1134. "network status list");
  1135. }
  1136. } else if (!strcmp(key, "all")) {
  1137. // XXXX NM
  1138. return dirserv_get_networkstatus_v2(directory, "authority", compress);
  1139. } else if (strlen(key)==HEX_DIGEST_LEN) {
  1140. cached_dir_t *cached = strmap_get(cached_v2_networkstatus, key);
  1141. if (cached)
  1142. return dirserv_get_obj(directory, compress, cached, NULL, 0, NULL,
  1143. "cached network status");
  1144. }
  1145. return 0;
  1146. }
  1147. /**
  1148. * Add a routerinfo_t to <b>descs_out</b> for each routers matching
  1149. * <b>key</b>. The key should be either "/tor/server/authority" for our own
  1150. * routerinfo; "/tor/server/all" for all the routerinfos we have,
  1151. * concatenated; or "/tor/server/FP" where FP is a plus-separated sequence of
  1152. * hex identity digests.
  1153. */
  1154. void
  1155. dirserv_get_routerdescs(smartlist_t *descs_out, const char *key)
  1156. {
  1157. smartlist_t *complete_list;
  1158. /* This is annoying. Can we unify these? */
  1159. if (descriptor_list)
  1160. complete_list = descriptor_list;
  1161. else {
  1162. routerlist_t *rlst;
  1163. router_get_routerlist(&rlst);
  1164. complete_list = rlst->routers;
  1165. }
  1166. if (!complete_list)
  1167. return;
  1168. if (!strcmp(key, "/tor/server/all")) {
  1169. smartlist_add_all(descs_out, descriptor_list);
  1170. } else if (!strcmp(key, "/tor/server/authority")) {
  1171. routerinfo_t *ri = router_get_my_routerinfo();
  1172. if (ri)
  1173. smartlist_add(descs_out, ri);
  1174. } else if (!strcmpstart(key, "/tor/server/fp/")) {
  1175. smartlist_t *hexdigests = smartlist_create();
  1176. smartlist_t *digests = smartlist_create();
  1177. key += strlen("/tor/server/fp/");
  1178. smartlist_split_string(hexdigests, key, "+", 0, 0);
  1179. SMARTLIST_FOREACH(hexdigests, char *, cp,
  1180. {
  1181. char *d;
  1182. if (strlen(cp) != HEX_DIGEST_LEN)
  1183. continue;
  1184. d = tor_malloc_zero(DIGEST_LEN);
  1185. base16_decode(d, DIGEST_LEN, cp, HEX_DIGEST_LEN);
  1186. tor_free(cp);
  1187. smartlist_add(digests, d);
  1188. });
  1189. smartlist_free(hexdigests);
  1190. /* XXXX should always return own descriptor. or special-case it. or
  1191. * something. */
  1192. SMARTLIST_FOREACH(descriptor_list, routerinfo_t *, ri,
  1193. SMARTLIST_FOREACH(digests, const char *, d,
  1194. if (!memcmp(d,ri->identity_digest,DIGEST_LEN)) {
  1195. smartlist_add(descs_out,ri);
  1196. break;
  1197. }));
  1198. SMARTLIST_FOREACH(digests, char *, d, tor_free(d));
  1199. smartlist_free(digests);
  1200. }
  1201. }
  1202. /** Called when a TLS handshake has completed successfully with a
  1203. * router listening at <b>address</b>:<b>or_port</b>, and has yielded
  1204. * a certificate with digest <b>digest_rcvd</b> and nickname
  1205. * <b>nickname_rcvd</b>. When this happens, it's clear that any other
  1206. * descriptors for that address/port combination must be unusable:
  1207. * delete them if they are not verified.
  1208. *
  1209. * Also, if as_advertised is 1, then inform the reachability checker
  1210. * that we could get to this guy.
  1211. */
  1212. void
  1213. dirserv_orconn_tls_done(const char *address,
  1214. uint16_t or_port,
  1215. const char *digest_rcvd,
  1216. const char *nickname_rcvd,
  1217. int as_advertised)
  1218. {
  1219. int i;
  1220. tor_assert(address);
  1221. tor_assert(digest_rcvd);
  1222. tor_assert(nickname_rcvd);
  1223. if (!descriptor_list)
  1224. return;
  1225. for (i = 0; i < smartlist_len(descriptor_list); ++i) {
  1226. routerinfo_t *ri = smartlist_get(descriptor_list, i);
  1227. int drop = 0;
  1228. if (strcasecmp(address, ri->address) || or_port != ri->or_port)
  1229. continue;
  1230. if (!ri->is_verified) {
  1231. /* We have a router at the same address! */
  1232. if (strcasecmp(ri->nickname, nickname_rcvd)) {
  1233. log_fn(LOG_NOTICE, "Dropping descriptor: nickname '%s' does not match nickname '%s' in cert from %s:%d",
  1234. ri->nickname, nickname_rcvd, address, or_port);
  1235. drop = 1;
  1236. } else if (memcmp(ri->identity_digest, digest_rcvd, DIGEST_LEN)) {
  1237. log_fn(LOG_NOTICE, "Dropping descriptor: identity key does not match key in cert from %s:%d",
  1238. address, or_port);
  1239. drop = 1;
  1240. }
  1241. }
  1242. if (drop) {
  1243. routerinfo_free(ri);
  1244. smartlist_del(descriptor_list, i--);
  1245. directory_set_dirty();
  1246. } else { /* correct nickname and digest. mark this router reachable! */
  1247. log_fn(LOG_INFO,"Found router %s to be reachable. Yay.", ri->nickname);
  1248. ri->last_reachable = time(NULL);
  1249. }
  1250. }
  1251. }
  1252. /** Release all storage used by the directory server. */
  1253. void
  1254. dirserv_free_all(void)
  1255. {
  1256. if (fingerprint_list) {
  1257. SMARTLIST_FOREACH(fingerprint_list, fingerprint_entry_t*, fp,
  1258. { tor_free(fp->nickname);
  1259. tor_free(fp->fingerprint);
  1260. tor_free(fp); });
  1261. smartlist_free(fingerprint_list);
  1262. fingerprint_list = NULL;
  1263. }
  1264. if (descriptor_list) {
  1265. SMARTLIST_FOREACH(descriptor_list, routerinfo_t *, ri,
  1266. routerinfo_free(ri));
  1267. smartlist_free(descriptor_list);
  1268. descriptor_list = NULL;
  1269. }
  1270. clear_cached_dir(&the_directory);
  1271. clear_cached_dir(&the_runningrouters);
  1272. clear_cached_dir(&cached_directory);
  1273. clear_cached_dir(&cached_runningrouters);
  1274. if (cached_v2_networkstatus) {
  1275. strmap_free(cached_v2_networkstatus, free_cached_dir);
  1276. cached_v2_networkstatus = NULL;
  1277. }
  1278. }