router.c 52 KB

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