dirserv.c 49 KB

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