router.c 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  1. /* Copyright 2001 Matej Pfajfar.
  2. * Copyright 2001-2004 Roger Dingledine.
  3. * Copyright 2004-2005 Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char router_c_id[] = "$Id$";
  7. #include "or.h"
  8. /**
  9. * \file router.c
  10. * \brief OR functionality, including key maintenance, generating
  11. * and uploading server descriptors, retrying OR connections.
  12. **/
  13. extern long stats_n_seconds_working;
  14. /* Exposed for test.c. */ void get_platform_str(char *platform, size_t len);
  15. /************************************************************/
  16. /*****
  17. * Key management: ORs only.
  18. *****/
  19. /** Private keys for this OR. There is also an SSL key managed by tortls.c.
  20. */
  21. static tor_mutex_t *key_lock=NULL;
  22. static time_t onionkey_set_at=0; /* When was onionkey last changed? */
  23. static crypto_pk_env_t *onionkey=NULL;
  24. static crypto_pk_env_t *lastonionkey=NULL;
  25. static crypto_pk_env_t *identitykey=NULL;
  26. /** Replace the current onion key with <b>k</b>. Does not affect lastonionkey;
  27. * to update onionkey correctly, call rotate_onion_key().
  28. */
  29. void
  30. set_onion_key(crypto_pk_env_t *k)
  31. {
  32. tor_mutex_acquire(key_lock);
  33. onionkey = k;
  34. onionkey_set_at = time(NULL);
  35. tor_mutex_release(key_lock);
  36. mark_my_descriptor_dirty();
  37. }
  38. /** Return the current onion key. Requires that the onion key has been
  39. * loaded or generated. */
  40. crypto_pk_env_t *
  41. get_onion_key(void)
  42. {
  43. tor_assert(onionkey);
  44. return onionkey;
  45. }
  46. /** Return the onion key that was current before the most recent onion
  47. * key rotation. If no rotation has been performed since this process
  48. * started, return NULL.
  49. */
  50. crypto_pk_env_t *
  51. get_previous_onion_key(void)
  52. {
  53. return lastonionkey;
  54. }
  55. /** Store a copy of the current onion key into *<b>key</b>, and a copy
  56. * of the most recent onion key into *<b>last</b>.
  57. */
  58. void
  59. dup_onion_keys(crypto_pk_env_t **key, crypto_pk_env_t **last)
  60. {
  61. tor_assert(key);
  62. tor_assert(last);
  63. tor_mutex_acquire(key_lock);
  64. *key = crypto_pk_dup_key(onionkey);
  65. if (lastonionkey)
  66. *last = crypto_pk_dup_key(lastonionkey);
  67. else
  68. *last = NULL;
  69. tor_mutex_release(key_lock);
  70. }
  71. /** Return the time when the onion key was last set. This is either the time
  72. * when the process launched, or the time of the most recent key rotation since
  73. * the process launched.
  74. */
  75. time_t
  76. get_onion_key_set_at(void)
  77. {
  78. return onionkey_set_at;
  79. }
  80. /** Set the current identity key to k.
  81. */
  82. void
  83. set_identity_key(crypto_pk_env_t *k)
  84. {
  85. identitykey = k;
  86. }
  87. /** Returns the current identity key; requires that the identity key has been
  88. * set.
  89. */
  90. crypto_pk_env_t *
  91. get_identity_key(void)
  92. {
  93. tor_assert(identitykey);
  94. return identitykey;
  95. }
  96. /** Return true iff the identity key has been set. */
  97. int
  98. identity_key_is_set(void)
  99. {
  100. return identitykey != NULL;
  101. }
  102. /** Replace the previous onion key with the current onion key, and generate
  103. * a new previous onion key. Immediately after calling this function,
  104. * the OR should:
  105. * - schedule all previous cpuworkers to shut down _after_ processing
  106. * pending work. (This will cause fresh cpuworkers to be generated.)
  107. * - generate and upload a fresh routerinfo.
  108. */
  109. void
  110. rotate_onion_key(void)
  111. {
  112. char fname[512];
  113. char fname_prev[512];
  114. crypto_pk_env_t *prkey;
  115. tor_snprintf(fname,sizeof(fname),
  116. "%s/keys/secret_onion_key",get_options()->DataDirectory);
  117. tor_snprintf(fname_prev,sizeof(fname_prev),
  118. "%s/keys/secret_onion_key.old",get_options()->DataDirectory);
  119. if (!(prkey = crypto_new_pk_env())) {
  120. log(LOG_ERR, "Error creating crypto environment.");
  121. goto error;
  122. }
  123. if (crypto_pk_generate_key(prkey)) {
  124. log(LOG_ERR, "Error generating onion key");
  125. goto error;
  126. }
  127. if (file_status(fname) == FN_FILE) {
  128. if (replace_file(fname, fname_prev))
  129. goto error;
  130. }
  131. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  132. log(LOG_ERR, "Couldn't write generated key to \"%s\".", fname);
  133. goto error;
  134. }
  135. log_fn(LOG_INFO, "Rotating onion key");
  136. tor_mutex_acquire(key_lock);
  137. if (lastonionkey)
  138. crypto_free_pk_env(lastonionkey);
  139. lastonionkey = onionkey;
  140. onionkey = prkey;
  141. onionkey_set_at = time(NULL);
  142. tor_mutex_release(key_lock);
  143. mark_my_descriptor_dirty();
  144. return;
  145. error:
  146. log_fn(LOG_WARN, "Couldn't rotate onion key.");
  147. }
  148. /* Read an RSA secret key key from a file that was once named fname_old,
  149. * but is now named fname_new. Rename the file from old to new as needed.
  150. */
  151. static crypto_pk_env_t *
  152. init_key_from_file_name_changed(const char *fname_old,
  153. const char *fname_new)
  154. {
  155. if (file_status(fname_new) == FN_FILE || file_status(fname_old) != FN_FILE)
  156. /* The new filename is there, or both are, or neither is. */
  157. return init_key_from_file(fname_new);
  158. /* The old filename exists, and the new one doesn't. Rename and load. */
  159. if (rename(fname_old, fname_new) < 0) {
  160. log_fn(LOG_ERR, "Couldn't rename \"%s\" to \"%s\": %s", fname_old, fname_new,
  161. strerror(errno));
  162. return NULL;
  163. }
  164. return init_key_from_file(fname_new);
  165. }
  166. /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist,
  167. * create a new RSA key and save it in <b>fname</b>. Return the read/created
  168. * key, or NULL on error.
  169. */
  170. crypto_pk_env_t *
  171. init_key_from_file(const char *fname)
  172. {
  173. crypto_pk_env_t *prkey = NULL;
  174. FILE *file = NULL;
  175. if (!(prkey = crypto_new_pk_env())) {
  176. log(LOG_ERR, "Error creating crypto environment.");
  177. goto error;
  178. }
  179. switch (file_status(fname)) {
  180. case FN_DIR:
  181. case FN_ERROR:
  182. log(LOG_ERR, "Can't read key from \"%s\"", fname);
  183. goto error;
  184. case FN_NOENT:
  185. log(LOG_INFO, "No key found in \"%s\"; generating fresh key.", fname);
  186. if (crypto_pk_generate_key(prkey)) {
  187. log(LOG_ERR, "Error generating onion key");
  188. goto error;
  189. }
  190. if (crypto_pk_check_key(prkey) <= 0) {
  191. log(LOG_ERR, "Generated key seems invalid");
  192. goto error;
  193. }
  194. log(LOG_INFO, "Generated key seems valid");
  195. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  196. log(LOG_ERR, "Couldn't write generated key to \"%s\".", fname);
  197. goto error;
  198. }
  199. return prkey;
  200. case FN_FILE:
  201. if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
  202. log(LOG_ERR, "Error loading private key.");
  203. goto error;
  204. }
  205. return prkey;
  206. default:
  207. tor_assert(0);
  208. }
  209. error:
  210. if (prkey)
  211. crypto_free_pk_env(prkey);
  212. if (file)
  213. fclose(file);
  214. return NULL;
  215. }
  216. /** Initialize all OR private keys, and the TLS context, as necessary.
  217. * On OPs, this only initializes the tls context.
  218. */
  219. int
  220. init_keys(void)
  221. {
  222. /* XXX009 Two problems with how this is called:
  223. * 1. It should be idempotent for servers, so we can call init_keys
  224. * as much as we need to.
  225. */
  226. char keydir[512];
  227. char keydir2[512];
  228. char fingerprint[FINGERPRINT_LEN+1];
  229. char fingerprint_line[FINGERPRINT_LEN+MAX_NICKNAME_LEN+3];/*nickname fp\n\0 */
  230. char *cp;
  231. const char *tmp, *mydesc, *datadir;
  232. crypto_pk_env_t *prkey;
  233. char digest[20];
  234. or_options_t *options = get_options();
  235. if (!key_lock)
  236. key_lock = tor_mutex_new();
  237. /* OP's don't need persistent keys; just make up an identity and
  238. * initialize the TLS context. */
  239. if (!server_mode(options)) {
  240. if (!(prkey = crypto_new_pk_env()))
  241. return -1;
  242. if (crypto_pk_generate_key(prkey))
  243. return -1;
  244. set_identity_key(prkey);
  245. /* Create a TLS context; default the client nickname to "client". */
  246. if (tor_tls_context_new(get_identity_key(), 1,
  247. options->Nickname ? options->Nickname : "client",
  248. MAX_SSL_KEY_LIFETIME) < 0) {
  249. log_fn(LOG_ERR, "Error creating TLS context for OP.");
  250. return -1;
  251. }
  252. return 0;
  253. }
  254. /* Make sure DataDirectory exists, and is private. */
  255. datadir = options->DataDirectory;
  256. if (check_private_dir(datadir, CPD_CREATE)) {
  257. return -1;
  258. }
  259. /* Check the key directory. */
  260. tor_snprintf(keydir,sizeof(keydir),"%s/keys", datadir);
  261. if (check_private_dir(keydir, CPD_CREATE)) {
  262. return -1;
  263. }
  264. cp = keydir + strlen(keydir); /* End of string. */
  265. /* 1. Read identity key. Make it if none is found. */
  266. tor_snprintf(keydir,sizeof(keydir),"%s/keys/identity.key",datadir);
  267. tor_snprintf(keydir2,sizeof(keydir2),"%s/keys/secret_id_key",datadir);
  268. log_fn(LOG_INFO,"Reading/making identity key \"%s\"...",keydir2);
  269. prkey = init_key_from_file_name_changed(keydir,keydir2);
  270. if (!prkey) return -1;
  271. set_identity_key(prkey);
  272. /* 2. Read onion key. Make it if none is found. */
  273. tor_snprintf(keydir,sizeof(keydir),"%s/keys/onion.key",datadir);
  274. tor_snprintf(keydir2,sizeof(keydir2),"%s/keys/secret_onion_key",datadir);
  275. log_fn(LOG_INFO,"Reading/making onion key \"%s\"...",keydir2);
  276. prkey = init_key_from_file_name_changed(keydir,keydir2);
  277. if (!prkey) return -1;
  278. set_onion_key(prkey);
  279. tor_snprintf(keydir,sizeof(keydir),"%s/keys/secret_onion_key.old",datadir);
  280. if (file_status(keydir) == FN_FILE) {
  281. prkey = init_key_from_file(keydir);
  282. if (prkey)
  283. lastonionkey = prkey;
  284. }
  285. /* 3. Initialize link key and TLS context. */
  286. if (tor_tls_context_new(get_identity_key(), 1, options->Nickname,
  287. MAX_SSL_KEY_LIFETIME) < 0) {
  288. log_fn(LOG_ERR, "Error initializing TLS context");
  289. return -1;
  290. }
  291. /* 4. Dump router descriptor to 'router.desc' */
  292. /* Must be called after keys are initialized. */
  293. tmp = mydesc = router_get_my_descriptor();
  294. if (!mydesc) {
  295. log_fn(LOG_ERR, "Error initializing descriptor.");
  296. return -1;
  297. }
  298. if (authdir_mode(options)) {
  299. const char *m;
  300. /* We need to add our own fingerprint so it gets recognized. */
  301. if (dirserv_add_own_fingerprint(options->Nickname, get_identity_key())) {
  302. log_fn(LOG_ERR, "Error adding own fingerprint to approved set");
  303. return -1;
  304. }
  305. if (dirserv_add_descriptor(tmp, &m) < 0) {
  306. log(LOG_ERR, "Unable to add own descriptor to directory: %s",
  307. m?m:"<unknown error>");
  308. return -1;
  309. }
  310. }
  311. tor_snprintf(keydir,sizeof(keydir),"%s/router.desc", datadir);
  312. log_fn(LOG_INFO,"Dumping descriptor to \"%s\"...",keydir);
  313. if (write_str_to_file(keydir, mydesc,0)) {
  314. return -1;
  315. }
  316. /* 5. Dump fingerprint to 'fingerprint' */
  317. tor_snprintf(keydir,sizeof(keydir),"%s/fingerprint", datadir);
  318. log_fn(LOG_INFO,"Dumping fingerprint to \"%s\"...",keydir);
  319. if (crypto_pk_get_fingerprint(get_identity_key(), fingerprint, 1)<0) {
  320. log_fn(LOG_ERR, "Error computing fingerprint");
  321. return -1;
  322. }
  323. tor_assert(strlen(options->Nickname) <= MAX_NICKNAME_LEN);
  324. if (tor_snprintf(fingerprint_line, sizeof(fingerprint_line),
  325. "%s %s\n",options->Nickname, fingerprint) < 0) {
  326. log_fn(LOG_ERR, "Error writing fingerprint line");
  327. return -1;
  328. }
  329. if (write_str_to_file(keydir, fingerprint_line, 0))
  330. return -1;
  331. if (!authdir_mode(options))
  332. return 0;
  333. /* 6. [authdirserver only] load approved-routers file */
  334. tor_snprintf(keydir,sizeof(keydir),"%s/approved-routers", datadir);
  335. log_fn(LOG_INFO,"Loading approved fingerprints from \"%s\"...",keydir);
  336. if (dirserv_parse_fingerprint_file(keydir) < 0) {
  337. log_fn(LOG_ERR, "Error loading fingerprints");
  338. return -1;
  339. }
  340. /* 6b. [authdirserver only] add own key to approved directories. */
  341. crypto_pk_get_digest(get_identity_key(), digest);
  342. if (!router_digest_is_trusted_dir(digest)) {
  343. add_trusted_dir_server(NULL, (uint16_t)options->DirPort, digest);
  344. }
  345. #if 0
  346. /* 7. [authdirserver only] load old directory, if it's there */
  347. tor_snprintf(keydir,sizeof(keydir),"%s/cached-directory", datadir);
  348. log_fn(LOG_INFO,"Loading cached directory from \"%s\"...",keydir);
  349. cp = read_file_to_str(keydir,0);
  350. if (!cp) {
  351. log_fn(LOG_INFO,"Cached directory \"%s\" not present. Ok.",keydir);
  352. } else {
  353. if (dirserv_load_from_directory_string(cp) < 0) {
  354. log_fn(LOG_WARN, "Cached directory \"%s\" is corrupt, only loaded part of it.", keydir);
  355. tor_free(cp);
  356. return 0;
  357. }
  358. tor_free(cp);
  359. }
  360. #endif
  361. /* success */
  362. return 0;
  363. }
  364. /* Keep track of whether we should upload our server descriptor,
  365. * and what type of server we are.
  366. */
  367. /** Whether we can reach our ORPort from the outside. */
  368. static int can_reach_or_port = 0;
  369. /** Whether we can reach our DirPort from the outside. */
  370. static int can_reach_dir_port = 0;
  371. /** Return 1 if or port is known reachable; else return 0. */
  372. int
  373. check_whether_orport_reachable(void)
  374. {
  375. or_options_t *options = get_options();
  376. return clique_mode(options) ||
  377. options->AssumeReachable ||
  378. can_reach_or_port;
  379. }
  380. /** Return 1 if we don't have a dirport configured, or if it's reachable. */
  381. int
  382. check_whether_dirport_reachable(void)
  383. {
  384. or_options_t *options = get_options();
  385. return !options->DirPort ||
  386. options->AssumeReachable ||
  387. can_reach_dir_port;
  388. }
  389. /**DOCDOC*/
  390. void
  391. consider_testing_reachability(void)
  392. {
  393. routerinfo_t *me = router_get_my_routerinfo();
  394. if (!me) {
  395. log_fn(LOG_WARN,"Bug: router_get_my_routerinfo() did not find my routerinfo?");
  396. return;
  397. }
  398. if (!check_whether_orport_reachable()) {
  399. circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING, me, 0, 1, 1);
  400. }
  401. if (!check_whether_dirport_reachable()) {
  402. if (me) {
  403. directory_initiate_command_router(me, DIR_PURPOSE_FETCH_DIR, 1, NULL, NULL, 0);
  404. } else {
  405. log(LOG_NOTICE,"Delaying checking DirPort reachability; can't build descriptor.");
  406. }
  407. }
  408. }
  409. /** Annotate that we found our ORPort reachable. */
  410. void
  411. router_orport_found_reachable(void)
  412. {
  413. if (!can_reach_or_port) {
  414. if (!clique_mode(get_options()))
  415. log(LOG_NOTICE,"Your ORPort is reachable from the outside. Excellent.%s",
  416. get_options()->NoPublish ? "" : " Publishing server descriptor.");
  417. can_reach_or_port = 1;
  418. mark_my_descriptor_dirty();
  419. consider_publishable_server(time(NULL), 1);
  420. }
  421. }
  422. /** Annotate that we found our DirPort reachable. */
  423. void
  424. router_dirport_found_reachable(void)
  425. {
  426. if (!can_reach_dir_port) {
  427. log(LOG_NOTICE,"Your DirPort is reachable from the outside. Excellent.");
  428. can_reach_dir_port = 1;
  429. }
  430. }
  431. /** Our router has just moved to a new IP. Reset stats. */
  432. void
  433. server_has_changed_ip(void)
  434. {
  435. stats_n_seconds_working = 0;
  436. can_reach_or_port = 0;
  437. can_reach_dir_port = 0;
  438. mark_my_descriptor_dirty();
  439. }
  440. /** Return true iff we believe ourselves to be an authoritative
  441. * directory server.
  442. */
  443. int
  444. authdir_mode(or_options_t *options)
  445. {
  446. return options->AuthoritativeDir != 0;
  447. }
  448. /** Return true iff we try to stay connected to all ORs at once.
  449. */
  450. int
  451. clique_mode(or_options_t *options)
  452. {
  453. return authdir_mode(options);
  454. }
  455. /** Return true iff we are trying to be a server.
  456. */
  457. int
  458. server_mode(or_options_t *options)
  459. {
  460. if (options->ClientOnly) return 0;
  461. return (options->ORPort != 0 || options->ORBindAddress);
  462. }
  463. /** Remember if we've advertised ourselves to the dirservers. */
  464. static int server_is_advertised=0;
  465. /** Return true iff we have published our descriptor lately.
  466. */
  467. int
  468. advertised_server_mode(void)
  469. {
  470. return server_is_advertised;
  471. }
  472. /**
  473. * Called with a boolean: set whether we have recently published our descriptor.
  474. */
  475. static void
  476. set_server_advertised(int s)
  477. {
  478. server_is_advertised = s;
  479. }
  480. /** Return true iff we are trying to be a socks proxy. */
  481. int
  482. proxy_mode(or_options_t *options)
  483. {
  484. return (options->SocksPort != 0 || options->SocksBindAddress);
  485. }
  486. /** Decide if we're a publishable server. We are a publishable server if:
  487. * - We don't have the ClientOnly option set
  488. * and
  489. * - We don't have the NoPublish option set
  490. * and
  491. * - We have ORPort set
  492. * and
  493. * - We believe we are reachable from the outside; or
  494. * - We have the AuthoritativeDirectory option set.
  495. */
  496. static int
  497. decide_if_publishable_server(time_t now)
  498. {
  499. or_options_t *options = get_options();
  500. if (options->ClientOnly)
  501. return 0;
  502. if (options->NoPublish)
  503. return 0;
  504. if (!server_mode(options))
  505. return 0;
  506. if (options->AuthoritativeDir)
  507. return 1;
  508. return check_whether_orport_reachable();
  509. }
  510. /** Initiate server descriptor upload as reasonable (if server is publishable,
  511. * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
  512. */
  513. void
  514. consider_publishable_server(time_t now, int force)
  515. {
  516. if (decide_if_publishable_server(now)) {
  517. set_server_advertised(1);
  518. if (router_rebuild_descriptor(0) == 0)
  519. router_upload_dir_desc_to_dirservers(force);
  520. } else {
  521. set_server_advertised(0);
  522. }
  523. }
  524. /*
  525. * Clique maintenance
  526. */
  527. /** OR only: if in clique mode, try to open connections to all of the
  528. * other ORs we know about. Otherwise, open connections to those we
  529. * think are in clique mode.o
  530. *
  531. * If <b>force</b> is zero, only open the connection if we don't already
  532. * have one.
  533. */
  534. void
  535. router_retry_connections(int force)
  536. {
  537. int i;
  538. time_t now = time(NULL);
  539. routerinfo_t *router;
  540. routerlist_t *rl;
  541. or_options_t *options = get_options();
  542. tor_assert(server_mode(options));
  543. router_get_routerlist(&rl);
  544. if (!rl) return;
  545. for (i=0;i < smartlist_len(rl->routers);i++) {
  546. router = smartlist_get(rl->routers, i);
  547. if (router_is_me(router))
  548. continue;
  549. if (!clique_mode(options) && !router_is_clique_mode(router))
  550. continue;
  551. if (force ||
  552. !connection_get_by_identity_digest(router->identity_digest,
  553. CONN_TYPE_OR)) {
  554. log_fn(LOG_INFO,"%sconnecting to %s at %s:%u.",
  555. clique_mode(options) ? "(forced) " : "",
  556. router->nickname, router->address, router->or_port);
  557. /* Remember when we started trying to determine reachability */
  558. if (!router->testing_since)
  559. router->testing_since = now;
  560. connection_or_connect(router->addr, router->or_port, router->identity_digest);
  561. }
  562. }
  563. }
  564. /** Return true iff this OR should try to keep connections open to all
  565. * other ORs. */
  566. int
  567. router_is_clique_mode(routerinfo_t *router)
  568. {
  569. if (router_digest_is_trusted_dir(router->identity_digest))
  570. return 1;
  571. return 0;
  572. }
  573. /*
  574. * OR descriptor generation.
  575. */
  576. /** My routerinfo. */
  577. static routerinfo_t *desc_routerinfo = NULL;
  578. /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
  579. * now. */
  580. static time_t desc_clean_since = 0;
  581. /** Boolean: do we need to regenerate the above? */
  582. static int desc_needs_upload = 0;
  583. /** OR only: If <b>force</b> is true, or we haven't uploaded this
  584. * descriptor successfully yet, try to upload our signed descriptor to
  585. * all the directory servers we know about.
  586. */
  587. void
  588. router_upload_dir_desc_to_dirservers(int force)
  589. {
  590. const char *s;
  591. s = router_get_my_descriptor();
  592. if (!s) {
  593. log_fn(LOG_WARN, "No descriptor; skipping upload");
  594. return;
  595. }
  596. if (!force && !desc_needs_upload)
  597. return;
  598. desc_needs_upload = 0;
  599. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR, s, strlen(s));
  600. }
  601. /** OR only: Check whether my exit policy says to allow connection to
  602. * conn. Return 0 if we accept; non-0 if we reject.
  603. */
  604. int
  605. router_compare_to_my_exit_policy(connection_t *conn)
  606. {
  607. tor_assert(desc_routerinfo);
  608. /* make sure it's resolved to something. this way we can't get a
  609. 'maybe' below. */
  610. if (!conn->addr)
  611. return -1;
  612. return router_compare_addr_to_addr_policy(conn->addr, conn->port,
  613. desc_routerinfo->exit_policy) != ADDR_POLICY_ACCEPTED;
  614. }
  615. /** Return true iff I'm a server and <b>digest</b> is equal to
  616. * my identity digest. */
  617. int
  618. router_digest_is_me(const char *digest)
  619. {
  620. routerinfo_t *me = router_get_my_routerinfo();
  621. if (!me || memcmp(me->identity_digest, digest, DIGEST_LEN))
  622. return 0;
  623. return 1;
  624. }
  625. /** A wrapper around router_digest_is_me(). */
  626. int
  627. router_is_me(routerinfo_t *router)
  628. {
  629. return router_digest_is_me(router->identity_digest);
  630. }
  631. /** Return a routerinfo for this OR, rebuilding a fresh one if
  632. * necessary. Return NULL on error, or if called on an OP. */
  633. routerinfo_t *
  634. router_get_my_routerinfo(void)
  635. {
  636. if (!server_mode(get_options()))
  637. return NULL;
  638. if (!desc_routerinfo) {
  639. if (router_rebuild_descriptor(1))
  640. return NULL;
  641. }
  642. return desc_routerinfo;
  643. }
  644. /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
  645. * one if necessary. Return NULL on error.
  646. */
  647. const char *
  648. router_get_my_descriptor(void)
  649. {
  650. if (!desc_routerinfo) {
  651. if (router_rebuild_descriptor(1))
  652. return NULL;
  653. }
  654. log_fn(LOG_DEBUG,"my desc is '%s'",desc_routerinfo->signed_descriptor);
  655. return desc_routerinfo->signed_descriptor;
  656. }
  657. /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild
  658. * a fresh routerinfo and signed server descriptor for this OR.
  659. * Return 0 on success, -1 on error.
  660. */
  661. int
  662. router_rebuild_descriptor(int force)
  663. {
  664. routerinfo_t *ri;
  665. uint32_t addr;
  666. char platform[256];
  667. int hibernating = we_are_hibernating();
  668. or_options_t *options = get_options();
  669. if (desc_clean_since && !force)
  670. return 0;
  671. if (resolve_my_address(options, &addr, NULL) < 0) {
  672. log_fn(LOG_WARN,"options->Address didn't resolve into an IP.");
  673. return -1;
  674. }
  675. ri = tor_malloc_zero(sizeof(routerinfo_t));
  676. ri->address = tor_dup_addr(addr);
  677. ri->nickname = tor_strdup(options->Nickname);
  678. ri->addr = addr;
  679. ri->or_port = options->ORPort;
  680. ri->dir_port = hibernating ?
  681. 0 : options->DirPort;
  682. ri->published_on = time(NULL);
  683. ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from main thread */
  684. ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
  685. if (crypto_pk_get_digest(ri->identity_pkey, ri->identity_digest)<0) {
  686. routerinfo_free(ri);
  687. return -1;
  688. }
  689. get_platform_str(platform, sizeof(platform));
  690. ri->platform = tor_strdup(platform);
  691. ri->bandwidthrate = (int)options->BandwidthRate;
  692. ri->bandwidthburst = (int)options->BandwidthBurst;
  693. ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
  694. if (options->BandwidthRate > options->MaxAdvertisedBandwidth)
  695. ri->bandwidthrate = (int)options->MaxAdvertisedBandwidth;
  696. config_parse_addr_policy(get_options()->ExitPolicy, &ri->exit_policy, -1);
  697. options_append_default_exit_policy(&ri->exit_policy);
  698. if (desc_routerinfo) /* inherit values */
  699. ri->is_verified = desc_routerinfo->is_verified;
  700. if (options->MyFamily) {
  701. ri->declared_family = smartlist_create();
  702. smartlist_split_string(ri->declared_family, options->MyFamily, ",",
  703. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  704. }
  705. ri->signed_descriptor = tor_malloc(8192);
  706. if (router_dump_router_to_string(ri->signed_descriptor, 8192,
  707. ri, get_identity_key())<0) {
  708. log_fn(LOG_WARN, "Couldn't dump router to string.");
  709. return -1;
  710. }
  711. ri->signed_descriptor_len = strlen(ri->signed_descriptor);
  712. crypto_digest(ri->signed_descriptor_digest,
  713. ri->signed_descriptor, ri->signed_descriptor_len);
  714. if (desc_routerinfo)
  715. routerinfo_free(desc_routerinfo);
  716. desc_routerinfo = ri;
  717. desc_clean_since = time(NULL);
  718. desc_needs_upload = 1;
  719. return 0;
  720. }
  721. /** Mark descriptor out of date if it's older than <b>when</b> */
  722. void
  723. mark_my_descriptor_dirty_if_older_than(time_t when)
  724. {
  725. if (desc_clean_since < when)
  726. mark_my_descriptor_dirty();
  727. }
  728. /** Call when the current descriptor is out of date. */
  729. void
  730. mark_my_descriptor_dirty(void)
  731. {
  732. desc_clean_since = 0;
  733. }
  734. #define MAX_BANDWIDTH_CHANGE_FREQ 20*60
  735. /** Check whether bandwidth has changed a lot since the last time we announced
  736. * bandwidth. If so, mark our descriptor dirty.*/
  737. void
  738. check_descriptor_bandwidth_changed(time_t now)
  739. {
  740. static time_t last_changed = 0;
  741. uint64_t prev, cur;
  742. if (!desc_routerinfo)
  743. return;
  744. prev = desc_routerinfo->bandwidthcapacity;
  745. cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
  746. if ((prev != cur && (!prev || !cur)) ||
  747. cur > prev*2 ||
  748. cur < prev/2) {
  749. if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now) {
  750. log_fn(LOG_INFO,"Measured bandwidth has changed; rebuilding descriptor.");
  751. mark_my_descriptor_dirty();
  752. last_changed = now;
  753. }
  754. }
  755. }
  756. /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
  757. * string describing the version of Tor and the operating system we're
  758. * currently running on.
  759. */
  760. void
  761. get_platform_str(char *platform, size_t len)
  762. {
  763. tor_snprintf(platform, len, "Tor %s on %s",
  764. VERSION, get_uname());
  765. return;
  766. }
  767. /* XXX need to audit this thing and count fenceposts. maybe
  768. * refactor so we don't have to keep asking if we're
  769. * near the end of maxlen?
  770. */
  771. #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  772. /** OR only: Given a routerinfo for this router, and an identity key to sign
  773. * with, encode the routerinfo as a signed server descriptor and write the
  774. * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
  775. * failure, and the number of bytes used on success.
  776. */
  777. int
  778. router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
  779. crypto_pk_env_t *ident_key)
  780. {
  781. char *onion_pkey; /* Onion key, PEM-encoded. */
  782. char *identity_pkey; /* Identity key, PEM-encoded. */
  783. char digest[DIGEST_LEN];
  784. char published[ISO_TIME_LEN+1];
  785. char fingerprint[FINGERPRINT_LEN+1];
  786. struct in_addr in;
  787. char addrbuf[INET_NTOA_BUF_LEN];
  788. size_t onion_pkeylen, identity_pkeylen;
  789. size_t written;
  790. int result=0;
  791. addr_policy_t *tmpe;
  792. char *bandwidth_usage;
  793. char *family_line;
  794. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  795. char *s_tmp, *s_dup;
  796. const char *cp;
  797. routerinfo_t *ri_tmp;
  798. #endif
  799. or_options_t *options = get_options();
  800. /* Make sure the identity key matches the one in the routerinfo. */
  801. if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
  802. log_fn(LOG_WARN,"Tried to sign a router with a private key that didn't match router's public key!");
  803. return -1;
  804. }
  805. /* record our fingerprint, so we can include it in the descriptor */
  806. if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
  807. log_fn(LOG_ERR, "Error computing fingerprint");
  808. return -1;
  809. }
  810. /* PEM-encode the onion key */
  811. if (crypto_pk_write_public_key_to_string(router->onion_pkey,
  812. &onion_pkey,&onion_pkeylen)<0) {
  813. log_fn(LOG_WARN,"write onion_pkey to string failed!");
  814. return -1;
  815. }
  816. /* PEM-encode the identity key key */
  817. if (crypto_pk_write_public_key_to_string(router->identity_pkey,
  818. &identity_pkey,&identity_pkeylen)<0) {
  819. log_fn(LOG_WARN,"write identity_pkey to string failed!");
  820. tor_free(onion_pkey);
  821. return -1;
  822. }
  823. /* Encode the publication time. */
  824. format_iso_time(published, router->published_on);
  825. /* How busy have we been? */
  826. bandwidth_usage = rep_hist_get_bandwidth_lines();
  827. if (router->declared_family && smartlist_len(router->declared_family)) {
  828. size_t n;
  829. char *s = smartlist_join_strings(router->declared_family, " ", 0, &n);
  830. n += strlen("family ") + 2; /* 1 for \n, 1 for \0. */
  831. family_line = tor_malloc(n);
  832. tor_snprintf(family_line, n, "family %s\n", s);
  833. tor_free(s);
  834. } else {
  835. family_line = tor_strdup("");
  836. }
  837. /* Generate the easy portion of the router descriptor. */
  838. result = tor_snprintf(s, maxlen,
  839. "router %s %s %d 0 %d\n"
  840. "platform %s\n"
  841. "published %s\n"
  842. "opt fingerprint %s\n"
  843. "uptime %ld\n"
  844. "bandwidth %d %d %d\n"
  845. "onion-key\n%s"
  846. "signing-key\n%s%s%s%s",
  847. router->nickname,
  848. router->address,
  849. router->or_port,
  850. (authdir_mode(options) || check_whether_dirport_reachable()) ?
  851. router->dir_port : 0,
  852. router->platform,
  853. published,
  854. fingerprint,
  855. stats_n_seconds_working,
  856. (int) router->bandwidthrate,
  857. (int) router->bandwidthburst,
  858. (int) router->bandwidthcapacity,
  859. onion_pkey, identity_pkey,
  860. family_line, bandwidth_usage,
  861. we_are_hibernating() ? "opt hibernating 1\n" : "");
  862. tor_free(family_line);
  863. tor_free(onion_pkey);
  864. tor_free(identity_pkey);
  865. tor_free(bandwidth_usage);
  866. if (result < 0)
  867. return -1;
  868. /* From now on, we use 'written' to remember the current length of 's'. */
  869. written = result;
  870. if (options->ContactInfo && strlen(options->ContactInfo)) {
  871. result = tor_snprintf(s+written,maxlen-written, "contact %s\n",
  872. options->ContactInfo);
  873. if (result<0)
  874. return -1;
  875. written += result;
  876. }
  877. /* Write the exit policy to the end of 's'. */
  878. for (tmpe=router->exit_policy; tmpe; tmpe=tmpe->next) {
  879. /* Write: "accept 1.2.3.4" */
  880. in.s_addr = htonl(tmpe->addr);
  881. tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
  882. result = tor_snprintf(s+written, maxlen-written, "%s %s",
  883. tmpe->policy_type == ADDR_POLICY_ACCEPT ? "accept" : "reject",
  884. tmpe->msk == 0 ? "*" : addrbuf);
  885. if (result < 0)
  886. return -1;
  887. written += result;
  888. if (tmpe->msk != 0xFFFFFFFFu && tmpe->msk != 0) {
  889. /* Write "/255.255.0.0" */
  890. in.s_addr = htonl(tmpe->msk);
  891. tor_inet_ntoa(&in, addrbuf, sizeof(addrbuf));
  892. result = tor_snprintf(s+written, maxlen-written, "/%s", addrbuf);
  893. if (result<0)
  894. return -1;
  895. written += result;
  896. }
  897. if (tmpe->prt_min <= 1 && tmpe->prt_max == 65535) {
  898. /* There is no port set; write ":*" */
  899. if (written+4 > maxlen)
  900. return -1;
  901. strlcat(s+written, ":*\n", maxlen-written);
  902. written += 3;
  903. } else if (tmpe->prt_min == tmpe->prt_max) {
  904. /* There is only one port; write ":80". */
  905. result = tor_snprintf(s+written, maxlen-written, ":%d\n", tmpe->prt_min);
  906. if (result<0)
  907. return -1;
  908. written += result;
  909. } else {
  910. /* There is a range of ports; write ":79-80". */
  911. result = tor_snprintf(s+written, maxlen-written, ":%d-%d\n", tmpe->prt_min,
  912. tmpe->prt_max);
  913. if (result<0)
  914. return -1;
  915. written += result;
  916. }
  917. if (tmpe->msk == 0 && tmpe->prt_min <= 1 && tmpe->prt_max == 65535)
  918. /* This was a catch-all rule, so future rules are irrelevant. */
  919. break;
  920. } /* end for */
  921. if (written+256 > maxlen) /* Not enough room for signature. */
  922. return -1;
  923. /* Sign the directory */
  924. strlcat(s+written, "router-signature\n", maxlen-written);
  925. written += strlen(s+written);
  926. s[written] = '\0';
  927. if (router_get_router_hash(s, digest) < 0)
  928. return -1;
  929. if (router_append_dirobj_signature(s+written,maxlen-written,
  930. digest,ident_key)<0) {
  931. log_fn(LOG_WARN, "Couldn't sign router descriptor");
  932. return -1;
  933. }
  934. written += strlen(s+written);
  935. if (written+2 > maxlen)
  936. return -1;
  937. /* include a last '\n' */
  938. s[written] = '\n';
  939. s[written+1] = 0;
  940. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  941. cp = s_tmp = s_dup = tor_strdup(s);
  942. ri_tmp = router_parse_entry_from_string(cp, NULL);
  943. if (!ri_tmp) {
  944. log_fn(LOG_ERR, "We just generated a router descriptor we can't parse: <<%s>>",
  945. s);
  946. return -1;
  947. }
  948. tor_free(s_dup);
  949. routerinfo_free(ri_tmp);
  950. #endif
  951. return written+1;
  952. }
  953. /** Return true iff <b>s</b> is a legally valid server nickname. */
  954. int
  955. is_legal_nickname(const char *s)
  956. {
  957. size_t len;
  958. tor_assert(s);
  959. len = strlen(s);
  960. return len > 0 && len <= MAX_NICKNAME_LEN &&
  961. strspn(s,LEGAL_NICKNAME_CHARACTERS)==len;
  962. }
  963. /** Return true iff <b>s</b> is a legally valid server nickname or
  964. * hex-encoded identity-key digest. */
  965. int
  966. is_legal_nickname_or_hexdigest(const char *s)
  967. {
  968. size_t len;
  969. tor_assert(s);
  970. if (*s!='$')
  971. return is_legal_nickname(s);
  972. len = strlen(s);
  973. return len == HEX_DIGEST_LEN+1 && strspn(s+1,HEX_CHARACTERS)==len-1;
  974. }
  975. /** Release all resources held in router keys. */
  976. void
  977. router_free_all_keys(void)
  978. {
  979. if (onionkey)
  980. crypto_free_pk_env(onionkey);
  981. if (lastonionkey)
  982. crypto_free_pk_env(lastonionkey);
  983. if (identitykey)
  984. crypto_free_pk_env(identitykey);
  985. if (key_lock)
  986. tor_mutex_free(key_lock);
  987. if (desc_routerinfo)
  988. routerinfo_free(desc_routerinfo);
  989. }