dirserv.c 49 KB

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