router.c 90 KB

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