router.c 89 KB

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