router.c 43 KB

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