dirserv.c 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324
  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 the_v2_networkstatus_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. static smartlist_t *
  211. get_descriptor_list(void)
  212. {
  213. routerlist_t *routerlist;
  214. router_get_routerlist(&routerlist);
  215. if (!routerlist)
  216. return NULL;
  217. return routerlist->routers;
  218. }
  219. /** Return -1 if <b>ri</b> has a private or otherwise bad address,
  220. * unless we're configured to not care. Return 0 if all ok. */
  221. static int
  222. dirserv_router_has_valid_address(routerinfo_t *ri)
  223. {
  224. struct in_addr iaddr;
  225. if (get_options()->DirAllowPrivateAddresses)
  226. return 0; /* whatever it is, we're fine with it */
  227. if (!tor_inet_aton(ri->address, &iaddr)) {
  228. log_fn(LOG_INFO,"Router '%s' published non-IP address '%s'. Refusing.",
  229. ri->nickname, ri->address);
  230. return -1;
  231. }
  232. if (is_internal_IP(ntohl(iaddr.s_addr))) {
  233. log_fn(LOG_INFO,"Router '%s' published internal IP address '%s'. Refusing.",
  234. ri->nickname, ri->address);
  235. return -1; /* it's a private IP, we should reject it */
  236. }
  237. return 0;
  238. }
  239. /** DOCDOC */
  240. int
  241. dirserv_wants_to_reject_router(routerinfo_t *ri, int *verified,
  242. const char **msg)
  243. {
  244. /* Okay. Now check whether the fingerprint is recognized. */
  245. int r = dirserv_router_fingerprint_is_known(ri);
  246. time_t now;
  247. if (r==-1) {
  248. log_fn(LOG_WARN, "Known nickname '%s', wrong fingerprint. Not adding (ContactInfo '%s', platform '%s').",
  249. ri->nickname, ri->contact_info ? ri->contact_info : "",
  250. ri->platform ? ri->platform : "");
  251. *msg = "Rejected: There is already a verified server with this nickname and a different fingerprint.";
  252. return -1;
  253. } else if (r==0) {
  254. char fp[FINGERPRINT_LEN+1];
  255. log_fn(LOG_INFO, "Unknown nickname '%s' (%s:%d). Will try to add.",
  256. ri->nickname, ri->address, ri->or_port);
  257. if (crypto_pk_get_fingerprint(ri->identity_pkey, fp, 1) < 0) {
  258. log_fn(LOG_WARN, "Error computing fingerprint for '%s'", ri->nickname);
  259. } else {
  260. log_fn(LOG_INFO, "Fingerprint line: %s %s", ri->nickname, fp);
  261. }
  262. *verified = 0;
  263. } else {
  264. *verified = 1;
  265. }
  266. /* Is there too much clock skew? */
  267. now = time(NULL);
  268. if (ri->published_on > now+ROUTER_ALLOW_SKEW) {
  269. 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').",
  270. ri->nickname, (int)((ri->published_on-now)/60),
  271. ri->contact_info ? ri->contact_info : "",
  272. ri->platform ? ri->platform : "");
  273. *msg = "Rejected: Your clock is set too far in the future, or your timezone is not correct.";
  274. return -1;
  275. }
  276. if (ri->published_on < now-ROUTER_MAX_AGE) {
  277. 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').",
  278. ri->nickname, (int)((now-ri->published_on)/60),
  279. ri->contact_info ? ri->contact_info : "",
  280. ri->platform ? ri->platform : "");
  281. *msg = "Rejected: Server is expired, or your clock is too far in the past, or your timezone is not correct.";
  282. return -1;
  283. }
  284. if (dirserv_router_has_valid_address(ri) < 0) {
  285. log_fn(LOG_NOTICE, "Router with nickname '%s' has invalid address '%s'. Not adding (ContactInfo '%s', platform '%s').",
  286. ri->nickname, ri->address,
  287. ri->contact_info ? ri->contact_info : "",
  288. ri->platform ? ri->platform : "");
  289. *msg = "Rejected: Address is not an IP, or IP is a private address.";
  290. return -1;
  291. }
  292. return 0;
  293. }
  294. /** Parse the server descriptor at <b>desc</b> and maybe insert it into
  295. * the list of server descriptors. Set *<b>msg</b> to a message that
  296. * should be passed back to the origin of this descriptor.
  297. *
  298. * Return 2 if descriptor is well-formed and accepted;
  299. * 1 if well-formed and accepted but origin should hear *msg;
  300. * 0 if well-formed but redundant with one we already have;
  301. * -1 if it looks vaguely like a router descriptor but rejected;
  302. * -2 if we can't find a router descriptor in <b>desc</b>.
  303. *
  304. */
  305. int
  306. dirserv_add_descriptor(const char *desc, const char **msg)
  307. {
  308. int r;
  309. routerinfo_t *ri = NULL;
  310. tor_assert(msg);
  311. *msg = NULL;
  312. /* Check: is the descriptor syntactically valid? */
  313. ri = router_parse_entry_from_string(desc, NULL);
  314. if (!ri) {
  315. log(LOG_WARN, "Couldn't parse descriptor");
  316. *msg = "Rejected: Couldn't parse server descriptor.";
  317. return -2;
  318. }
  319. if ((r = router_add_to_routerlist(ri, msg))<0) {
  320. return r == -1 ? 0 : -1;
  321. } else {
  322. smartlist_t *changed = smartlist_create();
  323. smartlist_add(changed, ri);
  324. control_event_descriptors_changed(changed);
  325. smartlist_free(changed);
  326. if (!*msg) {
  327. *msg = ri->is_verified ? "Verified server descriptor accepted" :
  328. "Unverified server descriptor accepted";
  329. }
  330. return r == 0 ? 2 : 1;
  331. }
  332. }
  333. /** Remove all descriptors whose nicknames or fingerprints no longer
  334. * are allowed by our fingerprint list. (Descriptors that used to be
  335. * good can become bad when we reload the fingerprint list.)
  336. */
  337. static void
  338. directory_remove_invalid(void)
  339. {
  340. int i;
  341. int changed = 0;
  342. smartlist_t *descriptor_list = get_descriptor_list();
  343. if (!descriptor_list)
  344. return;
  345. for (i = 0; i < smartlist_len(descriptor_list); ++i) {
  346. routerinfo_t *ent = smartlist_get(descriptor_list, i);
  347. int r = dirserv_router_fingerprint_is_known(ent);
  348. if (r<0) {
  349. log(LOG_INFO, "Router '%s' is now verified with a key; removing old router with same name and different key.",
  350. ent->nickname);
  351. routerinfo_free(ent);
  352. smartlist_del(descriptor_list, i--);
  353. changed = 1;
  354. } else if (r>0 && !ent->is_verified) {
  355. log(LOG_INFO, "Router '%s' is now approved.", ent->nickname);
  356. ent->is_verified = 1;
  357. changed = 1;
  358. } else if (r==0 && ent->is_verified) {
  359. log(LOG_INFO, "Router '%s' is no longer approved.", ent->nickname);
  360. ent->is_verified = 0;
  361. changed = 1;
  362. }
  363. }
  364. if (changed)
  365. directory_set_dirty();
  366. }
  367. /** Write a list of unregistered descriptors into a newly allocated
  368. * string and return it. Used by dirserv operators to keep track of
  369. * fast nodes that haven't registered.
  370. */
  371. char *
  372. dirserver_getinfo_unregistered(const char *question)
  373. {
  374. int i, r;
  375. smartlist_t *answerlist;
  376. char buf[1024];
  377. char *answer;
  378. routerinfo_t *ent;
  379. int min_bw = atoi(question);
  380. smartlist_t *descriptor_list = get_descriptor_list();
  381. if (!descriptor_list)
  382. return tor_strdup("");
  383. answerlist = smartlist_create();
  384. for (i = 0; i < smartlist_len(descriptor_list); ++i) {
  385. ent = smartlist_get(descriptor_list, i);
  386. r = dirserv_router_fingerprint_is_known(ent);
  387. if (ent->bandwidthcapacity >= (size_t)min_bw &&
  388. ent->bandwidthrate >= (size_t)min_bw &&
  389. r == 0) {
  390. /* then log this one */
  391. tor_snprintf(buf, sizeof(buf),
  392. "%s: BW %d on '%s'.",
  393. ent->nickname, ent->bandwidthcapacity,
  394. ent->platform ? ent->platform : "");
  395. smartlist_add(answerlist, tor_strdup(buf));
  396. }
  397. }
  398. answer = smartlist_join_strings(answerlist, "\r\n", 0, NULL);
  399. SMARTLIST_FOREACH(answerlist, char *, cp, tor_free(cp));
  400. smartlist_free(answerlist);
  401. return answer;
  402. }
  403. /** Mark the directory as <b>dirty</b> -- when we're next asked for a
  404. * directory, we will rebuild it instead of reusing the most recently
  405. * generated one.
  406. */
  407. void
  408. directory_set_dirty()
  409. {
  410. time_t now = time(NULL);
  411. if (!the_directory_is_dirty)
  412. the_directory_is_dirty = now;
  413. if (!runningrouters_is_dirty)
  414. runningrouters_is_dirty = now;
  415. }
  416. /**
  417. * Allocate and return a description of the status of the server <b>desc</b>,
  418. * for use in a router-status line. The server is listed
  419. * as running iff <b>is_live</b> is true.
  420. */
  421. static char *
  422. list_single_server_status(routerinfo_t *desc, int is_live)
  423. {
  424. char buf[MAX_NICKNAME_LEN+HEX_DIGEST_LEN+4]; /* !nickname=$hexdigest\0 */
  425. char *cp;
  426. tor_assert(desc);
  427. cp = buf;
  428. if (!is_live) {
  429. *cp++ = '!';
  430. }
  431. if (desc->is_verified) {
  432. strlcpy(cp, desc->nickname, sizeof(buf)-(cp-buf));
  433. cp += strlen(cp);
  434. *cp++ = '=';
  435. }
  436. *cp++ = '$';
  437. base16_encode(cp, HEX_DIGEST_LEN+1, desc->identity_digest,
  438. DIGEST_LEN);
  439. return tor_strdup(buf);
  440. }
  441. #define REACHABLE_TIMEOUT (60*60) /* an hour */
  442. /* Make sure this is 3 times the value of get_dir_fetch_period() */
  443. /** Treat a router as alive if
  444. * - It's me, and I'm not hibernating.
  445. * or - we're connected to it and we've found it reachable recently. */
  446. static int
  447. dirserv_thinks_router_is_reachable(routerinfo_t *router, time_t now)
  448. {
  449. connection_t *conn;
  450. if (router_is_me(router) && !we_are_hibernating())
  451. return 1;
  452. conn = connection_get_by_identity_digest(router->identity_digest,
  453. CONN_TYPE_OR);
  454. if (conn && conn->state == OR_CONN_STATE_OPEN)
  455. return get_options()->AssumeReachable ||
  456. now < router->last_reachable + REACHABLE_TIMEOUT;
  457. return 0;
  458. }
  459. /** Return 1 if we're confident that there's a problem with
  460. * <b>router</b>'s reachability and its operator should be notified.
  461. */
  462. int
  463. dirserv_thinks_router_is_blatantly_unreachable(routerinfo_t *router, time_t now)
  464. {
  465. connection_t *conn;
  466. if (router->is_hibernating)
  467. return 0;
  468. conn = connection_get_by_identity_digest(router->identity_digest,
  469. CONN_TYPE_OR);
  470. if (conn && conn->state == OR_CONN_STATE_OPEN &&
  471. now >= router->last_reachable + 2*REACHABLE_TIMEOUT &&
  472. router->testing_since &&
  473. now >= router->testing_since + 2*REACHABLE_TIMEOUT)
  474. return 1;
  475. return 0;
  476. }
  477. /** Based on the routerinfo_ts in <b>routers</b>, allocate the
  478. * contents of a router-status line, and store it in
  479. * *<b>router_status_out</b>. Return 0 on success, -1 on failure.
  480. */
  481. int
  482. list_server_status(smartlist_t *routers, char **router_status_out)
  483. {
  484. /* List of entries in a router-status style: An optional !, then an optional
  485. * equals-suffixed nickname, then a dollar-prefixed hexdigest. */
  486. smartlist_t *rs_entries;
  487. time_t now = time(NULL);
  488. int authdir_mode = get_options()->AuthoritativeDir;
  489. tor_assert(router_status_out);
  490. rs_entries = smartlist_create();
  491. SMARTLIST_FOREACH(routers, routerinfo_t *, ri,
  492. {
  493. if (authdir_mode) {
  494. /* Update router status in routerinfo_t. */
  495. ri->is_running = dirserv_thinks_router_is_reachable(ri, now);
  496. }
  497. smartlist_add(rs_entries, list_single_server_status(ri, ri->is_running));
  498. });
  499. *router_status_out = smartlist_join_strings(rs_entries, " ", 0, NULL);
  500. SMARTLIST_FOREACH(rs_entries, char *, cp, tor_free(cp));
  501. smartlist_free(rs_entries);
  502. return 0;
  503. }
  504. /* Given a (possibly empty) list of config_line_t, each line of which contains
  505. * a list of comma-separated version numbers surrounded by optional space,
  506. * allocate and return a new string containing the version numbers, in order,
  507. * separated by commas. Used to generate Recommended(Client|Server)?Versions */
  508. static char *
  509. format_versions_list(config_line_t *ln)
  510. {
  511. smartlist_t *versions;
  512. char *result;
  513. versions = smartlist_create();
  514. for ( ; ln; ln = ln->next) {
  515. smartlist_split_string(versions, ln->value, ",",
  516. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  517. }
  518. result = smartlist_join_strings(versions,",",0,NULL);
  519. SMARTLIST_FOREACH(versions,char *,s,tor_free(s));
  520. smartlist_free(versions);
  521. return result;
  522. }
  523. /** Generate a new directory and write it into a newly allocated string.
  524. * Point *<b>dir_out</b> to the allocated string. Sign the
  525. * directory with <b>private_key</b>. Return 0 on success, -1 on
  526. * failure.
  527. */
  528. int
  529. dirserv_dump_directory_to_string(char **dir_out,
  530. crypto_pk_env_t *private_key)
  531. {
  532. char *router_status;
  533. char *identity_pkey; /* Identity key, DER64-encoded. */
  534. char *recommended_versions;
  535. char digest[DIGEST_LEN];
  536. char published[ISO_TIME_LEN+1];
  537. time_t published_on;
  538. char *buf = NULL;
  539. size_t buf_len;
  540. size_t identity_pkey_len;
  541. smartlist_t *descriptor_list = get_descriptor_list();
  542. tor_assert(dir_out);
  543. *dir_out = NULL;
  544. if (!descriptor_list)
  545. return -1;
  546. if (list_server_status(descriptor_list, &router_status))
  547. return -1;
  548. if (crypto_pk_write_public_key_to_string(private_key,&identity_pkey,
  549. &identity_pkey_len)<0) {
  550. log_fn(LOG_WARN,"write identity_pkey to string failed!");
  551. return -1;
  552. }
  553. recommended_versions = format_versions_list(get_options()->RecommendedVersions);
  554. published_on = time(NULL);
  555. format_iso_time(published, published_on);
  556. buf_len = 2048+strlen(recommended_versions)+
  557. strlen(router_status);
  558. SMARTLIST_FOREACH(descriptor_list, routerinfo_t *, ri,
  559. buf_len += ri->signed_descriptor_len);
  560. buf = tor_malloc(buf_len);
  561. /* We'll be comparing against buf_len throughout the rest of the
  562. function, though strictly speaking we shouldn't be able to exceed
  563. it. This is C, after all, so we may as well check for buffer
  564. overruns.*/
  565. tor_snprintf(buf, buf_len,
  566. "signed-directory\n"
  567. "published %s\n"
  568. "recommended-software %s\n"
  569. "router-status %s\n"
  570. "dir-signing-key\n%s\n",
  571. published, recommended_versions, router_status,
  572. identity_pkey);
  573. tor_free(recommended_versions);
  574. tor_free(router_status);
  575. tor_free(identity_pkey);
  576. SMARTLIST_FOREACH(descriptor_list, routerinfo_t *, ri,
  577. if (strlcat(buf, ri->signed_descriptor, buf_len) >= buf_len)
  578. goto truncated);
  579. /* These multiple strlcat calls are inefficient, but dwarfed by the RSA
  580. signature.
  581. */
  582. if (strlcat(buf, "directory-signature ", buf_len) >= buf_len)
  583. goto truncated;
  584. if (strlcat(buf, get_options()->Nickname, buf_len) >= buf_len)
  585. goto truncated;
  586. if (strlcat(buf, "\n", buf_len) >= buf_len)
  587. goto truncated;
  588. if (router_get_dir_hash(buf,digest)) {
  589. log_fn(LOG_WARN,"couldn't compute digest");
  590. tor_free(buf);
  591. return -1;
  592. }
  593. if (router_append_dirobj_signature(buf,buf_len,digest,private_key)<0) {
  594. tor_free(buf);
  595. return -1;
  596. }
  597. *dir_out = buf;
  598. return 0;
  599. truncated:
  600. log_fn(LOG_WARN,"tried to exceed string length.");
  601. tor_free(buf);
  602. return -1;
  603. }
  604. /** Most recently generated encoded signed directory. (auth dirservers only.)*/
  605. static cached_dir_t the_directory = { NULL, NULL, 0, 0, 0 };
  606. /* Used only by non-auth dirservers: The directory and runningrouters we'll
  607. * serve when requested. */
  608. static cached_dir_t cached_directory = { NULL, NULL, 0, 0, 0 };
  609. static cached_dir_t cached_runningrouters = { NULL, NULL, 0, 0, 0 };
  610. /* Used for other dirservers' v2 network statuses. Map from hexdigest to
  611. * cached_dir_t. */
  612. static strmap_t *cached_v2_networkstatus = NULL;
  613. /** Possibly replace the contents of <b>d</b> with the value of
  614. * <b>directory</b> published on <b>when</b>, unless <b>when</b> is older than
  615. * the last value, or too far in the future.
  616. *
  617. * Does not copy <b>directory</b>; free it if it isn't used.
  618. */
  619. static void
  620. set_cached_dir(cached_dir_t *d, char *directory, time_t when)
  621. {
  622. time_t now = time(NULL);
  623. if (when<=d->published) {
  624. log_fn(LOG_INFO, "Ignoring old directory; not caching.");
  625. tor_free(directory);
  626. } else if (when>=now+ROUTER_MAX_AGE) {
  627. log_fn(LOG_INFO, "Ignoring future directory; not caching.");
  628. tor_free(directory);
  629. } else {
  630. /* if (when>d->published && when<now+ROUTER_MAX_AGE) */
  631. log_fn(LOG_DEBUG, "Caching directory.");
  632. tor_free(d->dir);
  633. d->dir = directory;
  634. d->dir_len = strlen(directory);
  635. tor_free(d->dir_z);
  636. if (tor_gzip_compress(&(d->dir_z), &(d->dir_z_len), d->dir, d->dir_len,
  637. ZLIB_METHOD)) {
  638. log_fn(LOG_WARN,"Error compressing cached directory");
  639. }
  640. d->published = when;
  641. }
  642. }
  643. /** Remove all storage held in <b>d</b>, but do not free <b>d</b> itself. */
  644. static void
  645. clear_cached_dir(cached_dir_t *d)
  646. {
  647. tor_free(d->dir);
  648. tor_free(d->dir_z);
  649. memset(d, 0, sizeof(cached_dir_t));
  650. }
  651. /** Free all storage held by the cached_dir_t in <b>d</b>. */
  652. static void
  653. free_cached_dir(void *_d)
  654. {
  655. cached_dir_t *d = (cached_dir_t *)_d;
  656. clear_cached_dir(d);
  657. tor_free(d);
  658. }
  659. /** If we have no cached directory, or it is older than <b>when</b>, then
  660. * replace it with <b>directory</b>, published at <b>when</b>.
  661. */
  662. void
  663. dirserv_set_cached_directory(const char *directory, time_t published,
  664. int is_running_routers)
  665. {
  666. cached_dir_t *d;
  667. d = is_running_routers ? &cached_runningrouters : &cached_directory;
  668. set_cached_dir(d, tor_strdup(directory), published);
  669. if (!is_running_routers) {
  670. char filename[512];
  671. tor_snprintf(filename,sizeof(filename),"%s/cached-directory", get_options()->DataDirectory);
  672. if (write_str_to_file(filename,cached_directory.dir,0) < 0) {
  673. log_fn(LOG_NOTICE, "Couldn't write cached directory to disk. Ignoring.");
  674. }
  675. }
  676. }
  677. /** We've just received a v2 network-status for an authoritative directory
  678. * with fingerprint <b>fp</b> (hex digest, no spaces), published at
  679. * <b>published</b>. Store it so we can serve it to others.
  680. */
  681. void
  682. dirserv_set_cached_networkstatus_v2(const char *directory, const char *fp,
  683. time_t published)
  684. {
  685. cached_dir_t *d;
  686. if (!cached_v2_networkstatus)
  687. cached_v2_networkstatus = strmap_new();
  688. tor_assert(strlen(fp) == HEX_DIGEST_LEN);
  689. if (!(d = strmap_get(cached_v2_networkstatus, fp))) {
  690. d = tor_malloc_zero(sizeof(cached_dir_t));
  691. strmap_set(cached_v2_networkstatus, fp, d);
  692. }
  693. tor_assert(d);
  694. set_cached_dir(d, tor_strdup(directory), published);
  695. }
  696. static cached_dir_t *
  697. dirserv_pick_cached_dir_obj(cached_dir_t *cache_src,
  698. cached_dir_t *auth_src,
  699. time_t dirty, int (*regenerate)(void),
  700. const char *name,
  701. int is_v1_object)
  702. {
  703. int authority = get_options()->AuthoritativeDir &&
  704. (!is_v1_object || get_options()->V1AuthoritativeDir);
  705. if (!authority) {
  706. return cache_src;
  707. } else {
  708. /* We're authoritative. */
  709. if (regenerate != NULL) {
  710. if (dirty && dirty + DIR_REGEN_SLACK_TIME < time(NULL)) {
  711. if (regenerate()) {
  712. log_fn(LOG_ERR, "Couldn't generate %s?", name);
  713. exit(1);
  714. }
  715. } else {
  716. log_fn(LOG_INFO, "The %s is still clean; reusing.", name);
  717. }
  718. }
  719. return auth_src ? auth_src : cache_src;
  720. }
  721. }
  722. /** Helper: If we're authoritative and <b>auth_src</b> is set, use
  723. * <b>auth_src</b>, otherwise use <b>cache_src</b>. If we're using
  724. * <b>auth_src</b> and it's been <b>dirty</b> for at least
  725. * DIR_REGEN_SLACK_TIME seconds, call <b>regenerate</b>() to make a fresh one.
  726. * Yields the compressed version of the directory object if <b>compress</b> is
  727. * set; otherwise return the uncompressed version. (In either case, sets
  728. * *<b>out</b> and returns the size of the buffer in *<b>out</b>.
  729. *
  730. * DOCDOC is_v1_object
  731. **/
  732. static size_t
  733. dirserv_get_obj(const char **out, int compress,
  734. cached_dir_t *cache_src,
  735. cached_dir_t *auth_src,
  736. time_t dirty, int (*regenerate)(void),
  737. const char *name,
  738. int is_v1_object)
  739. {
  740. cached_dir_t *d = dirserv_pick_cached_dir_obj(
  741. cache_src, auth_src,
  742. dirty, regenerate, name, is_v1_object);
  743. if (!d)
  744. return 0;
  745. *out = compress ? d->dir_z : d->dir;
  746. if (*out) {
  747. return compress ? d->dir_z_len : d->dir_len;
  748. } else {
  749. /* not yet available. */
  750. return 0;
  751. }
  752. }
  753. /** Set *<b>directory</b> to the most recently generated encoded signed
  754. * directory, generating a new one as necessary. If not an authoritative
  755. * directory may return 0 if no directory is yet cached.*/
  756. size_t
  757. dirserv_get_directory(const char **directory, int compress)
  758. {
  759. return dirserv_get_obj(directory, compress,
  760. &cached_directory, &the_directory,
  761. the_directory_is_dirty,
  762. dirserv_regenerate_directory,
  763. "server directory", 1);
  764. }
  765. /**
  766. * Generate a fresh directory (authdirservers only.)
  767. */
  768. static int
  769. dirserv_regenerate_directory(void)
  770. {
  771. char *new_directory=NULL;
  772. if (dirserv_dump_directory_to_string(&new_directory,
  773. get_identity_key())) {
  774. log(LOG_WARN, "Error creating directory.");
  775. tor_free(new_directory);
  776. return -1;
  777. }
  778. set_cached_dir(&the_directory, new_directory, time(NULL));
  779. log_fn(LOG_INFO,"New directory (size %d):\n%s",(int)the_directory.dir_len,
  780. the_directory.dir);
  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.dir, time(NULL), 0);
  785. return 0;
  786. }
  787. /** For authoritative directories: the current (v1) network status */
  788. static cached_dir_t the_runningrouters = { NULL, NULL, 0, 0, 0 };
  789. /** Replace the current running-routers list with a newly generated one. */
  790. static int
  791. generate_runningrouters(void)
  792. {
  793. char *s=NULL;
  794. char *router_status=NULL;
  795. char digest[DIGEST_LEN];
  796. char published[ISO_TIME_LEN+1];
  797. size_t len;
  798. crypto_pk_env_t *private_key = get_identity_key();
  799. char *identity_pkey; /* Identity key, DER64-encoded. */
  800. size_t identity_pkey_len;
  801. smartlist_t *descriptor_list = get_descriptor_list();
  802. if (list_server_status(descriptor_list, &router_status)) {
  803. goto err;
  804. }
  805. if (crypto_pk_write_public_key_to_string(private_key,&identity_pkey,
  806. &identity_pkey_len)<0) {
  807. log_fn(LOG_WARN,"write identity_pkey to string failed!");
  808. goto err;
  809. }
  810. format_iso_time(published, time(NULL));
  811. len = 2048+strlen(router_status);
  812. s = tor_malloc_zero(len);
  813. tor_snprintf(s, len,
  814. "network-status\n"
  815. "published %s\n"
  816. "router-status %s\n"
  817. "dir-signing-key\n%s"
  818. "directory-signature %s\n",
  819. published, router_status, identity_pkey, get_options()->Nickname);
  820. tor_free(router_status);
  821. tor_free(identity_pkey);
  822. if (router_get_runningrouters_hash(s,digest)) {
  823. log_fn(LOG_WARN,"couldn't compute digest");
  824. goto err;
  825. }
  826. if (router_append_dirobj_signature(s, len, digest, private_key)<0)
  827. goto err;
  828. set_cached_dir(&the_runningrouters, s, time(NULL));
  829. runningrouters_is_dirty = 0;
  830. return 0;
  831. err:
  832. tor_free(s);
  833. tor_free(router_status);
  834. return -1;
  835. }
  836. /** Set *<b>rr</b> to the most recently generated encoded signed
  837. * running-routers list, generating a new one as necessary. Return the
  838. * size of the directory on success, and 0 on failure. */
  839. size_t
  840. dirserv_get_runningrouters(const char **rr, int compress)
  841. {
  842. return dirserv_get_obj(rr, compress,
  843. &cached_runningrouters, &the_runningrouters,
  844. runningrouters_is_dirty,
  845. generate_runningrouters,
  846. "v1 network status list", 1);
  847. }
  848. /** Return true iff <b>ri</b> is "useful as an exit node", meaning
  849. * it allows exit to at least one /8 address space for at least
  850. * one of ports 80, 443, and 6667. */
  851. static int
  852. router_is_general_exit(routerinfo_t *ri)
  853. {
  854. static const int ports[] = { 80, 443, 6667 };
  855. int n_allowed = 3;
  856. int i;
  857. for (i = 0; i < 3; ++i) {
  858. struct addr_policy_t *policy = ri->exit_policy;
  859. for ( ; policy; policy = policy->next) {
  860. if (policy->prt_min > ports[i] || policy->prt_max < ports[i])
  861. continue; /* Doesn't cover our port. */
  862. if ((policy->msk & 0x00fffffful) != 0)
  863. continue; /* Narrower than a /8. */
  864. if ((policy->addr & 0xff000000ul) == 0x7f000000ul)
  865. continue; /* 127.x */
  866. /* We have a match that is at least a /8. */
  867. if (policy->policy_type != ADDR_POLICY_ACCEPT)
  868. --n_allowed;
  869. break;
  870. }
  871. }
  872. return n_allowed > 0;
  873. }
  874. /** For authoritative directories: the current (v2) network status */
  875. static cached_dir_t the_v2_networkstatus = { NULL, NULL, 0, 0, 0 };
  876. /** For authoritative directories only: replace the contents of
  877. * <b>the_v2_networkstatus</b> with a newly generated network status
  878. * object. */
  879. static int
  880. generate_v2_networkstatus(void)
  881. {
  882. #define BASE64_DIGEST_LEN 27
  883. #define LONGEST_STATUS_FLAG_NAME_LEN 7
  884. #define N_STATUS_FLAGS 6
  885. #define RS_ENTRY_LEN \
  886. ( /* first line */ \
  887. MAX_NICKNAME_LEN+BASE64_DIGEST_LEN*2+ISO_TIME_LEN+INET_NTOA_BUF_LEN+ \
  888. 5*2 /* ports */ + 10 /* punctuation */ + \
  889. /* second line */ \
  890. (LONGEST_STATUS_FLAG_NAME_LEN+1)*N_STATUS_FLAGS + 2)
  891. int r = -1;
  892. size_t len, identity_pkey_len;
  893. char *status = NULL, *client_versions = NULL, *server_versions = NULL,
  894. *identity_pkey = NULL, *hostname = NULL;
  895. char *outp, *endp;
  896. or_options_t *options = get_options();
  897. char fingerprint[FINGERPRINT_LEN+1];
  898. char ipaddr[INET_NTOA_BUF_LEN+1];
  899. char published[ISO_TIME_LEN];
  900. char digest[DIGEST_LEN];
  901. struct in_addr in;
  902. uint32_t addr;
  903. crypto_pk_env_t *private_key = get_identity_key();
  904. smartlist_t *descriptor_list = get_descriptor_list();
  905. const char *contact;
  906. if (!descriptor_list) {
  907. log_fn(LOG_WARN, "Couldn't get router list.");
  908. goto done;
  909. }
  910. if (resolve_my_address(options, &addr, &hostname)<0) {
  911. log_fn(LOG_WARN, "Couldn't resolve my hostname");
  912. goto done;
  913. }
  914. in.s_addr = htonl(addr);
  915. tor_inet_ntoa(&in, ipaddr, sizeof(ipaddr));
  916. format_iso_time(published, time(NULL));
  917. client_versions = format_versions_list(options->RecommendedClientVersions);
  918. server_versions = format_versions_list(options->RecommendedServerVersions);
  919. if (crypto_pk_write_public_key_to_string(private_key, &identity_pkey,
  920. &identity_pkey_len)<0) {
  921. log_fn(LOG_WARN,"Writing public key to string failed.");
  922. goto done;
  923. }
  924. if (crypto_pk_get_fingerprint(private_key, fingerprint, 0)<0) {
  925. log_fn(LOG_ERR, "Error computing fingerprint");
  926. return -1;
  927. }
  928. contact = get_options()->ContactInfo;
  929. if (!contact)
  930. contact = "(none)";
  931. len = 2048+strlen(client_versions)+strlen(server_versions)+identity_pkey_len*2;
  932. len += (RS_ENTRY_LEN)*smartlist_len(descriptor_list) ;
  933. status = tor_malloc(len);
  934. tor_snprintf(status, len,
  935. "network-status-version 2\n"
  936. "dir-source %s %s %d\n"
  937. "fingerprint %s\n"
  938. "contact %s\n"
  939. "published %s\n"
  940. "dir-options %s\n"
  941. "client-versions %s\n"
  942. "server-versions %s\n"
  943. "dir-signing-key\n%s\n",
  944. hostname, ipaddr, (int)options->DirPort,
  945. fingerprint,
  946. contact,
  947. published,
  948. "Names",
  949. client_versions,
  950. server_versions,
  951. identity_pkey);
  952. outp = status + strlen(status);
  953. endp = status + len;
  954. SMARTLIST_FOREACH(descriptor_list, routerinfo_t *, ri, {
  955. int f_exit = router_is_general_exit(ri);
  956. int f_stable = !router_is_unreliable(ri, 1, 0);
  957. int f_fast = !router_is_unreliable(ri, 0, 1);
  958. int f_running;
  959. int f_named = ri->is_verified;
  960. int f_valid = f_named;
  961. char identity64[128];
  962. char digest64[128];
  963. if (options->AuthoritativeDir) {
  964. connection_t *conn = connection_get_by_identity_digest(
  965. ri->identity_digest, CONN_TYPE_OR);
  966. f_running = (router_is_me(ri) && !we_are_hibernating()) ||
  967. (conn && conn->state == OR_CONN_STATE_OPEN);
  968. /* Update router status in routerinfo_t. */
  969. ri->is_running = f_running;
  970. } else {
  971. f_running = ri->is_running;
  972. }
  973. format_iso_time(published, ri->published_on);
  974. if (base64_encode(identity64, sizeof(identity64),
  975. ri->identity_digest, DIGEST_LEN)<0)
  976. goto done;
  977. if (base64_encode(digest64, sizeof(digest64),
  978. ri->signed_descriptor_digest, DIGEST_LEN)<0)
  979. goto done;
  980. identity64[BASE64_DIGEST_LEN] = '\0';
  981. digest64[BASE64_DIGEST_LEN] = '\0';
  982. in.s_addr = htonl(ri->addr);
  983. tor_inet_ntoa(&in, ipaddr, sizeof(ipaddr));
  984. if (tor_snprintf(outp, endp-outp,
  985. "r %s %s %s %s %s %d %d\n"
  986. "s%s%s%s%s%s%s\n",
  987. ri->nickname,
  988. identity64,
  989. digest64,
  990. published,
  991. ipaddr,
  992. ri->or_port,
  993. ri->dir_port,
  994. f_exit?" Exit":"",
  995. f_stable?" Stable":"",
  996. f_fast?" Fast":"",
  997. f_running?" Running":"",
  998. f_named?" Named":"",
  999. f_valid?" Valid":"")<0) {
  1000. log_fn(LOG_WARN, "Unable to print router status.");
  1001. goto done;
  1002. }
  1003. outp += strlen(outp);
  1004. });
  1005. if (tor_snprintf(outp, endp-outp, "directory-signature %s\n",
  1006. get_options()->Nickname)<0) {
  1007. log_fn(LOG_WARN, "Unable to write signature line.");
  1008. goto done;
  1009. }
  1010. if (router_get_networkstatus_v2_hash(status, digest)<0) {
  1011. log_fn(LOG_WARN, "Unable to hash network status");
  1012. goto done;
  1013. }
  1014. if (router_append_dirobj_signature(outp,endp-outp,digest,private_key)<0)
  1015. goto done;
  1016. set_cached_dir(&the_v2_networkstatus, status, time(NULL));
  1017. status = NULL; /* So it doesn't get double-freed. */
  1018. the_v2_networkstatus_is_dirty = 0;
  1019. router_set_networkstatus(the_v2_networkstatus.dir, time(NULL), 0);
  1020. r = 0;
  1021. done:
  1022. tor_free(client_versions);
  1023. tor_free(server_versions);
  1024. tor_free(status);
  1025. tor_free(hostname);
  1026. tor_free(identity_pkey);
  1027. return r;
  1028. }
  1029. /** Look for a network status object as specified by <b>key</b>, which should
  1030. * be either "authority" (to find a network status generated by us), a hex
  1031. * identity digest (to find a network status generated by given directory), or
  1032. * "all" (to return all the v2 network status objects we have, concatenated).
  1033. * If <b>compress</b>, find the version compressed with zlib. Return 0 if
  1034. * nothing was found; otherwise set *<b>directory</b> to the matching network
  1035. * status and return its length.
  1036. */
  1037. int
  1038. dirserv_get_networkstatus_v2(smartlist_t *result,
  1039. const char *key)
  1040. {
  1041. tor_assert(result);
  1042. if (!(strcmp(key,"authority"))) {
  1043. if (get_options()->AuthoritativeDir) {
  1044. cached_dir_t *d =
  1045. dirserv_pick_cached_dir_obj(NULL,
  1046. &the_v2_networkstatus,
  1047. the_v2_networkstatus_is_dirty,
  1048. generate_v2_networkstatus,
  1049. "network status list", 0);
  1050. if (d)
  1051. smartlist_add(result, d);
  1052. }
  1053. } else if (!strcmp(key, "all")) {
  1054. strmap_iter_t *iter = strmap_iter_init(cached_v2_networkstatus);
  1055. while (!strmap_iter_done(iter)) {
  1056. const char *fp;
  1057. void *val;
  1058. strmap_iter_get(iter, &fp, &val);
  1059. smartlist_add(result, val);
  1060. }
  1061. } else if (!strcmpstart(key, "fp/")) {
  1062. smartlist_t *hexdigests = smartlist_create();
  1063. smartlist_split_string(hexdigests, key+3, "+", 0, 0);
  1064. SMARTLIST_FOREACH(hexdigests, char *, cp,
  1065. {
  1066. cached_dir_t *cached;
  1067. tor_strlower(cp);
  1068. /* XXXX special-case own key? */
  1069. cached = strmap_get(cached_v2_networkstatus, cp);
  1070. if (cached)
  1071. smartlist_add(result, cached);
  1072. });
  1073. }
  1074. return 0;
  1075. }
  1076. /** Add a routerinfo_t to <b>descs_out</b> for each routers matching
  1077. * <b>key</b>. The key should be either "/tor/server/authority" for our own
  1078. * routerinfo; "/tor/server/all" for all the routerinfos we have,
  1079. * concatenated; or "/tor/server/FP" where FP is a plus-separated sequence of
  1080. * hex identity digests.
  1081. */
  1082. void
  1083. dirserv_get_routerdescs(smartlist_t *descs_out, const char *key)
  1084. {
  1085. smartlist_t *complete_list = get_descriptor_list();
  1086. if (!complete_list)
  1087. return;
  1088. if (!strcmp(key, "/tor/server/all")) {
  1089. smartlist_add_all(descs_out, complete_list);
  1090. } else if (!strcmp(key, "/tor/server/authority")) {
  1091. routerinfo_t *ri = router_get_my_routerinfo();
  1092. if (ri)
  1093. smartlist_add(descs_out, ri);
  1094. } else if (!strcmpstart(key, "/tor/server/fp/")) {
  1095. smartlist_t *hexdigests = smartlist_create();
  1096. smartlist_t *digests = smartlist_create();
  1097. key += strlen("/tor/server/fp/");
  1098. smartlist_split_string(hexdigests, key, "+", 0, 0);
  1099. SMARTLIST_FOREACH(hexdigests, char *, cp,
  1100. {
  1101. char *d;
  1102. if (strlen(cp) != HEX_DIGEST_LEN)
  1103. continue;
  1104. d = tor_malloc_zero(DIGEST_LEN);
  1105. base16_decode(d, DIGEST_LEN, cp, HEX_DIGEST_LEN);
  1106. tor_free(cp);
  1107. smartlist_add(digests, d);
  1108. });
  1109. smartlist_free(hexdigests);
  1110. /* XXXX should always return own descriptor. or special-case it. or
  1111. * something. */
  1112. SMARTLIST_FOREACH(complete_list, routerinfo_t *, ri,
  1113. SMARTLIST_FOREACH(digests, const char *, d,
  1114. if (!memcmp(d,ri->identity_digest,DIGEST_LEN)) {
  1115. smartlist_add(descs_out,ri);
  1116. break;
  1117. }));
  1118. SMARTLIST_FOREACH(digests, char *, d, tor_free(d));
  1119. smartlist_free(digests);
  1120. }
  1121. }
  1122. /** Called when a TLS handshake has completed successfully with a
  1123. * router listening at <b>address</b>:<b>or_port</b>, and has yielded
  1124. * a certificate with digest <b>digest_rcvd</b> and nickname
  1125. * <b>nickname_rcvd</b>. When this happens, it's clear that any other
  1126. * descriptors for that address/port combination must be unusable:
  1127. * delete them if they are not verified.
  1128. *
  1129. * Also, if as_advertised is 1, then inform the reachability checker
  1130. * that we could get to this guy.
  1131. */
  1132. void
  1133. dirserv_orconn_tls_done(const char *address,
  1134. uint16_t or_port,
  1135. const char *digest_rcvd,
  1136. const char *nickname_rcvd,
  1137. int as_advertised)
  1138. {
  1139. int i;
  1140. smartlist_t *descriptor_list = get_descriptor_list();
  1141. tor_assert(address);
  1142. tor_assert(digest_rcvd);
  1143. tor_assert(nickname_rcvd);
  1144. if (!descriptor_list)
  1145. return;
  1146. // XXXXNM We should really have a better solution here than dropping
  1147. // XXXXNM whole routers; otherwise, they come back way too easily.
  1148. for (i = 0; i < smartlist_len(descriptor_list); ++i) {
  1149. routerinfo_t *ri = smartlist_get(descriptor_list, i);
  1150. int drop = 0;
  1151. if (strcasecmp(address, ri->address) || or_port != ri->or_port)
  1152. continue;
  1153. if (!ri->is_verified) {
  1154. /* We have a router at the same address! */
  1155. if (strcasecmp(ri->nickname, nickname_rcvd)) {
  1156. log_fn(LOG_NOTICE, "Dropping descriptor: nickname '%s' does not match nickname '%s' in cert from %s:%d",
  1157. ri->nickname, nickname_rcvd, address, or_port);
  1158. drop = 1;
  1159. } else if (memcmp(ri->identity_digest, digest_rcvd, DIGEST_LEN)) {
  1160. log_fn(LOG_NOTICE, "Dropping descriptor: identity key does not match key in cert from %s:%d",
  1161. address, or_port);
  1162. drop = 1;
  1163. }
  1164. }
  1165. if (drop) {
  1166. routerinfo_free(ri);
  1167. smartlist_del(descriptor_list, i--);
  1168. directory_set_dirty();
  1169. } else { /* correct nickname and digest. mark this router reachable! */
  1170. log_fn(LOG_INFO,"Found router %s to be reachable. Yay.", ri->nickname);
  1171. ri->last_reachable = time(NULL);
  1172. ri->num_unreachable_notifications = 0;
  1173. }
  1174. }
  1175. }
  1176. /** Release all storage used by the directory server. */
  1177. void
  1178. dirserv_free_all(void)
  1179. {
  1180. if (fingerprint_list) {
  1181. SMARTLIST_FOREACH(fingerprint_list, fingerprint_entry_t*, fp,
  1182. { tor_free(fp->nickname);
  1183. tor_free(fp->fingerprint);
  1184. tor_free(fp); });
  1185. smartlist_free(fingerprint_list);
  1186. fingerprint_list = NULL;
  1187. }
  1188. clear_cached_dir(&the_directory);
  1189. clear_cached_dir(&the_runningrouters);
  1190. clear_cached_dir(&cached_directory);
  1191. clear_cached_dir(&cached_runningrouters);
  1192. if (cached_v2_networkstatus) {
  1193. strmap_free(cached_v2_networkstatus, free_cached_dir);
  1194. cached_v2_networkstatus = NULL;
  1195. }
  1196. }