router.c 90 KB

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