router.c 82 KB

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