router.c 60 KB

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