router.c 56 KB

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