router.c 86 KB

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