router.c 51 KB

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