router.c 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873
  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 certificatge 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. return -1;
  369. set_identity_key(prkey);
  370. /* Create a TLS context; default the client nickname to "client". */
  371. if (tor_tls_context_new(get_identity_key(),
  372. options->Nickname ? options->Nickname : "client",
  373. MAX_SSL_KEY_LIFETIME) < 0) {
  374. log_err(LD_GENERAL,"Error creating TLS context for Tor client.");
  375. return -1;
  376. }
  377. return 0;
  378. }
  379. /* Make sure DataDirectory exists, and is private. */
  380. if (check_private_dir(options->DataDirectory, CPD_CREATE)) {
  381. return -1;
  382. }
  383. /* Check the key directory. */
  384. keydir = get_datadir_fname("keys");
  385. if (check_private_dir(keydir, CPD_CREATE)) {
  386. tor_free(keydir);
  387. return -1;
  388. }
  389. tor_free(keydir);
  390. /* 1a. Read v3 directory authority key/cert information. */
  391. memset(v3_digest, 0, sizeof(v3_digest));
  392. if (authdir_mode_v3(options)) {
  393. if (init_v3_authority_keys()<0) {
  394. log_err(LD_GENERAL, "We're configured as a V3 authority, but we "
  395. "were unable to load our v3 authority keys and certificate! "
  396. "Use tor-gencert to generate them. Dying.");
  397. return -1;
  398. }
  399. if (get_my_v3_authority_cert()) {
  400. crypto_pk_get_digest(get_my_v3_authority_cert()->identity_key,
  401. v3_digest);
  402. v3_digest_set = 1;
  403. }
  404. }
  405. /* 1. Read identity key. Make it if none is found. */
  406. keydir = get_datadir_fname2("keys", "secret_id_key");
  407. log_info(LD_GENERAL,"Reading/making identity key \"%s\"...",keydir);
  408. prkey = init_key_from_file(keydir, 1, LOG_ERR);
  409. tor_free(keydir);
  410. if (!prkey) return -1;
  411. set_identity_key(prkey);
  412. /* 2. Read onion key. Make it if none is found. */
  413. keydir = get_datadir_fname2("keys", "secret_onion_key");
  414. log_info(LD_GENERAL,"Reading/making onion key \"%s\"...",keydir);
  415. prkey = init_key_from_file(keydir, 1, LOG_ERR);
  416. tor_free(keydir);
  417. if (!prkey) return -1;
  418. set_onion_key(prkey);
  419. if (options->command == CMD_RUN_TOR) {
  420. /* only mess with the state file if we're actually running Tor */
  421. or_state_t *state = get_or_state();
  422. if (state->LastRotatedOnionKey > 100 && state->LastRotatedOnionKey < now) {
  423. /* We allow for some parsing slop, but we don't want to risk accepting
  424. * values in the distant future. If we did, we might never rotate the
  425. * onion key. */
  426. onionkey_set_at = state->LastRotatedOnionKey;
  427. } else {
  428. /* We have no LastRotatedOnionKey set; either we just created the key
  429. * or it's a holdover from 0.1.2.4-alpha-dev or earlier. In either case,
  430. * start the clock ticking now so that we will eventually rotate it even
  431. * if we don't stay up for a full MIN_ONION_KEY_LIFETIME. */
  432. state->LastRotatedOnionKey = onionkey_set_at = now;
  433. or_state_mark_dirty(state, options->AvoidDiskWrites ?
  434. time(NULL)+3600 : 0);
  435. }
  436. }
  437. keydir = get_datadir_fname2("keys", "secret_onion_key.old");
  438. if (!lastonionkey && file_status(keydir) == FN_FILE) {
  439. prkey = init_key_from_file(keydir, 1, LOG_ERR);
  440. if (prkey)
  441. lastonionkey = prkey;
  442. }
  443. tor_free(keydir);
  444. /* 3. Initialize link key and TLS context. */
  445. if (tor_tls_context_new(get_identity_key(), options->Nickname,
  446. MAX_SSL_KEY_LIFETIME) < 0) {
  447. log_err(LD_GENERAL,"Error initializing TLS context");
  448. return -1;
  449. }
  450. /* 4. Build our router descriptor. */
  451. /* Must be called after keys are initialized. */
  452. mydesc = router_get_my_descriptor();
  453. if (authdir_mode(options)) {
  454. const char *m;
  455. routerinfo_t *ri;
  456. /* We need to add our own fingerprint so it gets recognized. */
  457. if (dirserv_add_own_fingerprint(options->Nickname, get_identity_key())) {
  458. log_err(LD_GENERAL,"Error adding own fingerprint to approved set");
  459. return -1;
  460. }
  461. if (mydesc) {
  462. ri = router_parse_entry_from_string(mydesc, NULL, 1, 0, NULL);
  463. if (!ri) {
  464. log_err(LD_GENERAL,"Generated a routerinfo we couldn't parse.");
  465. return -1;
  466. }
  467. if (dirserv_add_descriptor(ri, &m) < 0) {
  468. log_err(LD_GENERAL,"Unable to add own descriptor to directory: %s",
  469. m?m:"<unknown error>");
  470. return -1;
  471. }
  472. }
  473. }
  474. /* 5. Dump fingerprint to 'fingerprint' */
  475. keydir = get_datadir_fname("fingerprint");
  476. log_info(LD_GENERAL,"Dumping fingerprint to \"%s\"...",keydir);
  477. if (crypto_pk_get_fingerprint(get_identity_key(), fingerprint, 1)<0) {
  478. log_err(LD_GENERAL,"Error computing fingerprint");
  479. tor_free(keydir);
  480. return -1;
  481. }
  482. tor_assert(strlen(options->Nickname) <= MAX_NICKNAME_LEN);
  483. if (tor_snprintf(fingerprint_line, sizeof(fingerprint_line),
  484. "%s %s\n",options->Nickname, fingerprint) < 0) {
  485. log_err(LD_GENERAL,"Error writing fingerprint line");
  486. tor_free(keydir);
  487. return -1;
  488. }
  489. /* Check whether we need to write the fingerprint file. */
  490. cp = NULL;
  491. if (file_status(keydir) == FN_FILE)
  492. cp = read_file_to_str(keydir, 0, NULL);
  493. if (!cp || strcmp(cp, fingerprint_line)) {
  494. if (write_str_to_file(keydir, fingerprint_line, 0)) {
  495. log_err(LD_FS, "Error writing fingerprint line to file");
  496. tor_free(keydir);
  497. return -1;
  498. }
  499. }
  500. tor_free(cp);
  501. tor_free(keydir);
  502. log(LOG_NOTICE, LD_GENERAL,
  503. "Your Tor server's identity key fingerprint is '%s %s'",
  504. options->Nickname, fingerprint);
  505. if (!authdir_mode(options))
  506. return 0;
  507. /* 6. [authdirserver only] load approved-routers file */
  508. if (dirserv_load_fingerprint_file() < 0) {
  509. log_err(LD_GENERAL,"Error loading fingerprints");
  510. return -1;
  511. }
  512. /* 6b. [authdirserver only] add own key to approved directories. */
  513. crypto_pk_get_digest(get_identity_key(), digest);
  514. type = ((options->V1AuthoritativeDir ? V1_AUTHORITY : 0) |
  515. (options->V2AuthoritativeDir ? V2_AUTHORITY : 0) |
  516. (options->V3AuthoritativeDir ? V3_AUTHORITY : 0) |
  517. (options->BridgeAuthoritativeDir ? BRIDGE_AUTHORITY : 0) |
  518. (options->HSAuthoritativeDir ? HIDSERV_AUTHORITY : 0));
  519. if (!router_digest_is_trusted_dir(digest)) {
  520. add_trusted_dir_server(options->Nickname, NULL,
  521. (uint16_t)options->DirPort,
  522. (uint16_t)options->ORPort,
  523. digest,
  524. v3_digest,
  525. type);
  526. }
  527. if ((ds = router_get_trusteddirserver_by_digest(digest))) {
  528. if (ds->type != type) {
  529. log_warn(LD_DIR, "Configured authority type does not match authority "
  530. "type in DirServer list. Adjusting. (%d v %d)",
  531. type, ds->type);
  532. ds->type = type;
  533. }
  534. if (v3_digest_set && (ds->type & V3_AUTHORITY) &&
  535. memcmp(v3_digest, ds->v3_identity_digest, DIGEST_LEN)) {
  536. log_warn(LD_DIR, "V3 identity key does not match identity declared in "
  537. "DirServer line. Adjusting.");
  538. memcpy(ds->v3_identity_digest, v3_digest, DIGEST_LEN);
  539. }
  540. }
  541. return 0; /* success */
  542. }
  543. /* Keep track of whether we should upload our server descriptor,
  544. * and what type of server we are.
  545. */
  546. /** Whether we can reach our ORPort from the outside. */
  547. static int can_reach_or_port = 0;
  548. /** Whether we can reach our DirPort from the outside. */
  549. static int can_reach_dir_port = 0;
  550. /** Forget what we have learned about our reachability status. */
  551. void
  552. router_reset_reachability(void)
  553. {
  554. can_reach_or_port = can_reach_dir_port = 0;
  555. }
  556. /** Return 1 if ORPort is known reachable; else return 0. */
  557. int
  558. check_whether_orport_reachable(void)
  559. {
  560. or_options_t *options = get_options();
  561. return options->AssumeReachable ||
  562. can_reach_or_port;
  563. }
  564. /** Return 1 if we don't have a dirport configured, or if it's reachable. */
  565. int
  566. check_whether_dirport_reachable(void)
  567. {
  568. or_options_t *options = get_options();
  569. return !options->DirPort ||
  570. options->AssumeReachable ||
  571. we_are_hibernating() ||
  572. can_reach_dir_port;
  573. }
  574. /** Look at a variety of factors, and return 0 if we don't want to
  575. * advertise the fact that we have a DirPort open. Else return the
  576. * DirPort we want to advertise.
  577. *
  578. * Log a helpful message if we change our mind about whether to publish
  579. * a DirPort.
  580. */
  581. static int
  582. decide_to_advertise_dirport(or_options_t *options, uint16_t dir_port)
  583. {
  584. static int advertising=1; /* start out assuming we will advertise */
  585. int new_choice=1;
  586. const char *reason = NULL;
  587. /* Section one: reasons to publish or not publish that aren't
  588. * worth mentioning to the user, either because they're obvious
  589. * or because they're normal behavior. */
  590. if (!dir_port) /* short circuit the rest of the function */
  591. return 0;
  592. if (authdir_mode(options)) /* always publish */
  593. return dir_port;
  594. if (we_are_hibernating())
  595. return 0;
  596. if (!check_whether_dirport_reachable())
  597. return 0;
  598. /* Section two: reasons to publish or not publish that the user
  599. * might find surprising. These are generally config options that
  600. * make us choose not to publish. */
  601. if (accounting_is_enabled(options)) {
  602. /* if we might potentially hibernate */
  603. new_choice = 0;
  604. reason = "AccountingMax enabled";
  605. #define MIN_BW_TO_ADVERTISE_DIRPORT 51200
  606. } else if (options->BandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT ||
  607. (options->RelayBandwidthRate > 0 &&
  608. options->RelayBandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT)) {
  609. /* if we're advertising a small amount */
  610. new_choice = 0;
  611. reason = "BandwidthRate under 50KB";
  612. }
  613. if (advertising != new_choice) {
  614. if (new_choice == 1) {
  615. log(LOG_NOTICE, LD_DIR, "Advertising DirPort as %d", dir_port);
  616. } else {
  617. tor_assert(reason);
  618. log(LOG_NOTICE, LD_DIR, "Not advertising DirPort (Reason: %s)", reason);
  619. }
  620. advertising = new_choice;
  621. }
  622. return advertising ? dir_port : 0;
  623. }
  624. /** Some time has passed, or we just got new directory information.
  625. * See if we currently believe our ORPort or DirPort to be
  626. * unreachable. If so, launch a new test for it.
  627. *
  628. * For ORPort, we simply try making a circuit that ends at ourselves.
  629. * Success is noticed in onionskin_answer().
  630. *
  631. * For DirPort, we make a connection via Tor to our DirPort and ask
  632. * for our own server descriptor.
  633. * Success is noticed in connection_dir_client_reached_eof().
  634. */
  635. void
  636. consider_testing_reachability(int test_or, int test_dir)
  637. {
  638. routerinfo_t *me = router_get_my_routerinfo();
  639. int orport_reachable = check_whether_orport_reachable();
  640. if (!me)
  641. return;
  642. if (test_or && (!orport_reachable || !circuit_enough_testing_circs())) {
  643. log_info(LD_CIRC, "Testing %s of my ORPort: %s:%d.",
  644. !orport_reachable ? "reachability" : "bandwidth",
  645. me->address, me->or_port);
  646. circuit_launch_by_router(CIRCUIT_PURPOSE_TESTING, 0, me, 0, 1, 1);
  647. control_event_server_status(LOG_NOTICE,
  648. "CHECKING_REACHABILITY ORADDRESS=%s:%d",
  649. me->address, me->or_port);
  650. }
  651. if (test_dir && !check_whether_dirport_reachable() &&
  652. !connection_get_by_type_addr_port_purpose(
  653. CONN_TYPE_DIR, me->addr, me->dir_port,
  654. DIR_PURPOSE_FETCH_SERVERDESC)) {
  655. /* ask myself, via tor, for my server descriptor. */
  656. directory_initiate_command(me->address, me->addr,
  657. me->or_port, me->dir_port,
  658. 0, me->cache_info.identity_digest,
  659. DIR_PURPOSE_FETCH_SERVERDESC,
  660. ROUTER_PURPOSE_GENERAL,
  661. 1, "authority.z", NULL, 0, 0);
  662. control_event_server_status(LOG_NOTICE,
  663. "CHECKING_REACHABILITY DIRADDRESS=%s:%d",
  664. me->address, me->dir_port);
  665. }
  666. }
  667. /** Annotate that we found our ORPort reachable. */
  668. void
  669. router_orport_found_reachable(void)
  670. {
  671. if (!can_reach_or_port) {
  672. routerinfo_t *me = router_get_my_routerinfo();
  673. log_notice(LD_OR,"Self-testing indicates your ORPort is reachable from "
  674. "the outside. Excellent.%s",
  675. get_options()->_PublishServerDescriptor != NO_AUTHORITY ?
  676. " Publishing server descriptor." : "");
  677. can_reach_or_port = 1;
  678. mark_my_descriptor_dirty();
  679. if (!me)
  680. return;
  681. control_event_server_status(LOG_NOTICE,
  682. "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
  683. me->address, me->or_port);
  684. }
  685. }
  686. /** Annotate that we found our DirPort reachable. */
  687. void
  688. router_dirport_found_reachable(void)
  689. {
  690. if (!can_reach_dir_port) {
  691. routerinfo_t *me = router_get_my_routerinfo();
  692. log_notice(LD_DIRSERV,"Self-testing indicates your DirPort is reachable "
  693. "from the outside. Excellent.");
  694. can_reach_dir_port = 1;
  695. if (!me || decide_to_advertise_dirport(get_options(), me->dir_port))
  696. mark_my_descriptor_dirty();
  697. if (!me)
  698. return;
  699. control_event_server_status(LOG_NOTICE,
  700. "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
  701. me->address, me->dir_port);
  702. }
  703. }
  704. /** We have enough testing circuits open. Send a bunch of "drop"
  705. * cells down each of them, to exercise our bandwidth. */
  706. void
  707. router_perform_bandwidth_test(int num_circs, time_t now)
  708. {
  709. int num_cells = (int)(get_options()->BandwidthRate * 10 / CELL_NETWORK_SIZE);
  710. int max_cells = num_cells < CIRCWINDOW_START ?
  711. num_cells : CIRCWINDOW_START;
  712. int cells_per_circuit = max_cells / num_circs;
  713. origin_circuit_t *circ = NULL;
  714. log_notice(LD_OR,"Performing bandwidth self-test...done.");
  715. while ((circ = circuit_get_next_by_pk_and_purpose(circ, NULL,
  716. CIRCUIT_PURPOSE_TESTING))) {
  717. /* dump cells_per_circuit drop cells onto this circ */
  718. int i = cells_per_circuit;
  719. if (circ->_base.state != CIRCUIT_STATE_OPEN)
  720. continue;
  721. circ->_base.timestamp_dirty = now;
  722. while (i-- > 0) {
  723. if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
  724. RELAY_COMMAND_DROP,
  725. NULL, 0, circ->cpath->prev)<0) {
  726. return; /* stop if error */
  727. }
  728. }
  729. }
  730. }
  731. /** Return true iff we believe ourselves to be an authoritative
  732. * directory server.
  733. */
  734. int
  735. authdir_mode(or_options_t *options)
  736. {
  737. return options->AuthoritativeDir != 0;
  738. }
  739. /** Return true iff we believe ourselves to be a v1 authoritative
  740. * directory server.
  741. */
  742. int
  743. authdir_mode_v1(or_options_t *options)
  744. {
  745. return authdir_mode(options) && options->V1AuthoritativeDir != 0;
  746. }
  747. /** Return true iff we believe ourselves to be a v2 authoritative
  748. * directory server.
  749. */
  750. int
  751. authdir_mode_v2(or_options_t *options)
  752. {
  753. return authdir_mode(options) && options->V2AuthoritativeDir != 0;
  754. }
  755. /** Return true iff we believe ourselves to be a v3 authoritative
  756. * directory server.
  757. */
  758. int
  759. authdir_mode_v3(or_options_t *options)
  760. {
  761. return authdir_mode(options) && options->V3AuthoritativeDir != 0;
  762. }
  763. /** Return true if we belive ourselves to be any kind of non-bridge
  764. * authoritative directory */
  765. int
  766. authdir_mode_any_nonbridge(or_options_t *options)
  767. {
  768. return authdir_mode(options) &&
  769. (options->V1AuthoritativeDir ||
  770. options->V2AuthoritativeDir ||
  771. options->V3AuthoritativeDir);
  772. }
  773. /** Return true iff we are an authoritative directory server that
  774. * is willing to receive or serve descriptors on its dirport.
  775. */
  776. int
  777. authdir_mode_handles_descs(or_options_t *options)
  778. {
  779. return authdir_mode_any_nonbridge(options) ||
  780. authdir_mode_bridge(options);
  781. }
  782. /** Return true iff we are an authoritative directory server that
  783. * publishes its own network statuses.
  784. */
  785. int
  786. authdir_mode_publishes_statuses(or_options_t *options)
  787. {
  788. if (authdir_mode_bridge(options))
  789. return 0;
  790. return authdir_mode_any_nonbridge(options);
  791. }
  792. /** Return true iff we are an authoritative directory server that
  793. * tests reachability of the descriptors it learns about.
  794. */
  795. int
  796. authdir_mode_tests_reachability(or_options_t *options)
  797. {
  798. return authdir_mode_any_nonbridge(options);
  799. }
  800. /** Return true iff we believe ourselves to be a bridge authoritative
  801. * directory server.
  802. */
  803. int
  804. authdir_mode_bridge(or_options_t *options)
  805. {
  806. return authdir_mode(options) && options->BridgeAuthoritativeDir != 0;
  807. }
  808. /** Return true iff we try to stay connected to all ORs at once.
  809. */
  810. int
  811. clique_mode(or_options_t *options)
  812. {
  813. return authdir_mode_tests_reachability(options);
  814. }
  815. /** Return true iff we are trying to be a server.
  816. */
  817. int
  818. server_mode(or_options_t *options)
  819. {
  820. if (options->ClientOnly) return 0;
  821. return (options->ORPort != 0 || options->ORListenAddress);
  822. }
  823. /** Remember if we've advertised ourselves to the dirservers. */
  824. static int server_is_advertised=0;
  825. /** Return true iff we have published our descriptor lately.
  826. */
  827. int
  828. advertised_server_mode(void)
  829. {
  830. return server_is_advertised;
  831. }
  832. /**
  833. * Called with a boolean: set whether we have recently published our
  834. * descriptor.
  835. */
  836. static void
  837. set_server_advertised(int s)
  838. {
  839. server_is_advertised = s;
  840. }
  841. /** Return true iff we are trying to be a socks proxy. */
  842. int
  843. proxy_mode(or_options_t *options)
  844. {
  845. return (options->SocksPort != 0 || options->SocksListenAddress ||
  846. options->TransPort != 0 || options->TransListenAddress ||
  847. options->NatdPort != 0 || options->NatdListenAddress ||
  848. options->DNSPort != 0 || options->DNSListenAddress);
  849. }
  850. /** Decide if we're a publishable server. We are a publishable server if:
  851. * - We don't have the ClientOnly option set
  852. * and
  853. * - We have the PublishServerDescriptor option set to non-empty
  854. * and
  855. * - We have ORPort set
  856. * and
  857. * - We believe we are reachable from the outside; or
  858. * - We are an authoritative directory server.
  859. */
  860. static int
  861. decide_if_publishable_server(void)
  862. {
  863. or_options_t *options = get_options();
  864. if (options->ClientOnly)
  865. return 0;
  866. if (options->_PublishServerDescriptor == NO_AUTHORITY)
  867. return 0;
  868. if (!server_mode(options))
  869. return 0;
  870. if (authdir_mode(options))
  871. return 1;
  872. return check_whether_orport_reachable();
  873. }
  874. /** Initiate server descriptor upload as reasonable (if server is publishable,
  875. * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
  876. *
  877. * We need to rebuild the descriptor if it's dirty even if we're not
  878. * uploading, because our reachability testing *uses* our descriptor to
  879. * determine what IP address and ports to test.
  880. */
  881. void
  882. consider_publishable_server(int force)
  883. {
  884. int rebuilt;
  885. if (!server_mode(get_options()))
  886. return;
  887. rebuilt = router_rebuild_descriptor(0);
  888. if (decide_if_publishable_server()) {
  889. set_server_advertised(1);
  890. if (rebuilt == 0)
  891. router_upload_dir_desc_to_dirservers(force);
  892. } else {
  893. set_server_advertised(0);
  894. }
  895. }
  896. /*
  897. * Clique maintenance -- to be phased out.
  898. */
  899. /** Return true iff we believe this OR tries to keep connections open
  900. * to all other ORs. */
  901. int
  902. router_is_clique_mode(routerinfo_t *router)
  903. {
  904. if (router_digest_is_trusted_dir(router->cache_info.identity_digest))
  905. return 1;
  906. return 0;
  907. }
  908. /*
  909. * OR descriptor generation.
  910. */
  911. /** My routerinfo. */
  912. static routerinfo_t *desc_routerinfo = NULL;
  913. /** My extrainfo */
  914. static extrainfo_t *desc_extrainfo = NULL;
  915. /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
  916. * now. */
  917. static time_t desc_clean_since = 0;
  918. /** Boolean: do we need to regenerate the above? */
  919. static int desc_needs_upload = 0;
  920. /** OR only: If <b>force</b> is true, or we haven't uploaded this
  921. * descriptor successfully yet, try to upload our signed descriptor to
  922. * all the directory servers we know about.
  923. */
  924. void
  925. router_upload_dir_desc_to_dirservers(int force)
  926. {
  927. routerinfo_t *ri;
  928. extrainfo_t *ei;
  929. char *msg;
  930. size_t desc_len, extra_len = 0, total_len;
  931. authority_type_t auth = get_options()->_PublishServerDescriptor;
  932. ri = router_get_my_routerinfo();
  933. if (!ri) {
  934. log_info(LD_GENERAL, "No descriptor; skipping upload");
  935. return;
  936. }
  937. ei = router_get_my_extrainfo();
  938. if (auth == NO_AUTHORITY)
  939. return;
  940. if (!force && !desc_needs_upload)
  941. return;
  942. desc_needs_upload = 0;
  943. desc_len = ri->cache_info.signed_descriptor_len;
  944. extra_len = ei ? ei->cache_info.signed_descriptor_len : 0;
  945. total_len = desc_len + extra_len + 1;
  946. msg = tor_malloc(total_len);
  947. memcpy(msg, ri->cache_info.signed_descriptor_body, desc_len);
  948. if (ei) {
  949. memcpy(msg+desc_len, ei->cache_info.signed_descriptor_body, extra_len);
  950. }
  951. msg[desc_len+extra_len] = 0;
  952. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR,
  953. (auth & BRIDGE_AUTHORITY) ?
  954. ROUTER_PURPOSE_BRIDGE :
  955. ROUTER_PURPOSE_GENERAL,
  956. auth, msg, desc_len, extra_len);
  957. tor_free(msg);
  958. }
  959. /** OR only: Check whether my exit policy says to allow connection to
  960. * conn. Return 0 if we accept; non-0 if we reject.
  961. */
  962. int
  963. router_compare_to_my_exit_policy(edge_connection_t *conn)
  964. {
  965. if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
  966. return -1;
  967. /* make sure it's resolved to something. this way we can't get a
  968. 'maybe' below. */
  969. if (!conn->_base.addr)
  970. return -1;
  971. return compare_addr_to_addr_policy(conn->_base.addr, conn->_base.port,
  972. desc_routerinfo->exit_policy) != ADDR_POLICY_ACCEPTED;
  973. }
  974. /** Return true iff I'm a server and <b>digest</b> is equal to
  975. * my identity digest. */
  976. int
  977. router_digest_is_me(const char *digest)
  978. {
  979. return identitykey && !memcmp(identitykey_digest, digest, DIGEST_LEN);
  980. }
  981. /** A wrapper around router_digest_is_me(). */
  982. int
  983. router_is_me(routerinfo_t *router)
  984. {
  985. return router_digest_is_me(router->cache_info.identity_digest);
  986. }
  987. /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
  988. int
  989. router_fingerprint_is_me(const char *fp)
  990. {
  991. char digest[DIGEST_LEN];
  992. if (strlen(fp) == HEX_DIGEST_LEN &&
  993. base16_decode(digest, sizeof(digest), fp, HEX_DIGEST_LEN) == 0)
  994. return router_digest_is_me(digest);
  995. return 0;
  996. }
  997. /** Return a routerinfo for this OR, rebuilding a fresh one if
  998. * necessary. Return NULL on error, or if called on an OP. */
  999. routerinfo_t *
  1000. router_get_my_routerinfo(void)
  1001. {
  1002. if (!server_mode(get_options()))
  1003. return NULL;
  1004. if (router_rebuild_descriptor(0))
  1005. return NULL;
  1006. return desc_routerinfo;
  1007. }
  1008. /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
  1009. * one if necessary. Return NULL on error.
  1010. */
  1011. const char *
  1012. router_get_my_descriptor(void)
  1013. {
  1014. const char *body;
  1015. if (!router_get_my_routerinfo())
  1016. return NULL;
  1017. /* Make sure this is nul-terminated. */
  1018. tor_assert(desc_routerinfo->cache_info.saved_location == SAVED_NOWHERE);
  1019. body = signed_descriptor_get_body(&desc_routerinfo->cache_info);
  1020. tor_assert(!body[desc_routerinfo->cache_info.signed_descriptor_len]);
  1021. log_debug(LD_GENERAL,"my desc is '%s'", body);
  1022. return body;
  1023. }
  1024. /* Return the extrainfo document for this OR, or NULL if we have none.
  1025. * Rebuilt it (and the server descriptor) if necessary. */
  1026. extrainfo_t *
  1027. router_get_my_extrainfo(void)
  1028. {
  1029. if (!server_mode(get_options()))
  1030. return NULL;
  1031. if (router_rebuild_descriptor(0))
  1032. return NULL;
  1033. return desc_extrainfo;
  1034. }
  1035. /** A list of nicknames that we've warned about including in our family
  1036. * declaration verbatim rather than as digests. */
  1037. static smartlist_t *warned_nonexistent_family = NULL;
  1038. static int router_guess_address_from_dir_headers(uint32_t *guess);
  1039. /** Return our current best guess at our address, either because
  1040. * it's configured in torrc, or because we've learned it from
  1041. * dirserver headers. */
  1042. int
  1043. router_pick_published_address(or_options_t *options, uint32_t *addr)
  1044. {
  1045. if (resolve_my_address(LOG_INFO, options, addr, NULL) < 0) {
  1046. log_info(LD_CONFIG, "Could not determine our address locally. "
  1047. "Checking if directory headers provide any hints.");
  1048. if (router_guess_address_from_dir_headers(addr) < 0) {
  1049. log_info(LD_CONFIG, "No hints from directory headers either. "
  1050. "Will try again later.");
  1051. return -1;
  1052. }
  1053. }
  1054. return 0;
  1055. }
  1056. /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
  1057. * routerinfo, signed server descriptor, and extra-info document for this OR.
  1058. * Return 0 on success, -1 on temporary error.
  1059. */
  1060. int
  1061. router_rebuild_descriptor(int force)
  1062. {
  1063. routerinfo_t *ri;
  1064. extrainfo_t *ei;
  1065. uint32_t addr;
  1066. char platform[256];
  1067. int hibernating = we_are_hibernating();
  1068. or_options_t *options = get_options();
  1069. if (desc_clean_since && !force)
  1070. return 0;
  1071. if (router_pick_published_address(options, &addr) < 0) {
  1072. /* Stop trying to rebuild our descriptor every second. We'll
  1073. * learn that it's time to try again when server_has_changed_ip()
  1074. * marks it dirty. */
  1075. desc_clean_since = time(NULL);
  1076. return -1;
  1077. }
  1078. ri = tor_malloc_zero(sizeof(routerinfo_t));
  1079. ri->cache_info.routerlist_index = -1;
  1080. ri->address = tor_dup_addr(addr);
  1081. ri->nickname = tor_strdup(options->Nickname);
  1082. ri->addr = addr;
  1083. ri->or_port = options->ORPort;
  1084. ri->dir_port = options->DirPort;
  1085. ri->cache_info.published_on = time(NULL);
  1086. ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from
  1087. * main thread */
  1088. ri->identity_pkey = crypto_pk_dup_key(get_identity_key());
  1089. if (crypto_pk_get_digest(ri->identity_pkey,
  1090. ri->cache_info.identity_digest)<0) {
  1091. routerinfo_free(ri);
  1092. return -1;
  1093. }
  1094. get_platform_str(platform, sizeof(platform));
  1095. ri->platform = tor_strdup(platform);
  1096. /* compute ri->bandwidthrate as the min of various options */
  1097. ri->bandwidthrate = (int)options->BandwidthRate;
  1098. if (ri->bandwidthrate > options->MaxAdvertisedBandwidth)
  1099. ri->bandwidthrate = (int)options->MaxAdvertisedBandwidth;
  1100. if (options->RelayBandwidthRate > 0 &&
  1101. ri->bandwidthrate > options->RelayBandwidthRate)
  1102. ri->bandwidthrate = (int)options->RelayBandwidthRate;
  1103. /* and compute ri->bandwidthburst similarly */
  1104. ri->bandwidthburst = (int)options->BandwidthBurst;
  1105. if (options->RelayBandwidthBurst > 0 &&
  1106. ri->bandwidthburst > options->RelayBandwidthBurst)
  1107. ri->bandwidthburst = (int)options->RelayBandwidthBurst;
  1108. ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
  1109. policies_parse_exit_policy(options->ExitPolicy, &ri->exit_policy,
  1110. options->ExitPolicyRejectPrivate,
  1111. ri->address);
  1112. if (desc_routerinfo) { /* inherit values */
  1113. ri->is_valid = desc_routerinfo->is_valid;
  1114. ri->is_running = desc_routerinfo->is_running;
  1115. ri->is_named = desc_routerinfo->is_named;
  1116. }
  1117. if (authdir_mode(options))
  1118. ri->is_valid = ri->is_named = 1; /* believe in yourself */
  1119. if (options->MyFamily) {
  1120. smartlist_t *family;
  1121. if (!warned_nonexistent_family)
  1122. warned_nonexistent_family = smartlist_create();
  1123. family = smartlist_create();
  1124. ri->declared_family = smartlist_create();
  1125. smartlist_split_string(family, options->MyFamily, ",",
  1126. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1127. SMARTLIST_FOREACH(family, char *, name,
  1128. {
  1129. routerinfo_t *member;
  1130. if (!strcasecmp(name, options->Nickname))
  1131. member = ri;
  1132. else
  1133. member = router_get_by_nickname(name, 1);
  1134. if (!member) {
  1135. if (!smartlist_string_isin(warned_nonexistent_family, name) &&
  1136. !is_legal_hexdigest(name)) {
  1137. log_warn(LD_CONFIG,
  1138. "I have no descriptor for the router named \"%s\" "
  1139. "in my declared family; I'll use the nickname as is, but "
  1140. "this may confuse clients.", name);
  1141. smartlist_add(warned_nonexistent_family, tor_strdup(name));
  1142. }
  1143. smartlist_add(ri->declared_family, name);
  1144. name = NULL;
  1145. } else if (router_is_me(member)) {
  1146. /* Don't list ourself in our own family; that's redundant */
  1147. } else {
  1148. char *fp = tor_malloc(HEX_DIGEST_LEN+2);
  1149. fp[0] = '$';
  1150. base16_encode(fp+1,HEX_DIGEST_LEN+1,
  1151. member->cache_info.identity_digest, DIGEST_LEN);
  1152. smartlist_add(ri->declared_family, fp);
  1153. if (smartlist_string_isin(warned_nonexistent_family, name))
  1154. smartlist_string_remove(warned_nonexistent_family, name);
  1155. }
  1156. tor_free(name);
  1157. });
  1158. /* remove duplicates from the list */
  1159. smartlist_sort_strings(ri->declared_family);
  1160. smartlist_uniq_strings(ri->declared_family);
  1161. smartlist_free(family);
  1162. }
  1163. /* Now generate the extrainfo. */
  1164. ei = tor_malloc_zero(sizeof(extrainfo_t));
  1165. ei->cache_info.is_extrainfo = 1;
  1166. strlcpy(ei->nickname, get_options()->Nickname, sizeof(ei->nickname));
  1167. ei->cache_info.published_on = ri->cache_info.published_on;
  1168. memcpy(ei->cache_info.identity_digest, ri->cache_info.identity_digest,
  1169. DIGEST_LEN);
  1170. ei->cache_info.signed_descriptor_body = tor_malloc(8192);
  1171. if (extrainfo_dump_to_string(ei->cache_info.signed_descriptor_body, 8192,
  1172. ei, get_identity_key()) < 0) {
  1173. log_warn(LD_BUG, "Couldn't generate extra-info descriptor.");
  1174. return -1;
  1175. }
  1176. ei->cache_info.signed_descriptor_len =
  1177. strlen(ei->cache_info.signed_descriptor_body);
  1178. router_get_extrainfo_hash(ei->cache_info.signed_descriptor_body,
  1179. ei->cache_info.signed_descriptor_digest);
  1180. /* Now finish the router descriptor. */
  1181. memcpy(ri->cache_info.extra_info_digest,
  1182. ei->cache_info.signed_descriptor_digest,
  1183. DIGEST_LEN);
  1184. ri->cache_info.signed_descriptor_body = tor_malloc(8192);
  1185. if (router_dump_router_to_string(ri->cache_info.signed_descriptor_body, 8192,
  1186. ri, get_identity_key())<0) {
  1187. log_warn(LD_BUG, "Couldn't generate router descriptor.");
  1188. return -1;
  1189. }
  1190. ri->cache_info.signed_descriptor_len =
  1191. strlen(ri->cache_info.signed_descriptor_body);
  1192. router_get_router_hash(ri->cache_info.signed_descriptor_body,
  1193. ri->cache_info.signed_descriptor_digest);
  1194. tor_assert(! routerinfo_incompatible_with_extrainfo(ri, ei, NULL, NULL));
  1195. if (desc_routerinfo)
  1196. routerinfo_free(desc_routerinfo);
  1197. desc_routerinfo = ri;
  1198. if (desc_extrainfo)
  1199. extrainfo_free(desc_extrainfo);
  1200. desc_extrainfo = ei;
  1201. desc_clean_since = time(NULL);
  1202. desc_needs_upload = 1;
  1203. control_event_my_descriptor_changed();
  1204. return 0;
  1205. }
  1206. /** Mark descriptor out of date if it's older than <b>when</b> */
  1207. void
  1208. mark_my_descriptor_dirty_if_older_than(time_t when)
  1209. {
  1210. if (desc_clean_since < when)
  1211. mark_my_descriptor_dirty();
  1212. }
  1213. /** Call when the current descriptor is out of date. */
  1214. void
  1215. mark_my_descriptor_dirty(void)
  1216. {
  1217. desc_clean_since = 0;
  1218. }
  1219. /** How frequently will we republish our descriptor because of large (factor
  1220. * of 2) shifts in estimated bandwidth? */
  1221. #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
  1222. /** Check whether bandwidth has changed a lot since the last time we announced
  1223. * bandwidth. If so, mark our descriptor dirty. */
  1224. void
  1225. check_descriptor_bandwidth_changed(time_t now)
  1226. {
  1227. static time_t last_changed = 0;
  1228. uint64_t prev, cur;
  1229. if (!desc_routerinfo)
  1230. return;
  1231. prev = desc_routerinfo->bandwidthcapacity;
  1232. cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
  1233. if ((prev != cur && (!prev || !cur)) ||
  1234. cur > prev*2 ||
  1235. cur < prev/2) {
  1236. if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now) {
  1237. log_info(LD_GENERAL,
  1238. "Measured bandwidth has changed; rebuilding descriptor.");
  1239. mark_my_descriptor_dirty();
  1240. last_changed = now;
  1241. }
  1242. }
  1243. }
  1244. /** Note at log level severity that our best guess of address has changed from
  1245. * <b>prev</b> to <b>cur</b>. */
  1246. static void
  1247. log_addr_has_changed(int severity, uint32_t prev, uint32_t cur)
  1248. {
  1249. char addrbuf_prev[INET_NTOA_BUF_LEN];
  1250. char addrbuf_cur[INET_NTOA_BUF_LEN];
  1251. struct in_addr in_prev;
  1252. struct in_addr in_cur;
  1253. in_prev.s_addr = htonl(prev);
  1254. tor_inet_ntoa(&in_prev, addrbuf_prev, sizeof(addrbuf_prev));
  1255. in_cur.s_addr = htonl(cur);
  1256. tor_inet_ntoa(&in_cur, addrbuf_cur, sizeof(addrbuf_cur));
  1257. if (prev)
  1258. log_fn(severity, LD_GENERAL,
  1259. "Our IP Address has changed from %s to %s; "
  1260. "rebuilding descriptor.",
  1261. addrbuf_prev, addrbuf_cur);
  1262. else
  1263. log_notice(LD_GENERAL,
  1264. "Guessed our IP address as %s.",
  1265. addrbuf_cur);
  1266. }
  1267. /** Check whether our own address as defined by the Address configuration
  1268. * has changed. This is for routers that get their address from a service
  1269. * like dyndns. If our address has changed, mark our descriptor dirty. */
  1270. void
  1271. check_descriptor_ipaddress_changed(time_t now)
  1272. {
  1273. uint32_t prev, cur;
  1274. or_options_t *options = get_options();
  1275. (void) now;
  1276. if (!desc_routerinfo)
  1277. return;
  1278. prev = desc_routerinfo->addr;
  1279. if (resolve_my_address(LOG_INFO, options, &cur, NULL) < 0) {
  1280. log_info(LD_CONFIG,"options->Address didn't resolve into an IP.");
  1281. return;
  1282. }
  1283. if (prev != cur) {
  1284. log_addr_has_changed(LOG_INFO, prev, cur);
  1285. ip_address_changed(0);
  1286. }
  1287. }
  1288. /** The most recently guessed value of our IP address, based on directory
  1289. * headers. */
  1290. static uint32_t last_guessed_ip = 0;
  1291. /** A directory server told us our IP address is <b>suggestion</b>.
  1292. * If this address is different from the one we think we are now, and
  1293. * if our computer doesn't actually know its IP address, then switch. */
  1294. void
  1295. router_new_address_suggestion(const char *suggestion)
  1296. {
  1297. uint32_t addr, cur = 0;
  1298. struct in_addr in;
  1299. or_options_t *options = get_options();
  1300. /* first, learn what the IP address actually is */
  1301. if (!tor_inet_aton(suggestion, &in)) {
  1302. log_debug(LD_DIR, "Malformed X-Your-Address-Is header %s. Ignoring.",
  1303. escaped(suggestion));
  1304. return;
  1305. }
  1306. addr = ntohl(in.s_addr);
  1307. log_debug(LD_DIR, "Got X-Your-Address-Is: %s.", suggestion);
  1308. if (!server_mode(options)) {
  1309. last_guessed_ip = addr; /* store it in case we need it later */
  1310. return;
  1311. }
  1312. if (resolve_my_address(LOG_INFO, options, &cur, NULL) >= 0) {
  1313. /* We're all set -- we already know our address. Great. */
  1314. last_guessed_ip = cur; /* store it in case we need it later */
  1315. return;
  1316. }
  1317. if (is_internal_IP(addr, 0)) {
  1318. /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
  1319. return;
  1320. }
  1321. /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
  1322. * us an answer different from what we had the last time we managed to
  1323. * resolve it. */
  1324. if (last_guessed_ip != addr) {
  1325. control_event_server_status(LOG_NOTICE,
  1326. "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
  1327. suggestion);
  1328. log_addr_has_changed(LOG_NOTICE, last_guessed_ip, addr);
  1329. ip_address_changed(0);
  1330. last_guessed_ip = addr; /* router_rebuild_descriptor() will fetch it */
  1331. }
  1332. }
  1333. /** We failed to resolve our address locally, but we'd like to build
  1334. * a descriptor and publish / test reachability. If we have a guess
  1335. * about our address based on directory headers, answer it and return
  1336. * 0; else return -1. */
  1337. static int
  1338. router_guess_address_from_dir_headers(uint32_t *guess)
  1339. {
  1340. if (last_guessed_ip) {
  1341. *guess = last_guessed_ip;
  1342. return 0;
  1343. }
  1344. return -1;
  1345. }
  1346. extern const char tor_svn_revision[]; /* from main.c */
  1347. /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
  1348. * string describing the version of Tor and the operating system we're
  1349. * currently running on.
  1350. */
  1351. void
  1352. get_platform_str(char *platform, size_t len)
  1353. {
  1354. tor_snprintf(platform, len, "Tor %s on %s", get_version(), get_uname());
  1355. }
  1356. /* XXX need to audit this thing and count fenceposts. maybe
  1357. * refactor so we don't have to keep asking if we're
  1358. * near the end of maxlen?
  1359. */
  1360. #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  1361. /** OR only: Given a routerinfo for this router, and an identity key to sign
  1362. * with, encode the routerinfo as a signed server descriptor and write the
  1363. * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
  1364. * failure, and the number of bytes used on success.
  1365. */
  1366. int
  1367. router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
  1368. crypto_pk_env_t *ident_key)
  1369. {
  1370. char *onion_pkey; /* Onion key, PEM-encoded. */
  1371. char *identity_pkey; /* Identity key, PEM-encoded. */
  1372. char digest[DIGEST_LEN];
  1373. char published[ISO_TIME_LEN+1];
  1374. char fingerprint[FINGERPRINT_LEN+1];
  1375. char extra_info_digest[HEX_DIGEST_LEN+1];
  1376. size_t onion_pkeylen, identity_pkeylen;
  1377. size_t written;
  1378. int result=0;
  1379. addr_policy_t *tmpe;
  1380. char *family_line;
  1381. or_options_t *options = get_options();
  1382. /* Make sure the identity key matches the one in the routerinfo. */
  1383. if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
  1384. log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
  1385. "match router's public key!");
  1386. return -1;
  1387. }
  1388. /* record our fingerprint, so we can include it in the descriptor */
  1389. if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
  1390. log_err(LD_BUG,"Error computing fingerprint");
  1391. return -1;
  1392. }
  1393. /* PEM-encode the onion key */
  1394. if (crypto_pk_write_public_key_to_string(router->onion_pkey,
  1395. &onion_pkey,&onion_pkeylen)<0) {
  1396. log_warn(LD_BUG,"write onion_pkey to string failed!");
  1397. return -1;
  1398. }
  1399. /* PEM-encode the identity key key */
  1400. if (crypto_pk_write_public_key_to_string(router->identity_pkey,
  1401. &identity_pkey,&identity_pkeylen)<0) {
  1402. log_warn(LD_BUG,"write identity_pkey to string failed!");
  1403. tor_free(onion_pkey);
  1404. return -1;
  1405. }
  1406. /* Encode the publication time. */
  1407. format_iso_time(published, router->cache_info.published_on);
  1408. if (router->declared_family && smartlist_len(router->declared_family)) {
  1409. size_t n;
  1410. char *family = smartlist_join_strings(router->declared_family, " ", 0, &n);
  1411. n += strlen("family ") + 2; /* 1 for \n, 1 for \0. */
  1412. family_line = tor_malloc(n);
  1413. tor_snprintf(family_line, n, "family %s\n", family);
  1414. tor_free(family);
  1415. } else {
  1416. family_line = tor_strdup("");
  1417. }
  1418. base16_encode(extra_info_digest, sizeof(extra_info_digest),
  1419. router->cache_info.extra_info_digest, DIGEST_LEN);
  1420. /* Generate the easy portion of the router descriptor. */
  1421. result = tor_snprintf(s, maxlen,
  1422. "router %s %s %d 0 %d\n"
  1423. "platform %s\n"
  1424. "opt protocols Link 1 Circuit 1\n"
  1425. "published %s\n"
  1426. "opt fingerprint %s\n"
  1427. "uptime %ld\n"
  1428. "bandwidth %d %d %d\n"
  1429. "opt extra-info-digest %s\n%s"
  1430. "onion-key\n%s"
  1431. "signing-key\n%s"
  1432. "%s%s%s",
  1433. router->nickname,
  1434. router->address,
  1435. router->or_port,
  1436. decide_to_advertise_dirport(options, router->dir_port),
  1437. router->platform,
  1438. published,
  1439. fingerprint,
  1440. stats_n_seconds_working,
  1441. (int) router->bandwidthrate,
  1442. (int) router->bandwidthburst,
  1443. (int) router->bandwidthcapacity,
  1444. extra_info_digest,
  1445. options->DownloadExtraInfo ? "opt caches-extra-info\n" : "",
  1446. onion_pkey, identity_pkey,
  1447. family_line,
  1448. we_are_hibernating() ? "opt hibernating 1\n" : "",
  1449. options->HidServDirectoryV2 ? "opt hidden-service-dir\n" : "");
  1450. tor_free(family_line);
  1451. tor_free(onion_pkey);
  1452. tor_free(identity_pkey);
  1453. if (result < 0) {
  1454. log_warn(LD_BUG,"descriptor snprintf #1 ran out of room!");
  1455. return -1;
  1456. }
  1457. /* From now on, we use 'written' to remember the current length of 's'. */
  1458. written = result;
  1459. if (options->ContactInfo && strlen(options->ContactInfo)) {
  1460. result = tor_snprintf(s+written,maxlen-written, "contact %s\n",
  1461. options->ContactInfo);
  1462. if (result<0) {
  1463. log_warn(LD_BUG,"descriptor snprintf #2 ran out of room!");
  1464. return -1;
  1465. }
  1466. written += result;
  1467. }
  1468. /* Write the exit policy to the end of 's'. */
  1469. tmpe = router->exit_policy;
  1470. if (dns_seems_to_be_broken()) {
  1471. /* DNS is screwed up; don't claim to be an exit. */
  1472. strlcat(s+written, "reject *:*\n", maxlen-written);
  1473. written += strlen("reject *:*\n");
  1474. tmpe = NULL;
  1475. }
  1476. for ( ; tmpe; tmpe=tmpe->next) {
  1477. result = policy_write_item(s+written, maxlen-written, tmpe);
  1478. if (result < 0) {
  1479. log_warn(LD_BUG,"descriptor policy_write_item ran out of room!");
  1480. return -1;
  1481. }
  1482. tor_assert(result == (int)strlen(s+written));
  1483. written += result;
  1484. if (written+2 > maxlen) {
  1485. log_warn(LD_BUG,"descriptor policy_write_item ran out of room (2)!");
  1486. return -1;
  1487. }
  1488. s[written++] = '\n';
  1489. }
  1490. if (written+256 > maxlen) { /* Not enough room for signature. */
  1491. log_warn(LD_BUG,"not enough room left in descriptor for signature!");
  1492. return -1;
  1493. }
  1494. /* Sign the directory */
  1495. strlcpy(s+written, "router-signature\n", maxlen-written);
  1496. written += strlen(s+written);
  1497. s[written] = '\0';
  1498. if (router_get_router_hash(s, digest) < 0) {
  1499. return -1;
  1500. }
  1501. note_crypto_pk_op(SIGN_RTR);
  1502. if (router_append_dirobj_signature(s+written,maxlen-written,
  1503. digest,ident_key)<0) {
  1504. log_warn(LD_BUG, "Couldn't sign router descriptor");
  1505. return -1;
  1506. }
  1507. written += strlen(s+written);
  1508. if (written+2 > maxlen) {
  1509. log_warn(LD_BUG,"Not enough room to finish descriptor.");
  1510. return -1;
  1511. }
  1512. /* include a last '\n' */
  1513. s[written] = '\n';
  1514. s[written+1] = 0;
  1515. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  1516. {
  1517. char *s_dup;
  1518. const char *cp;
  1519. routerinfo_t *ri_tmp;
  1520. cp = s_dup = tor_strdup(s);
  1521. ri_tmp = router_parse_entry_from_string(cp, NULL, 1, 0, NULL);
  1522. if (!ri_tmp) {
  1523. log_err(LD_BUG,
  1524. "We just generated a router descriptor we can't parse.");
  1525. log_err(LD_BUG, "Descriptor was: <<%s>>", s);
  1526. return -1;
  1527. }
  1528. tor_free(s_dup);
  1529. routerinfo_free(ri_tmp);
  1530. }
  1531. #endif
  1532. return written+1;
  1533. }
  1534. /** Write the contents of <b>extrainfo</b> to the <b>maxlen</b>-byte string
  1535. * <b>s</b>, signing them with <b>ident_key</b>. Return 0 on success,
  1536. * negative on failure. */
  1537. int
  1538. extrainfo_dump_to_string(char *s, size_t maxlen, extrainfo_t *extrainfo,
  1539. crypto_pk_env_t *ident_key)
  1540. {
  1541. char identity[HEX_DIGEST_LEN+1];
  1542. char published[ISO_TIME_LEN+1];
  1543. char digest[DIGEST_LEN];
  1544. char *bandwidth_usage;
  1545. int result;
  1546. size_t len;
  1547. base16_encode(identity, sizeof(identity),
  1548. extrainfo->cache_info.identity_digest, DIGEST_LEN);
  1549. format_iso_time(published, extrainfo->cache_info.published_on);
  1550. bandwidth_usage = rep_hist_get_bandwidth_lines(1);
  1551. result = tor_snprintf(s, maxlen,
  1552. "extra-info %s %s\n"
  1553. "published %s\n%s"
  1554. "router-signature\n",
  1555. extrainfo->nickname, identity,
  1556. published, bandwidth_usage);
  1557. tor_free(bandwidth_usage);
  1558. if (result<0)
  1559. return -1;
  1560. len = strlen(s);
  1561. if (router_get_extrainfo_hash(s, digest)<0)
  1562. return -1;
  1563. if (router_append_dirobj_signature(s+len, maxlen-len, digest, ident_key)<0)
  1564. return -1;
  1565. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  1566. {
  1567. char *cp, *s_dup;
  1568. extrainfo_t *ei_tmp;
  1569. cp = s_dup = tor_strdup(s);
  1570. ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL);
  1571. if (!ei_tmp) {
  1572. log_err(LD_BUG,
  1573. "We just generated an extrainfo descriptor we can't parse.");
  1574. log_err(LD_BUG, "Descriptor was: <<%s>>", s);
  1575. return -1;
  1576. }
  1577. tor_free(s_dup);
  1578. extrainfo_free(ei_tmp);
  1579. }
  1580. #endif
  1581. return strlen(s)+1;
  1582. }
  1583. /** Return true iff <b>s</b> is a legally valid server nickname. */
  1584. int
  1585. is_legal_nickname(const char *s)
  1586. {
  1587. size_t len;
  1588. tor_assert(s);
  1589. len = strlen(s);
  1590. return len > 0 && len <= MAX_NICKNAME_LEN &&
  1591. strspn(s,LEGAL_NICKNAME_CHARACTERS) == len;
  1592. }
  1593. /** Return true iff <b>s</b> is a legally valid server nickname or
  1594. * hex-encoded identity-key digest. */
  1595. int
  1596. is_legal_nickname_or_hexdigest(const char *s)
  1597. {
  1598. if (*s!='$')
  1599. return is_legal_nickname(s);
  1600. else
  1601. return is_legal_hexdigest(s);
  1602. }
  1603. /** Return true iff <b>s</b> is a legally valid hex-encoded identity-key
  1604. * digest. */
  1605. int
  1606. is_legal_hexdigest(const char *s)
  1607. {
  1608. size_t len;
  1609. tor_assert(s);
  1610. if (s[0] == '$') s++;
  1611. len = strlen(s);
  1612. if (len > HEX_DIGEST_LEN) {
  1613. if (s[HEX_DIGEST_LEN] == '=' ||
  1614. s[HEX_DIGEST_LEN] == '~') {
  1615. if (!is_legal_nickname(s+HEX_DIGEST_LEN+1))
  1616. return 0;
  1617. } else {
  1618. return 0;
  1619. }
  1620. }
  1621. return (len >= HEX_DIGEST_LEN &&
  1622. strspn(s,HEX_CHARACTERS)==HEX_DIGEST_LEN);
  1623. }
  1624. /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
  1625. * verbose representation of the identity of <b>router</b>. The format is:
  1626. * A dollar sign.
  1627. * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
  1628. * A "=" if the router is named; a "~" if it is not.
  1629. * The router's nickname.
  1630. **/
  1631. void
  1632. router_get_verbose_nickname(char *buf, routerinfo_t *router)
  1633. {
  1634. buf[0] = '$';
  1635. base16_encode(buf+1, HEX_DIGEST_LEN+1, router->cache_info.identity_digest,
  1636. DIGEST_LEN);
  1637. buf[1+HEX_DIGEST_LEN] = router->is_named ? '=' : '~';
  1638. strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
  1639. }
  1640. /** Forget that we have issued any router-related warnings, so that we'll
  1641. * warn again if we see the same errors. */
  1642. void
  1643. router_reset_warnings(void)
  1644. {
  1645. if (warned_nonexistent_family) {
  1646. SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
  1647. smartlist_clear(warned_nonexistent_family);
  1648. }
  1649. }
  1650. /** Given a router purpose, convert it to a string. Don't call this on
  1651. * ROUTER_PURPOSE_UNKNOWN: The whole point of that value is that we don't
  1652. * know its string representation. */
  1653. const char *
  1654. router_purpose_to_string(uint8_t p)
  1655. {
  1656. switch (p)
  1657. {
  1658. case ROUTER_PURPOSE_GENERAL: return "general";
  1659. case ROUTER_PURPOSE_BRIDGE: return "bridge";
  1660. case ROUTER_PURPOSE_CONTROLLER: return "controller";
  1661. default:
  1662. tor_assert(0);
  1663. }
  1664. return NULL;
  1665. }
  1666. /** Given a string, convert it to a router purpose. */
  1667. uint8_t
  1668. router_purpose_from_string(const char *s)
  1669. {
  1670. if (!strcmp(s, "general"))
  1671. return ROUTER_PURPOSE_GENERAL;
  1672. else if (!strcmp(s, "bridge"))
  1673. return ROUTER_PURPOSE_BRIDGE;
  1674. else if (!strcmp(s, "controller"))
  1675. return ROUTER_PURPOSE_CONTROLLER;
  1676. else
  1677. return ROUTER_PURPOSE_UNKNOWN;
  1678. }
  1679. /** Release all static resources held in router.c */
  1680. void
  1681. router_free_all(void)
  1682. {
  1683. if (onionkey)
  1684. crypto_free_pk_env(onionkey);
  1685. if (lastonionkey)
  1686. crypto_free_pk_env(lastonionkey);
  1687. if (identitykey)
  1688. crypto_free_pk_env(identitykey);
  1689. if (key_lock)
  1690. tor_mutex_free(key_lock);
  1691. if (desc_routerinfo)
  1692. routerinfo_free(desc_routerinfo);
  1693. if (desc_extrainfo)
  1694. extrainfo_free(desc_extrainfo);
  1695. if (authority_signing_key)
  1696. crypto_free_pk_env(authority_signing_key);
  1697. if (authority_key_certificate)
  1698. authority_cert_free(authority_key_certificate);
  1699. if (warned_nonexistent_family) {
  1700. SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
  1701. smartlist_free(warned_nonexistent_family);
  1702. }
  1703. }