router.c 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600
  1. /* Copyright (c) 2001 Matej Pfajfar.
  2. * Copyright (c) 2001-2004, Roger Dingledine.
  3. * Copyright (c) 2004-2007, Roger Dingledine, Nick Mathewson. */
  4. /* See LICENSE for licensing information */
  5. /* $Id$ */
  6. const char router_c_id[] =
  7. "$Id$";
  8. #define ROUTER_PRIVATE
  9. #include "or.h"
  10. /**
  11. * \file router.c
  12. * \brief OR functionality, including key maintenance, generating
  13. * and uploading server descriptors, retrying OR connections.
  14. **/
  15. extern long stats_n_seconds_working;
  16. /************************************************************/
  17. /*****
  18. * Key management: ORs only.
  19. *****/
  20. /** Private keys for this OR. There is also an SSL key managed by tortls.c.
  21. */
  22. static tor_mutex_t *key_lock=NULL;
  23. static time_t onionkey_set_at=0; /**< When was onionkey last changed? */
  24. /** Current private onionskin decryption key: used to decode CREATE cells. */
  25. static crypto_pk_env_t *onionkey=NULL;
  26. /** Previous private onionskin decription key: used to decode CREATE cells
  27. * generated by clients that have an older version of our descriptor. */
  28. static crypto_pk_env_t *lastonionkey=NULL;
  29. /** Private "identity key": used to sign directory info and TLS
  30. * certificates. Never changes. */
  31. static crypto_pk_env_t *identitykey=NULL;
  32. /** Digest of identitykey. */
  33. static char identitykey_digest[DIGEST_LEN];
  34. /** Replace the current onion key with <b>k</b>. Does not affect lastonionkey;
  35. * to update onionkey correctly, call rotate_onion_key().
  36. */
  37. static void
  38. set_onion_key(crypto_pk_env_t *k)
  39. {
  40. tor_mutex_acquire(key_lock);
  41. onionkey = k;
  42. onionkey_set_at = time(NULL);
  43. tor_mutex_release(key_lock);
  44. mark_my_descriptor_dirty();
  45. }
  46. /** Return the current onion key. Requires that the onion key has been
  47. * loaded or generated. */
  48. crypto_pk_env_t *
  49. get_onion_key(void)
  50. {
  51. tor_assert(onionkey);
  52. return onionkey;
  53. }
  54. /** Store a copy of the current onion key into *<b>key</b>, and a copy
  55. * of the most recent onion key into *<b>last</b>.
  56. */
  57. void
  58. dup_onion_keys(crypto_pk_env_t **key, crypto_pk_env_t **last)
  59. {
  60. tor_assert(key);
  61. tor_assert(last);
  62. tor_mutex_acquire(key_lock);
  63. tor_assert(onionkey);
  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. crypto_pk_get_digest(identitykey, identitykey_digest);
  89. }
  90. /** Returns the current identity key; requires that the identity key has been
  91. * set.
  92. */
  93. crypto_pk_env_t *
  94. get_identity_key(void)
  95. {
  96. tor_assert(identitykey);
  97. return identitykey;
  98. }
  99. /** Return true iff the identity key has been set. */
  100. int
  101. identity_key_is_set(void)
  102. {
  103. return identitykey != NULL;
  104. }
  105. /** Replace the previous onion key with the current onion key, and generate
  106. * a new previous onion key. Immediately after calling this function,
  107. * the OR should:
  108. * - schedule all previous cpuworkers to shut down _after_ processing
  109. * pending work. (This will cause fresh cpuworkers to be generated.)
  110. * - generate and upload a fresh routerinfo.
  111. */
  112. void
  113. rotate_onion_key(void)
  114. {
  115. char fname[512];
  116. char fname_prev[512];
  117. crypto_pk_env_t *prkey;
  118. or_state_t *state = get_or_state();
  119. time_t now;
  120. tor_snprintf(fname,sizeof(fname),
  121. "%s"PATH_SEPARATOR"keys"PATH_SEPARATOR"secret_onion_key",
  122. get_options()->DataDirectory);
  123. tor_snprintf(fname_prev,sizeof(fname_prev),
  124. "%s"PATH_SEPARATOR"keys"PATH_SEPARATOR"secret_onion_key.old",
  125. get_options()->DataDirectory);
  126. if (!(prkey = crypto_new_pk_env())) {
  127. log_err(LD_GENERAL,"Error constructing rotated onion key");
  128. goto error;
  129. }
  130. if (crypto_pk_generate_key(prkey)) {
  131. log_err(LD_BUG,"Error generating onion key");
  132. goto error;
  133. }
  134. if (file_status(fname) == FN_FILE) {
  135. if (replace_file(fname, fname_prev))
  136. goto error;
  137. }
  138. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  139. log_err(LD_FS,"Couldn't write generated onion key to \"%s\".", fname);
  140. goto error;
  141. }
  142. log_info(LD_GENERAL, "Rotating onion key");
  143. tor_mutex_acquire(key_lock);
  144. if (lastonionkey)
  145. crypto_free_pk_env(lastonionkey);
  146. lastonionkey = onionkey;
  147. onionkey = prkey;
  148. now = time(NULL);
  149. state->LastRotatedOnionKey = onionkey_set_at = now;
  150. tor_mutex_release(key_lock);
  151. mark_my_descriptor_dirty();
  152. or_state_mark_dirty(state, get_options()->AvoidDiskWrites ? now+3600 : 0);
  153. return;
  154. error:
  155. log_warn(LD_GENERAL, "Couldn't rotate onion key.");
  156. }
  157. /** Try to read an RSA key from <b>fname</b>. If <b>fname</b> doesn't exist,
  158. * create a new RSA key and save it in <b>fname</b>. Return the read/created
  159. * key, or NULL on error.
  160. */
  161. crypto_pk_env_t *
  162. init_key_from_file(const char *fname)
  163. {
  164. crypto_pk_env_t *prkey = NULL;
  165. FILE *file = NULL;
  166. if (!(prkey = crypto_new_pk_env())) {
  167. log_err(LD_GENERAL,"Error constructing key");
  168. goto error;
  169. }
  170. switch (file_status(fname)) {
  171. case FN_DIR:
  172. case FN_ERROR:
  173. log_err(LD_FS,"Can't read key from \"%s\"", fname);
  174. goto error;
  175. case FN_NOENT:
  176. log_info(LD_GENERAL, "No key found in \"%s\"; generating fresh key.",
  177. fname);
  178. if (crypto_pk_generate_key(prkey)) {
  179. log_err(LD_GENERAL,"Error generating onion key");
  180. goto error;
  181. }
  182. if (crypto_pk_check_key(prkey) <= 0) {
  183. log_err(LD_GENERAL,"Generated key seems invalid");
  184. goto error;
  185. }
  186. log_info(LD_GENERAL, "Generated key seems valid");
  187. if (crypto_pk_write_private_key_to_filename(prkey, fname)) {
  188. log_err(LD_FS,"Couldn't write generated key to \"%s\".", fname);
  189. goto error;
  190. }
  191. return prkey;
  192. case FN_FILE:
  193. if (crypto_pk_read_private_key_from_filename(prkey, fname)) {
  194. log_err(LD_GENERAL,"Error loading private key.");
  195. goto error;
  196. }
  197. return prkey;
  198. default:
  199. tor_assert(0);
  200. }
  201. error:
  202. if (prkey)
  203. crypto_free_pk_env(prkey);
  204. if (file)
  205. fclose(file);
  206. return NULL;
  207. }
  208. /** Initialize all OR private keys, and the TLS context, as necessary.
  209. * On OPs, this only initializes the tls context. Return 0 on success,
  210. * or -1 if Tor should die.
  211. */
  212. int
  213. init_keys(void)
  214. {
  215. char keydir[512];
  216. char fingerprint[FINGERPRINT_LEN+1];
  217. /*nickname<space>fp\n\0 */
  218. char fingerprint_line[MAX_NICKNAME_LEN+FINGERPRINT_LEN+3];
  219. const char *mydesc, *datadir;
  220. crypto_pk_env_t *prkey;
  221. char digest[20];
  222. char *cp;
  223. or_options_t *options = get_options();
  224. or_state_t *state = get_or_state();
  225. if (!key_lock)
  226. key_lock = tor_mutex_new();
  227. /* OP's don't need persistent keys; just make up an identity and
  228. * initialize the TLS context. */
  229. if (!server_mode(options)) {
  230. if (!(prkey = crypto_new_pk_env()))
  231. return -1;
  232. if (crypto_pk_generate_key(prkey))
  233. return -1;
  234. set_identity_key(prkey);
  235. /* Create a TLS context; default the client nickname to "client". */
  236. if (tor_tls_context_new(get_identity_key(),
  237. options->Nickname ? options->Nickname : "client",
  238. MAX_SSL_KEY_LIFETIME) < 0) {
  239. log_err(LD_GENERAL,"Error creating TLS context for Tor client.");
  240. return -1;
  241. }
  242. return 0;
  243. }
  244. /* Make sure DataDirectory exists, and is private. */
  245. datadir = options->DataDirectory;
  246. if (check_private_dir(datadir, CPD_CREATE)) {
  247. return -1;
  248. }
  249. /* Check the key directory. */
  250. tor_snprintf(keydir,sizeof(keydir),"%s"PATH_SEPARATOR"keys", datadir);
  251. if (check_private_dir(keydir, CPD_CREATE)) {
  252. return -1;
  253. }
  254. /* 1. Read identity key. Make it if none is found. */
  255. tor_snprintf(keydir,sizeof(keydir),
  256. "%s"PATH_SEPARATOR"keys"PATH_SEPARATOR"secret_id_key",datadir);
  257. log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir);
  258. prkey = init_key_from_file(keydir);
  259. if (!prkey) return -1;
  260. set_identity_key(prkey);
  261. /* 2. Read onion key. Make it if none is found. */
  262. tor_snprintf(keydir,sizeof(keydir),
  263. "%s"PATH_SEPARATOR"keys"PATH_SEPARATOR"secret_onion_key",datadir);
  264. log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir);
  265. prkey = init_key_from_file(keydir);
  266. if (!prkey) return -1;
  267. set_onion_key(prkey);
  268. if (state->LastRotatedOnionKey > 100) { /* allow for some parsing slop. */
  269. onionkey_set_at = state->LastRotatedOnionKey;
  270. } else {
  271. /* We have no LastRotatedOnionKey set; either we just created the key
  272. * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
  273. * start the clock ticking now so that we will eventually rotate it even
  274. * if we don't stay up for a full MIN_ONION_KEY_LIFETIME. */
  275. state->LastRotatedOnionKey = onionkey_set_at = time(NULL);
  276. or_state_mark_dirty(state, options->AvoidDiskWrites ? time(NULL)+3600 : 0);
  277. }
  278. tor_snprintf(keydir,sizeof(keydir),
  279. "%s"PATH_SEPARATOR"keys"PATH_SEPARATOR"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(), options->Nickname,
  287. MAX_SSL_KEY_LIFETIME) < 0) {
  288. log_err(LD_GENERAL,"Error initializing TLS context");
  289. return -1;
  290. }
  291. /* 4. Build our router descriptor. */
  292. /* Must be called after keys are initialized. */
  293. mydesc = router_get_my_descriptor();
  294. if (authdir_mode(options)) {
  295. const char *m;
  296. /* We need to add our own fingerprint so it gets recognized. */
  297. if (dirserv_add_own_fingerprint(options->Nickname, get_identity_key())) {
  298. log_err(LD_GENERAL,"Error adding own fingerprint to approved set");
  299. return -1;
  300. }
  301. if (!mydesc) {
  302. log_err(LD_GENERAL,"Error initializing descriptor.");
  303. return -1;
  304. }
  305. if (dirserv_add_descriptor(mydesc, NULL, &m) < 0) {
  306. log_err(LD_GENERAL,"Unable to add own descriptor to directory: %s",
  307. m?m:"<unknown error>");
  308. return -1;
  309. }
  310. }
  311. /* 5. Dump fingerprint to 'fingerprint' */
  312. tor_snprintf(keydir,sizeof(keydir),"%s"PATH_SEPARATOR"fingerprint", datadir);
  313. log_info(LD_GENERAL,"Dumping fingerprint to \"%s\"...",keydir);
  314. if (crypto_pk_get_fingerprint(get_identity_key(), fingerprint, 1)<0) {
  315. log_err(LD_GENERAL,"Error computing fingerprint");
  316. return -1;
  317. }
  318. tor_assert(strlen(options->Nickname) <= MAX_NICKNAME_LEN);
  319. if (tor_snprintf(fingerprint_line, sizeof(fingerprint_line),
  320. "%s %s\n",options->Nickname, fingerprint) < 0) {
  321. log_err(LD_GENERAL,"Error writing fingerprint line");
  322. return -1;
  323. }
  324. /* Check whether we need to write the fingerprint file. */
  325. cp = NULL;
  326. if (file_status(keydir) == FN_FILE)
  327. cp = read_file_to_str(keydir, 0, NULL);
  328. if (!cp || strcmp(cp, fingerprint_line)) {
  329. if (write_str_to_file(keydir, fingerprint_line, 0)) {
  330. log_err(LD_FS, "Error writing fingerprint line to file");
  331. return -1;
  332. }
  333. }
  334. tor_free(cp);
  335. log(LOG_NOTICE, LD_GENERAL,
  336. "Your Tor server's identity key fingerprint is '%s %s'",
  337. options->Nickname, fingerprint);
  338. if (!authdir_mode(options))
  339. return 0;
  340. /* 6. [authdirserver only] load approved-routers file */
  341. if (dirserv_load_fingerprint_file() < 0) {
  342. log_err(LD_GENERAL,"Error loading fingerprints");
  343. return -1;
  344. }
  345. /* 6b. [authdirserver only] add own key to approved directories. */
  346. crypto_pk_get_digest(get_identity_key(), digest);
  347. if (!router_digest_is_trusted_dir(digest)) {
  348. add_trusted_dir_server(options->Nickname, NULL,
  349. (uint16_t)options->DirPort,
  350. (uint16_t)options->ORPort,
  351. digest,
  352. options->V1AuthoritativeDir, /* v1 authority */
  353. options->V2AuthoritativeDir, /* v2 authority */
  354. options->BridgeAuthoritativeDir, /* bridge auth */
  355. options->HSAuthoritativeDir /*hidserv authority*/);
  356. }
  357. return 0; /* success */
  358. }
  359. /* Keep track of whether we should upload our server descriptor,
  360. * and what type of server we are.
  361. */
  362. /** Whether we can reach our ORPort from the outside. */
  363. static int can_reach_or_port = 0;
  364. /** Whether we can reach our DirPort from the outside. */
  365. static int can_reach_dir_port = 0;
  366. /** Forget what we have learned about our reachability status. */
  367. void
  368. router_reset_reachability(void)
  369. {
  370. can_reach_or_port = can_reach_dir_port = 0;
  371. }
  372. /** Return 1 if ORPort is known reachable; else return 0. */
  373. int
  374. check_whether_orport_reachable(void)
  375. {
  376. or_options_t *options = get_options();
  377. return 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. we_are_hibernating() ||
  388. can_reach_dir_port;
  389. }
  390. /** Look at a variety of factors, and return 0 if we don't want to
  391. * advertise the fact that we have a DirPort open. Else return the
  392. * DirPort we want to advertise.
  393. *
  394. * Log a helpful message if we change our mind about whether to publish
  395. * a DirPort.
  396. */
  397. static int
  398. decide_to_advertise_dirport(or_options_t *options, routerinfo_t *router)
  399. {
  400. static int advertising=1; /* start out assuming we will advertise */
  401. int new_choice=1;
  402. const char *reason = NULL;
  403. /* Section one: reasons to publish or not publish that aren't
  404. * worth mentioning to the user, either because they're obvious
  405. * or because they're normal behavior. */
  406. if (!router->dir_port) /* short circuit the rest of the function */
  407. return 0;
  408. if (authdir_mode(options)) /* always publish */
  409. return router->dir_port;
  410. if (we_are_hibernating())
  411. return 0;
  412. if (!check_whether_dirport_reachable())
  413. return 0;
  414. /* Section two: reasons to publish or not publish that the user
  415. * might find surprising. These are generally config options that
  416. * make us choose not to publish. */
  417. if (accounting_is_enabled(options)) {
  418. /* if we might potentially hibernate */
  419. new_choice = 0;
  420. reason = "AccountingMax enabled";
  421. } else if (router->bandwidthrate < 51200) {
  422. /* if we're advertising a small amount */
  423. new_choice = 0;
  424. reason = "BandwidthRate under 50KB";
  425. }
  426. if (advertising != new_choice) {
  427. if (new_choice == 1) {
  428. log(LOG_NOTICE, LD_DIR, "Advertising DirPort as %d", router->dir_port);
  429. } else {
  430. tor_assert(reason);
  431. log(LOG_NOTICE, LD_DIR, "Not advertising DirPort (Reason: %s)", reason);
  432. }
  433. advertising = new_choice;
  434. }
  435. return advertising ? router->dir_port : 0;
  436. }
  437. /** Some time has passed, or we just got new directory information.
  438. * See if we currently believe our ORPort or DirPort to be
  439. * unreachable. If so, launch a new test for it.
  440. *
  441. * For ORPort, we simply try making a circuit that ends at ourselves.
  442. * Success is noticed in onionskin_answer().
  443. *
  444. * For DirPort, we make a connection via Tor to our DirPort and ask
  445. * for our own server descriptor.
  446. * Success is noticed in connection_dir_client_reached_eof().
  447. */
  448. void
  449. consider_testing_reachability(int test_or, int test_dir)
  450. {
  451. routerinfo_t *me = router_get_my_routerinfo();
  452. int orport_reachable = check_whether_orport_reachable();
  453. if (!me)
  454. return;
  455. if (test_or && (!orport_reachable || !circuit_enough_testing_circs())) {
  456. log_info(LD_CIRC, "Testing %s of my ORPort: %s:%d.",
  457. !orport_reachable ? "reachability" : "bandwidth",
  458. me->address, me->or_port);
  459. circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING, 0, me, 0, 1, 1);
  460. control_event_server_status(LOG_NOTICE,
  461. "CHECKING_REACHABILITY ORADDRESS=%s:%d",
  462. me->address, me->or_port);
  463. }
  464. if (test_dir && !check_whether_dirport_reachable() &&
  465. !connection_get_by_type_addr_port_purpose(
  466. CONN_TYPE_DIR, me->addr, me->dir_port,
  467. DIR_PURPOSE_FETCH_SERVERDESC)) {
  468. /* ask myself, via tor, for my server descriptor. */
  469. directory_initiate_command(me->address, me->addr,
  470. me->or_port, me->dir_port,
  471. 0, me->cache_info.identity_digest,
  472. DIR_PURPOSE_FETCH_SERVERDESC,
  473. 1, "authority", NULL, 0);
  474. control_event_server_status(LOG_NOTICE,
  475. "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
  476. me->address, me->dir_port);
  477. }
  478. }
  479. /** Annotate that we found our ORPort reachable. */
  480. void
  481. router_orport_found_reachable(void)
  482. {
  483. if (!can_reach_or_port) {
  484. routerinfo_t *me = router_get_my_routerinfo();
  485. log_notice(LD_OR,"Self-testing indicates your ORPort is reachable from "
  486. "the outside. Excellent.%s",
  487. get_options()->_PublishServerDescriptor != NO_AUTHORITY ?
  488. " Publishing server descriptor." : "");
  489. can_reach_or_port = 1;
  490. mark_my_descriptor_dirty();
  491. if (!me)
  492. return;
  493. control_event_server_status(LOG_NOTICE,
  494. "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
  495. me->address, me->dir_port);
  496. }
  497. }
  498. /** Annotate that we found our DirPort reachable. */
  499. void
  500. router_dirport_found_reachable(void)
  501. {
  502. if (!can_reach_dir_port) {
  503. routerinfo_t *me = router_get_my_routerinfo();
  504. log_notice(LD_DIRSERV,"Self-testing indicates your DirPort is reachable "
  505. "from the outside. Excellent.");
  506. can_reach_dir_port = 1;
  507. mark_my_descriptor_dirty();
  508. if (!me)
  509. return;
  510. control_event_server_status(LOG_NOTICE,
  511. "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
  512. me->address, me->dir_port);
  513. }
  514. }
  515. /** We have enough testing circuits open. Send a bunch of "drop"
  516. * cells down each of them, to exercise our bandwidth. */
  517. void
  518. router_perform_bandwidth_test(int num_circs, time_t now)
  519. {
  520. int num_cells = (int)(get_options()->BandwidthRate * 10 / CELL_NETWORK_SIZE);
  521. int max_cells = num_cells < CIRCWINDOW_START ?
  522. num_cells : CIRCWINDOW_START;
  523. int cells_per_circuit = max_cells / num_circs;
  524. origin_circuit_t *circ = NULL;
  525. log_notice(LD_OR,"Performing bandwidth self-test...done.");
  526. while ((circ = circuit_get_next_by_pk_and_purpose(circ, NULL,
  527. CIRCUIT_PURPOSE_TESTING))) {
  528. /* dump cells_per_circuit drop cells onto this circ */
  529. int i = cells_per_circuit;
  530. if (circ->_base.state != CIRCUIT_STATE_OPEN)
  531. continue;
  532. circ->_base.timestamp_dirty = now;
  533. while (i-- > 0) {
  534. if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
  535. RELAY_COMMAND_DROP,
  536. NULL, 0, circ->cpath->prev)<0) {
  537. return; /* stop if error */
  538. }
  539. }
  540. }
  541. }
  542. /** Return true iff we believe ourselves to be an authoritative
  543. * directory server.
  544. */
  545. int
  546. authdir_mode(or_options_t *options)
  547. {
  548. return options->AuthoritativeDir != 0;
  549. }
  550. /** Return true iff we believe ourselves to be a v1 authoritative
  551. * directory server.
  552. */
  553. int
  554. authdir_mode_v1(or_options_t *options)
  555. {
  556. return authdir_mode(options) && options->V1AuthoritativeDir != 0;
  557. }
  558. /** Return true iff we believe ourselves to be a v2 authoritative
  559. * directory server.
  560. */
  561. int
  562. authdir_mode_v2(or_options_t *options)
  563. {
  564. return authdir_mode(options) && options->V2AuthoritativeDir != 0;
  565. }
  566. /** Return true iff we are an authoritative directory server that
  567. * handles descriptors -- including receiving posts, creating directories,
  568. * and testing reachability.
  569. */
  570. int
  571. authdir_mode_handles_descs(or_options_t *options)
  572. {
  573. return authdir_mode_v1(options) || authdir_mode_v2(options);
  574. }
  575. /** Return true iff we believe ourselves to be a bridge authoritative
  576. * directory server.
  577. */
  578. int
  579. authdir_mode_bridge(or_options_t *options)
  580. {
  581. return authdir_mode(options) && options->BridgeAuthoritativeDir != 0;
  582. }
  583. /** Return true iff we try to stay connected to all ORs at once.
  584. */
  585. int
  586. clique_mode(or_options_t *options)
  587. {
  588. return authdir_mode_handles_descs(options);
  589. }
  590. /** Return true iff we are trying to be a server.
  591. */
  592. int
  593. server_mode(or_options_t *options)
  594. {
  595. if (options->ClientOnly) return 0;
  596. return (options->ORPort != 0 || options->ORListenAddress);
  597. }
  598. /** Remember if we've advertised ourselves to the dirservers. */
  599. static int server_is_advertised=0;
  600. /** Return true iff we have published our descriptor lately.
  601. */
  602. int
  603. advertised_server_mode(void)
  604. {
  605. return server_is_advertised;
  606. }
  607. /**
  608. * Called with a boolean: set whether we have recently published our
  609. * descriptor.
  610. */
  611. static void
  612. set_server_advertised(int s)
  613. {
  614. server_is_advertised = s;
  615. }
  616. /** Return true iff we are trying to be a socks proxy. */
  617. int
  618. proxy_mode(or_options_t *options)
  619. {
  620. return (options->SocksPort != 0 || options->SocksListenAddress);
  621. }
  622. /** Decide if we're a publishable server. We are a publishable server if:
  623. * - We don't have the ClientOnly option set
  624. * and
  625. * - We have the PublishServerDescriptor option set to non-empty
  626. * and
  627. * - We have ORPort set
  628. * and
  629. * - We believe we are reachable from the outside; or
  630. * - We are an authoritative directory server.
  631. */
  632. static int
  633. decide_if_publishable_server(void)
  634. {
  635. or_options_t *options = get_options();
  636. if (options->ClientOnly)
  637. return 0;
  638. if (options->_PublishServerDescriptor == NO_AUTHORITY)
  639. return 0;
  640. if (!server_mode(options))
  641. return 0;
  642. if (authdir_mode(options))
  643. return 1;
  644. return check_whether_orport_reachable();
  645. }
  646. /** Initiate server descriptor upload as reasonable (if server is publishable,
  647. * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
  648. *
  649. * We need to rebuild the descriptor if it's dirty even if we're not
  650. * uploading, because our reachability testing *uses* our descriptor to
  651. * determine what IP address and ports to test.
  652. */
  653. void
  654. consider_publishable_server(int force)
  655. {
  656. int rebuilt;
  657. if (!server_mode(get_options()))
  658. return;
  659. rebuilt = router_rebuild_descriptor(0);
  660. if (decide_if_publishable_server()) {
  661. set_server_advertised(1);
  662. if (rebuilt == 0)
  663. router_upload_dir_desc_to_dirservers(force);
  664. } else {
  665. set_server_advertised(0);
  666. }
  667. }
  668. /*
  669. * Clique maintenance -- to be phased out.
  670. */
  671. /** Return true iff we believe this OR tries to keep connections open
  672. * to all other ORs. */
  673. int
  674. router_is_clique_mode(routerinfo_t *router)
  675. {
  676. if (router_digest_is_trusted_dir(router->cache_info.identity_digest))
  677. return 1;
  678. return 0;
  679. }
  680. /*
  681. * OR descriptor generation.
  682. */
  683. /** My routerinfo. */
  684. static routerinfo_t *desc_routerinfo = NULL;
  685. /** DOCDOC */
  686. static extrainfo_t *desc_extrainfo = NULL;
  687. /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
  688. * now. */
  689. static time_t desc_clean_since = 0;
  690. /** Boolean: do we need to regenerate the above? */
  691. static int desc_needs_upload = 0;
  692. /** OR only: If <b>force</b> is true, or we haven't uploaded this
  693. * descriptor successfully yet, try to upload our signed descriptor to
  694. * all the directory servers we know about.
  695. */
  696. void
  697. router_upload_dir_desc_to_dirservers(int force)
  698. {
  699. routerinfo_t *ri;
  700. extrainfo_t *ei;
  701. char *msg;
  702. size_t desc_len, extra_len = 0, total_len;
  703. ri = router_get_my_routerinfo();
  704. if (!ri) {
  705. log_info(LD_GENERAL, "No descriptor; skipping upload");
  706. return;
  707. }
  708. ei = router_get_my_extrainfo();
  709. if (get_options()->_PublishServerDescriptor == NO_AUTHORITY)
  710. return;
  711. if (!force && !desc_needs_upload)
  712. return;
  713. desc_needs_upload = 0;
  714. desc_len = ri->cache_info.signed_descriptor_len;
  715. extra_len = ei ? ei->cache_info.signed_descriptor_len : 0;
  716. total_len = desc_len + extra_len + 1;
  717. msg = tor_malloc(total_len);
  718. memcpy(msg, ri->cache_info.signed_descriptor_body, desc_len);
  719. if (ei) {
  720. memcpy(msg+desc_len, ei->cache_info.signed_descriptor_body, extra_len);
  721. }
  722. msg[desc_len+extra_len] = 0;
  723. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR, V2_AUTHORITY,
  724. msg, desc_len, extra_len);
  725. tor_free(msg);
  726. }
  727. /** OR only: Check whether my exit policy says to allow connection to
  728. * conn. Return 0 if we accept; non-0 if we reject.
  729. */
  730. int
  731. router_compare_to_my_exit_policy(edge_connection_t *conn)
  732. {
  733. if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
  734. return -1;
  735. /* make sure it's resolved to something. this way we can't get a
  736. 'maybe' below. */
  737. if (!conn->_base.addr)
  738. return -1;
  739. return compare_addr_to_addr_policy(conn->_base.addr, conn->_base.port,
  740. desc_routerinfo->exit_policy) != ADDR_POLICY_ACCEPTED;
  741. }
  742. /** Return true iff I'm a server and <b>digest</b> is equal to
  743. * my identity digest. */
  744. int
  745. router_digest_is_me(const char *digest)
  746. {
  747. return identitykey && !memcmp(identitykey_digest, digest, DIGEST_LEN);
  748. }
  749. /** A wrapper around router_digest_is_me(). */
  750. int
  751. router_is_me(routerinfo_t *router)
  752. {
  753. return router_digest_is_me(router->cache_info.identity_digest);
  754. }
  755. /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
  756. int
  757. router_fingerprint_is_me(const char *fp)
  758. {
  759. char digest[DIGEST_LEN];
  760. if (strlen(fp) == HEX_DIGEST_LEN &&
  761. base16_decode(digest, sizeof(digest), fp, HEX_DIGEST_LEN) == 0)
  762. return router_digest_is_me(digest);
  763. return 0;
  764. }
  765. /** Return a routerinfo for this OR, rebuilding a fresh one if
  766. * necessary. Return NULL on error, or if called on an OP. */
  767. routerinfo_t *
  768. router_get_my_routerinfo(void)
  769. {
  770. if (!server_mode(get_options()))
  771. return NULL;
  772. if (router_rebuild_descriptor(0))
  773. return NULL;
  774. return desc_routerinfo;
  775. }
  776. /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
  777. * one if necessary. Return NULL on error.
  778. */
  779. const char *
  780. router_get_my_descriptor(void)
  781. {
  782. const char *body;
  783. if (!router_get_my_routerinfo())
  784. return NULL;
  785. /* Make sure this is nul-terminated. */
  786. tor_assert(desc_routerinfo->cache_info.saved_location == SAVED_NOWHERE);
  787. body = signed_descriptor_get_body(&desc_routerinfo->cache_info);
  788. tor_assert(!body[desc_routerinfo->cache_info.signed_descriptor_len]);
  789. log_debug(LD_GENERAL,"my desc is '%s'", body);
  790. return body;
  791. }
  792. /** DOCDOC */
  793. extrainfo_t *
  794. router_get_my_extrainfo(void)
  795. {
  796. if (!server_mode(get_options()))
  797. return NULL;
  798. if (router_rebuild_descriptor(0))
  799. return NULL;
  800. return desc_extrainfo;
  801. }
  802. /** A list of nicknames that we've warned about including in our family
  803. * declaration verbatim rather than as digests. */
  804. static smartlist_t *warned_nonexistent_family = NULL;
  805. static int router_guess_address_from_dir_headers(uint32_t *guess);
  806. /** Return our current best guess at our address, either because
  807. * it's configured in torrc, or because we've learned it from
  808. * dirserver headers. */
  809. int
  810. router_pick_published_address(or_options_t *options, uint32_t *addr)
  811. {
  812. if (resolve_my_address(LOG_INFO, options, addr, NULL) < 0) {
  813. log_info(LD_CONFIG, "Could not determine our address locally. "
  814. "Checking if directory headers provide any hints.");
  815. if (router_guess_address_from_dir_headers(addr) < 0) {
  816. log_info(LD_CONFIG, "No hints from directory headers either. "
  817. "Will try again later.");
  818. return -1;
  819. }
  820. }
  821. return 0;
  822. }
  823. /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild
  824. * a fresh routerinfo and signed server descriptor for this OR.
  825. * Return 0 on success, -1 on temporary error.
  826. * DOCDOC extrainfo.
  827. */
  828. int
  829. router_rebuild_descriptor(int force)
  830. {
  831. routerinfo_t *ri;
  832. extrainfo_t *ei;
  833. uint32_t addr;
  834. char platform[256];
  835. int hibernating = we_are_hibernating();
  836. or_options_t *options = get_options();
  837. if (desc_clean_since && !force)
  838. return 0;
  839. if (router_pick_published_address(options, &addr) < 0) {
  840. /* Stop trying to rebuild our descriptor every second. We'll
  841. * learn that it's time to try again when server_has_changed_ip()
  842. * marks it dirty. */
  843. desc_clean_since = time(NULL);
  844. return -1;
  845. }
  846. ri = tor_malloc_zero(sizeof(routerinfo_t));
  847. ri->routerlist_index = -1;
  848. ri->address = tor_dup_addr(addr);
  849. ri->nickname = tor_strdup(options->Nickname);
  850. ri->addr = addr;
  851. ri->or_port = options->ORPort;
  852. ri->dir_port = options->DirPort;
  853. ri->cache_info.published_on = time(NULL);
  854. ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from
  855. * main thread */
  856. ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
  857. if (crypto_pk_get_digest(ri->identity_pkey,
  858. ri->cache_info.identity_digest)<0) {
  859. routerinfo_free(ri);
  860. return -1;
  861. }
  862. get_platform_str(platform, sizeof(platform));
  863. ri->platform = tor_strdup(platform);
  864. /* compute ri->bandwidthrate as the min of various options */
  865. ri->bandwidthrate = (int)options->BandwidthRate;
  866. if (ri->bandwidthrate > options->MaxAdvertisedBandwidth)
  867. ri->bandwidthrate = (int)options->MaxAdvertisedBandwidth;
  868. if (options->RelayBandwidthRate > 0 &&
  869. ri->bandwidthrate > options->RelayBandwidthRate)
  870. ri->bandwidthrate = (int)options->RelayBandwidthRate;
  871. /* and compute ri->bandwidthburst similarly */
  872. ri->bandwidthburst = (int)options->BandwidthBurst;
  873. if (options->RelayBandwidthBurst > 0 &&
  874. ri->bandwidthburst > options->RelayBandwidthBurst)
  875. ri->bandwidthburst = (int)options->RelayBandwidthBurst;
  876. ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
  877. policies_parse_exit_policy(options->ExitPolicy, &ri->exit_policy,
  878. options->ExitPolicyRejectPrivate);
  879. if (desc_routerinfo) { /* inherit values */
  880. ri->is_valid = desc_routerinfo->is_valid;
  881. ri->is_running = desc_routerinfo->is_running;
  882. ri->is_named = desc_routerinfo->is_named;
  883. }
  884. if (authdir_mode(options))
  885. ri->is_valid = ri->is_named = 1; /* believe in yourself */
  886. if (options->MyFamily) {
  887. smartlist_t *family;
  888. if (!warned_nonexistent_family)
  889. warned_nonexistent_family = smartlist_create();
  890. family = smartlist_create();
  891. ri->declared_family = smartlist_create();
  892. smartlist_split_string(family, options->MyFamily, ",",
  893. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  894. SMARTLIST_FOREACH(family, char *, name,
  895. {
  896. routerinfo_t *member;
  897. if (!strcasecmp(name, options->Nickname))
  898. member = ri;
  899. else
  900. member = router_get_by_nickname(name, 1);
  901. if (!member) {
  902. if (!smartlist_string_isin(warned_nonexistent_family, name) &&
  903. !is_legal_hexdigest(name)) {
  904. log_warn(LD_CONFIG,
  905. "I have no descriptor for the router named \"%s\" "
  906. "in my declared family; I'll use the nickname as is, but "
  907. "this may confuse clients.", name);
  908. smartlist_add(warned_nonexistent_family, tor_strdup(name));
  909. }
  910. smartlist_add(ri->declared_family, name);
  911. name = NULL;
  912. } else if (router_is_me(member)) {
  913. /* Don't list ourself in our own family; that's redundant */
  914. } else {
  915. char *fp = tor_malloc(HEX_DIGEST_LEN+2);
  916. fp[0] = '$';
  917. base16_encode(fp+1,HEX_DIGEST_LEN+1,
  918. member->cache_info.identity_digest, DIGEST_LEN);
  919. smartlist_add(ri->declared_family, fp);
  920. if (smartlist_string_isin(warned_nonexistent_family, name))
  921. smartlist_string_remove(warned_nonexistent_family, name);
  922. }
  923. tor_free(name);
  924. });
  925. /* remove duplicates from the list */
  926. smartlist_sort_strings(ri->declared_family);
  927. smartlist_uniq_strings(ri->declared_family);
  928. smartlist_free(family);
  929. }
  930. /* Now generate the extrainfo. */
  931. ei = tor_malloc_zero(sizeof(extrainfo_t));
  932. strlcpy(ei->nickname, get_options()->Nickname, sizeof(ei->nickname));
  933. ei->cache_info.published_on = ri->cache_info.published_on;
  934. memcpy(ei->cache_info.identity_digest, ri->cache_info.identity_digest,
  935. DIGEST_LEN);
  936. ei->cache_info.signed_descriptor_body = tor_malloc(8192);
  937. if (extrainfo_dump_to_string(ei->cache_info.signed_descriptor_body, 8192,
  938. ei, get_identity_key()) < 0) {
  939. log_warn(LD_BUG, "Couldn't generate extra-info descriptor.");
  940. return -1;
  941. }
  942. ei->cache_info.signed_descriptor_len =
  943. strlen(ei->cache_info.signed_descriptor_body);
  944. router_get_extrainfo_hash(ei->cache_info.signed_descriptor_body,
  945. ei->cache_info.signed_descriptor_digest);
  946. /* Now finish the router descriptor. */
  947. memcpy(ri->cache_info.extra_info_digest,
  948. ei->cache_info.signed_descriptor_digest,
  949. DIGEST_LEN);
  950. ri->cache_info.signed_descriptor_body = tor_malloc(8192);
  951. if (router_dump_router_to_string(ri->cache_info.signed_descriptor_body, 8192,
  952. ri, get_identity_key())<0) {
  953. log_warn(LD_BUG, "Couldn't generate router descriptor.");
  954. return -1;
  955. }
  956. ri->cache_info.signed_descriptor_len =
  957. strlen(ri->cache_info.signed_descriptor_body);
  958. /* XXXX020 router_get_router_hash??? */
  959. crypto_digest(ri->cache_info.signed_descriptor_digest,
  960. ri->cache_info.signed_descriptor_body,
  961. ri->cache_info.signed_descriptor_len);
  962. tor_assert(! routerinfo_incompatible_with_extrainfo(ri, ei));
  963. if (desc_routerinfo)
  964. routerinfo_free(desc_routerinfo);
  965. desc_routerinfo = ri;
  966. if (desc_extrainfo)
  967. extrainfo_free(desc_extrainfo);
  968. desc_extrainfo = ei;
  969. desc_clean_since = time(NULL);
  970. desc_needs_upload = 1;
  971. control_event_my_descriptor_changed();
  972. return 0;
  973. }
  974. /** Mark descriptor out of date if it's older than <b>when</b> */
  975. void
  976. mark_my_descriptor_dirty_if_older_than(time_t when)
  977. {
  978. if (desc_clean_since < when)
  979. mark_my_descriptor_dirty();
  980. }
  981. /** Call when the current descriptor is out of date. */
  982. void
  983. mark_my_descriptor_dirty(void)
  984. {
  985. desc_clean_since = 0;
  986. }
  987. /** How frequently will we republish our descriptor because of large (factor
  988. * of 2) shifts in estimated bandwidth? */
  989. #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
  990. /** Check whether bandwidth has changed a lot since the last time we announced
  991. * bandwidth. If so, mark our descriptor dirty. */
  992. void
  993. check_descriptor_bandwidth_changed(time_t now)
  994. {
  995. static time_t last_changed = 0;
  996. uint64_t prev, cur;
  997. if (!desc_routerinfo)
  998. return;
  999. prev = desc_routerinfo->bandwidthcapacity;
  1000. cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
  1001. if ((prev != cur && (!prev || !cur)) ||
  1002. cur > prev*2 ||
  1003. cur < prev/2) {
  1004. if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now) {
  1005. log_info(LD_GENERAL,
  1006. "Measured bandwidth has changed; rebuilding descriptor.");
  1007. mark_my_descriptor_dirty();
  1008. last_changed = now;
  1009. }
  1010. }
  1011. }
  1012. /** Note at log level severity that our best guess of address has changed from
  1013. * <b>prev</b> to <b>cur</b>. */
  1014. static void
  1015. log_addr_has_changed(int severity, uint32_t prev, uint32_t cur)
  1016. {
  1017. char addrbuf_prev[INET_NTOA_BUF_LEN];
  1018. char addrbuf_cur[INET_NTOA_BUF_LEN];
  1019. struct in_addr in_prev;
  1020. struct in_addr in_cur;
  1021. in_prev.s_addr = htonl(prev);
  1022. tor_inet_ntoa(&in_prev, addrbuf_prev, sizeof(addrbuf_prev));
  1023. in_cur.s_addr = htonl(cur);
  1024. tor_inet_ntoa(&in_cur, addrbuf_cur, sizeof(addrbuf_cur));
  1025. if (prev)
  1026. log_fn(severity, LD_GENERAL,
  1027. "Our IP Address has changed from %s to %s; "
  1028. "rebuilding descriptor.",
  1029. addrbuf_prev, addrbuf_cur);
  1030. else
  1031. log_notice(LD_GENERAL,
  1032. "Guessed our IP address as %s.",
  1033. addrbuf_cur);
  1034. }
  1035. /** Check whether our own address as defined by the Address configuration
  1036. * has changed. This is for routers that get their address from a service
  1037. * like dyndns. If our address has changed, mark our descriptor dirty. */
  1038. void
  1039. check_descriptor_ipaddress_changed(time_t now)
  1040. {
  1041. uint32_t prev, cur;
  1042. or_options_t *options = get_options();
  1043. (void) now;
  1044. if (!desc_routerinfo)
  1045. return;
  1046. prev = desc_routerinfo->addr;
  1047. if (resolve_my_address(LOG_INFO, options, &cur, NULL) < 0) {
  1048. log_info(LD_CONFIG,"options->Address didn't resolve into an IP.");
  1049. return;
  1050. }
  1051. if (prev != cur) {
  1052. log_addr_has_changed(LOG_INFO, prev, cur);
  1053. ip_address_changed(0);
  1054. }
  1055. }
  1056. /** The most recently guessed value of our IP address, based on directory
  1057. * headers. */
  1058. static uint32_t last_guessed_ip = 0;
  1059. /** A directory server told us our IP address is <b>suggestion</b>.
  1060. * If this address is different from the one we think we are now, and
  1061. * if our computer doesn't actually know its IP address, then switch. */
  1062. void
  1063. router_new_address_suggestion(const char *suggestion)
  1064. {
  1065. uint32_t addr, cur = 0;
  1066. struct in_addr in;
  1067. or_options_t *options = get_options();
  1068. /* first, learn what the IP address actually is */
  1069. if (!tor_inet_aton(suggestion, &in)) {
  1070. log_debug(LD_DIR, "Malformed X-Your-Address-Is header %s. Ignoring.",
  1071. escaped(suggestion));
  1072. return;
  1073. }
  1074. addr = ntohl(in.s_addr);
  1075. log_debug(LD_DIR, "Got X-Your-Address-Is: %s.", suggestion);
  1076. if (!server_mode(options)) {
  1077. last_guessed_ip = addr; /* store it in case we need it later */
  1078. return;
  1079. }
  1080. if (resolve_my_address(LOG_INFO, options, &cur, NULL) >= 0) {
  1081. /* We're all set -- we already know our address. Great. */
  1082. last_guessed_ip = cur; /* store it in case we need it later */
  1083. return;
  1084. }
  1085. if (is_internal_IP(addr, 0)) {
  1086. /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
  1087. return;
  1088. }
  1089. /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
  1090. * us an answer different from what we had the last time we managed to
  1091. * resolve it. */
  1092. if (last_guessed_ip != addr) {
  1093. control_event_server_status(LOG_NOTICE,
  1094. "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
  1095. suggestion);
  1096. log_addr_has_changed(LOG_NOTICE, last_guessed_ip, addr);
  1097. ip_address_changed(0);
  1098. last_guessed_ip = addr; /* router_rebuild_descriptor() will fetch it */
  1099. }
  1100. }
  1101. /** We failed to resolve our address locally, but we'd like to build
  1102. * a descriptor and publish / test reachability. If we have a guess
  1103. * about our address based on directory headers, answer it and return
  1104. * 0; else return -1. */
  1105. static int
  1106. router_guess_address_from_dir_headers(uint32_t *guess)
  1107. {
  1108. if (last_guessed_ip) {
  1109. *guess = last_guessed_ip;
  1110. return 0;
  1111. }
  1112. return -1;
  1113. }
  1114. extern const char tor_svn_revision[]; /* from main.c */
  1115. /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
  1116. * string describing the version of Tor and the operating system we're
  1117. * currently running on.
  1118. */
  1119. void
  1120. get_platform_str(char *platform, size_t len)
  1121. {
  1122. char svn_version_buf[128];
  1123. if (!strcmpend(VERSION, "-dev") &&
  1124. tor_svn_revision && strlen(tor_svn_revision)) {
  1125. tor_snprintf(svn_version_buf, sizeof(svn_version_buf), " (r%s)",
  1126. tor_svn_revision);
  1127. } else {
  1128. svn_version_buf[0] = 0;
  1129. }
  1130. tor_snprintf(platform, len, "Tor %s%s on %s",
  1131. VERSION, svn_version_buf, get_uname());
  1132. return;
  1133. }
  1134. /* XXX need to audit this thing and count fenceposts. maybe
  1135. * refactor so we don't have to keep asking if we're
  1136. * near the end of maxlen?
  1137. */
  1138. #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  1139. /** OR only: Given a routerinfo for this router, and an identity key to sign
  1140. * with, encode the routerinfo as a signed server descriptor and write the
  1141. * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
  1142. * failure, and the number of bytes used on success.
  1143. */
  1144. int
  1145. router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
  1146. crypto_pk_env_t *ident_key)
  1147. {
  1148. char *onion_pkey; /* Onion key, PEM-encoded. */
  1149. char *identity_pkey; /* Identity key, PEM-encoded. */
  1150. char digest[DIGEST_LEN];
  1151. char published[ISO_TIME_LEN+1];
  1152. char fingerprint[FINGERPRINT_LEN+1];
  1153. char extra_info_digest[HEX_DIGEST_LEN+1];
  1154. size_t onion_pkeylen, identity_pkeylen;
  1155. size_t written;
  1156. int result=0;
  1157. addr_policy_t *tmpe;
  1158. char *bandwidth_usage;
  1159. char *family_line;
  1160. or_options_t *options = get_options();
  1161. /* Make sure the identity key matches the one in the routerinfo. */
  1162. if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
  1163. log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
  1164. "match router's public key!");
  1165. return -1;
  1166. }
  1167. /* record our fingerprint, so we can include it in the descriptor */
  1168. if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
  1169. log_err(LD_BUG,"Error computing fingerprint");
  1170. return -1;
  1171. }
  1172. /* PEM-encode the onion key */
  1173. if (crypto_pk_write_public_key_to_string(router->onion_pkey,
  1174. &onion_pkey,&onion_pkeylen)<0) {
  1175. log_warn(LD_BUG,"write onion_pkey to string failed!");
  1176. return -1;
  1177. }
  1178. /* PEM-encode the identity key key */
  1179. if (crypto_pk_write_public_key_to_string(router->identity_pkey,
  1180. &identity_pkey,&identity_pkeylen)<0) {
  1181. log_warn(LD_BUG,"write identity_pkey to string failed!");
  1182. tor_free(onion_pkey);
  1183. return -1;
  1184. }
  1185. /* Encode the publication time. */
  1186. format_iso_time(published, router->cache_info.published_on);
  1187. /* How busy have we been? */
  1188. bandwidth_usage = rep_hist_get_bandwidth_lines(0);
  1189. if (router->declared_family && smartlist_len(router->declared_family)) {
  1190. size_t n;
  1191. char *s = smartlist_join_strings(router->declared_family, " ", 0, &n);
  1192. n += strlen("family ") + 2; /* 1 for \n, 1 for \0. */
  1193. family_line = tor_malloc(n);
  1194. tor_snprintf(family_line, n, "family %s\n", s);
  1195. tor_free(s);
  1196. } else {
  1197. family_line = tor_strdup("");
  1198. }
  1199. base16_encode(extra_info_digest, sizeof(extra_info_digest),
  1200. router->cache_info.extra_info_digest, DIGEST_LEN);
  1201. /* Generate the easy portion of the router descriptor. */
  1202. result = tor_snprintf(s, maxlen,
  1203. "router %s %s %d 0 %d\n"
  1204. "platform %s\n"
  1205. "published %s\n"
  1206. "opt fingerprint %s\n"
  1207. "uptime %ld\n"
  1208. "bandwidth %d %d %d\n"
  1209. "opt extra-info-digest %s\n"
  1210. "onion-key\n%s"
  1211. "signing-key\n%s"
  1212. "%s%s%s",
  1213. router->nickname,
  1214. router->address,
  1215. router->or_port,
  1216. decide_to_advertise_dirport(options, router),
  1217. router->platform,
  1218. published,
  1219. fingerprint,
  1220. stats_n_seconds_working,
  1221. (int) router->bandwidthrate,
  1222. (int) router->bandwidthburst,
  1223. (int) router->bandwidthcapacity,
  1224. extra_info_digest,
  1225. onion_pkey, identity_pkey,
  1226. family_line, bandwidth_usage,
  1227. we_are_hibernating() ? "opt hibernating 1\n" : "");
  1228. tor_free(family_line);
  1229. tor_free(onion_pkey);
  1230. tor_free(identity_pkey);
  1231. tor_free(bandwidth_usage);
  1232. if (result < 0) {
  1233. log_warn(LD_BUG,"descriptor snprintf #1 ran out of room!");
  1234. return -1;
  1235. }
  1236. /* From now on, we use 'written' to remember the current length of 's'. */
  1237. written = result;
  1238. if (options->ContactInfo && strlen(options->ContactInfo)) {
  1239. result = tor_snprintf(s+written,maxlen-written, "contact %s\n",
  1240. options->ContactInfo);
  1241. if (result<0) {
  1242. log_warn(LD_BUG,"descriptor snprintf #2 ran out of room!");
  1243. return -1;
  1244. }
  1245. written += result;
  1246. }
  1247. /* Write the exit policy to the end of 's'. */
  1248. tmpe = router->exit_policy;
  1249. if (dns_seems_to_be_broken()) {
  1250. /* DNS is screwed up; don't claim to be an exit. */
  1251. strlcat(s+written, "reject *:*\n", maxlen-written);
  1252. written += strlen("reject *:*\n");
  1253. tmpe = NULL;
  1254. }
  1255. for ( ; tmpe; tmpe=tmpe->next) {
  1256. result = policy_write_item(s+written, maxlen-written, tmpe);
  1257. if (result < 0) {
  1258. log_warn(LD_BUG,"descriptor policy_write_item ran out of room!");
  1259. return -1;
  1260. }
  1261. tor_assert(result == (int)strlen(s+written));
  1262. written += result;
  1263. if (written+2 > maxlen) {
  1264. log_warn(LD_BUG,"descriptor policy_write_item ran out of room (2)!");
  1265. return -1;
  1266. }
  1267. s[written++] = '\n';
  1268. }
  1269. if (written+256 > maxlen) { /* Not enough room for signature. */
  1270. log_warn(LD_BUG,"not enough room left in descriptor for signature!");
  1271. return -1;
  1272. }
  1273. /* Sign the directory */
  1274. strlcpy(s+written, "router-signature\n", maxlen-written);
  1275. written += strlen(s+written);
  1276. s[written] = '\0';
  1277. if (router_get_router_hash(s, digest) < 0) {
  1278. return -1;
  1279. }
  1280. note_crypto_pk_op(SIGN_RTR);
  1281. if (router_append_dirobj_signature(s+written,maxlen-written,
  1282. digest,ident_key)<0) {
  1283. log_warn(LD_BUG, "Couldn't sign router descriptor");
  1284. return -1;
  1285. }
  1286. written += strlen(s+written);
  1287. if (written+2 > maxlen) {
  1288. log_warn(LD_BUG,"Not enough room to finish descriptor.");
  1289. return -1;
  1290. }
  1291. /* include a last '\n' */
  1292. s[written] = '\n';
  1293. s[written+1] = 0;
  1294. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  1295. {
  1296. char *s_dup;
  1297. const char *cp;
  1298. routerinfo_t *ri_tmp;
  1299. cp = s_dup = tor_strdup(s);
  1300. ri_tmp = router_parse_entry_from_string(cp, NULL, 1);
  1301. if (!ri_tmp) {
  1302. log_err(LD_BUG,
  1303. "We just generated a router descriptor we can't parse.");
  1304. log_err(LD_BUG, "Descriptor was: <<%s>>", s);
  1305. return -1;
  1306. }
  1307. tor_free(s_dup);
  1308. routerinfo_free(ri_tmp);
  1309. }
  1310. #endif
  1311. return written+1;
  1312. }
  1313. /** DOCDOC */
  1314. int
  1315. extrainfo_dump_to_string(char *s, size_t maxlen, extrainfo_t *extrainfo,
  1316. crypto_pk_env_t *ident_key)
  1317. {
  1318. char identity[HEX_DIGEST_LEN+1];
  1319. char published[ISO_TIME_LEN+1];
  1320. char digest[DIGEST_LEN];
  1321. char *bandwidth_usage;
  1322. int result;
  1323. size_t len;
  1324. base16_encode(identity, sizeof(identity),
  1325. extrainfo->cache_info.identity_digest, DIGEST_LEN);
  1326. format_iso_time(published, extrainfo->cache_info.published_on);
  1327. bandwidth_usage = rep_hist_get_bandwidth_lines(1);
  1328. result = tor_snprintf(s, maxlen,
  1329. "extra-info %s %s\n"
  1330. "published %s\n%s"
  1331. "router-signature\n",
  1332. extrainfo->nickname, identity,
  1333. published, bandwidth_usage);
  1334. tor_free(bandwidth_usage);
  1335. if (result<0)
  1336. return -1;
  1337. len = strlen(s);
  1338. if (router_get_extrainfo_hash(s, digest)<0)
  1339. return -1;
  1340. if (router_append_dirobj_signature(s+len, maxlen-len, digest, ident_key)<0)
  1341. return -1;
  1342. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  1343. {
  1344. char *cp, *s_dup;
  1345. extrainfo_t *ei_tmp;
  1346. cp = s_dup = tor_strdup(s);
  1347. ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL);
  1348. if (!ei_tmp) {
  1349. log_err(LD_BUG,
  1350. "We just generated an extrainfo descriptor we can't parse.");
  1351. log_err(LD_BUG, "Descriptor was: <<%s>>", s);
  1352. return -1;
  1353. }
  1354. tor_free(s_dup);
  1355. extrainfo_free(ei_tmp);
  1356. }
  1357. #endif
  1358. return strlen(s)+1;
  1359. }
  1360. /** Return true iff <b>s</b> is a legally valid server nickname. */
  1361. int
  1362. is_legal_nickname(const char *s)
  1363. {
  1364. size_t len;
  1365. tor_assert(s);
  1366. len = strlen(s);
  1367. return len > 0 && len <= MAX_NICKNAME_LEN &&
  1368. strspn(s,LEGAL_NICKNAME_CHARACTERS) == len;
  1369. }
  1370. /** Return true iff <b>s</b> is a legally valid server nickname or
  1371. * hex-encoded identity-key digest. */
  1372. int
  1373. is_legal_nickname_or_hexdigest(const char *s)
  1374. {
  1375. if (*s!='$')
  1376. return is_legal_nickname(s);
  1377. else
  1378. return is_legal_hexdigest(s);
  1379. }
  1380. /** Return true iff <b>s</b> is a legally valid hex-encoded identity-key
  1381. * digest. */
  1382. int
  1383. is_legal_hexdigest(const char *s)
  1384. {
  1385. size_t len;
  1386. tor_assert(s);
  1387. if (s[0] == '$') s++;
  1388. len = strlen(s);
  1389. if (len > HEX_DIGEST_LEN) {
  1390. if (s[HEX_DIGEST_LEN] == '=' ||
  1391. s[HEX_DIGEST_LEN] == '~') {
  1392. if (!is_legal_nickname(s+HEX_DIGEST_LEN+1))
  1393. return 0;
  1394. } else {
  1395. return 0;
  1396. }
  1397. }
  1398. return (len >= HEX_DIGEST_LEN &&
  1399. strspn(s,HEX_CHARACTERS)==HEX_DIGEST_LEN);
  1400. }
  1401. /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
  1402. * verbose representation of the identity of <b>router</b>. The format is:
  1403. * A dollar sign.
  1404. * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
  1405. * A "=" if the router is named; a "~" if it is not.
  1406. * The router's nickname.
  1407. **/
  1408. void
  1409. router_get_verbose_nickname(char *buf, routerinfo_t *router)
  1410. {
  1411. buf[0] = '$';
  1412. base16_encode(buf+1, HEX_DIGEST_LEN+1, router->cache_info.identity_digest,
  1413. DIGEST_LEN);
  1414. buf[1+HEX_DIGEST_LEN] = router->is_named ? '=' : '~';
  1415. strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
  1416. }
  1417. /** Forget that we have issued any router-related warnings, so that we'll
  1418. * warn again if we see the same errors. */
  1419. void
  1420. router_reset_warnings(void)
  1421. {
  1422. if (warned_nonexistent_family) {
  1423. SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
  1424. smartlist_clear(warned_nonexistent_family);
  1425. }
  1426. }
  1427. /** Release all static resources held in router.c */
  1428. void
  1429. router_free_all(void)
  1430. {
  1431. if (onionkey)
  1432. crypto_free_pk_env(onionkey);
  1433. if (lastonionkey)
  1434. crypto_free_pk_env(lastonionkey);
  1435. if (identitykey)
  1436. crypto_free_pk_env(identitykey);
  1437. if (key_lock)
  1438. tor_mutex_free(key_lock);
  1439. if (desc_routerinfo)
  1440. routerinfo_free(desc_routerinfo);
  1441. if (desc_extrainfo)
  1442. extrainfo_free(desc_extrainfo);
  1443. if (warned_nonexistent_family) {
  1444. SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
  1445. smartlist_free(warned_nonexistent_family);
  1446. }
  1447. }