router.c 88 KB

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