router.c 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303
  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. dirinfo_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_DIRINFO : NO_DIRINFO) |
  648. (options->V2AuthoritativeDir ? V2_DIRINFO : NO_DIRINFO) |
  649. (options->V3AuthoritativeDir ?
  650. (V3_DIRINFO|MICRODESC_DIRINFO|EXTRAINFO_DIRINFO) : NO_DIRINFO) |
  651. (options->BridgeAuthoritativeDir ? BRIDGE_DIRINFO : NO_DIRINFO) |
  652. (options->HSAuthoritativeDir ? HIDSERV_DIRINFO : NO_DIRINFO));
  653. ds = router_get_trusteddirserver_by_digest(digest);
  654. if (!ds) {
  655. ds = add_trusted_dir_server(options->Nickname, NULL,
  656. (uint16_t)options->DirPort,
  657. (uint16_t)options->ORPort,
  658. digest,
  659. v3_digest,
  660. type);
  661. if (!ds) {
  662. log_err(LD_GENERAL,"We want to be a directory authority, but we "
  663. "couldn't add ourselves to the authority list. Failing.");
  664. return -1;
  665. }
  666. }
  667. if (ds->type != type) {
  668. log_warn(LD_DIR, "Configured authority type does not match authority "
  669. "type in DirServer list. Adjusting. (%d v %d)",
  670. type, ds->type);
  671. ds->type = type;
  672. }
  673. if (v3_digest_set && (ds->type & V3_DIRINFO) &&
  674. tor_memneq(v3_digest, ds->v3_identity_digest, DIGEST_LEN)) {
  675. log_warn(LD_DIR, "V3 identity key does not match identity declared in "
  676. "DirServer line. Adjusting.");
  677. memcpy(ds->v3_identity_digest, v3_digest, DIGEST_LEN);
  678. }
  679. if (cert) { /* add my own cert to the list of known certs */
  680. log_info(LD_DIR, "adding my own v3 cert");
  681. if (trusted_dirs_load_certs_from_string(
  682. cert->cache_info.signed_descriptor_body, 0, 0)<0) {
  683. log_warn(LD_DIR, "Unable to parse my own v3 cert! Failing.");
  684. return -1;
  685. }
  686. }
  687. return 0; /* success */
  688. }
  689. /* Keep track of whether we should upload our server descriptor,
  690. * and what type of server we are.
  691. */
  692. /** Whether we can reach our ORPort from the outside. */
  693. static int can_reach_or_port = 0;
  694. /** Whether we can reach our DirPort from the outside. */
  695. static int can_reach_dir_port = 0;
  696. /** Forget what we have learned about our reachability status. */
  697. void
  698. router_reset_reachability(void)
  699. {
  700. can_reach_or_port = can_reach_dir_port = 0;
  701. }
  702. /** Return 1 if ORPort is known reachable; else return 0. */
  703. int
  704. check_whether_orport_reachable(void)
  705. {
  706. or_options_t *options = get_options();
  707. return options->AssumeReachable ||
  708. can_reach_or_port;
  709. }
  710. /** Return 1 if we don't have a dirport configured, or if it's reachable. */
  711. int
  712. check_whether_dirport_reachable(void)
  713. {
  714. or_options_t *options = get_options();
  715. return !options->DirPort ||
  716. options->AssumeReachable ||
  717. we_are_hibernating() ||
  718. can_reach_dir_port;
  719. }
  720. /** Look at a variety of factors, and return 0 if we don't want to
  721. * advertise the fact that we have a DirPort open. Else return the
  722. * DirPort we want to advertise.
  723. *
  724. * Log a helpful message if we change our mind about whether to publish
  725. * a DirPort.
  726. */
  727. static int
  728. decide_to_advertise_dirport(or_options_t *options, uint16_t dir_port)
  729. {
  730. static int advertising=1; /* start out assuming we will advertise */
  731. int new_choice=1;
  732. const char *reason = NULL;
  733. /* Section one: reasons to publish or not publish that aren't
  734. * worth mentioning to the user, either because they're obvious
  735. * or because they're normal behavior. */
  736. if (!dir_port) /* short circuit the rest of the function */
  737. return 0;
  738. if (authdir_mode(options)) /* always publish */
  739. return dir_port;
  740. if (we_are_hibernating())
  741. return 0;
  742. if (!check_whether_dirport_reachable())
  743. return 0;
  744. /* Section two: reasons to publish or not publish that the user
  745. * might find surprising. These are generally config options that
  746. * make us choose not to publish. */
  747. if (accounting_is_enabled(options)) {
  748. /* if we might potentially hibernate */
  749. new_choice = 0;
  750. reason = "AccountingMax enabled";
  751. #define MIN_BW_TO_ADVERTISE_DIRPORT 51200
  752. } else if (options->BandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT ||
  753. (options->RelayBandwidthRate > 0 &&
  754. options->RelayBandwidthRate < MIN_BW_TO_ADVERTISE_DIRPORT)) {
  755. /* if we're advertising a small amount */
  756. new_choice = 0;
  757. reason = "BandwidthRate under 50KB";
  758. }
  759. if (advertising != new_choice) {
  760. if (new_choice == 1) {
  761. log(LOG_NOTICE, LD_DIR, "Advertising DirPort as %d", dir_port);
  762. } else {
  763. tor_assert(reason);
  764. log(LOG_NOTICE, LD_DIR, "Not advertising DirPort (Reason: %s)", reason);
  765. }
  766. advertising = new_choice;
  767. }
  768. return advertising ? dir_port : 0;
  769. }
  770. /** Some time has passed, or we just got new directory information.
  771. * See if we currently believe our ORPort or DirPort to be
  772. * unreachable. If so, launch a new test for it.
  773. *
  774. * For ORPort, we simply try making a circuit that ends at ourselves.
  775. * Success is noticed in onionskin_answer().
  776. *
  777. * For DirPort, we make a connection via Tor to our DirPort and ask
  778. * for our own server descriptor.
  779. * Success is noticed in connection_dir_client_reached_eof().
  780. */
  781. void
  782. consider_testing_reachability(int test_or, int test_dir)
  783. {
  784. const routerinfo_t *me = router_get_my_routerinfo();
  785. int orport_reachable = check_whether_orport_reachable();
  786. tor_addr_t addr;
  787. or_options_t *options = get_options();
  788. if (!me)
  789. return;
  790. if (routerset_contains_router(options->ExcludeNodes, me, -1) &&
  791. options->StrictNodes) {
  792. /* If we've excluded ourself, and StrictNodes is set, we can't test
  793. * ourself. */
  794. if (test_or || test_dir) {
  795. #define SELF_EXCLUDED_WARN_INTERVAL 3600
  796. static ratelim_t warning_limit=RATELIM_INIT(SELF_EXCLUDED_WARN_INTERVAL);
  797. char *msg;
  798. if ((msg = rate_limit_log(&warning_limit, approx_time()))) {
  799. log_warn(LD_CIRC, "Can't peform self-tests for this relay: we have "
  800. "listed ourself in ExcludeNodes, and StrictNodes is set. "
  801. "We cannot learn whether we are usable, and will not "
  802. "be able to advertise ourself.%s", msg);
  803. tor_free(msg);
  804. }
  805. }
  806. return;
  807. }
  808. if (test_or && (!orport_reachable || !circuit_enough_testing_circs())) {
  809. extend_info_t *ei;
  810. log_info(LD_CIRC, "Testing %s of my ORPort: %s:%d.",
  811. !orport_reachable ? "reachability" : "bandwidth",
  812. me->address, me->or_port);
  813. ei = extend_info_from_router(me);
  814. circuit_launch_by_extend_info(CIRCUIT_PURPOSE_TESTING, ei,
  815. CIRCLAUNCH_NEED_CAPACITY|CIRCLAUNCH_IS_INTERNAL);
  816. extend_info_free(ei);
  817. }
  818. tor_addr_from_ipv4h(&addr, me->addr);
  819. if (test_dir && !check_whether_dirport_reachable() &&
  820. !connection_get_by_type_addr_port_purpose(
  821. CONN_TYPE_DIR, &addr, me->dir_port,
  822. DIR_PURPOSE_FETCH_SERVERDESC)) {
  823. /* ask myself, via tor, for my server descriptor. */
  824. directory_initiate_command(me->address, &addr,
  825. me->or_port, me->dir_port,
  826. 0, /* does not matter */
  827. 0, me->cache_info.identity_digest,
  828. DIR_PURPOSE_FETCH_SERVERDESC,
  829. ROUTER_PURPOSE_GENERAL,
  830. 1, "authority.z", NULL, 0, 0);
  831. }
  832. }
  833. /** Annotate that we found our ORPort reachable. */
  834. void
  835. router_orport_found_reachable(void)
  836. {
  837. const routerinfo_t *me = router_get_my_routerinfo();
  838. if (!can_reach_or_port && me) {
  839. log_notice(LD_OR,"Self-testing indicates your ORPort is reachable from "
  840. "the outside. Excellent.%s",
  841. get_options()->_PublishServerDescriptor != NO_DIRINFO ?
  842. " Publishing server descriptor." : "");
  843. can_reach_or_port = 1;
  844. mark_my_descriptor_dirty();
  845. control_event_server_status(LOG_NOTICE,
  846. "REACHABILITY_SUCCEEDED ORADDRESS=%s:%d",
  847. me->address, me->or_port);
  848. }
  849. }
  850. /** Annotate that we found our DirPort reachable. */
  851. void
  852. router_dirport_found_reachable(void)
  853. {
  854. const routerinfo_t *me = router_get_my_routerinfo();
  855. if (!can_reach_dir_port && me) {
  856. log_notice(LD_DIRSERV,"Self-testing indicates your DirPort is reachable "
  857. "from the outside. Excellent.");
  858. can_reach_dir_port = 1;
  859. if (decide_to_advertise_dirport(get_options(), me->dir_port))
  860. mark_my_descriptor_dirty();
  861. control_event_server_status(LOG_NOTICE,
  862. "REACHABILITY_SUCCEEDED DIRADDRESS=%s:%d",
  863. me->address, me->dir_port);
  864. }
  865. }
  866. /** We have enough testing circuits open. Send a bunch of "drop"
  867. * cells down each of them, to exercise our bandwidth. */
  868. void
  869. router_perform_bandwidth_test(int num_circs, time_t now)
  870. {
  871. int num_cells = (int)(get_options()->BandwidthRate * 10 / CELL_NETWORK_SIZE);
  872. int max_cells = num_cells < CIRCWINDOW_START ?
  873. num_cells : CIRCWINDOW_START;
  874. int cells_per_circuit = max_cells / num_circs;
  875. origin_circuit_t *circ = NULL;
  876. log_notice(LD_OR,"Performing bandwidth self-test...done.");
  877. while ((circ = circuit_get_next_by_pk_and_purpose(circ, NULL,
  878. CIRCUIT_PURPOSE_TESTING))) {
  879. /* dump cells_per_circuit drop cells onto this circ */
  880. int i = cells_per_circuit;
  881. if (circ->_base.state != CIRCUIT_STATE_OPEN)
  882. continue;
  883. circ->_base.timestamp_dirty = now;
  884. while (i-- > 0) {
  885. if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
  886. RELAY_COMMAND_DROP,
  887. NULL, 0, circ->cpath->prev)<0) {
  888. return; /* stop if error */
  889. }
  890. }
  891. }
  892. }
  893. /** Return true iff we believe ourselves to be an authoritative
  894. * directory server.
  895. */
  896. int
  897. authdir_mode(or_options_t *options)
  898. {
  899. return options->AuthoritativeDir != 0;
  900. }
  901. /** Return true iff we believe ourselves to be a v1 authoritative
  902. * directory server.
  903. */
  904. int
  905. authdir_mode_v1(or_options_t *options)
  906. {
  907. return authdir_mode(options) && options->V1AuthoritativeDir != 0;
  908. }
  909. /** Return true iff we believe ourselves to be a v2 authoritative
  910. * directory server.
  911. */
  912. int
  913. authdir_mode_v2(or_options_t *options)
  914. {
  915. return authdir_mode(options) && options->V2AuthoritativeDir != 0;
  916. }
  917. /** Return true iff we believe ourselves to be a v3 authoritative
  918. * directory server.
  919. */
  920. int
  921. authdir_mode_v3(or_options_t *options)
  922. {
  923. return authdir_mode(options) && options->V3AuthoritativeDir != 0;
  924. }
  925. /** Return true iff we are a v1, v2, or v3 directory authority. */
  926. int
  927. authdir_mode_any_main(or_options_t *options)
  928. {
  929. return options->V1AuthoritativeDir ||
  930. options->V2AuthoritativeDir ||
  931. options->V3AuthoritativeDir;
  932. }
  933. /** Return true if we believe ourselves to be any kind of
  934. * authoritative directory beyond just a hidserv authority. */
  935. int
  936. authdir_mode_any_nonhidserv(or_options_t *options)
  937. {
  938. return options->BridgeAuthoritativeDir ||
  939. authdir_mode_any_main(options);
  940. }
  941. /** Return true iff we are an authoritative directory server that is
  942. * authoritative about receiving and serving descriptors of type
  943. * <b>purpose</b> its dirport. Use -1 for "any purpose". */
  944. int
  945. authdir_mode_handles_descs(or_options_t *options, int purpose)
  946. {
  947. if (purpose < 0)
  948. return authdir_mode_any_nonhidserv(options);
  949. else if (purpose == ROUTER_PURPOSE_GENERAL)
  950. return authdir_mode_any_main(options);
  951. else if (purpose == ROUTER_PURPOSE_BRIDGE)
  952. return (options->BridgeAuthoritativeDir);
  953. else
  954. return 0;
  955. }
  956. /** Return true iff we are an authoritative directory server that
  957. * publishes its own network statuses.
  958. */
  959. int
  960. authdir_mode_publishes_statuses(or_options_t *options)
  961. {
  962. if (authdir_mode_bridge(options))
  963. return 0;
  964. return authdir_mode_any_nonhidserv(options);
  965. }
  966. /** Return true iff we are an authoritative directory server that
  967. * tests reachability of the descriptors it learns about.
  968. */
  969. int
  970. authdir_mode_tests_reachability(or_options_t *options)
  971. {
  972. return authdir_mode_handles_descs(options, -1);
  973. }
  974. /** Return true iff we believe ourselves to be a bridge authoritative
  975. * directory server.
  976. */
  977. int
  978. authdir_mode_bridge(or_options_t *options)
  979. {
  980. return authdir_mode(options) && options->BridgeAuthoritativeDir != 0;
  981. }
  982. /** Return true iff we are trying to be a server.
  983. */
  984. int
  985. server_mode(or_options_t *options)
  986. {
  987. if (options->ClientOnly) return 0;
  988. return (options->ORPort != 0 || options->ORListenAddress);
  989. }
  990. /** Return true iff we are trying to be a non-bridge server.
  991. */
  992. int
  993. public_server_mode(or_options_t *options)
  994. {
  995. if (!server_mode(options)) return 0;
  996. return (!options->BridgeRelay);
  997. }
  998. /** Return true iff the combination of options in <b>options</b> and parameters
  999. * in the consensus mean that we don't want to allow exits from circuits
  1000. * we got from addresses not known to be servers. */
  1001. int
  1002. should_refuse_unknown_exits(or_options_t *options)
  1003. {
  1004. if (options->RefuseUnknownExits != -1) {
  1005. return options->RefuseUnknownExits;
  1006. } else {
  1007. return networkstatus_get_param(NULL, "refuseunknownexits", 1, 0, 1);
  1008. }
  1009. }
  1010. /** Remember if we've advertised ourselves to the dirservers. */
  1011. static int server_is_advertised=0;
  1012. /** Return true iff we have published our descriptor lately.
  1013. */
  1014. int
  1015. advertised_server_mode(void)
  1016. {
  1017. return server_is_advertised;
  1018. }
  1019. /**
  1020. * Called with a boolean: set whether we have recently published our
  1021. * descriptor.
  1022. */
  1023. static void
  1024. set_server_advertised(int s)
  1025. {
  1026. server_is_advertised = s;
  1027. }
  1028. /** Return true iff we are trying to be a socks proxy. */
  1029. int
  1030. proxy_mode(or_options_t *options)
  1031. {
  1032. return (options->SocksPort != 0 ||
  1033. options->TransPort != 0 ||
  1034. options->NATDPort != 0 ||
  1035. options->DNSPort != 0);
  1036. }
  1037. /** Decide if we're a publishable server. We are a publishable server if:
  1038. * - We don't have the ClientOnly option set
  1039. * and
  1040. * - We have the PublishServerDescriptor option set to non-empty
  1041. * and
  1042. * - We have ORPort set
  1043. * and
  1044. * - We believe we are reachable from the outside; or
  1045. * - We are an authoritative directory server.
  1046. */
  1047. static int
  1048. decide_if_publishable_server(void)
  1049. {
  1050. or_options_t *options = get_options();
  1051. if (options->ClientOnly)
  1052. return 0;
  1053. if (options->_PublishServerDescriptor == NO_DIRINFO)
  1054. return 0;
  1055. if (!server_mode(options))
  1056. return 0;
  1057. if (authdir_mode(options))
  1058. return 1;
  1059. return check_whether_orport_reachable();
  1060. }
  1061. /** Initiate server descriptor upload as reasonable (if server is publishable,
  1062. * etc). <b>force</b> is as for router_upload_dir_desc_to_dirservers.
  1063. *
  1064. * We need to rebuild the descriptor if it's dirty even if we're not
  1065. * uploading, because our reachability testing *uses* our descriptor to
  1066. * determine what IP address and ports to test.
  1067. */
  1068. void
  1069. consider_publishable_server(int force)
  1070. {
  1071. int rebuilt;
  1072. if (!server_mode(get_options()))
  1073. return;
  1074. rebuilt = router_rebuild_descriptor(0);
  1075. if (decide_if_publishable_server()) {
  1076. set_server_advertised(1);
  1077. if (rebuilt == 0)
  1078. router_upload_dir_desc_to_dirservers(force);
  1079. } else {
  1080. set_server_advertised(0);
  1081. }
  1082. }
  1083. /*
  1084. * OR descriptor generation.
  1085. */
  1086. /** My routerinfo. */
  1087. static routerinfo_t *desc_routerinfo = NULL;
  1088. /** My extrainfo */
  1089. static extrainfo_t *desc_extrainfo = NULL;
  1090. /** Since when has our descriptor been "clean"? 0 if we need to regenerate it
  1091. * now. */
  1092. static time_t desc_clean_since = 0;
  1093. /** Boolean: do we need to regenerate the above? */
  1094. static int desc_needs_upload = 0;
  1095. /** OR only: If <b>force</b> is true, or we haven't uploaded this
  1096. * descriptor successfully yet, try to upload our signed descriptor to
  1097. * all the directory servers we know about.
  1098. */
  1099. void
  1100. router_upload_dir_desc_to_dirservers(int force)
  1101. {
  1102. const routerinfo_t *ri;
  1103. extrainfo_t *ei;
  1104. char *msg;
  1105. size_t desc_len, extra_len = 0, total_len;
  1106. dirinfo_type_t auth = get_options()->_PublishServerDescriptor;
  1107. ri = router_get_my_routerinfo();
  1108. if (!ri) {
  1109. log_info(LD_GENERAL, "No descriptor; skipping upload");
  1110. return;
  1111. }
  1112. ei = router_get_my_extrainfo();
  1113. if (auth == NO_DIRINFO)
  1114. return;
  1115. if (!force && !desc_needs_upload)
  1116. return;
  1117. desc_needs_upload = 0;
  1118. desc_len = ri->cache_info.signed_descriptor_len;
  1119. extra_len = ei ? ei->cache_info.signed_descriptor_len : 0;
  1120. total_len = desc_len + extra_len + 1;
  1121. msg = tor_malloc(total_len);
  1122. memcpy(msg, ri->cache_info.signed_descriptor_body, desc_len);
  1123. if (ei) {
  1124. memcpy(msg+desc_len, ei->cache_info.signed_descriptor_body, extra_len);
  1125. }
  1126. msg[desc_len+extra_len] = 0;
  1127. directory_post_to_dirservers(DIR_PURPOSE_UPLOAD_DIR,
  1128. (auth & BRIDGE_DIRINFO) ?
  1129. ROUTER_PURPOSE_BRIDGE :
  1130. ROUTER_PURPOSE_GENERAL,
  1131. auth, msg, desc_len, extra_len);
  1132. tor_free(msg);
  1133. }
  1134. /** OR only: Check whether my exit policy says to allow connection to
  1135. * conn. Return 0 if we accept; non-0 if we reject.
  1136. */
  1137. int
  1138. router_compare_to_my_exit_policy(edge_connection_t *conn)
  1139. {
  1140. if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
  1141. return -1;
  1142. /* make sure it's resolved to something. this way we can't get a
  1143. 'maybe' below. */
  1144. if (tor_addr_is_null(&conn->_base.addr))
  1145. return -1;
  1146. /* XXXX IPv6 */
  1147. if (tor_addr_family(&conn->_base.addr) != AF_INET)
  1148. return -1;
  1149. return compare_tor_addr_to_addr_policy(&conn->_base.addr, conn->_base.port,
  1150. desc_routerinfo->exit_policy) != ADDR_POLICY_ACCEPTED;
  1151. }
  1152. /** Return true iff my exit policy is reject *:*. Return -1 if we don't
  1153. * have a descriptor */
  1154. int
  1155. router_my_exit_policy_is_reject_star(void)
  1156. {
  1157. if (!router_get_my_routerinfo()) /* make sure desc_routerinfo exists */
  1158. return -1;
  1159. return desc_routerinfo->policy_is_reject_star;
  1160. }
  1161. /** Return true iff I'm a server and <b>digest</b> is equal to
  1162. * my server identity key digest. */
  1163. int
  1164. router_digest_is_me(const char *digest)
  1165. {
  1166. return (server_identitykey &&
  1167. tor_memeq(server_identitykey_digest, digest, DIGEST_LEN));
  1168. }
  1169. /** Return true iff I'm a server and <b>digest</b> is equal to
  1170. * my identity digest. */
  1171. int
  1172. router_extrainfo_digest_is_me(const char *digest)
  1173. {
  1174. extrainfo_t *ei = router_get_my_extrainfo();
  1175. if (!ei)
  1176. return 0;
  1177. return tor_memeq(digest,
  1178. ei->cache_info.signed_descriptor_digest,
  1179. DIGEST_LEN);
  1180. }
  1181. /** A wrapper around router_digest_is_me(). */
  1182. int
  1183. router_is_me(const routerinfo_t *router)
  1184. {
  1185. return router_digest_is_me(router->cache_info.identity_digest);
  1186. }
  1187. /** Return true iff <b>fp</b> is a hex fingerprint of my identity digest. */
  1188. int
  1189. router_fingerprint_is_me(const char *fp)
  1190. {
  1191. char digest[DIGEST_LEN];
  1192. if (strlen(fp) == HEX_DIGEST_LEN &&
  1193. base16_decode(digest, sizeof(digest), fp, HEX_DIGEST_LEN) == 0)
  1194. return router_digest_is_me(digest);
  1195. return 0;
  1196. }
  1197. /** Return a routerinfo for this OR, rebuilding a fresh one if
  1198. * necessary. Return NULL on error, or if called on an OP. */
  1199. const routerinfo_t *
  1200. router_get_my_routerinfo(void)
  1201. {
  1202. if (!server_mode(get_options()))
  1203. return NULL;
  1204. if (router_rebuild_descriptor(0))
  1205. return NULL;
  1206. return desc_routerinfo;
  1207. }
  1208. /** OR only: Return a signed server descriptor for this OR, rebuilding a fresh
  1209. * one if necessary. Return NULL on error.
  1210. */
  1211. const char *
  1212. router_get_my_descriptor(void)
  1213. {
  1214. const char *body;
  1215. if (!router_get_my_routerinfo())
  1216. return NULL;
  1217. /* Make sure this is nul-terminated. */
  1218. tor_assert(desc_routerinfo->cache_info.saved_location == SAVED_NOWHERE);
  1219. body = signed_descriptor_get_body(&desc_routerinfo->cache_info);
  1220. tor_assert(!body[desc_routerinfo->cache_info.signed_descriptor_len]);
  1221. log_debug(LD_GENERAL,"my desc is '%s'", body);
  1222. return body;
  1223. }
  1224. /** Return the extrainfo document for this OR, or NULL if we have none.
  1225. * Rebuilt it (and the server descriptor) if necessary. */
  1226. extrainfo_t *
  1227. router_get_my_extrainfo(void)
  1228. {
  1229. if (!server_mode(get_options()))
  1230. return NULL;
  1231. if (router_rebuild_descriptor(0))
  1232. return NULL;
  1233. return desc_extrainfo;
  1234. }
  1235. /** A list of nicknames that we've warned about including in our family
  1236. * declaration verbatim rather than as digests. */
  1237. static smartlist_t *warned_nonexistent_family = NULL;
  1238. static int router_guess_address_from_dir_headers(uint32_t *guess);
  1239. /** Make a current best guess at our address, either because
  1240. * it's configured in torrc, or because we've learned it from
  1241. * dirserver headers. Place the answer in *<b>addr</b> and return
  1242. * 0 on success, else return -1 if we have no guess. */
  1243. int
  1244. router_pick_published_address(or_options_t *options, uint32_t *addr)
  1245. {
  1246. if (resolve_my_address(LOG_INFO, options, addr, NULL) < 0) {
  1247. log_info(LD_CONFIG, "Could not determine our address locally. "
  1248. "Checking if directory headers provide any hints.");
  1249. if (router_guess_address_from_dir_headers(addr) < 0) {
  1250. log_info(LD_CONFIG, "No hints from directory headers either. "
  1251. "Will try again later.");
  1252. return -1;
  1253. }
  1254. }
  1255. log_info(LD_CONFIG,"Success: chose address '%s'.", fmt_addr32(*addr));
  1256. return 0;
  1257. }
  1258. /** If <b>force</b> is true, or our descriptor is out-of-date, rebuild a fresh
  1259. * routerinfo, signed server descriptor, and extra-info document for this OR.
  1260. * Return 0 on success, -1 on temporary error.
  1261. */
  1262. int
  1263. router_rebuild_descriptor(int force)
  1264. {
  1265. routerinfo_t *ri;
  1266. extrainfo_t *ei;
  1267. uint32_t addr;
  1268. char platform[256];
  1269. int hibernating = we_are_hibernating();
  1270. or_options_t *options = get_options();
  1271. if (desc_clean_since && !force)
  1272. return 0;
  1273. if (router_pick_published_address(options, &addr) < 0) {
  1274. /* Stop trying to rebuild our descriptor every second. We'll
  1275. * learn that it's time to try again when ip_address_changed()
  1276. * marks it dirty. */
  1277. desc_clean_since = time(NULL);
  1278. return -1;
  1279. }
  1280. ri = tor_malloc_zero(sizeof(routerinfo_t));
  1281. ri->cache_info.routerlist_index = -1;
  1282. ri->address = tor_dup_ip(addr);
  1283. ri->nickname = tor_strdup(options->Nickname);
  1284. ri->addr = addr;
  1285. ri->or_port = options->ORPort;
  1286. ri->dir_port = options->DirPort;
  1287. ri->cache_info.published_on = time(NULL);
  1288. ri->onion_pkey = crypto_pk_dup_key(get_onion_key()); /* must invoke from
  1289. * main thread */
  1290. ri->identity_pkey = crypto_pk_dup_key(get_server_identity_key());
  1291. if (crypto_pk_get_digest(ri->identity_pkey,
  1292. ri->cache_info.identity_digest)<0) {
  1293. routerinfo_free(ri);
  1294. return -1;
  1295. }
  1296. get_platform_str(platform, sizeof(platform));
  1297. ri->platform = tor_strdup(platform);
  1298. /* compute ri->bandwidthrate as the min of various options */
  1299. ri->bandwidthrate = get_effective_bwrate(options);
  1300. /* and compute ri->bandwidthburst similarly */
  1301. ri->bandwidthburst = get_effective_bwburst(options);
  1302. ri->bandwidthcapacity = hibernating ? 0 : rep_hist_bandwidth_assess();
  1303. if (dns_seems_to_be_broken() || has_dns_init_failed()) {
  1304. /* DNS is screwed up; don't claim to be an exit. */
  1305. policies_exit_policy_append_reject_star(&ri->exit_policy);
  1306. } else {
  1307. policies_parse_exit_policy(options->ExitPolicy, &ri->exit_policy,
  1308. options->ExitPolicyRejectPrivate,
  1309. ri->address, !options->BridgeRelay);
  1310. }
  1311. ri->policy_is_reject_star =
  1312. policy_is_reject_star(ri->exit_policy);
  1313. #if 0
  1314. /* XXXX NM NM I belive this is safe to remove */
  1315. if (authdir_mode(options))
  1316. ri->is_valid = ri->is_named = 1; /* believe in yourself */
  1317. #endif
  1318. if (options->MyFamily) {
  1319. smartlist_t *family;
  1320. if (!warned_nonexistent_family)
  1321. warned_nonexistent_family = smartlist_create();
  1322. family = smartlist_create();
  1323. ri->declared_family = smartlist_create();
  1324. smartlist_split_string(family, options->MyFamily, ",",
  1325. SPLIT_SKIP_SPACE|SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 0);
  1326. SMARTLIST_FOREACH_BEGIN(family, char *, name) {
  1327. const node_t *member;
  1328. if (!strcasecmp(name, options->Nickname))
  1329. goto skip; /* Don't list ourself, that's redundant */
  1330. else
  1331. member = node_get_by_nickname(name, 1);
  1332. if (!member) {
  1333. int is_legal = is_legal_nickname_or_hexdigest(name);
  1334. if (!smartlist_string_isin(warned_nonexistent_family, name) &&
  1335. !is_legal_hexdigest(name)) {
  1336. if (is_legal)
  1337. log_warn(LD_CONFIG,
  1338. "I have no descriptor for the router named \"%s\" in my "
  1339. "declared family; I'll use the nickname as is, but "
  1340. "this may confuse clients.", name);
  1341. else
  1342. log_warn(LD_CONFIG, "There is a router named \"%s\" in my "
  1343. "declared family, but that isn't a legal nickname. "
  1344. "Skipping it.", escaped(name));
  1345. smartlist_add(warned_nonexistent_family, tor_strdup(name));
  1346. }
  1347. if (is_legal) {
  1348. smartlist_add(ri->declared_family, name);
  1349. name = NULL;
  1350. }
  1351. } else if (router_digest_is_me(member->identity)) {
  1352. /* Don't list ourself in our own family; that's redundant */
  1353. /* XXX shouldn't be possible */
  1354. } else {
  1355. char *fp = tor_malloc(HEX_DIGEST_LEN+2);
  1356. fp[0] = '$';
  1357. base16_encode(fp+1,HEX_DIGEST_LEN+1,
  1358. member->identity, DIGEST_LEN);
  1359. smartlist_add(ri->declared_family, fp);
  1360. if (smartlist_string_isin(warned_nonexistent_family, name))
  1361. smartlist_string_remove(warned_nonexistent_family, name);
  1362. }
  1363. skip:
  1364. tor_free(name);
  1365. } SMARTLIST_FOREACH_END(name);
  1366. /* remove duplicates from the list */
  1367. smartlist_sort_strings(ri->declared_family);
  1368. smartlist_uniq_strings(ri->declared_family);
  1369. smartlist_free(family);
  1370. }
  1371. /* Now generate the extrainfo. */
  1372. ei = tor_malloc_zero(sizeof(extrainfo_t));
  1373. ei->cache_info.is_extrainfo = 1;
  1374. strlcpy(ei->nickname, get_options()->Nickname, sizeof(ei->nickname));
  1375. ei->cache_info.published_on = ri->cache_info.published_on;
  1376. memcpy(ei->cache_info.identity_digest, ri->cache_info.identity_digest,
  1377. DIGEST_LEN);
  1378. if (extrainfo_dump_to_string(&ei->cache_info.signed_descriptor_body,
  1379. ei, get_server_identity_key()) < 0) {
  1380. log_warn(LD_BUG, "Couldn't generate extra-info descriptor.");
  1381. extrainfo_free(ei);
  1382. ei = NULL;
  1383. } else {
  1384. ei->cache_info.signed_descriptor_len =
  1385. strlen(ei->cache_info.signed_descriptor_body);
  1386. router_get_extrainfo_hash(ei->cache_info.signed_descriptor_body,
  1387. ei->cache_info.signed_descriptor_digest);
  1388. }
  1389. /* Now finish the router descriptor. */
  1390. if (ei) {
  1391. memcpy(ri->cache_info.extra_info_digest,
  1392. ei->cache_info.signed_descriptor_digest,
  1393. DIGEST_LEN);
  1394. } else {
  1395. /* ri was allocated with tor_malloc_zero, so there is no need to
  1396. * zero ri->cache_info.extra_info_digest here. */
  1397. }
  1398. ri->cache_info.signed_descriptor_body = tor_malloc(8192);
  1399. if (router_dump_router_to_string(ri->cache_info.signed_descriptor_body, 8192,
  1400. ri, get_server_identity_key()) < 0) {
  1401. log_warn(LD_BUG, "Couldn't generate router descriptor.");
  1402. routerinfo_free(ri);
  1403. extrainfo_free(ei);
  1404. return -1;
  1405. }
  1406. ri->cache_info.signed_descriptor_len =
  1407. strlen(ri->cache_info.signed_descriptor_body);
  1408. ri->purpose =
  1409. options->BridgeRelay ? ROUTER_PURPOSE_BRIDGE : ROUTER_PURPOSE_GENERAL;
  1410. ri->cache_info.send_unencrypted = 1;
  1411. /* Let bridges serve their own descriptors unencrypted, so they can
  1412. * pass reachability testing. (If they want to be harder to notice,
  1413. * they can always leave the DirPort off). */
  1414. if (ei && !options->BridgeRelay)
  1415. ei->cache_info.send_unencrypted = 1;
  1416. router_get_router_hash(ri->cache_info.signed_descriptor_body,
  1417. strlen(ri->cache_info.signed_descriptor_body),
  1418. ri->cache_info.signed_descriptor_digest);
  1419. if (ei) {
  1420. tor_assert(! routerinfo_incompatible_with_extrainfo(ri, ei, NULL, NULL));
  1421. }
  1422. routerinfo_free(desc_routerinfo);
  1423. desc_routerinfo = ri;
  1424. extrainfo_free(desc_extrainfo);
  1425. desc_extrainfo = ei;
  1426. desc_clean_since = time(NULL);
  1427. desc_needs_upload = 1;
  1428. control_event_my_descriptor_changed();
  1429. return 0;
  1430. }
  1431. /** Mark descriptor out of date if it's older than <b>when</b> */
  1432. void
  1433. mark_my_descriptor_dirty_if_older_than(time_t when)
  1434. {
  1435. if (desc_clean_since < when)
  1436. mark_my_descriptor_dirty();
  1437. }
  1438. /** Call when the current descriptor is out of date. */
  1439. void
  1440. mark_my_descriptor_dirty(void)
  1441. {
  1442. desc_clean_since = 0;
  1443. }
  1444. /** How frequently will we republish our descriptor because of large (factor
  1445. * of 2) shifts in estimated bandwidth? */
  1446. #define MAX_BANDWIDTH_CHANGE_FREQ (20*60)
  1447. /** Check whether bandwidth has changed a lot since the last time we announced
  1448. * bandwidth. If so, mark our descriptor dirty. */
  1449. void
  1450. check_descriptor_bandwidth_changed(time_t now)
  1451. {
  1452. static time_t last_changed = 0;
  1453. uint64_t prev, cur;
  1454. if (!desc_routerinfo)
  1455. return;
  1456. prev = desc_routerinfo->bandwidthcapacity;
  1457. cur = we_are_hibernating() ? 0 : rep_hist_bandwidth_assess();
  1458. if ((prev != cur && (!prev || !cur)) ||
  1459. cur > prev*2 ||
  1460. cur < prev/2) {
  1461. if (last_changed+MAX_BANDWIDTH_CHANGE_FREQ < now) {
  1462. log_info(LD_GENERAL,
  1463. "Measured bandwidth has changed; rebuilding descriptor.");
  1464. mark_my_descriptor_dirty();
  1465. last_changed = now;
  1466. }
  1467. }
  1468. }
  1469. /** Note at log level severity that our best guess of address has changed from
  1470. * <b>prev</b> to <b>cur</b>. */
  1471. static void
  1472. log_addr_has_changed(int severity, uint32_t prev, uint32_t cur,
  1473. const char *source)
  1474. {
  1475. char addrbuf_prev[INET_NTOA_BUF_LEN];
  1476. char addrbuf_cur[INET_NTOA_BUF_LEN];
  1477. struct in_addr in_prev;
  1478. struct in_addr in_cur;
  1479. in_prev.s_addr = htonl(prev);
  1480. tor_inet_ntoa(&in_prev, addrbuf_prev, sizeof(addrbuf_prev));
  1481. in_cur.s_addr = htonl(cur);
  1482. tor_inet_ntoa(&in_cur, addrbuf_cur, sizeof(addrbuf_cur));
  1483. if (prev)
  1484. log_fn(severity, LD_GENERAL,
  1485. "Our IP Address has changed from %s to %s; "
  1486. "rebuilding descriptor (source: %s).",
  1487. addrbuf_prev, addrbuf_cur, source);
  1488. else
  1489. log_notice(LD_GENERAL,
  1490. "Guessed our IP address as %s (source: %s).",
  1491. addrbuf_cur, source);
  1492. }
  1493. /** Check whether our own address as defined by the Address configuration
  1494. * has changed. This is for routers that get their address from a service
  1495. * like dyndns. If our address has changed, mark our descriptor dirty. */
  1496. void
  1497. check_descriptor_ipaddress_changed(time_t now)
  1498. {
  1499. uint32_t prev, cur;
  1500. or_options_t *options = get_options();
  1501. (void) now;
  1502. if (!desc_routerinfo)
  1503. return;
  1504. prev = desc_routerinfo->addr;
  1505. if (resolve_my_address(LOG_INFO, options, &cur, NULL) < 0) {
  1506. log_info(LD_CONFIG,"options->Address didn't resolve into an IP.");
  1507. return;
  1508. }
  1509. if (prev != cur) {
  1510. log_addr_has_changed(LOG_NOTICE, prev, cur, "resolve");
  1511. ip_address_changed(0);
  1512. }
  1513. }
  1514. /** The most recently guessed value of our IP address, based on directory
  1515. * headers. */
  1516. static uint32_t last_guessed_ip = 0;
  1517. /** A directory server <b>d_conn</b> told us our IP address is
  1518. * <b>suggestion</b>.
  1519. * If this address is different from the one we think we are now, and
  1520. * if our computer doesn't actually know its IP address, then switch. */
  1521. void
  1522. router_new_address_suggestion(const char *suggestion,
  1523. const dir_connection_t *d_conn)
  1524. {
  1525. uint32_t addr, cur = 0;
  1526. struct in_addr in;
  1527. or_options_t *options = get_options();
  1528. /* first, learn what the IP address actually is */
  1529. if (!tor_inet_aton(suggestion, &in)) {
  1530. log_debug(LD_DIR, "Malformed X-Your-Address-Is header %s. Ignoring.",
  1531. escaped(suggestion));
  1532. return;
  1533. }
  1534. addr = ntohl(in.s_addr);
  1535. log_debug(LD_DIR, "Got X-Your-Address-Is: %s.", suggestion);
  1536. if (!server_mode(options)) {
  1537. last_guessed_ip = addr; /* store it in case we need it later */
  1538. return;
  1539. }
  1540. if (resolve_my_address(LOG_INFO, options, &cur, NULL) >= 0) {
  1541. /* We're all set -- we already know our address. Great. */
  1542. last_guessed_ip = cur; /* store it in case we need it later */
  1543. return;
  1544. }
  1545. if (is_internal_IP(addr, 0)) {
  1546. /* Don't believe anybody who says our IP is, say, 127.0.0.1. */
  1547. return;
  1548. }
  1549. if (tor_addr_eq_ipv4h(&d_conn->_base.addr, addr)) {
  1550. /* Don't believe anybody who says our IP is their IP. */
  1551. log_debug(LD_DIR, "A directory server told us our IP address is %s, "
  1552. "but he's just reporting his own IP address. Ignoring.",
  1553. suggestion);
  1554. return;
  1555. }
  1556. /* Okay. We can't resolve our own address, and X-Your-Address-Is is giving
  1557. * us an answer different from what we had the last time we managed to
  1558. * resolve it. */
  1559. if (last_guessed_ip != addr) {
  1560. control_event_server_status(LOG_NOTICE,
  1561. "EXTERNAL_ADDRESS ADDRESS=%s METHOD=DIRSERV",
  1562. suggestion);
  1563. log_addr_has_changed(LOG_NOTICE, last_guessed_ip, addr,
  1564. d_conn->_base.address);
  1565. ip_address_changed(0);
  1566. last_guessed_ip = addr; /* router_rebuild_descriptor() will fetch it */
  1567. }
  1568. }
  1569. /** We failed to resolve our address locally, but we'd like to build
  1570. * a descriptor and publish / test reachability. If we have a guess
  1571. * about our address based on directory headers, answer it and return
  1572. * 0; else return -1. */
  1573. static int
  1574. router_guess_address_from_dir_headers(uint32_t *guess)
  1575. {
  1576. if (last_guessed_ip) {
  1577. *guess = last_guessed_ip;
  1578. return 0;
  1579. }
  1580. return -1;
  1581. }
  1582. /** Set <b>platform</b> (max length <b>len</b>) to a NUL-terminated short
  1583. * string describing the version of Tor and the operating system we're
  1584. * currently running on.
  1585. */
  1586. void
  1587. get_platform_str(char *platform, size_t len)
  1588. {
  1589. tor_snprintf(platform, len, "Tor %s on %s", get_version(), get_uname());
  1590. }
  1591. /* XXX need to audit this thing and count fenceposts. maybe
  1592. * refactor so we don't have to keep asking if we're
  1593. * near the end of maxlen?
  1594. */
  1595. #define DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  1596. /** OR only: Given a routerinfo for this router, and an identity key to sign
  1597. * with, encode the routerinfo as a signed server descriptor and write the
  1598. * result into <b>s</b>, using at most <b>maxlen</b> bytes. Return -1 on
  1599. * failure, and the number of bytes used on success.
  1600. */
  1601. int
  1602. router_dump_router_to_string(char *s, size_t maxlen, routerinfo_t *router,
  1603. crypto_pk_env_t *ident_key)
  1604. {
  1605. char *onion_pkey; /* Onion key, PEM-encoded. */
  1606. char *identity_pkey; /* Identity key, PEM-encoded. */
  1607. char digest[DIGEST_LEN];
  1608. char published[ISO_TIME_LEN+1];
  1609. char fingerprint[FINGERPRINT_LEN+1];
  1610. int has_extra_info_digest;
  1611. char extra_info_digest[HEX_DIGEST_LEN+1];
  1612. size_t onion_pkeylen, identity_pkeylen;
  1613. size_t written;
  1614. int result=0;
  1615. addr_policy_t *tmpe;
  1616. char *family_line;
  1617. or_options_t *options = get_options();
  1618. /* Make sure the identity key matches the one in the routerinfo. */
  1619. if (crypto_pk_cmp_keys(ident_key, router->identity_pkey)) {
  1620. log_warn(LD_BUG,"Tried to sign a router with a private key that didn't "
  1621. "match router's public key!");
  1622. return -1;
  1623. }
  1624. /* record our fingerprint, so we can include it in the descriptor */
  1625. if (crypto_pk_get_fingerprint(router->identity_pkey, fingerprint, 1)<0) {
  1626. log_err(LD_BUG,"Error computing fingerprint");
  1627. return -1;
  1628. }
  1629. /* PEM-encode the onion key */
  1630. if (crypto_pk_write_public_key_to_string(router->onion_pkey,
  1631. &onion_pkey,&onion_pkeylen)<0) {
  1632. log_warn(LD_BUG,"write onion_pkey to string failed!");
  1633. return -1;
  1634. }
  1635. /* PEM-encode the identity key */
  1636. if (crypto_pk_write_public_key_to_string(router->identity_pkey,
  1637. &identity_pkey,&identity_pkeylen)<0) {
  1638. log_warn(LD_BUG,"write identity_pkey to string failed!");
  1639. tor_free(onion_pkey);
  1640. return -1;
  1641. }
  1642. /* Encode the publication time. */
  1643. format_iso_time(published, router->cache_info.published_on);
  1644. if (router->declared_family && smartlist_len(router->declared_family)) {
  1645. size_t n;
  1646. char *family = smartlist_join_strings(router->declared_family, " ", 0, &n);
  1647. n += strlen("family ") + 2; /* 1 for \n, 1 for \0. */
  1648. family_line = tor_malloc(n);
  1649. tor_snprintf(family_line, n, "family %s\n", family);
  1650. tor_free(family);
  1651. } else {
  1652. family_line = tor_strdup("");
  1653. }
  1654. has_extra_info_digest =
  1655. ! tor_digest_is_zero(router->cache_info.extra_info_digest);
  1656. if (has_extra_info_digest) {
  1657. base16_encode(extra_info_digest, sizeof(extra_info_digest),
  1658. router->cache_info.extra_info_digest, DIGEST_LEN);
  1659. }
  1660. /* Generate the easy portion of the router descriptor. */
  1661. result = tor_snprintf(s, maxlen,
  1662. "router %s %s %d 0 %d\n"
  1663. "platform %s\n"
  1664. "opt protocols Link 1 2 Circuit 1\n"
  1665. "published %s\n"
  1666. "opt fingerprint %s\n"
  1667. "uptime %ld\n"
  1668. "bandwidth %d %d %d\n"
  1669. "%s%s%s%s"
  1670. "onion-key\n%s"
  1671. "signing-key\n%s"
  1672. "%s%s%s%s",
  1673. router->nickname,
  1674. router->address,
  1675. router->or_port,
  1676. decide_to_advertise_dirport(options, router->dir_port),
  1677. router->platform,
  1678. published,
  1679. fingerprint,
  1680. stats_n_seconds_working,
  1681. (int) router->bandwidthrate,
  1682. (int) router->bandwidthburst,
  1683. (int) router->bandwidthcapacity,
  1684. has_extra_info_digest ? "opt extra-info-digest " : "",
  1685. has_extra_info_digest ? extra_info_digest : "",
  1686. has_extra_info_digest ? "\n" : "",
  1687. options->DownloadExtraInfo ? "opt caches-extra-info\n" : "",
  1688. onion_pkey, identity_pkey,
  1689. family_line,
  1690. we_are_hibernating() ? "opt hibernating 1\n" : "",
  1691. options->HidServDirectoryV2 ? "opt hidden-service-dir\n" : "",
  1692. options->AllowSingleHopExits ? "opt allow-single-hop-exits\n" : "");
  1693. tor_free(family_line);
  1694. tor_free(onion_pkey);
  1695. tor_free(identity_pkey);
  1696. if (result < 0) {
  1697. log_warn(LD_BUG,"descriptor snprintf #1 ran out of room!");
  1698. return -1;
  1699. }
  1700. /* From now on, we use 'written' to remember the current length of 's'. */
  1701. written = result;
  1702. if (options->ContactInfo && strlen(options->ContactInfo)) {
  1703. const char *ci = options->ContactInfo;
  1704. if (strchr(ci, '\n') || strchr(ci, '\r'))
  1705. ci = escaped(ci);
  1706. result = tor_snprintf(s+written,maxlen-written, "contact %s\n", ci);
  1707. if (result<0) {
  1708. log_warn(LD_BUG,"descriptor snprintf #2 ran out of room!");
  1709. return -1;
  1710. }
  1711. written += result;
  1712. }
  1713. /* Write the exit policy to the end of 's'. */
  1714. if (!router->exit_policy || !smartlist_len(router->exit_policy)) {
  1715. strlcat(s+written, "reject *:*\n", maxlen-written);
  1716. written += strlen("reject *:*\n");
  1717. tmpe = NULL;
  1718. } else if (router->exit_policy) {
  1719. int i;
  1720. for (i = 0; i < smartlist_len(router->exit_policy); ++i) {
  1721. tmpe = smartlist_get(router->exit_policy, i);
  1722. result = policy_write_item(s+written, maxlen-written, tmpe, 1);
  1723. if (result < 0) {
  1724. log_warn(LD_BUG,"descriptor policy_write_item ran out of room!");
  1725. return -1;
  1726. }
  1727. tor_assert(result == (int)strlen(s+written));
  1728. written += result;
  1729. if (written+2 > maxlen) {
  1730. log_warn(LD_BUG,"descriptor policy_write_item ran out of room (2)!");
  1731. return -1;
  1732. }
  1733. s[written++] = '\n';
  1734. }
  1735. }
  1736. if (written + DIROBJ_MAX_SIG_LEN > maxlen) {
  1737. /* Not enough room for signature. */
  1738. log_warn(LD_BUG,"not enough room left in descriptor for signature!");
  1739. return -1;
  1740. }
  1741. /* Sign the descriptor */
  1742. strlcpy(s+written, "router-signature\n", maxlen-written);
  1743. written += strlen(s+written);
  1744. s[written] = '\0';
  1745. if (router_get_router_hash(s, strlen(s), digest) < 0) {
  1746. return -1;
  1747. }
  1748. note_crypto_pk_op(SIGN_RTR);
  1749. if (router_append_dirobj_signature(s+written,maxlen-written,
  1750. digest,DIGEST_LEN,ident_key)<0) {
  1751. log_warn(LD_BUG, "Couldn't sign router descriptor");
  1752. return -1;
  1753. }
  1754. written += strlen(s+written);
  1755. if (written+2 > maxlen) {
  1756. log_warn(LD_BUG,"Not enough room to finish descriptor.");
  1757. return -1;
  1758. }
  1759. /* include a last '\n' */
  1760. s[written] = '\n';
  1761. s[written+1] = 0;
  1762. #ifdef DEBUG_ROUTER_DUMP_ROUTER_TO_STRING
  1763. {
  1764. char *s_dup;
  1765. const char *cp;
  1766. routerinfo_t *ri_tmp;
  1767. cp = s_dup = tor_strdup(s);
  1768. ri_tmp = router_parse_entry_from_string(cp, NULL, 1, 0, NULL);
  1769. if (!ri_tmp) {
  1770. log_err(LD_BUG,
  1771. "We just generated a router descriptor we can't parse.");
  1772. log_err(LD_BUG, "Descriptor was: <<%s>>", s);
  1773. return -1;
  1774. }
  1775. tor_free(s_dup);
  1776. routerinfo_free(ri_tmp);
  1777. }
  1778. #endif
  1779. return (int)written+1;
  1780. }
  1781. /** Load the contents of <b>filename</b>, find the last line starting with
  1782. * <b>end_line</b>, ensure that its timestamp is not more than 25 hours in
  1783. * the past or more than 1 hour in the future with respect to <b>now</b>,
  1784. * and write the file contents starting with that line to *<b>out</b>.
  1785. * Return 1 for success, 0 if the file does not exist, or -1 if the file
  1786. * does not contain a line matching these criteria or other failure. */
  1787. static int
  1788. load_stats_file(const char *filename, const char *end_line, time_t now,
  1789. char **out)
  1790. {
  1791. int r = -1;
  1792. char *fname = get_datadir_fname(filename);
  1793. char *contents, *start = NULL, *tmp, timestr[ISO_TIME_LEN+1];
  1794. time_t written;
  1795. switch (file_status(fname)) {
  1796. case FN_FILE:
  1797. /* X022 Find an alternative to reading the whole file to memory. */
  1798. if ((contents = read_file_to_str(fname, 0, NULL))) {
  1799. tmp = strstr(contents, end_line);
  1800. /* Find last block starting with end_line */
  1801. while (tmp) {
  1802. start = tmp;
  1803. tmp = strstr(tmp + 1, end_line);
  1804. }
  1805. if (!start)
  1806. goto notfound;
  1807. if (strlen(start) < strlen(end_line) + 1 + sizeof(timestr))
  1808. goto notfound;
  1809. strlcpy(timestr, start + 1 + strlen(end_line), sizeof(timestr));
  1810. if (parse_iso_time(timestr, &written) < 0)
  1811. goto notfound;
  1812. if (written < now - (25*60*60) || written > now + (1*60*60))
  1813. goto notfound;
  1814. *out = tor_strdup(start);
  1815. r = 1;
  1816. }
  1817. notfound:
  1818. tor_free(contents);
  1819. break;
  1820. case FN_NOENT:
  1821. r = 0;
  1822. break;
  1823. case FN_ERROR:
  1824. case FN_DIR:
  1825. default:
  1826. break;
  1827. }
  1828. tor_free(fname);
  1829. return r;
  1830. }
  1831. /** Write the contents of <b>extrainfo</b> and aggregated statistics to
  1832. * *<b>s_out</b>, signing them with <b>ident_key</b>. Return 0 on
  1833. * success, negative on failure. */
  1834. int
  1835. extrainfo_dump_to_string(char **s_out, extrainfo_t *extrainfo,
  1836. crypto_pk_env_t *ident_key)
  1837. {
  1838. or_options_t *options = get_options();
  1839. char identity[HEX_DIGEST_LEN+1];
  1840. char published[ISO_TIME_LEN+1];
  1841. char digest[DIGEST_LEN];
  1842. char *bandwidth_usage;
  1843. int result;
  1844. static int write_stats_to_extrainfo = 1;
  1845. char sig[DIROBJ_MAX_SIG_LEN+1];
  1846. char *s, *pre, *contents, *cp, *s_dup = NULL;
  1847. time_t now = time(NULL);
  1848. smartlist_t *chunks = smartlist_create();
  1849. extrainfo_t *ei_tmp = NULL;
  1850. base16_encode(identity, sizeof(identity),
  1851. extrainfo->cache_info.identity_digest, DIGEST_LEN);
  1852. format_iso_time(published, extrainfo->cache_info.published_on);
  1853. bandwidth_usage = rep_hist_get_bandwidth_lines();
  1854. tor_asprintf(&pre, "extra-info %s %s\npublished %s\n%s",
  1855. extrainfo->nickname, identity,
  1856. published, bandwidth_usage);
  1857. tor_free(bandwidth_usage);
  1858. smartlist_add(chunks, pre);
  1859. if (geoip_is_loaded()) {
  1860. char *chunk=NULL;
  1861. tor_asprintf(&chunk, "geoip-db-digest %s\n", geoip_db_digest());
  1862. smartlist_add(chunks, chunk);
  1863. }
  1864. if (options->ExtraInfoStatistics && write_stats_to_extrainfo) {
  1865. log_info(LD_GENERAL, "Adding stats to extra-info descriptor.");
  1866. if (options->DirReqStatistics &&
  1867. load_stats_file("stats"PATH_SEPARATOR"dirreq-stats",
  1868. "dirreq-stats-end", now, &contents) > 0) {
  1869. smartlist_add(chunks, contents);
  1870. }
  1871. if (options->EntryStatistics &&
  1872. load_stats_file("stats"PATH_SEPARATOR"entry-stats",
  1873. "entry-stats-end", now, &contents) > 0) {
  1874. smartlist_add(chunks, contents);
  1875. }
  1876. if (options->CellStatistics &&
  1877. load_stats_file("stats"PATH_SEPARATOR"buffer-stats",
  1878. "cell-stats-end", now, &contents) > 0) {
  1879. smartlist_add(chunks, contents);
  1880. }
  1881. if (options->ExitPortStatistics &&
  1882. load_stats_file("stats"PATH_SEPARATOR"exit-stats",
  1883. "exit-stats-end", now, &contents) > 0) {
  1884. smartlist_add(chunks, contents);
  1885. }
  1886. if (options->ConnDirectionStatistics &&
  1887. load_stats_file("stats"PATH_SEPARATOR"conn-stats",
  1888. "conn-bi-direct", now, &contents) > 0) {
  1889. smartlist_add(chunks, contents);
  1890. }
  1891. }
  1892. if (should_record_bridge_info(options) && write_stats_to_extrainfo) {
  1893. const char *bridge_stats = geoip_get_bridge_stats_extrainfo(now);
  1894. if (bridge_stats) {
  1895. smartlist_add(chunks, tor_strdup(bridge_stats));
  1896. }
  1897. }
  1898. smartlist_add(chunks, tor_strdup("router-signature\n"));
  1899. s = smartlist_join_strings(chunks, "", 0, NULL);
  1900. while (strlen(s) > MAX_EXTRAINFO_UPLOAD_SIZE - DIROBJ_MAX_SIG_LEN) {
  1901. /* So long as there are at least two chunks (one for the initial
  1902. * extra-info line and one for the router-signature), we can keep removing
  1903. * things. */
  1904. if (smartlist_len(chunks) > 2) {
  1905. /* We remove the next-to-last element (remember, len-1 is the last
  1906. element), since we need to keep the router-signature element. */
  1907. int idx = smartlist_len(chunks) - 2;
  1908. char *e = smartlist_get(chunks, idx);
  1909. smartlist_del_keeporder(chunks, idx);
  1910. log_warn(LD_GENERAL, "We just generated an extra-info descriptor "
  1911. "with statistics that exceeds the 50 KB "
  1912. "upload limit. Removing last added "
  1913. "statistics.");
  1914. tor_free(e);
  1915. tor_free(s);
  1916. s = smartlist_join_strings(chunks, "", 0, NULL);
  1917. } else {
  1918. log_warn(LD_BUG, "We just generated an extra-info descriptors that "
  1919. "exceeds the 50 KB upload limit.");
  1920. goto err;
  1921. }
  1922. }
  1923. memset(sig, 0, sizeof(sig));
  1924. if (router_get_extrainfo_hash(s, digest) < 0 ||
  1925. router_append_dirobj_signature(sig, sizeof(sig), digest, DIGEST_LEN,
  1926. ident_key) < 0) {
  1927. log_warn(LD_BUG, "Could not append signature to extra-info "
  1928. "descriptor.");
  1929. goto err;
  1930. }
  1931. smartlist_add(chunks, tor_strdup(sig));
  1932. tor_free(s);
  1933. s = smartlist_join_strings(chunks, "", 0, NULL);
  1934. cp = s_dup = tor_strdup(s);
  1935. ei_tmp = extrainfo_parse_entry_from_string(cp, NULL, 1, NULL);
  1936. if (!ei_tmp) {
  1937. if (write_stats_to_extrainfo) {
  1938. log_warn(LD_GENERAL, "We just generated an extra-info descriptor "
  1939. "with statistics that we can't parse. Not "
  1940. "adding statistics to this or any future "
  1941. "extra-info descriptors.");
  1942. write_stats_to_extrainfo = 0;
  1943. result = extrainfo_dump_to_string(s_out, extrainfo, ident_key);
  1944. goto done;
  1945. } else {
  1946. log_warn(LD_BUG, "We just generated an extrainfo descriptor we "
  1947. "can't parse.");
  1948. goto err;
  1949. }
  1950. }
  1951. *s_out = s;
  1952. s = NULL; /* prevent free */
  1953. result = 0;
  1954. goto done;
  1955. err:
  1956. result = -1;
  1957. done:
  1958. tor_free(s);
  1959. SMARTLIST_FOREACH(chunks, char *, cp, tor_free(cp));
  1960. smartlist_free(chunks);
  1961. tor_free(s_dup);
  1962. extrainfo_free(ei_tmp);
  1963. return result;
  1964. }
  1965. /** Return true iff <b>s</b> is a legally valid server nickname. */
  1966. int
  1967. is_legal_nickname(const char *s)
  1968. {
  1969. size_t len;
  1970. tor_assert(s);
  1971. len = strlen(s);
  1972. return len > 0 && len <= MAX_NICKNAME_LEN &&
  1973. strspn(s,LEGAL_NICKNAME_CHARACTERS) == len;
  1974. }
  1975. /** Return true iff <b>s</b> is a legally valid server nickname or
  1976. * hex-encoded identity-key digest. */
  1977. int
  1978. is_legal_nickname_or_hexdigest(const char *s)
  1979. {
  1980. if (*s!='$')
  1981. return is_legal_nickname(s);
  1982. else
  1983. return is_legal_hexdigest(s);
  1984. }
  1985. /** Return true iff <b>s</b> is a legally valid hex-encoded identity-key
  1986. * digest. */
  1987. int
  1988. is_legal_hexdigest(const char *s)
  1989. {
  1990. size_t len;
  1991. tor_assert(s);
  1992. if (s[0] == '$') s++;
  1993. len = strlen(s);
  1994. if (len > HEX_DIGEST_LEN) {
  1995. if (s[HEX_DIGEST_LEN] == '=' ||
  1996. s[HEX_DIGEST_LEN] == '~') {
  1997. if (!is_legal_nickname(s+HEX_DIGEST_LEN+1))
  1998. return 0;
  1999. } else {
  2000. return 0;
  2001. }
  2002. }
  2003. return (len >= HEX_DIGEST_LEN &&
  2004. strspn(s,HEX_CHARACTERS)==HEX_DIGEST_LEN);
  2005. }
  2006. /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
  2007. * verbose representation of the identity of <b>router</b>. The format is:
  2008. * A dollar sign.
  2009. * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
  2010. * A "=" if the router is named; a "~" if it is not.
  2011. * The router's nickname.
  2012. **/
  2013. void
  2014. router_get_verbose_nickname(char *buf, const routerinfo_t *router)
  2015. {
  2016. const char *good_digest = networkstatus_get_router_digest_by_nickname(
  2017. router->nickname);
  2018. int is_named = good_digest && !memcmp(good_digest,
  2019. router->cache_info.identity_digest,
  2020. DIGEST_LEN);
  2021. buf[0] = '$';
  2022. base16_encode(buf+1, HEX_DIGEST_LEN+1, router->cache_info.identity_digest,
  2023. DIGEST_LEN);
  2024. buf[1+HEX_DIGEST_LEN] = is_named ? '=' : '~';
  2025. strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
  2026. }
  2027. /** Set <b>buf</b> (which must have MAX_VERBOSE_NICKNAME_LEN+1 bytes) to the
  2028. * verbose representation of the identity of <b>router</b>. The format is:
  2029. * A dollar sign.
  2030. * The upper-case hexadecimal encoding of the SHA1 hash of router's identity.
  2031. * A "=" if the router is named; a "~" if it is not.
  2032. * The router's nickname.
  2033. **/
  2034. void
  2035. routerstatus_get_verbose_nickname(char *buf, const routerstatus_t *router)
  2036. {
  2037. buf[0] = '$';
  2038. base16_encode(buf+1, HEX_DIGEST_LEN+1, router->identity_digest,
  2039. DIGEST_LEN);
  2040. buf[1+HEX_DIGEST_LEN] = router->is_named ? '=' : '~';
  2041. strlcpy(buf+1+HEX_DIGEST_LEN+1, router->nickname, MAX_NICKNAME_LEN+1);
  2042. }
  2043. /** Forget that we have issued any router-related warnings, so that we'll
  2044. * warn again if we see the same errors. */
  2045. void
  2046. router_reset_warnings(void)
  2047. {
  2048. if (warned_nonexistent_family) {
  2049. SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
  2050. smartlist_clear(warned_nonexistent_family);
  2051. }
  2052. }
  2053. /** Given a router purpose, convert it to a string. Don't call this on
  2054. * ROUTER_PURPOSE_UNKNOWN: The whole point of that value is that we don't
  2055. * know its string representation. */
  2056. const char *
  2057. router_purpose_to_string(uint8_t p)
  2058. {
  2059. switch (p)
  2060. {
  2061. case ROUTER_PURPOSE_GENERAL: return "general";
  2062. case ROUTER_PURPOSE_BRIDGE: return "bridge";
  2063. case ROUTER_PURPOSE_CONTROLLER: return "controller";
  2064. default:
  2065. tor_assert(0);
  2066. }
  2067. return NULL;
  2068. }
  2069. /** Given a string, convert it to a router purpose. */
  2070. uint8_t
  2071. router_purpose_from_string(const char *s)
  2072. {
  2073. if (!strcmp(s, "general"))
  2074. return ROUTER_PURPOSE_GENERAL;
  2075. else if (!strcmp(s, "bridge"))
  2076. return ROUTER_PURPOSE_BRIDGE;
  2077. else if (!strcmp(s, "controller"))
  2078. return ROUTER_PURPOSE_CONTROLLER;
  2079. else
  2080. return ROUTER_PURPOSE_UNKNOWN;
  2081. }
  2082. /** Release all static resources held in router.c */
  2083. void
  2084. router_free_all(void)
  2085. {
  2086. crypto_free_pk_env(onionkey);
  2087. crypto_free_pk_env(lastonionkey);
  2088. crypto_free_pk_env(server_identitykey);
  2089. crypto_free_pk_env(client_identitykey);
  2090. tor_mutex_free(key_lock);
  2091. routerinfo_free(desc_routerinfo);
  2092. extrainfo_free(desc_extrainfo);
  2093. crypto_free_pk_env(authority_signing_key);
  2094. authority_cert_free(authority_key_certificate);
  2095. crypto_free_pk_env(legacy_signing_key);
  2096. authority_cert_free(legacy_key_certificate);
  2097. if (warned_nonexistent_family) {
  2098. SMARTLIST_FOREACH(warned_nonexistent_family, char *, cp, tor_free(cp));
  2099. smartlist_free(warned_nonexistent_family);
  2100. }
  2101. }