router.c 97 KB

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