router.c 80 KB

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