router.c 90 KB

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