router.c 47 KB

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