router.c 83 KB

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