router.c 36 KB

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