router.c 73 KB

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