router.c 86 KB

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